repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/legacy/LegacyBookmark.kt
1
584
package voice.data.legacy import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.File import java.time.Instant import java.util.UUID @Entity(tableName = "bookmark") data class LegacyBookmark( @ColumnInfo(name = "file") val mediaFile: File, @ColumnInfo(name = "title") val title: String?, @ColumnInfo(name = "time") val time: Long, @ColumnInfo(name = "addedAt") val addedAt: Instant, @ColumnInfo(name = "setBySleepTimer") val setBySleepTimer: Boolean, @ColumnInfo(name = "id") @PrimaryKey val id: UUID, )
gpl-3.0
537adaaf73b5642856b89df54e3a6196
22.36
39
0.729452
3.518072
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/remote/RemoteBrowserService.kt
1
9043
package com.lasthopesoftware.bluewater.client.browsing.remote import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import androidx.media.MediaBrowserServiceCompat import com.lasthopesoftware.bluewater.R import com.lasthopesoftware.bluewater.client.browsing.items.Item import com.lasthopesoftware.bluewater.client.browsing.items.access.CachedItemProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.FileProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.RateControlledFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedCachedFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.SelectedConnectionFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertyCache import com.lasthopesoftware.bluewater.client.browsing.items.media.image.CachedImageProvider import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository import com.lasthopesoftware.bluewater.client.browsing.library.access.SpecificLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider import com.lasthopesoftware.bluewater.client.browsing.library.revisions.ScopedRevisionProvider import com.lasthopesoftware.bluewater.client.browsing.library.views.access.CachedLibraryViewsProvider import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionProvider import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder import com.lasthopesoftware.bluewater.shared.android.MediaSession.MediaSessionService import com.lasthopesoftware.bluewater.shared.android.services.promiseBoundService import com.lasthopesoftware.bluewater.shared.policies.ratelimiting.PromisingRateLimiter import com.lasthopesoftware.bluewater.shared.promises.extensions.keepPromise import com.lasthopesoftware.resources.PackageValidator import kotlin.math.max class RemoteBrowserService : MediaBrowserServiceCompat() { companion object { // Potentially useful magic android strings (see https://github.com/android/uamp/blob/99e44c1c5106218c62eff552b64bbc12f1883a22/common/src/main/java/com/example/android/uamp/media/MusicService.kt) private const val mediaSearchSupported = "android.media.browse.SEARCH_SUPPORTED" private const val contentStyleBrowsableHint = "android.media.browse.CONTENT_STYLE_BROWSABLE_HINT" private const val contentStylePlayableHint = "android.media.browse.CONTENT_STYLE_PLAYABLE_HINT" private const val contentStyleSupport = "android.media.browse.CONTENT_STYLE_SUPPORTED" private const val contentStyleList = 1 private const val contentStyleGrid = 2 const val serviceFileMediaIdPrefix = "sf" const val itemFileMediaIdPrefix = "it" private const val playlistFileMediaIdPrefix = "pl" const val mediaIdDelimiter = ':' private val rateLimiter by lazy { PromisingRateLimiter<Map<String, String>>(max(Runtime.getRuntime().availableProcessors() - 1, 1)) } private val magicPropertyBuilder by lazy { MagicPropertyBuilder(RemoteBrowserService::class.java) } private val root by lazy { magicPropertyBuilder.buildProperty("root") } private val recentRoot by lazy { magicPropertyBuilder.buildProperty("recentRoot") } private val rejection by lazy { magicPropertyBuilder.buildProperty("rejection") } val error by lazy { magicPropertyBuilder.buildProperty("error") } } private val packageValidator by lazy { PackageValidator(this, R.xml.allowed_media_browser_callers) } private val libraryViewsProvider by lazy { CachedLibraryViewsProvider.getInstance(this) } private val itemProvider by lazy { CachedItemProvider.getInstance(this) } private val fileProvider by lazy { val stringListProvider = FileStringListProvider(SelectedConnectionProvider(this)) FileProvider(stringListProvider) } private val filePropertiesProvider by lazy { SelectedConnectionFilePropertiesProvider(SelectedConnectionProvider(this)) { c -> val filePropertyCache = FilePropertyCache.getInstance() ScopedCachedFilePropertiesProvider( c, filePropertyCache, RateControlledFilePropertiesProvider( ScopedFilePropertiesProvider( c, ScopedRevisionProvider(c), filePropertyCache ), rateLimiter ) ) } } private val imageProvider by lazy { CachedImageProvider.getInstance(this) } private val selectedLibraryIdProvider by lazy { SelectedBrowserLibraryIdentifierProvider(getApplicationSettingsRepository()) } private val mediaItemServiceFileLookup by lazy { MediaItemServiceFileLookup( filePropertiesProvider, imageProvider ) } private val nowPlayingMediaItemLookup by lazy { val libraryRepository = LibraryRepository(this) selectedLibraryIdProvider.selectedLibraryId .then { it?.let { l -> val repository = NowPlayingRepository( SpecificLibraryProvider(l, libraryRepository), libraryRepository ) NowPlayingMediaItemLookup( repository, mediaItemServiceFileLookup ) } } } private val mediaItemBrowser by lazy { MediaItemsBrowser( selectedLibraryIdProvider, itemProvider, fileProvider, libraryViewsProvider, mediaItemServiceFileLookup ) } private val lazyMediaSessionService = lazy { promiseBoundService<MediaSessionService>() } override fun onCreate() { super.onCreate() lazyMediaSessionService.value.then { s -> sessionToken = s.service.mediaSession.sessionToken } } override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? = if (!packageValidator.isKnownCaller(clientPackageName, clientUid)) null else rootHints ?.takeIf { it.getBoolean(BrowserRoot.EXTRA_RECENT) } ?.let { Bundle() } ?.apply { putBoolean(BrowserRoot.EXTRA_RECENT, true) } // Return a tree with a single playable media item for resumption. ?.let { extras -> BrowserRoot(recentRoot, extras) } ?: Bundle() .apply { putBoolean(mediaSearchSupported, true) putBoolean(contentStyleSupport, true) putInt(contentStyleBrowsableHint, contentStyleGrid) putInt(contentStylePlayableHint, contentStyleList) } .let { bundle -> BrowserRoot(root, bundle) } override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) { if (parentId == rejection) { result.sendResult(ArrayList()) return } result.detach() if (parentId == recentRoot) { nowPlayingMediaItemLookup .eventually { lookup -> lookup?.promiseNowPlayingItem().keepPromise() } .then { it?.let { mutableListOf(it) }.apply(result::sendResult) } .excuse { e -> result.sendError(Bundle().apply { putString(error, e.message) }) } return } val promisedMediaItems = parentId .takeIf { id -> id.startsWith(itemFileMediaIdPrefix) } ?.substring(3) ?.toIntOrNull() ?.let { id -> mediaItemBrowser.promiseItems(Item(id)).keepPromise(emptyList()) } ?: mediaItemBrowser.promiseLibraryItems().keepPromise(emptyList()) promisedMediaItems .then { items -> result.sendResult(items.toMutableList()) } .excuse { e -> result.sendError(Bundle().apply { putString(error, e.message) }) } } override fun onLoadItem(itemId: String?, result: Result<MediaBrowserCompat.MediaItem>) { val itemIdParts = itemId?.split(mediaIdDelimiter, limit = 2) if (itemIdParts == null || itemIdParts.size < 2) return super.onLoadItem(itemId, result) val type = itemIdParts[0] if (type != serviceFileMediaIdPrefix) return super.onLoadItem(itemId, result) val id = itemIdParts[1].toIntOrNull() ?: return super.onLoadItem(itemId, result) result.detach() mediaItemServiceFileLookup.promiseMediaItemWithImage(ServiceFile(id)) .then(result::sendResult) .excuse { e -> result.sendError(Bundle().apply { putString(error, e.message) }) } } override fun onSearch(query: String, extras: Bundle?, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) { result.detach() mediaItemBrowser.promiseItems(query) .then { items -> result.sendResult(items.toMutableList()) } .excuse { e -> result.sendError(Bundle().apply { putString(error, e.message) }) } } override fun onDestroy() { if (lazyMediaSessionService.isInitialized()) lazyMediaSessionService.value.then { unbindService(it.serviceConnection) } super.onDestroy() } }
lgpl-3.0
66d0c7b2f8746b72c84fbf45ee3239a8
42.061905
197
0.794095
4.253528
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/stored/library/items/files/StoredFileAccess.kt
1
8457
package com.lasthopesoftware.bluewater.client.stored.library.items.files import android.content.Context import android.database.SQLException import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryEntityInformation import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFileEntityInformation import com.lasthopesoftware.bluewater.repository.InsertBuilder.Companion.fromTable import com.lasthopesoftware.bluewater.repository.RepositoryAccessHelper import com.lasthopesoftware.bluewater.repository.UpdateBuilder import com.lasthopesoftware.bluewater.repository.fetch import com.lasthopesoftware.bluewater.repository.fetchFirst import com.lasthopesoftware.resources.executors.ThreadPools import com.namehillsoftware.handoff.promises.Promise import com.namehillsoftware.handoff.promises.queued.MessageWriter import com.namehillsoftware.handoff.promises.queued.QueuedPromise import org.slf4j.LoggerFactory class StoredFileAccess(private val context: Context) : AccessStoredFiles { private val storedFileAccessExecutor by lazy { ThreadPools.databaseTableExecutor<StoredFileAccess>() } override fun getStoredFile(storedFileId: Int): Promise<StoredFile?> = QueuedPromise(MessageWriter<StoredFile> { RepositoryAccessHelper(context).use { repositoryAccessHelper -> getStoredFile(repositoryAccessHelper, storedFileId) } }, storedFileAccessExecutor) override fun getStoredFile(library: Library, serviceFile: ServiceFile): Promise<StoredFile?> = getStoredFileTask(library, serviceFile) override fun promiseDanglingFiles(): Promise<Collection<StoredFile>> = QueuedPromise(MessageWriter{ RepositoryAccessHelper(context).use { helper -> helper .mapSql( """SELECT DISTINCT * FROM ${StoredFileEntityInformation.tableName} WHERE ${StoredFileEntityInformation.libraryIdColumnName} NOT IN ( SELECT id FROM ${LibraryEntityInformation.tableName})""" ) .fetch() } }, storedFileAccessExecutor) private fun getStoredFileTask(library: Library, serviceFile: ServiceFile): Promise<StoredFile?> = QueuedPromise(MessageWriter<StoredFile> { RepositoryAccessHelper(context).use { repositoryAccessHelper -> getStoredFile( library, repositoryAccessHelper, serviceFile ) } }, storedFileAccessExecutor) override val downloadingStoredFiles: Promise<List<StoredFile>> get() = QueuedPromise(MessageWriter { RepositoryAccessHelper(context).use { repositoryAccessHelper -> repositoryAccessHelper .mapSql( selectFromStoredFiles + " WHERE " + StoredFileEntityInformation.isDownloadCompleteColumnName + " = @" + StoredFileEntityInformation.isDownloadCompleteColumnName ) .addParameter(StoredFileEntityInformation.isDownloadCompleteColumnName, false) .fetch() } }, storedFileAccessExecutor) override fun markStoredFileAsDownloaded(storedFile: StoredFile): Promise<StoredFile> = QueuedPromise(MessageWriter { RepositoryAccessHelper(context).use { repositoryAccessHelper -> repositoryAccessHelper.beginTransaction().use { closeableTransaction -> repositoryAccessHelper .mapSql( " UPDATE " + StoredFileEntityInformation.tableName + " SET " + StoredFileEntityInformation.isDownloadCompleteColumnName + " = 1" + " WHERE id = @id" ) .addParameter("id", storedFile.id) .execute() closeableTransaction.setTransactionSuccessful() } } storedFile.setIsDownloadComplete(true) }, storedFileAccessExecutor) override fun addMediaFile(library: Library, serviceFile: ServiceFile, mediaFileId: Int, filePath: String): Promise<Unit> = QueuedPromise(MessageWriter { RepositoryAccessHelper(context).use { repositoryAccessHelper -> val storedFile = getStoredFile(library, repositoryAccessHelper, serviceFile) ?: run { createStoredFile(library, repositoryAccessHelper, serviceFile) getStoredFile(library, repositoryAccessHelper, serviceFile) ?.setIsOwner(false) ?.setIsDownloadComplete(true) ?.setPath(filePath) } storedFile?.storedMediaId = mediaFileId updateStoredFile(repositoryAccessHelper, storedFile) } }, storedFileAccessExecutor) private fun getStoredFile(library: Library, helper: RepositoryAccessHelper, serviceFile: ServiceFile): StoredFile? = helper .mapSql( " SELECT * " + " FROM " + StoredFileEntityInformation.tableName + " " + " WHERE " + StoredFileEntityInformation.serviceIdColumnName + " = @" + StoredFileEntityInformation.serviceIdColumnName + " AND " + StoredFileEntityInformation.libraryIdColumnName + " = @" + StoredFileEntityInformation.libraryIdColumnName ) .addParameter(StoredFileEntityInformation.serviceIdColumnName, serviceFile.key) .addParameter(StoredFileEntityInformation.libraryIdColumnName, library.id) .fetchFirst() private fun getStoredFile(helper: RepositoryAccessHelper, storedFileId: Int): StoredFile = helper .mapSql("SELECT * FROM " + StoredFileEntityInformation.tableName + " WHERE id = @id") .addParameter("id", storedFileId) .fetchFirst() private fun createStoredFile(library: Library, repositoryAccessHelper: RepositoryAccessHelper, serviceFile: ServiceFile) = repositoryAccessHelper.beginTransaction().use { closeableTransaction -> repositoryAccessHelper .mapSql(insertSql) .addParameter(StoredFileEntityInformation.serviceIdColumnName, serviceFile.key) .addParameter(StoredFileEntityInformation.libraryIdColumnName, library.id) .addParameter(StoredFileEntityInformation.isOwnerColumnName, true) .execute() closeableTransaction.setTransactionSuccessful() } override fun deleteStoredFile(storedFile: StoredFile): Promise<Unit> = QueuedPromise(MessageWriter { RepositoryAccessHelper(context).use { repositoryAccessHelper -> try { repositoryAccessHelper.beginTransaction().use { closeableTransaction -> repositoryAccessHelper .mapSql("DELETE FROM " + StoredFileEntityInformation.tableName + " WHERE id = @id") .addParameter("id", storedFile.id) .execute() closeableTransaction.setTransactionSuccessful() } } catch (e: SQLException) { logger.error("There was an error deleting serviceFile " + storedFile.id, e) } } }, storedFileAccessExecutor) companion object { private val logger by lazy { LoggerFactory.getLogger(StoredFileAccess::class.java) } private const val selectFromStoredFiles = "SELECT * FROM " + StoredFileEntityInformation.tableName private val insertSql by lazy { fromTable(StoredFileEntityInformation.tableName) .addColumn(StoredFileEntityInformation.serviceIdColumnName) .addColumn(StoredFileEntityInformation.libraryIdColumnName) .addColumn(StoredFileEntityInformation.isOwnerColumnName) .build() } private val updateSql by lazy { UpdateBuilder .fromTable(StoredFileEntityInformation.tableName) .addSetter(StoredFileEntityInformation.serviceIdColumnName) .addSetter(StoredFileEntityInformation.storedMediaIdColumnName) .addSetter(StoredFileEntityInformation.pathColumnName) .addSetter(StoredFileEntityInformation.isOwnerColumnName) .addSetter(StoredFileEntityInformation.isDownloadCompleteColumnName) .setFilter("WHERE id = @id") .buildQuery() } private fun updateStoredFile(repositoryAccessHelper: RepositoryAccessHelper, storedFile: StoredFile?) { if (storedFile == null) return repositoryAccessHelper.beginTransaction().use { closeableTransaction -> repositoryAccessHelper .mapSql(updateSql) .addParameter(StoredFileEntityInformation.serviceIdColumnName, storedFile.serviceId) .addParameter(StoredFileEntityInformation.storedMediaIdColumnName, storedFile.storedMediaId) .addParameter(StoredFileEntityInformation.pathColumnName, storedFile.path) .addParameter(StoredFileEntityInformation.isOwnerColumnName, storedFile.isOwner) .addParameter( StoredFileEntityInformation.isDownloadCompleteColumnName, storedFile.isDownloadComplete ) .addParameter("id", storedFile.id) .execute() closeableTransaction.setTransactionSuccessful() } } } }
lgpl-3.0
6f5314fd745a11cc49331a1ff0d8e8b0
42.147959
125
0.781838
4.732513
false
false
false
false
AoEiuV020/PaNovel
IronDB/src/main/java/cc/aoeiuv020/irondb/impl/DatabaseImpl.kt
1
3330
package cc.aoeiuv020.irondb.impl import cc.aoeiuv020.irondb.DataSerializer import cc.aoeiuv020.irondb.Database import cc.aoeiuv020.irondb.FileWrapper import cc.aoeiuv020.irondb.KeySerializer import java.io.File import java.io.IOException import java.lang.reflect.Type /** * Created by AoEiuV020 on 2018.05.27-16:11:58. */ internal class DatabaseImpl( private val base: File, private val subSerializer: KeySerializer, private val keySerializer: KeySerializer, private val dataSerializer: DataSerializer ) : Database { private val keyLocker = KeyLocker() init { base.exists() || base.mkdirs() || throw IOException("failed mkdirs ${base.path}") base.canWrite() || throw IOException("failed write ${base.path}") } override fun sub(table: String) = DatabaseImpl( base = base.resolve(table).canonicalFile, subSerializer = subSerializer, keySerializer = keySerializer, dataSerializer = dataSerializer ) override fun <T> write(key: String, value: T?, type: Type) { val serializedKey = keySerializer.serialize(key) // 以防万一,写入前确保文件夹存在, base.run { exists() || mkdirs() } val file = base.resolve(serializedKey) // 锁住key, keyLocker.runInAcquire(serializedKey) { if (value == null) { // 值空则删除对应文件, file.delete() } else { val data = dataSerializer.serialize(value, type) file.writeText(data) } } } override fun file(key: String): FileWrapper { val serializedKey = keySerializer.serialize(key) return FileWrapperImpl(serializedKey) } inner class FileWrapperImpl( private val serializedKey: String ) : FileWrapper { val file = base.resolve(serializedKey) override fun <T> use(block: (File) -> T): T { // 以防万一,写入前确保文件夹存在, base.run { exists() || mkdirs() } // 锁住key, return keyLocker.runInAcquire(serializedKey) { block(file) } } override fun delete(): Boolean { // 锁住key, return keyLocker.runInAcquire(serializedKey) { file.delete() } } } /** * @return key不存在则返回null, */ override fun <T> read(key: String, type: Type): T? { val serializedKey = keySerializer.serialize(key) val file = base.resolve(serializedKey) // 锁住key, return keyLocker.runInAcquire(serializedKey) { if (!file.exists()) { // 文件不存在直接返回null, null } else { val string = file.readText() dataSerializer.deserialize(string, type) } } } override fun drop() { // 要不要释放keyLocker, base.deleteRecursively() } /** * @return 返回用于判断指定key是否存在的集合,不可用于读出key, */ override fun keysContainer(): Collection<String> = KeysContainer(base, keySerializer) }
gpl-3.0
32a0b73c0175d81ce75fcfda483c3b76
27.862385
89
0.570248
4.161376
false
false
false
false
kar/challenges
recruitment-blinkist/app/src/main/java/gs/kar/rblinkist/MainActivity.kt
1
2631
package gs.kar.rblinkist import android.databinding.ObservableArrayList import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration 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 com.bumptech.glide.Glide import com.github.nitrico.lastadapter.LastAdapter import com.github.nitrico.lastadapter.Type import gs.kar.rblinkist.databinding.ItemBlinkBinding import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.channels.consumeEach import kotlinx.coroutines.experimental.launch import org.kodein.di.generic.instance class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) } class LibraryFragment : Fragment() { private val state: State<BlinkistState> by DI.instance() private val update: Update<Message, BlinkistState> by DI.instance() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_library, container, false) as RecyclerView view.layoutManager = LinearLayoutManager(context) return view } override fun onStart() { super.onStart() bind(view as RecyclerView) } private fun bind(view: RecyclerView) { view.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) val blinkType = Type<ItemBlinkBinding>(R.layout.item_blink) .onBind { val url = it.binding.item?.volumeInfo?.imageLinks?.default() if (url != null) Glide.with(view).load(url).into(it.binding.thumbnail) } launch { val observable = ObservableArrayList<Blink>() launch(UI) { LastAdapter(observable, BR.item).map<Blink>(blinkType).into(view) } val channel = state.subscribe() channel.consumeEach { blinkist -> launch(UI) { observable.appendFrom(blinkist.blinks) } } } } } }
apache-2.0
3fa8da6e301258c0fd2de0aecc23b463
36.056338
100
0.669327
4.801095
false
false
false
false
nemerosa/ontrack
ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/ui/CascUserMenuExtension.kt
1
919
package net.nemerosa.ontrack.extension.casc.ui import net.nemerosa.ontrack.extension.api.UserMenuExtension import net.nemerosa.ontrack.extension.casc.CascExtensionFeature import net.nemerosa.ontrack.extension.support.AbstractExtension import net.nemerosa.ontrack.model.security.GlobalFunction import net.nemerosa.ontrack.model.security.GlobalSettings import net.nemerosa.ontrack.model.support.Action import net.nemerosa.ontrack.model.support.ActionType import org.springframework.stereotype.Component @Component class CascUserMenuExtension( extensionFeature: CascExtensionFeature, ) : AbstractExtension(extensionFeature), UserMenuExtension { override fun getAction() = Action( id = "casc-control", name = "Configuration as Code", type = ActionType.LINK, uri = "casc-control" ) override fun getGlobalFunction(): Class<out GlobalFunction> = GlobalSettings::class.java }
mit
f83e4a1e16d825683461d26ed8f95d8b
35.8
92
0.792165
4.397129
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsTraitMethodImplLineMarkerProvider.kt
1
1618
package org.rust.ide.annotator import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder import com.intellij.psi.PsiElement import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsTraitItem import org.rust.lang.core.psi.ext.RsFunctionRole import org.rust.lang.core.psi.ext.role import org.rust.lang.core.psi.ext.superMethod import org.rust.lang.core.psi.ext.parentOfType import javax.swing.Icon /** * Annotates the implementation of a trait method with an icon on the gutter. */ class RsTraitMethodImplLineMarkerProvider : RelatedItemLineMarkerProvider() { override fun collectNavigationMarkers(el: PsiElement, result: MutableCollection<in RelatedItemLineMarkerInfo<PsiElement>>) { if (!(el is RsFunction && el.role == RsFunctionRole.IMPL_METHOD)) return val traitMethod = el.superMethod ?: return val trait = traitMethod.parentOfType<RsTraitItem>() ?: return val action: String val icon: Icon if (traitMethod.isAbstract) { action = "Implements" icon = RsIcons.IMPLEMENTING_METHOD } else { action = "Overrides" icon = RsIcons.OVERRIDING_METHOD } val builder = NavigationGutterIconBuilder .create(icon) .setTargets(listOf(traitMethod)) .setTooltipText("$action method in `${trait.name}`") result.add(builder.createLineMarkerInfo(el.fn)) } }
mit
fd8440fc26de780357dc5cc31ea43c92
36.627907
128
0.723115
4.384824
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/TranslationConstants.kt
1
841
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations object TranslationConstants { const val DEFAULT_LOCALE = "en_us" const val I18N_CLIENT_CLASS = "net.minecraft.client.resources.I18n" const val I18N_COMMON_CLASS = "net.minecraft.util.text.translation.I18n" const val CONSTRUCTOR = "<init>" const val TRANSLATION_COMPONENT_CLASS = "net.minecraft.util.text.TextComponentTranslation" const val COMMAND_EXCEPTION_CLASS = "net.minecraft.command.CommandException" const val FORMAT = "func_135052_a" const val TRANSLATE_TO_LOCAL = "func_74838_a" const val TRANSLATE_TO_LOCAL_FORMATTED = "func_74837_a" const val SET_BLOCK_NAME = "func_149663_c" const val SET_ITEM_NAME = "func_77655_b" }
mit
d476d671f338742fc87df237a49206de
32.64
94
0.717004
3.391129
false
false
false
false
samtstern/quickstart-android
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RatingDialogFragment.kt
1
2195
package com.google.firebase.example.fireeats.kotlin import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.google.firebase.auth.ktx.auth import com.google.firebase.example.fireeats.databinding.DialogRatingBinding import com.google.firebase.example.fireeats.kotlin.model.Rating import com.google.firebase.ktx.Firebase /** * Dialog Fragment containing rating form. */ class RatingDialogFragment : DialogFragment() { private var _binding: DialogRatingBinding? = null private val binding get() = _binding!! private var ratingListener: RatingListener? = null internal interface RatingListener { fun onRating(rating: Rating) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = DialogRatingBinding.inflate(inflater, container, false) binding.restaurantFormButton.setOnClickListener { onSubmitClicked() } binding.restaurantFormCancel.setOnClickListener { onCancelClicked() } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onAttach(context: Context) { super.onAttach(context) if (context is RatingListener) { ratingListener = context } } override fun onResume() { super.onResume() dialog?.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun onSubmitClicked() { val user = Firebase.auth.currentUser user?.let { val rating = Rating( it, binding.restaurantFormRating.rating.toDouble(), binding.restaurantFormText.text.toString()) ratingListener?.onRating(rating) } dismiss() } private fun onCancelClicked() { dismiss() } companion object { const val TAG = "RatingDialog" } }
apache-2.0
6824f794dfd451d14853b71b9a220f99
25.445783
77
0.661048
4.921525
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonTest/kotlin/com/dragonbones/parser/DataParserTest.kt
1
818
package com.dragonbones.parser import com.soywiz.korge.dragonbones.* import com.soywiz.korio.async.* import com.soywiz.korio.file.std.* import doIOTest import kotlin.test.* class DataParserTest { @Test fun testReadingJson() = suspendTest({ doIOTest }) { //val data = BinaryDataParser().parseDragonBonesDataJson(resourcesVfs["Dragon/Dragon_ske.json"].readString()) val json = resourcesVfs["Dragon/Dragon_ske.json"].readString() val data = DataParser.parseDragonBonesDataJson(json)!! assertEquals(listOf("Dragon"), data.armatureNames) //println(data) } @Test fun testReadingBinary() = suspendTest({ doIOTest }) { val data = resourcesVfs["Dragon/Dragon_ske.dbbin"].readDbSkeleton(KorgeDbFactory()) assertEquals(listOf("Dragon"), data.armatureNames) //println(data) } }
apache-2.0
b2641dcc9d6184188344a7ee879712d3
31.72
111
0.727384
3.619469
false
true
false
false
AlexLandau/semlang
kotlin/semlang-module-repository/src/main/kotlin/parseDir.kt
1
11845
package net.semlang.modules import net.semlang.api.* import net.semlang.api.parser.Issue import net.semlang.api.parser.IssueLevel import net.semlang.parser.* import net.semlang.refill.* import net.semlang.sem2.translate.collectTypesSummary import net.semlang.sem2.translate.translateSem2ContextToSem1 import net.semlang.validator.* import java.io.File import java.lang.UnsupportedOperationException sealed class ModuleDirectoryParsingResult { // TODO: We may want to go one step further and also include type information in here for the validator to use // (Counterpoint: If a dialect misreports its types, the validation may be inaccurate if that info is reused) data class Success(val module: UnvalidatedModule): ModuleDirectoryParsingResult() data class Failure(val errors: List<Issue>, val warnings: List<Issue>): ModuleDirectoryParsingResult() } enum class Dialect(val extensions: Set<String>, val needsTypeInfoToParse: Boolean) { Sem1(setOf("sem"), false) { override fun parseWithoutTypeInfo(file: File): ParsingResult { return net.semlang.parser.parseFile(file) } private fun toIR(result: ParsingResult): IR { return IR(result) } private fun fromIR(ir: IR): ParsingResult { return ir.value as ParsingResult } override fun parseToIR(documentUri: String, text: String): IR { return toIR(net.semlang.parser.parseString(text, documentUri)) } override fun getTypesSummary(ir: IR, moduleName: ModuleName, upstreamModules: List<ValidatedModule>): TypesSummary { val parsingResult = fromIR(ir) val context = when (parsingResult) { is ParsingResult.Success -> parsingResult.context is ParsingResult.Failure -> parsingResult.partialContext } return getTypesSummary(context, {}) } override fun parseWithTypeInfo(ir: IR, allTypesSummary: TypesInfo, typesMetadata: TypesMetadata): ParsingResult { return fromIR(ir) } }, Sem2(setOf("sem2"), true) { override fun parseWithoutTypeInfo(file: File): ParsingResult { throw UnsupportedOperationException() } override fun parseToIR(documentUri: String, text: String): IR { return toIR(net.semlang.sem2.parser.parseString(text, documentUri)) } private fun toIR(parsingResult: net.semlang.sem2.parser.ParsingResult): IR { return IR(parsingResult) } private fun fromIR(ir: IR): net.semlang.sem2.parser.ParsingResult { return ir.value as net.semlang.sem2.parser.ParsingResult } override fun getTypesSummary(ir: IR, moduleName: ModuleName, upstreamModules: List<ValidatedModule>): TypesSummary { val parsingResult = fromIR(ir) val context = when (parsingResult) { is net.semlang.sem2.parser.ParsingResult.Success -> parsingResult.context is net.semlang.sem2.parser.ParsingResult.Failure -> parsingResult.partialContext } return collectTypesSummary(context) } override fun parseWithTypeInfo(ir: IR, allTypesSummary: TypesInfo, typesMetadata: TypesMetadata): ParsingResult { val sem2Result = fromIR(ir) return when (sem2Result) { is net.semlang.sem2.parser.ParsingResult.Success -> { translateSem2ContextToSem1(sem2Result.context, allTypesSummary, typesMetadata) } is net.semlang.sem2.parser.ParsingResult.Failure -> { val sem2PartialTranslation = translateSem2ContextToSem1(sem2Result.partialContext, allTypesSummary, typesMetadata) when (sem2PartialTranslation) { is ParsingResult.Success -> ParsingResult.Failure( sem2Result.errors, sem2PartialTranslation.context ) is ParsingResult.Failure -> ParsingResult.Failure( sem2Result.errors + sem2PartialTranslation.errors, sem2PartialTranslation.partialContext ) } } } } }, ; // Single-pass parsing API abstract fun parseWithoutTypeInfo(file: File): ParsingResult // Two-pass parsing API (IR type should be a single type per dialect) abstract fun parseToIR(documentUri: String, text: String): IR abstract fun getTypesSummary(ir: IR, moduleName: ModuleName, upstreamModules: List<ValidatedModule>): TypesSummary abstract fun parseWithTypeInfo(ir: IR, allTypesSummary: TypesInfo, typesMetadata: TypesMetadata): ParsingResult /** * An intermediate representation used by the dialect to prevent needing to parse a file multiple times. */ data class IR(val value: Any) } fun parseModuleDirectory(directory: File, repository: ModuleRepository): ModuleDirectoryParsingResult { return parseModuleDirectoryUsingTrickle(directory, repository) // val configFile = File(directory, "module.conf") // val parsedConfig = parseConfigFile(configFile) // return when (parsedConfig) { // is ModuleInfoParsingResult.Failure -> { // val error = Issue("Couldn't parse module.conf: ${parsedConfig.error.message}", null, IssueLevel.ERROR) // ModuleDirectoryParsingResult.Failure(listOf(error), listOf()) // } // is ModuleInfoParsingResult.Success -> { // val moduleName = parsedConfig.info.name // val upstreamModules = listOf<ValidatedModule>() // TODO: Support dependencies // // // TODO: Generalize to support "external" dialects // val allFiles = directory.listFiles() // val filesByDialect = sortByDialect(allFiles) // // val combinedParsingResult = if (filesByDialect.keys.any { it.needsTypeInfoToParse }) { // // Collect type info in one pass, then parse in a second pass // collectParsingResultsTwoPasses(filesByDialect, moduleName, upstreamModules) // } else { // // Parse everything in one pass // collectParsingResultsSinglePass(filesByDialect) // } // // when (combinedParsingResult) { // is ParsingResult.Success -> { // ModuleDirectoryParsingResult.Success(UnvalidatedModule(parsedConfig.info, combinedParsingResult.context)) // } // is ParsingResult.Failure -> { // ModuleDirectoryParsingResult.Failure(combinedParsingResult.errors, listOf()) // } // } // } // } } //fun collectParsingResultsTwoPasses(filesByDialect: Map<Dialect, List<File>>, moduleName: ModuleName, upstreamModules: List<ValidatedModule>): ParsingResult { // val typesSummaries = ArrayList<TypesSummary>() // val irs = HashMap<File, Dialect.IR>() // for ((dialect, files) in filesByDialect.entries) { // for (file in files) { // try { // val ir = dialect.parseToIR(file.absolutePath, file.readText()) // irs[file] = ir // typesSummaries.add(dialect.getTypesSummary(ir, moduleName, upstreamModules)) // } catch (e: RuntimeException) { // throw RuntimeException("Error collecting types summary from file $file", e) // } // } // } // // val allTypesSummary = combineTypesSummaries(typesSummaries) // // TODO: Actually support upstream modules // val moduleId = ModuleUniqueId(moduleName, "") // val moduleVersionMappings = mapOf<ModuleNonUniqueId, ModuleUniqueId>() // val recordIssue: (Issue) -> Unit = {} // TODO: Handle error case with conflicts across files // val allTypesInfo = getTypesInfoFromSummary(allTypesSummary, moduleId, upstreamModules, moduleVersionMappings, recordIssue) // // val parsingResults = ArrayList<ParsingResult>() // for ((dialect, files) in filesByDialect.entries) { // for (file in files) { // try { // parsingResults.add(dialect.parseWithTypeInfo(irs[file]!!, allTypesInfo)) // } catch (e: RuntimeException) { // throw RuntimeException("Error parsing file $file", e) // } // // } // } // return combineParsingResults(parsingResults) //} //fun collectParsingResultsSinglePass(filesByDialect: Map<Dialect, List<File>>): ParsingResult { // val parsingResults = ArrayList<ParsingResult>() // for ((dialect, files) in filesByDialect.entries) { // for (file in files) { // try { // parsingResults.add(dialect.parseWithoutTypeInfo(file)) // } catch (e: RuntimeException) { // throw RuntimeException("Error parsing file $file", e) // } // } // } // return combineParsingResults(parsingResults) //} //fun sortByDialect(allFiles: Array<out File>): Map<Dialect, List<File>> { // val results = HashMap<Dialect, MutableList<File>>() // for (file in allFiles) { // for (dialect in Dialect.values()) { // if (dialect.extensions.contains(file.extension)) { // if (!results.containsKey(dialect)) { // results[dialect] = ArrayList() // } // results[dialect]!!.add(file) // } // } // } // return results //} fun parseAndValidateModuleDirectory(directory: File, nativeModuleVersion: String, repository: ModuleRepository): ValidationResult { val dirParseResult = parseModuleDirectory(directory, repository) return when (dirParseResult) { is ModuleDirectoryParsingResult.Success -> { val module = dirParseResult.module val dependencies = module.info.dependencies.map { dependencyId -> val uniqueId = repository.getModuleUniqueId(dependencyId, directory) repository.loadModule(uniqueId) } validateModule(module.contents, module.info.name, nativeModuleVersion, dependencies) } is ModuleDirectoryParsingResult.Failure -> { ValidationResult.Failure(dirParseResult.errors, dirParseResult.warnings) } } } fun parseModuleDirectoryUsingTrickle(directory: File, repository: ModuleRepository): ModuleDirectoryParsingResult { val configFile = File(directory, "module.conf") val definition = getFilesParsingDefinition(directory, repository) val instance = definition.instantiateSync() instance.setInput(CONFIG_TEXT, configFile.readText()) for (file in directory.listFiles()) { if (file.name != "module.conf") { instance.setInputs( listOf( // TODO: AddKey constructor would be nice here, or some kind of builder construct TrickleInputChange.EditKeys(SOURCE_FILE_URLS, listOf(file.absolutePath), listOf()), // TODO: Ditto for a singleton set-keyed constructor TrickleInputChange.SetKeyed(SOURCE_TEXTS, mapOf(file.absolutePath to file.readText())) ) ) } } // TODO: Also handle the case where we get an error in config parsing return instance.getValue(MODULE_PARSING_RESULT) } // TODO: Support other dialects, probably by making dialect determination another asynchronous step in the process // TODO: This maybe shouldn't be public long-term fun determineDialect(filePath: String): Dialect? { if (filePath.endsWith(".sem") || filePath.endsWith(".sem1")) { return Dialect.Sem1 } if (filePath.endsWith(".sem2")) { return Dialect.Sem2 } return null }
apache-2.0
3d8332262ef03dff148a44b29a7ca2b0
42.712177
159
0.640523
4.632382
false
false
false
false
stripe/stripe-android
payments-model/src/main/java/com/stripe/android/model/CardBrand.kt
1
7906
package com.stripe.android.model import androidx.annotation.DrawableRes import androidx.annotation.RestrictTo import com.stripe.android.cards.CardNumber import com.stripe.payments.model.R import java.util.regex.Pattern /** * A representation of supported card brands and related data */ @Suppress("LongParameterList", "MaxLineLength") enum class CardBrand( val code: String, val displayName: String, @DrawableRes val icon: Int, @DrawableRes val cvcIcon: Int = R.drawable.stripe_ic_cvc, @DrawableRes val errorIcon: Int = R.drawable.stripe_ic_error, /** * Accepted CVC lengths */ val cvcLength: Set<Int> = setOf(3), /** * The default max length when the card number is formatted without spaces (e.g. "4242424242424242") * * Note that [CardBrand.DinersClub]'s max length depends on the BIN (e.g. card number prefix). * In the case of a [CardBrand.DinersClub] card, use [getMaxLengthForCardNumber]. */ private val defaultMaxLength: Int = 16, /** * Based on [Issuer identification number table](http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29) */ private val pattern: Pattern? = null, /** * Patterns for discrete lengths */ private val partialPatterns: Map<Int, Pattern>, /** * By default, a [CardBrand] does not have variants. */ private val variantMaxLength: Map<Pattern, Int> = emptyMap(), /** * The rendering order in the card details cell */ private val renderingOrder: Int ) { Visa( "visa", "Visa", R.drawable.stripe_ic_visa, pattern = Pattern.compile("^(4)[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^4$") ), renderingOrder = 1 ), MasterCard( "mastercard", "Mastercard", R.drawable.stripe_ic_mastercard, pattern = Pattern.compile( "^(2221|2222|2223|2224|2225|2226|2227|2228|2229|222|223|224|225|226|" + "227|228|229|23|24|25|26|270|271|2720|50|51|52|53|54|55|56|57|58|59|67)[0-9]*$" ), partialPatterns = mapOf( 1 to Pattern.compile("^2|5|6$"), 2 to Pattern.compile("^(22|23|24|25|26|27|50|51|52|53|54|55|56|57|58|59|67)$") ), renderingOrder = 2 ), AmericanExpress( "amex", "American Express", R.drawable.stripe_ic_amex, cvcIcon = R.drawable.stripe_ic_cvc_amex, cvcLength = setOf(3, 4), defaultMaxLength = 15, pattern = Pattern.compile("^(34|37)[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^3$") ), renderingOrder = 3 ), Discover( "discover", "Discover", R.drawable.stripe_ic_discover, pattern = Pattern.compile("^(60|64|65)[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^6$") ), renderingOrder = 4 ), /** * JCB * * BIN range: 352800 to 358999 */ JCB( "jcb", "JCB", R.drawable.stripe_ic_jcb, pattern = Pattern.compile("^(352[89]|35[3-8][0-9])[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^3$"), 2 to Pattern.compile("^(35)$"), 3 to Pattern.compile("^(35[2-8])$") ), renderingOrder = 5 ), /** * Diners Club * * 14-digits: BINs starting with 36 * 16-digits: BINs starting with 30, 38, 39 */ DinersClub( "diners", "Diners Club", R.drawable.stripe_ic_diners, defaultMaxLength = 16, pattern = Pattern.compile("^(36|30|38|39)[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^3$") ), variantMaxLength = mapOf( Pattern.compile("^(36)[0-9]*$") to 14 ), renderingOrder = 6 ), UnionPay( "unionpay", "UnionPay", R.drawable.stripe_ic_unionpay, pattern = Pattern.compile("^(62|81)[0-9]*$"), partialPatterns = mapOf( 1 to Pattern.compile("^6|8$") ), renderingOrder = 7 ), Unknown( "unknown", "Unknown", R.drawable.stripe_ic_unknown, cvcLength = setOf(3, 4), partialPatterns = emptyMap(), renderingOrder = -1 ); val maxCvcLength: Int get() { return cvcLength.maxOrNull() ?: CVC_COMMON_LENGTH } /** * Checks to see whether the input number is of the correct length, given the assumed brand of * the card. This function does not perform a Luhn check. * * @param cardNumber the card number with no spaces or dashes * @return `true` if the card number is the correct length for the assumed brand */ fun isValidCardNumberLength(cardNumber: String?): Boolean { return cardNumber != null && Unknown != this && cardNumber.length == getMaxLengthForCardNumber(cardNumber) } fun isValidCvc(cvc: String): Boolean { return cvcLength.contains(cvc.length) } fun isMaxCvc(cvcText: String?): Boolean { val cvcLength = cvcText?.trim()?.length ?: 0 return maxCvcLength == cvcLength } /** * If the [CardBrand] has variants, and the [cardNumber] starts with one of the variant * prefixes, return the length for that variant. Otherwise, return [defaultMaxLength]. * * Note: currently only [CardBrand.DinersClub] has variants */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun getMaxLengthForCardNumber(cardNumber: String): Int { val normalizedCardNumber = CardNumber.Unvalidated(cardNumber).normalized return variantMaxLength.entries.firstOrNull { (pattern, _) -> pattern.matcher(normalizedCardNumber).matches() }?.value ?: defaultMaxLength } private fun getPatternForLength(cardNumber: String): Pattern? { return partialPatterns[cardNumber.length] ?: pattern } companion object { /** * @param cardNumber a card number * @return the [CardBrand] that matches the [cardNumber]'s prefix, if one is found; * otherwise, [CardBrand.Unknown] */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun fromCardNumber(cardNumber: String?): CardBrand { if (cardNumber.isNullOrBlank()) { return Unknown } // Only return a card brand if we know exactly which one, if there is more than // one possibility return unknown return ( getMatchingCards(cardNumber).takeIf { it.size == 1 } ?: listOf(Unknown) ).first() } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun getCardBrands(cardNumber: String?): List<CardBrand> { if (cardNumber.isNullOrBlank()) { return orderedBrands } return getMatchingCards(cardNumber).takeIf { it.isNotEmpty() } ?: listOf(Unknown) } private fun getMatchingCards(cardNumber: String) = values().filter { cardBrand -> cardBrand.getPatternForLength(cardNumber)?.matcher(cardNumber) ?.matches() == true } /** * @param code a brand code, such as `Visa` or `American Express`. * See [PaymentMethod.Card.brand]. */ fun fromCode(code: String?): CardBrand { return values().firstOrNull { it.code.equals(code, ignoreCase = true) } ?: Unknown } val orderedBrands = values() .toList() .filter { it.renderingOrder > 0 } .sortedBy { it.renderingOrder } private const val CVC_COMMON_LENGTH: Int = 3 } }
mit
833f7c843efa4a06e17fdb29d914e6b9
29.525097
138
0.575765
4.154493
false
false
false
false
TeamWizardry/LibrarianLib
testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/content/TestEntity.kt
1
4714
package com.teamwizardry.librarianlib.testcore.content import com.teamwizardry.librarianlib.testcore.TestModContentManager import com.teamwizardry.librarianlib.testcore.TestModResourceManager import com.teamwizardry.librarianlib.testcore.bridge.TestCoreEntityTypes import com.teamwizardry.librarianlib.testcore.content.impl.TestEntityImpl import com.teamwizardry.librarianlib.testcore.content.impl.TestEntityRenderer import com.teamwizardry.librarianlib.testcore.util.PlayerTestContext import com.teamwizardry.librarianlib.testcore.util.SidedAction import com.teamwizardry.librarianlib.testcore.util.TestContext import net.fabricmc.fabric.api.`object`.builder.v1.entity.FabricEntityTypeBuilder import net.fabricmc.fabric.api.client.rendereregistry.v1.EntityRendererRegistry import net.minecraft.entity.Entity import net.minecraft.entity.EntityDimensions import net.minecraft.entity.EntityType import net.minecraft.entity.SpawnGroup import net.minecraft.entity.damage.DamageSource import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.ItemStack import net.minecraft.util.Hand import net.minecraft.util.Identifier import net.minecraft.util.math.Vec3d import net.minecraft.util.registry.Registry import net.minecraft.world.World public class TestEntity(manager: TestModContentManager, id: Identifier) : TestConfig(manager, id) { public val type: EntityType<TestEntityImpl> by lazy { FabricEntityTypeBuilder.create<TestEntityImpl>(SpawnGroup.MISC) .entityFactory<TestEntityImpl> { type, world -> TestEntityImpl(this, type, world) } .dimensions(EntityDimensions.fixed(0.5f, 0.5f)) .build() } public val spawnerItem: TestItem = manager.create(id.path + "_spawner") { rightClick.server { spawn(player) } } override var name: String get() = super.name set(value) { super.name = value spawnerItem.name = value } override var description: String? get() = super.description set(value) { super.description = value spawnerItem.description = value } public val lookLength: Double = 1.0 /** * Designed to be modified at runtime. When true, all entities using this config will have the "glowing" effect * applied. */ public var enableGlow: Boolean = false /** * Called when the player right-clicks this entity * * @see Entity.applyPlayerInteraction */ public val rightClick: SidedAction<RightClickContext> = SidedAction() /** * Called every tick * * @see Entity.tick */ public val tick: SidedAction<TickContext> = SidedAction() /** * Called when the entity is hit. Set [HitContext.kill] to false if the entity should not be killed. * * @see Entity.handleAttack */ public val hit: SidedAction<HitContext> = SidedAction() public data class RightClickContext( val target: TestEntityImpl, val player: PlayerEntity, val hand: Hand, val hitPos: Vec3d ) : PlayerTestContext(player) { val world: World = target.world val stack: ItemStack = player.getStackInHand(hand) } public data class TickContext(val target: TestEntityImpl) : TestContext() { val world: World = target.world } public data class HitContext(val target: TestEntityImpl, val actor: Entity, var kill: Boolean) : TestContext() { val world: World = target.world } public data class AttackContext(val target: TestEntityImpl, val source: DamageSource, var amount: Float) : TestContext() { val world: World = target.world } /** * Spawns this entity with the same eye position and look vector as the passed player. Only call this on the logical * server. */ public fun spawn(player: PlayerEntity) { val eye = player.getCameraPosVec(0f) val entity = TestEntityImpl(this, type, player.world) entity.setPos(eye.x, eye.y - entity.eyeY, eye.z) entity.pitch = player.pitch entity.yaw = player.yaw player.world.spawnEntity(entity) } override fun registerCommon(resources: TestModResourceManager) { Registry.register(Registry.ENTITY_TYPE, this.id, this.type) TestCoreEntityTypes.types.add(this.type) } override fun registerClient(resources: TestModResourceManager) { EntityRendererRegistry.INSTANCE.register(this.type) { dispatcher -> TestEntityRenderer(dispatcher) } resources.lang .entity(id, name) .item(spawnerItem.id, name) } }
lgpl-3.0
d5b57bbf6af7fb1e2f1ef06a12563156
33.408759
120
0.694103
4.305023
false
true
false
false
Undin/intellij-rust
debugger/src/main/kotlin/org/rust/debugger/RsBackendConsoleInjectionHelper.kt
3
2447
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.Document import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebugSessionListener import com.jetbrains.cidr.execution.debugger.BackendConsoleInjectionHelper import com.jetbrains.cidr.execution.debugger.CidrDebugProcess import com.jetbrains.cidr.execution.debugger.backend.lang.GDBExpressionPlaceholder import org.rust.lang.RsDebugInjectionListener import org.rust.lang.core.psi.ext.ancestorOrSelf import org.rust.openapiext.virtualFile class RsBackendConsoleInjectionHelper : BackendConsoleInjectionHelper { override fun subscribeToInjection(session: XDebugSession) { val connection = session.project.messageBus.connect() val listener = object : RsDebugInjectionListener, XDebugSessionListener { @Volatile private var document: Document? = null override fun evalDebugContext(host: PsiLanguageInjectionHost, context: RsDebugInjectionListener.DebugContext) { val document = host.originalDocument ?: return val process = document.getUserData(CidrDebugProcess.DEBUG_PROCESS_KEY) ?: return context.element = process.debuggerContext?.ancestorOrSelf() } override fun didInject(host: PsiLanguageInjectionHost) { if (host is GDBExpressionPlaceholder) { this.document = host.originalDocument } } override fun stackFrameChanged() { val file = document?.virtualFile ?: return invokeLater(ModalityState.NON_MODAL) { PsiDocumentManager.getInstance(session.project).reparseFiles(setOf(file), true) } } override fun sessionStopped() { connection.disconnect() } } connection.subscribe(RsDebugInjectionListener.INJECTION_TOPIC, listener) session.addSessionListener(listener) } private val PsiLanguageInjectionHost.originalDocument: Document? get() = containingFile.originalFile.viewProvider.document }
mit
a35760e86c98003baffe840f77acf8fc
39.783333
123
0.711892
5.228632
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/lints/RsDoubleMustUseInspectionTest.kt
2
2048
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import org.rust.ide.inspections.RsInspectionsTestBase class RsDoubleMustUseInspectionTest : RsInspectionsTestBase(RsDoubleMustUseInspection::class) { fun `test double must_use with outer attr`() = checkFixByText("Remove `#[must_use]` from the function", """ #[must_use] struct S; <weak_warning descr="This function has a `#[must_use]` attribute, but returns a type already marked as `#[must_use]`">/*caret*/#[must_use]</weak_warning> fn foo() -> S { S } fn main() {} """, """ #[must_use] struct S; fn foo() -> S { S } fn main() {} """) fun `test double must_use with inner attr`() = checkFixByText("Remove `#[must_use]` from the function", """ #[must_use] struct S; fn foo() -> S { <weak_warning descr="This function has a `#[must_use]` attribute, but returns a type already marked as `#[must_use]`">/*caret*/#![must_use]</weak_warning> S } fn main() {} """, """ #[must_use] struct S; fn foo() -> S { S } fn main() {} """) fun `test double must_use with normalizable associated type`() = checkFixByText("Remove `#[must_use]` from the function", """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } #[must_use] struct S; <weak_warning descr="This function has a `#[must_use]` attribute, but returns a type already marked as `#[must_use]`">/*caret*/#[must_use]</weak_warning> fn foo() -> <Struct as Trait>::Item { S } fn main() {} """, """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } #[must_use] struct S; fn foo() -> <Struct as Trait>::Item { S } fn main() {} """) }
mit
239a9fb27885f1e960d970188ef0b058
27.054795
166
0.543945
3.953668
false
true
false
false
ioc1778/incubator
incubator-quant/src/main/java/com/riaektiv/quant/options/PlainLeastSquaresMonteCarloModel.kt
2
6700
package com.riaektiv.quant.options import org.apache.commons.math3.fitting.leastsquares.LeastSquaresBuilder import org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer import org.apache.commons.math3.fitting.leastsquares.MultivariateJacobianFunction import org.apache.commons.math3.linear.Array2DRowRealMatrix import org.apache.commons.math3.linear.ArrayRealVector import org.apache.commons.math3.util.Pair import java.util.* /** * Coding With Passion Since 1991 * Created: 9/24/2016, 6:52 PM Eastern Time * @author Sergey Chuykov */ class PlainLeastSquaresMonteCarloModel { // John C. Hull // Options, Futures and Other Derivatives, 9th edition // page 646-649 class Node(val stockPrice: Double, var value: Double = 0.0, var valueThreshold: Double = 0.0) { override fun toString(): String { return "{$stockPrice}" } fun cashflow(): Double { return if (value > valueThreshold) value else 0.0 } } private var nodes = newArray(0, 0) fun newArray(samples: Int, steps: Int): Array<Array<Node?>?> { val path = arrayOfNulls<Array<Node?>?>(samples) for (sample in 0..samples - 1) { path[sample] = arrayOfNulls<Node?>(steps) } return path } fun buildPaths(samples: Int, steps: Int, stockPrice: Double, mu: Double, sigma: Double) { nodes = newArray(samples, steps) val gbm = GeometricBrownianMotion(stockPrice, mu, sigma) val dT = 1.0 / 365.0 // 1 day for (sample in 0..samples - 1) { for (step in 0..steps - 1) { val t = step * dT val price = gbm.calculate(t) nodes[sample]!![step] = Node(price) } } } fun payoff(stockPrice: Double, putOrCall: Int, strike: Double): Double { return Math.max(0.0, if (putOrCall == Option.CALL) stockPrice - strike else strike - stockPrice) } fun payoff(stockPrice: Double, option: Option): Double { return payoff(stockPrice, option.putOrCall, option.strike) } fun inTheMoney(stockPrice: Double, option: Option): Boolean { return if (option.putOrCall == Option.CALL) (stockPrice > option.strike) else (option.strike > stockPrice) } fun optimize(observations: DoubleArray, target: DoubleArray): DoubleArray { val model = MultivariateJacobianFunction { params -> val a = params.getEntry(0) val b = params.getEntry(1) val c = params.getEntry(2) val value = ArrayRealVector(observations.size) val jacobian = Array2DRowRealMatrix(observations.size, 3) for (i in observations.indices) { val S = observations[i] val modelI = a + b * S + c * S * S // a+b*S+c*S^2 value.setEntry(i, modelI) // (d)/(da)(a+b S+c S^2) = 1 jacobian.setEntry(i, 0, 1.0) // (d)/(db)(a+b S+c S^2) = S jacobian.setEntry(i, 1, S) // (d)/(dc)(a+b S+c S^2) = S^2 jacobian.setEntry(i, 2, S * S) } Pair(value, jacobian) } val problem = LeastSquaresBuilder() .start(doubleArrayOf(1.0, 1.0, 1.0)) .model(model) .target(target) .lazyEvaluation(false) .maxEvaluations(1000) .maxIterations(1000) .build() val optimum = LevenbergMarquardtOptimizer().optimize(problem) val a = optimum.point.getEntry(0) val b = optimum.point.getEntry(1) val c = optimum.point.getEntry(2) return doubleArrayOf(a, b, c) } fun calculateValuesAtExpiration(option: Option, nodes: Array<Array<Node?>?>) { val step = nodes[0]!!.size - 1 val size = nodes.size for (path in 0..size - 1) { val node = nodes[path]!![step]!! node.value = payoff(node.stockPrice, option) } } fun evaluate(option: Option, rate: Double, step: Int, nodes: Array<Array<Node?>?>): DoubleArray { val discount = Math.exp(-rate) val size = nodes.size val paths = ArrayList<Int>(size) for (path in 0..size - 1) { val node = nodes[path]!![step] if (node != null) { if (inTheMoney(node.stockPrice, option)) { paths.add(path) } } } val observations = ArrayList<Double>(paths.size) val target = ArrayList<Double>(paths.size) for (path in paths) { val node = nodes[path]!![step]!! observations.add(node.stockPrice) val next = nodes[path]!![step + 1]!! val cashflow = next.cashflow() target.add(if (cashflow > 0.0) cashflow * discount else 0.0) } val abc = optimize(observations.toDoubleArray(), target.toDoubleArray()) for (path in paths) { val node = nodes[path]!![step] if (node != null) { node.valueThreshold = abc[0] + abc[1] * node.stockPrice + abc[2] * node.stockPrice * node.stockPrice node.value = payoff(node.stockPrice, option) } } return abc } fun calculateValue(option: Option, rate: Double, nodes: Array<Array<Node?>?>): Double { var value = 0.0 val lastIdx = nodes[0]!!.size - 1 for (path in 0..nodes.size - 1) { val last = nodes[path]!![lastIdx]!! last.value = payoff(last.stockPrice, option) for (step in 0..lastIdx) { val node = nodes[path]!![step]!! val cashflow = node.cashflow() //print(String.format("%8.3f ", cashflow)) if (cashflow > 0.0) { value += cashflow * Math.exp(-rate * step) break } } //println() } return value / nodes.size } fun calculate(option: Option, rate: Double, nodes: Array<Array<Node?>?>): Double { calculateValuesAtExpiration(option, nodes) var step = nodes[0]!!.size - 2 while (step > 0) { evaluate(option, rate, step, nodes) step-- } return calculateValue(option, rate, nodes) } fun calculate(samples: Int, steps: Int, option: Option, rate: Double, stockPrice: Double, mu: Double, sigma: Double): Double { buildPaths(samples, steps, stockPrice, mu, sigma); return calculate(option, rate, nodes) } }
bsd-3-clause
e613765bd140a87415e059eb2a2f96cf
31.371981
130
0.555075
3.866128
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/posting/AddMessagePresenter.kt
1
5892
package com.sedsoftware.yaptalker.presentation.feature.posting import com.arellomobile.mvp.InjectViewState import com.sedsoftware.yaptalker.data.system.SchedulersProvider import com.sedsoftware.yaptalker.domain.interactor.EmojiInteractor import com.sedsoftware.yaptalker.presentation.base.BasePresenter import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.PresenterLifecycle import com.sedsoftware.yaptalker.presentation.base.enums.navigation.RequestCode import com.sedsoftware.yaptalker.presentation.feature.posting.adapter.EmojiClickListener import com.sedsoftware.yaptalker.presentation.feature.posting.tags.MessageTagCodes import com.sedsoftware.yaptalker.presentation.feature.posting.tags.MessageTagCodes.Tag import com.sedsoftware.yaptalker.presentation.feature.posting.tags.MessageTags import com.sedsoftware.yaptalker.presentation.mapper.EmojiModelMapper import com.sedsoftware.yaptalker.presentation.model.base.EmojiModel import com.uber.autodispose.kotlin.autoDisposable import io.reactivex.observers.DisposableObserver import ru.terrakok.cicerone.Router import timber.log.Timber import java.util.Locale import javax.inject.Inject @InjectViewState class AddMessagePresenter @Inject constructor( private val router: Router, private val emojiInteractor: EmojiInteractor, private val emojiMapper: EmojiModelMapper, private val schedulers: SchedulersProvider ) : BasePresenter<AddMessageView>(), EmojiClickListener { private var clearCurrentList = false private var isBOpened = false private var isIOpened = false private var isUOpened = false override fun onFirstViewAttach() { super.onFirstViewAttach() loadEmojiList() } override fun attachView(view: AddMessageView?) { super.attachView(view) viewState.updateCurrentUiState() } override fun detachView(view: AddMessageView?) { viewState.hideKeyboard() super.detachView(view) } override fun onEmojiClicked(code: String) { viewState.insertTag(" $code ") } fun insertChosenTag(selectionStart: Int, selectionEnd: Int, @Tag tag: Long) { when { tag == MessageTagCodes.TAG_LINK -> onLinkTagClicked() tag == MessageTagCodes.TAG_VIDEO -> onVideoLinkTagClicked() selectionStart != selectionEnd -> onTagClickedWithSelection(tag) else -> onTagClickedWithNoSelection(tag) } } fun insertLinkTag(url: String, title: String) { val result = String.format(Locale.getDefault(), MessageTags.LINK_BLOCK, url, title) viewState.insertTag(result) } fun insertVideoTag(url: String) { val result = String.format(Locale.getDefault(), MessageTags.VIDEO_BLOCK, url) viewState.insertTag(result) } fun sendMessageTextBackToView(message: String, isEdited: Boolean, chosenImagePath: String) { if (isEdited) { router.exitWithResult(RequestCode.EDITED_MESSAGE_TEXT, message) } else { router.exitWithResult(RequestCode.MESSAGE_TEXT, Pair(message, chosenImagePath)) } } fun onSmilesButtonClicked() { viewState.hideKeyboard() viewState.callForSmilesBottomSheet() } fun onImageAttachButtonClicked() { viewState.showImagePickerDialog() } private fun onTagClickedWithSelection(@Tag tag: Long) { when (tag) { MessageTagCodes.TAG_B -> { viewState.insertTags(MessageTags.B_OPEN, MessageTags.B_CLOSE) } MessageTagCodes.TAG_I -> { viewState.insertTags(MessageTags.I_OPEN, MessageTags.I_CLOSE) } MessageTagCodes.TAG_U -> { viewState.insertTags(MessageTags.U_OPEN, MessageTags.U_CLOSE) } } } private fun onTagClickedWithNoSelection(@Tag tag: Long) { when (tag) { MessageTagCodes.TAG_B -> { if (isBOpened) { viewState.insertTag(MessageTags.B_CLOSE) } else { viewState.insertTag(MessageTags.B_OPEN) } isBOpened = !isBOpened } MessageTagCodes.TAG_I -> { if (isIOpened) { viewState.insertTag(MessageTags.I_CLOSE) } else { viewState.insertTag(MessageTags.I_OPEN) } isIOpened = !isIOpened } MessageTagCodes.TAG_U -> { if (isUOpened) { viewState.insertTag(MessageTags.U_CLOSE) } else { viewState.insertTag(MessageTags.U_OPEN) } isUOpened = !isUOpened } } } private fun onLinkTagClicked() { viewState.showLinkParametersDialogs() } private fun onVideoLinkTagClicked() { viewState.showVideoLinkParametersDialog() } private fun loadEmojiList() { clearCurrentList = true emojiInteractor .loadEmojiList() .map(emojiMapper) .observeOn(schedulers.ui()) .autoDisposable(event(PresenterLifecycle.DESTROY)) .subscribe(getEmojiObserver()) } private fun getEmojiObserver() = object : DisposableObserver<EmojiModel>() { override fun onNext(item: EmojiModel) { if (clearCurrentList) { clearCurrentList = false viewState.clearEmojiList() } viewState.appendEmojiItem(item) } override fun onComplete() { Timber.i("Emoji list loading completed.") } override fun onError(error: Throwable) { error.message?.let { viewState.showErrorMessage(it) } } } }
apache-2.0
2a2629d1b0d32371cef2a3d7ab634083
32.477273
96
0.64019
4.751613
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/AwardParentViewHolder.kt
2
1428
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.widget.ImageView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.work_awards_parent_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.WorkAwardsParent import ru.fantlab.android.ui.widgets.FontTextView import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder class AwardParentViewHolder : TreeViewBinder<AwardParentViewHolder.ViewHolder>() { override val layoutId = R.layout.work_awards_parent_row_item override fun provideViewHolder(itemView: View) = ViewHolder(itemView) override fun bindView( holder: RecyclerView.ViewHolder, position: Int, node: TreeNode<*>, onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener? ) { (holder as ViewHolder).expandButton.rotation = 0f val rotateDegree = if (node.isExpand) 90f else 0f holder.expandButton.rotation = rotateDegree val parentNode = node.content as WorkAwardsParent holder.title.text = parentNode.title holder.expandButton.isVisible = !node.isLeaf } class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) { val expandButton: ImageView = rootView.expandButton var title: FontTextView = rootView.awardsTitle } }
gpl-3.0
c70a7c1863c82fc47206f0e4f442313d
38.666667
125
0.813725
3.83871
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/madara/midnightmessscans/src/MidnightMessScans.kt
1
4436
package eu.kanade.tachiyomi.extension.en.midnightmessscans import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservable import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.CacheControl import okhttp3.FormBody import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.concurrent.TimeUnit import kotlin.math.absoluteValue import kotlin.random.Random @Nsfw class MidnightMessScans : Madara("Midnight Mess Scans", "https://midnightmess.org", "en") { override fun mangaDetailsParse(document: Document): SManga { val manga = SManga.create() with(document) { select("div.post-title h3").first()?.let { manga.title = it.ownText() } select("div.author-content").first()?.let { if (it.text().notUpdating()) manga.author = it.text() } select("div.artist-content").first()?.let { if (it.text().notUpdating()) manga.artist = it.text() } select("div.summary_content div.post-content").let { manga.description = it.select("div.manga-excerpt").text() } select("div.summary_image img").first()?.let { manga.thumbnail_url = imageFromElement(it) } select("div.summary-content").last()?.let { manga.status = when (it.text()) { // I don't know what's the corresponding for COMPLETED and LICENSED // There's no support for "Canceled" or "On Hold" "Completed", "Completo", "Concluído", "Concluido", "Terminé" -> SManga.COMPLETED "OnGoing", "Продолжается", "Updating", "Em Lançamento", "Em andamento", "Em Andamento", "En cours", "Ativo", "Lançando" -> SManga.ONGOING else -> SManga.UNKNOWN } } val genres = select("div.genres-content a") .map { element -> element.text().toLowerCase(Locale.ROOT) } .toMutableSet() // add tag(s) to genre select("div.tags-content a").forEach { element -> if (genres.contains(element.text()).not()) { genres.add(element.text().toLowerCase(Locale.ROOT)) } } // add manga/manhwa/manhua thinggy to genre document.select(seriesTypeSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not() && it.notUpdating() && it != "-" && genres.contains(it).not()) { genres.add(it.toLowerCase(Locale.ROOT)) } } manga.genre = genres.toList().joinToString(", ") { it.capitalize(Locale.ROOT) } // add alternative name to manga description document.select(altNameSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not() && it.notUpdating()) { manga.description += when { manga.description.isNullOrEmpty() -> altName + it else -> "\n\n$altName" + it } } } } return manga } override fun getGenreList() = listOf( Genre("Bilibili", "bilibili"), Genre("Complete", "complete"), Genre("Manga", "manga"), Genre("Manhwa", "manhwa"), Genre("Manhua", "manhua"), Genre("Shounen ai", "shounen-ai"), Genre("Thiccass", "thiccass"), Genre("Usahime", "usahime"), Genre("Yaoi", "yaoi"), ) }
apache-2.0
99f4be1653fb96f79804d23e3f582a65
39.181818
157
0.602489
4.307992
false
false
false
false
REDNBLACK/advent-of-code2016
src/main/kotlin/day10/Advent10.kt
1
5985
package day10 import array2d import day08.Operation.Type.* import day10.Operation.Direction import day10.Operation.Direction.BOT import day10.Operation.Direction.OUTPUT import day10.Operation.Target import day10.Operation.Type.HIGH import day10.Operation.Type.LOW import mul import parseInput import splitToLines import java.util.* /** --- Day 10: Balance Bots --- You come upon a factory in which many robots are zooming around handing small microchips to each other. Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it in a marked "output" bin. Sometimes, bots take microchips from "input" bins, too. Inspecting one of the microchips, it seems like they each contain a single number; the bots must use some logic to decide what to do with each chip. You access the local control computer and download the bots' instructions (your puzzle input). Some of the instructions specify that a specific-valued microchip should be given to a specific bot; the rest of the instructions indicate what a given bot should do with its lower-value or higher-value chip. For example, consider the following instructions: value 5 goes to bot 2 bot 2 gives low to bot 1 and high to bot 0 value 3 goes to bot 1 bot 1 gives low to output 1 and high to bot 0 bot 0 gives low to output 2 and high to output 0 value 2 goes to bot 2 Initially, bot 1 starts with a value-3 chip, and bot 2 starts with a value-2 chip and a value-5 chip. Because bot 2 has two microchips, it gives its lower one (2) to bot 1 and its higher one (5) to bot 0. Then, bot 1 has two microchips; it puts the value-2 chip in output 1 and gives the value-3 chip to bot 0. Finally, bot 0 has two microchips; it puts the 3 in output 2 and the 5 in output 0. In the end, output bin 0 contains a value-5 microchip, output bin 1 contains a value-2 microchip, and output bin 2 contains a value-3 microchip. In this configuration, bot number 2 is responsible for comparing value-5 microchips with value-2 microchips. Based on your instructions, what is the number of the bot that is responsible for comparing value-61 microchips with value-17 microchips? --- Part Two --- What do you get if you multiply together the values of one chip in each of outputs 0, 1, and 2? */ fun main(args: Array<String>) { val test = """ |value 5 goes to bot 2 |bot 2 gives low to bot 1 and high to bot 0 |value 3 goes to bot 1 |bot 1 gives low to output 1 and high to bot 0 |bot 0 gives low to output 2 and high to output 0 |value 2 goes to bot 2 """.trimMargin() val input = parseInput("day10-input.txt") println(findBot(test, { b -> b.low() == 2 && b.high() == 5 }) == (2 to 30)) println(findBot(input, { b -> b.low() == 17 && b.high() == 61 })) } fun findBot(input: String, predicate: (Bot) -> Boolean): Pair<Int, Int> { val bots = parseBots(input) val outputs = HashMap<Int, Int>() val operations = parseOperations(input) var botNumber = 0 val done = mutableSetOf<Int>() while (done.size < operations.size) { for ((index, operation) in operations.withIndex()) { val bot = bots.getOrElse(operation.botNumber, { Bot(operation.botNumber) }) if (!bot.hasChips()) continue if (predicate(bot)) botNumber = bot.number for ((number, direction, type) in operation.targets) { val value = when (type) { LOW -> bot.low(); HIGH -> bot.high() } when (direction) { OUTPUT -> outputs.compute(number, { k, v -> value }) BOT -> bots.compute(number, { k, v -> (v ?: Bot(k)).addChip(value) }) } } bots.put(operation.botNumber, bot.clearChips()) done.add(index) } } return botNumber to (0..2).map { outputs[it] }.filterNotNull().mul() } data class Bot(val number: Int, val chips: Set<Int> = setOf()) { fun hasChips() = chips.size == 2 fun low() = chips.min() ?: throw RuntimeException() fun high() = chips.max() ?: throw RuntimeException() fun addChip(value: Int) = copy(chips = chips.plus(value)) fun clearChips() = copy(chips = setOf()) } data class Operation(val botNumber: Int, val targets: Set<Target>) { enum class Direction { OUTPUT, BOT } enum class Type { LOW, HIGH } data class Target(val entityNumber: Int, val direction: Direction, val type: Type) } private fun parseOperations(input: String) = input.splitToLines() .filter { it.startsWith("bot") } .sortedDescending() .map { val (botNumber, lowDirection, lowNumber, highDirection, highNumber) = Regex("""bot (\d+) gives low to (bot|output) (\d+) and high to (bot|output) (\d+)""") .findAll(it) .map { it.groupValues.drop(1).toList() } .toList() .flatMap { it } Operation( botNumber = botNumber.toInt(), targets = setOf( Target(lowNumber.toInt(), Direction.valueOf(lowDirection.toUpperCase()), LOW), Target(highNumber.toInt(), Direction.valueOf(highDirection.toUpperCase()), HIGH) ) ) } private fun parseBots(input: String) = input.splitToLines() .filter { it.startsWith("value") } .map { val (value, botNumber) = Regex("""(\d+)""") .findAll(it) .map { it.groupValues[1] } .map(String::toInt) .toList() botNumber to value } .groupBy { it.first } .map { it.key to Bot(it.key, it.value.map { it.second }.toSet()) } .toMap(HashMap())
mit
0e31fdb7287dfddc6bd013d8f7e45e94
41.446809
253
0.619549
4.046653
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/parking_access/AddParkingAccess.kt
1
924
package de.westnordost.streetcomplete.quests.parking_access import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao class AddParkingAccess(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) { override val tagFilters = "nodes, ways, relations with amenity=parking and (!access or access=unknown)" override val commitMessage = "Add type of parking access" override val icon = R.drawable.ic_quest_parking_access override fun getTitle(tags: Map<String, String>) = R.string.quest_parking_access_title override fun createForm() = AddParkingAccessForm() override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) { changes.addOrModify("access", answer) } }
gpl-3.0
c5803f858cb5e874128660eb6e6af812
43
107
0.792208
4.62
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/lang/XSLT.kt
1
2372
/* * Copyright (C) 2018-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xslt.lang import com.intellij.lang.xml.XMLLanguage import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher import com.intellij.openapi.fileTypes.FileNameMatcher import com.intellij.openapi.fileTypes.LanguageFileType import uk.co.reecedunn.intellij.plugin.core.lang.LanguageData import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmLanguageVersion /** * XML Stylesheet Language: Transform */ @Suppress("MemberVisibilityCanBePrivate") object XSLT : XMLLanguage(INSTANCE, "XSLT", "application/xslt+xml") { // region Language const val NAMESPACE: String = "http://www.w3.org/1999/XSL/Transform" override fun isCaseSensitive(): Boolean = true override fun getDisplayName(): String = "XSLT" override fun getAssociatedFileType(): LanguageFileType? = null init { putUserData(LanguageData.KEY, object : LanguageData { override val associations: List<FileNameMatcher> = listOf( ExtensionFileNameMatcher("xsl"), ExtensionFileNameMatcher("xslt") ) override val mimeTypes: Array<String> = arrayOf("application/xslt+xml") }) } // endregion // region Versions val VERSION_1_0: XpmLanguageVersion = XsltVersion("1.0", XsltSpec.REC_1_0_19991116) val VERSION_2_0: XpmLanguageVersion = XsltVersion("2.0", XsltSpec.REC_2_0_20070123) val VERSION_3_0: XpmLanguageVersion = XsltVersion("3.0", XsltSpec.REC_3_0_20170608) val VERSION_4_0: XpmLanguageVersion = XsltVersion("4.0", XsltSpec.ED_4_0_20210113) val versions: Map<String, XpmLanguageVersion> = listOf( VERSION_1_0, VERSION_2_0, VERSION_3_0, VERSION_4_0 ).associateBy { it.version } // endregion }
apache-2.0
b424aab34aefa3efc66b39cac1b5dc6f
34.402985
87
0.710793
4.034014
false
false
false
false
modmuss50/Fluxed-Redstone
src/main/kotlin/me/modmuss50/fr/mutlipart/PipeMultipart.kt
1
17337
package me.modmuss50.fr.mutlipart import cofh.api.energy.IEnergyConnection import cofh.api.energy.IEnergyProvider import cofh.api.energy.IEnergyReceiver import ic2.api.energy.EnergyNet import ic2.api.energy.tile.IEnergySink import ic2.api.energy.tile.IEnergySource import me.modmuss50.fr.FluxedRedstone import me.modmuss50.fr.network.FRNetworkHandler import net.minecraft.block.Block import net.minecraft.block.properties.PropertyBool import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.ResourceLocation import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.property.ExtendedBlockState import net.minecraftforge.common.property.IExtendedBlockState import net.minecraftforge.common.property.Properties import net.minecraftforge.energy.CapabilityEnergy import net.minecraftforge.energy.IEnergyStorage import reborncore.common.misc.Functions import reborncore.common.misc.vecmath.Vecs3dCube import reborncore.mcmultipart.MCMultiPartMod import reborncore.mcmultipart.microblock.IMicroblock import reborncore.mcmultipart.multipart.ISlottedPart import reborncore.mcmultipart.multipart.Multipart import reborncore.mcmultipart.multipart.MultipartHelper import reborncore.mcmultipart.multipart.PartSlot import reborncore.mcmultipart.raytrace.PartMOP import java.util.* open class PipeMultipart() : Multipart(), ISlottedPart, ITickable, IEnergyStorage { override fun getSlotMask(): EnumSet<PartSlot>? { return EnumSet.of(PartSlot.CENTER) } open fun getPipeType(): PipeTypeEnum { return PipeTypeEnum.REDSTONE } var boundingBoxes = arrayOfNulls<Vecs3dCube>(14) var center = 0.6F var offset = 0.1F var connectedSides = HashMap<EnumFacing, BlockPos>() var ic2ConnectionCache = HashSet<EnumFacing>() var power = 0 init { refreshBounding() } fun refreshBounding() { val centerFirst = (center - offset).toDouble() val thickness = getPipeType().thickness!! val w = (thickness / 16) - 0.5 boundingBoxes[6] = Vecs3dCube(centerFirst.toDouble() - w - 0.03, centerFirst.toDouble() - w - 0.08, centerFirst.toDouble() - w - 0.03, centerFirst.toDouble() + w + 0.08, centerFirst.toDouble() + w + 0.04, centerFirst.toDouble() + w + 0.08) boundingBoxes[6] = Vecs3dCube(centerFirst - w, centerFirst - w, centerFirst - w, centerFirst + w, centerFirst + w, centerFirst + w) var i = 0 for (dir in EnumFacing.values()) { val xMin1 = (if (dir.frontOffsetX < 0) 0.0 else (if (dir.frontOffsetX === 0) centerFirst - w else centerFirst + w)) val xMax1 = (if (dir.frontOffsetX > 0) 1.0 else (if (dir.frontOffsetX === 0) centerFirst + w else centerFirst - w)) val yMin1 = (if (dir.frontOffsetY < 0) 0.0 else (if (dir.frontOffsetY === 0) centerFirst - w else centerFirst + w)) val yMax1 = (if (dir.frontOffsetY > 0) 1.0 else (if (dir.frontOffsetY === 0) centerFirst + w else centerFirst - w)) val zMin1 = (if (dir.frontOffsetZ < 0) 0.0 else (if (dir.frontOffsetZ === 0) centerFirst - w else centerFirst + w)) val zMax1 = (if (dir.frontOffsetZ > 0) 1.0 else (if (dir.frontOffsetZ === 0) centerFirst + w else centerFirst - w)) boundingBoxes[i] = Vecs3dCube(xMin1, yMin1, zMin1, xMax1, yMax1, zMax1) i++ } } override fun addCollisionBoxes(mask: AxisAlignedBB?, list: MutableList<AxisAlignedBB>?, collidingEntity: Entity?) { for (facing in EnumFacing.values()) { if (connectedSides.containsKey(facing)) { if (boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB().intersectsWith(mask)) { list!!.add(boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB()) } } } if (boundingBoxes[6]!!.toAABB().intersectsWith(mask)) { list!!.add(boundingBoxes[6]!!.toAABB()) } } override fun addSelectionBoxes(list: MutableList<AxisAlignedBB>?) { for (facing in EnumFacing.values()) { if (connectedSides.containsKey(facing)) { list!!.add(boundingBoxes[Functions.getIntDirFromDirection(facing)]!!.toAABB()) } } list!!.add(boundingBoxes[6]!!.toAABB()) } override fun getModelPath(): ResourceLocation? { return ResourceLocation("fluxedredstone:FRPipe") } fun checkConnections(refreshIC2: Boolean = false) { connectedSides.clear() if (FluxedRedstone.ic2Support && world.isRemote) { if (refreshIC2) { ic2ConnectionCache.clear() } if (nextId > 8192) nextId = 0 // Request a new connection map nextId++ FluxedRedstone.ic2Interface.waiting.forcePut(nextId, this) FRNetworkHandler.instance.sendToServer(FRNetworkHandler.MsgRequestIC2Map(nextId, pos)) } for (facing in EnumFacing.values()) { if (shouldConnectTo(pos, facing)) { connectedSides.put(facing, pos) } } } fun shouldConnectTo(pos: BlockPos?, dir: EnumFacing?): Boolean { if (dir != null) { if (internalShouldConnectTo(pos, dir)) { var otherPipe = getPipe(world, pos!!.offset(dir), dir) if (otherPipe != null && !otherPipe.internalShouldConnectTo(otherPipe.pos, dir.opposite)) { return false } return true } } return false } fun internalShouldConnectTo(pos: BlockPos?, dir: EnumFacing?): Boolean { var slottedPart = PartSlot.getFaceSlot(dir) if (slottedPart != null) { var part = container.getPartInSlot(slottedPart) if (part != null && part is IMicroblock.IFaceMicroblock) { if (!part.isFaceHollow) { return false } } } // if (!OcclusionHelper.occlusionTest(container.parts, this, boundingBoxes[Functions.getIntDirFromDirection(dir)]!!.toAABB())) { // return false // } var otherPipe = getPipe(world, pos!!.offset(dir), dir) if (otherPipe != null) { return true } var tile = world.getTileEntity(pos.offset(dir)) if (tile != null) { if(FluxedRedstone.RFSupport){ if (tile is IEnergyConnection) { if (tile.canConnectEnergy(dir)) { return true } } } if(FluxedRedstone.teslaSupport && FluxedRedstone.teslaManager.canConnect(tile, dir!!)){ return true } if (tile.hasCapability(CapabilityEnergy.ENERGY, dir?.opposite)) { return true } if (FluxedRedstone.ic2Support) { if (world.isRemote && ic2ConnectionCache.contains(dir)) { return true } else if (!world.isRemote) { return FluxedRedstone.ic2Interface.connectable(EnergyNet.instance.getTile(world, pos.offset(dir!!)), dir.opposite) } } } return false } fun getPipe(world: World, blockPos: BlockPos, side: EnumFacing?): PipeMultipart? { val container = MultipartHelper.getPartContainer(world, blockPos) ?: return null if (side != null) { val part = container.getPartInSlot(PartSlot.getFaceSlot(side)) if (part is IMicroblock.IFaceMicroblock && !part.isFaceHollow()) { return null } } val part = container.getPartInSlot(PartSlot.CENTER) if (part is PipeMultipart) { return part } else { return null } } override fun getExtendedState(state: IBlockState?): IBlockState? { var extState = state as IExtendedBlockState return extState.withProperty(UP, shouldConnectTo(pos, EnumFacing.UP))!!.withProperty(DOWN, shouldConnectTo(pos, EnumFacing.DOWN))!!.withProperty(NORTH, shouldConnectTo(pos, EnumFacing.NORTH))!!.withProperty(EAST, shouldConnectTo(pos, EnumFacing.EAST))!!.withProperty(WEST, shouldConnectTo(pos, EnumFacing.WEST))!!.withProperty(SOUTH, shouldConnectTo(pos, EnumFacing.SOUTH)).withProperty(TYPE, getPipeType()) } override fun onAdded() { super.onAdded() checkConnections(true) } override fun onNeighborBlockChange(block: Block?) { super.onNeighborBlockChange(block) checkConnections(true) } override fun createBlockState(): BlockStateContainer? { return ExtendedBlockState(MCMultiPartMod.multipart, arrayOf(TYPE), arrayOf(UP, DOWN, NORTH, EAST, WEST, SOUTH)) } override fun update() { if (world != null) { if (world.totalWorldTime % 80 == 0.toLong()) { checkConnections(false) } if (world.isRemote) { return } for (face in EnumFacing.values()) { if (connectedSides.containsKey(face)) { var offPos = pos.offset(face) var tile = world.getTileEntity(offPos)!! if(tile == null){ continue } //Tesla if(FluxedRedstone.teslaSupport){ FluxedRedstone.teslaManager.update(this, tile, face) } //Forge if (tile.hasCapability(CapabilityEnergy.ENERGY, face.opposite)) { var energy: IEnergyStorage? = tile.getCapability(CapabilityEnergy.ENERGY, face.opposite) var didExtract = false //Let other machines push to FE though the caps // if (energy!!.canExtract()) { // var move = energy.extractEnergy(Math.min(getPipeType().maxRF, getPipeType().maxRF * 4 - power), false) // if (move != 0) { // power += move // didExtract = true // } // // } if (energy!!.canReceive() && !didExtract) { var move = energy.receiveEnergy(Math.min(getPipeType().maxRF, power), false) if (move != 0) { power -= move } } } //RF if (FluxedRedstone.RFSupport && tile is IEnergyConnection) { if (tile is IEnergyProvider) { if (tile.canConnectEnergy(face)) { var move = tile.extractEnergy(face.opposite, Math.min(getPipeType().maxRF, getPipeType().maxRF * 4 - power), false) if (move != 0) { power += move } } } if (tile is IEnergyReceiver) { if (tile.canConnectEnergy(face)) { var move = tile.receiveEnergy(face.opposite, Math.min(getPipeType().maxRF, power), false) if (move != 0) { power -= move } } } } // EU if (FluxedRedstone.ic2Support && !world.isRemote) { // EnergyNet is serverside only val ic2Tile = EnergyNet.instance.getTile(tile.world, tile.pos) if (ic2Tile != null) { if (ic2Tile is IEnergySource && ic2Tile.emitsEnergyTo(IC2Interface.DUMMY_ACCEPTOR, face.opposite)) { var move = Math.min(getPipeType().maxRF.toDouble() / FluxedRedstone.rfPerEU, (getPipeType().maxRF * 4 - power) / FluxedRedstone.rfPerEU) if (move != 0.0 && move <= ic2Tile.offeredEnergy) { ic2Tile.drawEnergy(move) power += Math.round(move * FluxedRedstone.rfPerEU).toInt() } } else if (ic2Tile is IEnergySink && ic2Tile.acceptsEnergyFrom(IC2Interface.DUMMY_EMITTER, face.opposite)) { var move = Math.min(getPipeType().maxRF.toDouble() / FluxedRedstone.rfPerEU, power / FluxedRedstone.rfPerEU) if (move != 0.0 && ic2Tile.demandedEnergy >= move) { var leftover = ic2Tile.injectEnergy(face.opposite, move, 12.0) // What does the 3rd parameter do? Someone tell me! power -= Math.round(move * FluxedRedstone.rfPerEU).toInt() power += Math.floor(leftover * FluxedRedstone.rfPerEU).toInt() } } } } var pipe = getPipe(world, pos.offset(face), face) if (pipe != null) { var averPower = (power + pipe.power) / 2 pipe.power = averPower if(averPower % 2 != 0 && power != 0){ averPower ++ } power = averPower } } } } } override fun writeToNBT(tag: NBTTagCompound?): NBTTagCompound { super.writeToNBT(tag) tag!!.setInteger("power", power) return tag } override fun readFromNBT(tag: NBTTagCompound?) { super.readFromNBT(tag) power = tag!!.getInteger("power") } override fun getPickBlock(player: EntityPlayer?, hit: PartMOP?): ItemStack? { return ItemStack(FluxedRedstone.itemMultiPipe.get(getPipeType())) } override fun getDrops(): MutableList<ItemStack>? { var list = ArrayList<ItemStack>() list.add(ItemStack(FluxedRedstone.itemMultiPipe.get(getPipeType()))) return list } override fun getHardness(hit: PartMOP?): Float { return 1F } companion object { val UP = Properties.toUnlisted(PropertyBool.create("up")) val DOWN = Properties.toUnlisted(PropertyBool.create("down")) val NORTH = Properties.toUnlisted(PropertyBool.create("north")) val EAST = Properties.toUnlisted(PropertyBool.create("east")) val SOUTH = Properties.toUnlisted(PropertyBool.create("south")) val WEST = Properties.toUnlisted(PropertyBool.create("west")) var TYPE = PropertyEnum.create("variant", PipeTypeEnum::class.java) var nextId = -1 } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { if(capability == CapabilityEnergy.ENERGY){ return true } return super.hasCapability(capability, facing) } override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { if(capability == CapabilityEnergy.ENERGY){ return this as T } return super.getCapability(capability, facing) } override fun canExtract(): Boolean { return true } override fun getMaxEnergyStored(): Int { return getPipeType().maxRF * 4 } override fun getEnergyStored(): Int { return power } override fun extractEnergy(maxExtract: Int, simulate: Boolean): Int { if (!canExtract()) return 0 val energyExtracted = Math.min(power, Math.min(getPipeType().maxRF, maxExtract)) if (!simulate) power -= energyExtracted return energyExtracted } override fun receiveEnergy(maxReceive: Int, simulate: Boolean): Int { if (!canReceive()) return 0 val energyReceived = Math.min(maxEnergyStored - power, Math.min(getPipeType().maxRF, maxReceive)) if (!simulate) power += energyReceived return energyReceived } override fun canReceive(): Boolean { return power < maxEnergyStored } }
mit
4dcb8ed4329ae62188ef2e1e5850b1d9
37.959551
415
0.560132
4.52545
false
false
false
false
da1z/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/util.kt
2
2395
// Copyright 2000-2017 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.groovy.highlighter import com.intellij.codeHighlighting.TextEditorHighlightingPass import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.HighlightInfoType import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiMethod import org.jetbrains.plugins.groovy.GroovyLanguage import org.jetbrains.plugins.groovy.lang.lexer.TokenSets import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod internal fun PsiFile.getGroovyFile(): GroovyFileBase? = viewProvider.getPsi(GroovyLanguage) as? GroovyFileBase internal abstract class GroovyHighlightingPass(val myFile: PsiFile, document: Document) : TextEditorHighlightingPass(myFile.project, document) { private val myInfos = mutableListOf<HighlightInfo>() override fun doApplyInformationToEditor() { if (myDocument == null || myInfos.isEmpty()) return UpdateHighlightersUtil.setHighlightersToEditor( myProject, myDocument, 0, myFile.textLength, myInfos, colorsScheme, id ) } protected fun addInfo(element: PsiElement, attribute: TextAttributesKey) { val builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION) builder.range(element).needsUpdateOnTyping(false).textAttributes(attribute).create()?.let { myInfos.add(it) } } } internal fun PsiMethod.isMethodWithLiteralName() = this is GrMethod && nameIdentifierGroovy.isStringNameElement() internal fun GrReferenceElement<*>.isReferenceWithLiteralName() = referenceNameElement.isStringNameElement() private fun PsiElement?.isStringNameElement() = this?.node?.elementType in TokenSets.STRING_LITERAL_SET internal fun GrReferenceElement<*>.isAnonymousClassReference(): Boolean { return (parent as? GrAnonymousClassDefinition)?.baseClassReferenceGroovy == this }
apache-2.0
e75c4596181edf93a2272380b47f200e
46.9
140
0.820459
4.57935
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt
1
4404
package info.nightscout.androidaps.plugins.iob.iobCobCalculator import dagger.Reusable import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.DateUtil import java.util.* import javax.inject.Inject import kotlin.math.roundToLong @Reusable class GlucoseStatusProvider @Inject constructor( private val aapsLogger: AAPSLogger, private val iobCobCalculator: IobCobCalculator, private val dateUtil: DateUtil ) { val glucoseStatusData: GlucoseStatus? get() = getGlucoseStatusData() fun getGlucoseStatusData(allowOldData: Boolean = false): GlucoseStatus? { val data = iobCobCalculator.ads.getBgReadingsDataTableCopy() val sizeRecords = data.size if (sizeRecords == 0) { aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==0") return null } if (data[0].timestamp < dateUtil.now() - 7 * 60 * 1000L && !allowOldData) { aapsLogger.debug(LTag.GLUCOSE, "oldData") return null } val now = data[0] val nowDate = now.timestamp var change: Double if (sizeRecords == 1) { aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==1") return GlucoseStatus( glucose = now.value, noise = 0.0, delta = 0.0, shortAvgDelta = 0.0, longAvgDelta = 0.0, date = nowDate ).asRounded() } val nowValueList = ArrayList<Double>() val lastDeltas = ArrayList<Double>() val shortDeltas = ArrayList<Double>() val longDeltas = ArrayList<Double>() // Use the latest sgv value in the now calculations nowValueList.add(now.value) for (i in 1 until sizeRecords) { if (data[i].value > 38) { val then = data[i] val thenDate = then.timestamp val minutesAgo = ((nowDate - thenDate) / (1000.0 * 60)).roundToLong() // multiply by 5 to get the same units as delta, i.e. mg/dL/5m change = now.value - then.value val avgDel = change / minutesAgo * 5 aapsLogger.debug(LTag.GLUCOSE, "$then minutesAgo=$minutesAgo avgDelta=$avgDel") // use the average of all data points in the last 2.5m for all further "now" calculations if (0 < minutesAgo && minutesAgo < 2.5) { // Keep and average all values within the last 2.5 minutes nowValueList.add(then.value) now.value = average(nowValueList) // short_deltas are calculated from everything ~5-15 minutes ago } else if (2.5 < minutesAgo && minutesAgo < 17.5) { //console.error(minutesAgo, avgDelta); shortDeltas.add(avgDel) // last_deltas are calculated from everything ~5 minutes ago if (2.5 < minutesAgo && minutesAgo < 7.5) { lastDeltas.add(avgDel) } // long_deltas are calculated from everything ~20-40 minutes ago } else if (17.5 < minutesAgo && minutesAgo < 42.5) { longDeltas.add(avgDel) } else { // Do not process any more records after >= 42.5 minutes break } } } val shortAverageDelta = average(shortDeltas) val delta = if (lastDeltas.isEmpty()) { shortAverageDelta } else { average(lastDeltas) } return GlucoseStatus( glucose = now.value, date = nowDate, noise = 0.0, //for now set to nothing as not all CGMs report noise shortAvgDelta = shortAverageDelta, delta = delta, longAvgDelta = average(longDeltas), ).also { aapsLogger.debug(LTag.GLUCOSE, it.log()) }.asRounded() } companion object { fun average(array: ArrayList<Double>): Double { var sum = 0.0 if (array.size == 0) return 0.0 for (value in array) { sum += value } return sum / array.size } } }
agpl-3.0
f6b173c29769138ffe244fc3d86453a8
37.640351
105
0.557675
4.573209
false
false
false
false
mutcianm/android-dsl
misc/MyActivity.kt
2
2445
package com.example.andr; import android.app.Activity import android.os.Bundle import android.widget.* import com.example.andr.dsl.* import android.view.View import android.widget.LinearLayout.LayoutParams import android.view.ViewGroup import android.graphics.Color public class MyActivity() : Activity() { /** * Called when the activity is first created. */ protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); UI(this) { linearLayout{ orientation = (LinearLayout.VERTICAL) style{ X -> when(X){ is Button -> X.setTextColor(Color.BLUE) is EditText -> X.setBackgroundColor(Color.DKGRAY) else -> X } } val et = editText { text = "EditText" } button { text = "button1" setOnClickListener { et.text = savedInstanceState.toString() } } button{ text = "Butt2" setOnClickListener { alertDialog("exit?") { setPositiveButton("OK") { a,i -> ctx.finish() } setNegativeButton("no") { a,i -> et.text = "okno" } } } } listView { for (i in (0..3)){ ratingBar { rating = i.toFloat() } } } linearLayout{ orientation = LinearLayout.HORIZONTAL val butt = button { text ="Frame1" } checkBox { orientation = LinearLayout.HORIZONTAL text = "somecb" setOnClickListener { butt.text = isChecked().toString() } } orientation = LinearLayout.HORIZONTAL } } } } }
apache-2.0
38d02529a0c6502711f6128b7427f343
31.613333
73
0.384867
6.52
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/feedforward/squareddistance/SquaredDistanceLayerUtils.kt
1
1732
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.feedforward.squareddistance import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.models.feedforward.squareddistance.SquaredDistanceLayer import com.kotlinnlp.simplednn.core.layers.models.feedforward.squareddistance.SquaredDistanceLayerParameters import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * */ internal object SquaredDistanceLayerUtils { /** * */ fun buildLayer(): SquaredDistanceLayer<DenseNDArray> = SquaredDistanceLayer( inputArray = AugmentedArray(values = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.5, -0.4))), outputArray = AugmentedArray(1), params = this.getParams35(), inputType = LayerType.Input.Dense, dropout = 0.0 ) /** * */ private fun getParams35() = SquaredDistanceLayerParameters(inputSize = 3, rank = 5).apply { wB.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.4, 0.6, -0.5), doubleArrayOf(-0.5, 0.4, 0.2), doubleArrayOf(0.5, 0.4, 0.1), doubleArrayOf(0.5, 0.2, -0.2), doubleArrayOf(-0.3, 0.4, 0.4) ))) } /** * */ fun getOutputErrors() = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8)) }
mpl-2.0
073801b95d97b4322fb5369f8037e816
32.960784
108
0.691686
3.963387
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/reader/usecases/ReaderSiteFollowUseCaseTest.kt
1
13376
package org.wordpress.android.ui.reader.usecases import androidx.arch.core.executor.testing.InstantTaskExecutorRule import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.toList import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyLong import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.datasets.ReaderBlogTableWrapper import org.wordpress.android.test import org.wordpress.android.ui.reader.actions.ReaderActions.ActionListener import org.wordpress.android.ui.reader.actions.ReaderBlogActionsWrapper import org.wordpress.android.ui.reader.tracker.ReaderTracker import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.Failed.NoNetwork import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.Failed.RequestFailed import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.FollowStatusChanged import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.Success import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper import org.wordpress.android.util.NetworkUtilsWrapper private const val FOLLOW_BLOG_ACTION_LISTENER_PARAM_POSITION = 3 private const val SOURCE = "source" @InternalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class ReaderSiteFollowUseCaseTest { @Rule @JvmField val rule = InstantTaskExecutorRule() lateinit var useCase: ReaderSiteFollowUseCase @Mock lateinit var readerBlogTableWrapper: ReaderBlogTableWrapper @Mock lateinit var readerUtilsWrapper: ReaderUtilsWrapper @Mock lateinit var readerBlogActionsWrapper: ReaderBlogActionsWrapper @Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock lateinit var readerTracker: ReaderTracker private val useCaseParam = ReaderSiteFollowUseCase.Param(11L, 13L, "FakeBlogName") @Before fun setup() { useCase = ReaderSiteFollowUseCase( networkUtilsWrapper, readerBlogActionsWrapper, readerBlogTableWrapper, readerUtilsWrapper, readerTracker ) whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true) whenever(readerUtilsWrapper.isExternalFeed(anyLong(), anyLong())).thenReturn(false) } @Test fun `NoNetwork returned when no network found`() = test { // Given whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) // Act val result = useCase.toggleFollow(useCaseParam, SOURCE).toList(mutableListOf()) // Then assertThat(result).contains(NoNetwork) } @Test fun `Success returned on success response`() = testWithFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result)).contains(Success) } @Test fun `RequestFailed returned on failed response`() = testWithFailedResponseForFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result)).contains(RequestFailed) } @Test fun `follow site action returns info to show enable notification`() = testWithUnFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).showEnableNotification).isTrue } @Test fun `un-follow site action returns info to not show enable notification`() = testWithFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).showEnableNotification).isFalse } @Test fun `follow site action returns info that site is followed`() = testWithUnFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).following).isTrue } @Test fun `un-follow site action returns info that site is un-followed`() = testWithFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).following).isFalse } @Test fun `follow site action returns info to not delete notification subscriptions`() = testWithUnFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat(result.size).isGreaterThanOrEqualTo(2) assertThat((result[1] as FollowStatusChanged).deleteNotificationSubscription).isFalse } @Test fun `un-follow site action returns info to delete notification subscriptions`() = testWithFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat(result.size).isGreaterThanOrEqualTo(2) assertThat((result[1] as FollowStatusChanged).deleteNotificationSubscription).isTrue } @Test fun `request failure on un-follow site action returns info that site is followed`() = testWithFailedResponseForFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat(result.size).isGreaterThanOrEqualTo(2) assertThat((result[1] as FollowStatusChanged).following).isTrue } @Test fun `request failure on follow site action returns info that site is not followed`() = testWithFailedResponseForUnFollowedSitePost { // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat(result.size).isGreaterThanOrEqualTo(2) assertThat((result[1] as FollowStatusChanged).following).isFalse } @Test fun `follow external feed post action returns info to not show enable notification`() = testWithUnFollowedSitePost { // Given whenever(readerUtilsWrapper.isExternalFeed(anyLong(), anyLong())).thenReturn(true) // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).showEnableNotification).isFalse } @Test fun `un-follow external feed post action returns info to not show enable notification`() = testWithFollowedSitePost { // Given whenever(readerUtilsWrapper.isExternalFeed(anyLong(), anyLong())).thenReturn(true) // Act val result = useCase.toggleFollow(useCaseParam, SOURCE) .toList(mutableListOf()) // Assert assertThat((result[0] as FollowStatusChanged).showEnableNotification).isFalse } @Test fun `toggling follow for un-followed site post initiates follow blog (or site) action`() = testWithUnFollowedSitePost { // Act useCase.toggleFollow(useCaseParam, SOURCE).toList(mutableListOf()) // Assert verify(readerBlogActionsWrapper).followBlog( anyLong(), anyLong(), eq(true), anyOrNull(), eq(SOURCE), eq(readerTracker) ) } @Test fun `toggling follow for followed site post initiates un-follow blog (or site) action`() = testWithFollowedSitePost { // Act useCase.toggleFollow(useCaseParam, SOURCE).toList(mutableListOf()) // Assert verify(readerBlogActionsWrapper).followBlog( anyLong(), anyLong(), eq(false), anyOrNull(), eq(SOURCE), eq(readerTracker) ) } @Test fun `follow blog (or site) action is triggered for selected reader post`() = testWithFollowedSitePost { // Act useCase.toggleFollow(useCaseParam, SOURCE).toList(mutableListOf()) // Assert verify(readerBlogActionsWrapper).followBlog( eq(useCaseParam.blogId), eq(useCaseParam.feedId), anyBoolean(), anyOrNull(), eq(SOURCE), eq(readerTracker) ) } private fun <T> testWithFollowedSitePost(block: suspend CoroutineScope.() -> T) { test { whenever(readerBlogTableWrapper.isSiteFollowed(useCaseParam.blogId, useCaseParam.feedId)).thenReturn(true) whenever( readerBlogActionsWrapper.followBlog( anyLong(), anyLong(), anyBoolean(), anyOrNull(), anyString(), eq(readerTracker) ) ).then { (it.arguments[FOLLOW_BLOG_ACTION_LISTENER_PARAM_POSITION] as ActionListener).onActionResult(true) true } block() } } private fun <T> testWithUnFollowedSitePost(block: suspend CoroutineScope.() -> T) { test { whenever(readerBlogTableWrapper.isSiteFollowed(useCaseParam.blogId, useCaseParam.feedId)).thenReturn(false) whenever( readerBlogActionsWrapper.followBlog( anyLong(), anyLong(), anyBoolean(), anyOrNull(), anyString(), eq(readerTracker) ) ).then { (it.arguments[FOLLOW_BLOG_ACTION_LISTENER_PARAM_POSITION] as ActionListener).onActionResult(true) true } block() } } private fun <T> testWithFailedResponseForFollowedSitePost(block: suspend CoroutineScope.() -> T) { test { whenever(readerBlogTableWrapper.isSiteFollowed(useCaseParam.blogId, useCaseParam.feedId)).thenReturn(true) whenever( readerBlogActionsWrapper.followBlog( anyLong(), anyLong(), anyBoolean(), anyOrNull(), anyString(), eq(readerTracker) ) ).then { (it.arguments[FOLLOW_BLOG_ACTION_LISTENER_PARAM_POSITION] as ActionListener).onActionResult(false) true } block() } } private fun <T> testWithFailedResponseForUnFollowedSitePost(block: suspend CoroutineScope.() -> T) { test { whenever(readerBlogTableWrapper.isSiteFollowed(useCaseParam.blogId, useCaseParam.feedId)).thenReturn(false) whenever( readerBlogActionsWrapper.followBlog( anyLong(), anyLong(), anyBoolean(), anyOrNull(), anyString(), eq(readerTracker) ) ).then { (it.arguments[FOLLOW_BLOG_ACTION_LISTENER_PARAM_POSITION] as ActionListener).onActionResult(false) true } block() } } }
gpl-2.0
19df8c69bb882cca53bcd4238939cc1e
36.892351
119
0.574387
5.753118
false
true
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ezlink/CEPASPurse.kt
1
2264
/* * CEPASPurse.kt * * Copyright 2011 Sean Cross <[email protected]> * Copyright 2011-2014 Eric Butler <[email protected]> * Copyright 2018 Michael Farrell <[email protected]> * * Authors: * Sean Cross <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.ezlink import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.util.ImmutableByteArray class CEPASPurse(purseData: ImmutableByteArray) { val autoLoadAmount: Int = purseData.getBitsFromBufferSigned(40, 24) val can: ImmutableByteArray = purseData.sliceOffLen(8, 8) val cepasVersion: Byte = purseData[0] val csn: ImmutableByteArray = purseData.sliceOffLen(16, 8) val issuerDataLength: Int = 0x00ff and purseData[41].toInt() val issuerSpecificData: ImmutableByteArray = purseData.sliceOffLen(62, issuerDataLength) val lastCreditTransactionHeader: ImmutableByteArray = purseData.sliceOffLen(32, 8) val lastCreditTransactionTRP: Int = purseData.byteArrayToInt(28, 4) val lastTransactionDebitOptionsByte: Byte = purseData[62 + issuerDataLength] val lastTransactionTRP: Int = purseData.byteArrayToInt(42, 4) val logfileRecordCount: Byte = purseData[40] val purseBalance: Int = purseData.getBitsFromBufferSigned(16, 24) val purseExpiryDate: Timestamp = EZLinkTransitData.daysToCalendar(purseData.byteArrayToInt(24, 2)) val purseStatus: Byte = purseData[1] val purseCreationDate: Timestamp = EZLinkTransitData.daysToCalendar(purseData.byteArrayToInt(26, 2)) val lastTransactionRecord: CEPASTransaction = CEPASTransaction(purseData.sliceOffLen(46, 16)) }
gpl-3.0
0ce4cae9ceedfbfd4a5c9d0fef012036
47.170213
104
0.76811
3.870085
false
false
false
false
phicdy/toto-anticipation
android/api/src/test/java/com/phicdy/totoanticipation/api/TestRakutenTotoInfoPage.kt
1
35423
package com.phicdy.totoanticipation.api object TestRakutenTotoInfoPage { const val text = """ <!DOCTYPE html> <html lang="ja prefix="og: http://ogp.me/ns# fb: http://www.facebook.com/2008/fbml"> <head> <meta http-equiv="Content-Type content="text/html; charset=utf-8 /> <meta name="description content="第923回のtotoくじ情報をチェック!楽天totoならBIG、totoをインターネットでいつでも購入。キャリーオーバーで最高6億円のくじ!"> <meta name="keywords content="第923回,toto,くじ,情報,BIG,トト,ビッグ,楽天,rakuten,購入"> <meta name="format-detection content="telephone=no"> <meta property="og:title content="第923回 totoくじ情報:楽天toto id="meta_title /> <meta property="og:description content="第923回のtotoくじ情報をチェック!楽天totoならBIG、totoをインターネットでいつでも購入。キャリーオーバーで最高6億円のくじ! id="meta_description /> <meta property="og:site_name content="楽天toto /> <meta property="og:image content="http://toto.rakuten.co.jp/img/other/ogt_toto.gif /> <meta property="og:type content="sports_league /> <title>楽天toto: 第923回totoくじ情報</title> <link rel="shortcut icon href="/favicon.ico /> <link rel="apple-touch-icon-precomposed href="/apple-touch-icon.png /> <link rel="canonical href="https://toto.rakuten.co.jp/toto/schedule/0923/"> <script type="text/javascript src="/js/jquery-1.3.2.min.js?v=1449219349"></script> <script type="text/javascript src="/shared/js/mjl.js?v=1310019901"></script> <script type="text/javascript src="/shared/js/jquery-1.5.1.min.js?v=1310019901"></script> <script type="text/javascript src="/shared/js/run.js?v=1336964417"></script> <script type="text/javascript src="/toto/schedule/js/info_stripe.js?v=1336447762"></script> <link rel="stylesheet type="text/css media="screen href="/css/import.css?v=1337068748 /> <link rel="stylesheet type="text/css media="screen href="/css/general.css?v=1369701410 /> <link rel="stylesheet type="text/css media="screen href="/shared/css/pc.css?v=1336964417 /> <link rel="stylesheet type="text/css media="screen href="/toto/schedule/css/info.css?v=1336447761 /> </head> <body> <div id="page"> <div id="str-container"> <!-- header --> <!-- ========== header ========== --> <!-- Standard RakutenCommonHeader v0.1.4 HTML starts--> <div class="rc-h-standard rc-h-liquid spd"> <noscript> <div class="rc-h-noscript-bar"> <div class="rc-h-inner"> <p>JavaScriptが無効の為、一部のコンテンツをご利用いただけません。JavaScriptの設定を有効にしてからご利用いただきますようお願いいたします。(<a href="http://ichiba.faq.rakuten.co.jp/app/answers/detail/a_id/154">設定方法</a>)</p> </div> </div> </noscript> <div class="rc-h-utility-bar"> <div class="rc-h-inner"> <ul class="rc-h-group-nav"> <li id="grpNote"> <noscript><a href="https://card.rakuten.co.jp/entry/">今すぐ2,000ポイント!</a></noscript> </li> <li class="rc-h-dropdown rc-h-group-dropdown"><a href="http://www.rakuten.co.jp/sitemap/">楽天グループ</a> <ul class="rc-h-dropdown-panel"> <li><a href="http://travel.rakuten.co.jp/??scid=wi_grp_gmx_tot_hepullbu_trv rel="nofollow">楽天トラベル</a></li> <li><a href="http://toolbar.rakuten.co.jp/?scid=wi_grp_gmx_tot_hepullbu_too rel="nofollow">楽天ツールバー</a></li> <li><a href="http://www.infoseek.co.jp/?scid=wi_grp_gmx_tot_hepullbu_ifs rel="nofollow">Infoseek</a></li> <li><a href="http://www.rakuten-edy.co.jp/?scid=wi_grp_gmx_tot_hepullbu_edy rel="nofollow">楽天Edy</a></li> <li><a href="http://uranai.rakuten.co.jp/?scid=wi_grp_gmx_tot_hepullbu_frt rel="nofollow">楽天占い</a></li> <li><a href="http://www.rakuten.co.jp/sitemap/ rel="nofollow">サービス一覧</a></li> </ul> </li> <li><a href="http://www.rakuten-bank.co.jp/?scid=wi_grp_gmx_tot_hetopbu_bnk rel="nofollow">銀行</a></li> <li><a href="http://books.rakuten.co.jp/?scid=wi_grp_gmx_tot_hetopbu_boo rel="nofollow">ブックス</a></li> <li><a href="http://ad2.trafficgate.net/t/r/8194/1441/99636_99636/ rel="nofollow">カード</a></li> <li><a href="http://www.rakuten.co.jp/">楽天市場</a></li> </ul> </div> </div> <div class="rc-h-service-bar"> <div class="rc-h-inner"> <div class="rc-h-site-id"> <div class="rc-h-logo"><strong><a href="/"><img src="/shared/images/header/rc-h-logo.gif width="195 height="32 alt="楽天toto"/></a></strong></div> <div class="rc-h-title"><a href="/"><img src="/shared/images/header/bnr_title_no1.jpg alt="楽天はBIG1等当せん本数 第1位"/></a></div> <!--<div class="rc-h-icon"><img src="img/rc-h-icon.gif width="40 height="40 alt=""/></div>--> </div> <div class="rc-h-site-menu"> <div class="rc-h-menu-btns"> <ul class="rc-h-help-nav"> <li><a href="https://verify.rakuten.co.jp/">ご本人情報登録手続き</a></li> <li><a href="/beginner/">初めての方へ</a></li> <li><a href="/sitemap/sitemap.html">サイトマップ</a></li> <li><a href="https://toto.faq.rakuten.co.jp/app/">ヘルプ</a></li> </ul> <ul class="rc-h-action-nav"> <li><a href="/member/registTop/ class="rc-h-action-btn"><span class="rc-h-btn-icon rc-h-icon-beginner"></span><span class="rc-h-btn-label">利用登録</span></a></li> <li><a href="/my-toto/ class="rc-h-action-btn"><span class="rc-h-btn-icon rc-h-icon-mypage"></span><span class="rc-h-btn-label">マイページ</span></a></li> <li><a href="/member/history/historyList/ class="rc-h-action-btn"><span class="rc-h-btn-icon rc-h-icon-history"></span><span class="rc-h-btn-label">購入履歴・当せん結果</span></a></li> </ul> </div> <div class="rc-h-promotion"><a href="/"><img src="/shared/images/header/bnr_no1.jpg width="170 height="48 alt="楽天はBIG1等当せん本数 第1位"/></a></div> </div> </div> </div> <div class="rc-h-section-bar naviTop"> <div class="rc-h-inner"> <ul class="rc-h-section-nav"> <li><a href="/">トップ</a></li> <li><a href="/big/">BIG</a></li> <li><a href="/toto/ class="rc-h-active">toto</a></li> <li><a href="/tips/">totoBIG当せん虎の巻</a></li> <li><a href="/member/history/historyList/">購入履歴・当せん結果</a></li> <li><a href="/my-toto/">マイページ</a></li> <li><a href="/toto-hiroba/">toto予想ひろば</a></li> </ul> </div> </div> <div class="rc-h-subsection-bar naviToto"> <div class="rc-h-inner"> <ul class="rc-h-subsection-nav"> <li><a href="/toto/vote/totoChoiceSchedule/">totoを購入する</a></li> <li><a href="/toto/omakase/totoReservationSetCondition/">totoを定期購入する</a></li> <li><a href="/toto/schedule/">toto販売スケジュールをみる</a></li> <li><a href="/toto/result/">totoくじ結果をみる</a></li> </ul> </div> </div> </div> <script src="//jp.rakuten-static.com/1/js/lib/prm_selector_02.js"></script> <script src="/shared/js/rc-h-standard.js"></script> <p class="jsAttention">Java Scriptの設定がオンになっていないため、一部ご利用いただけない機能があります。<br>お手数ですが設定をオンにしてご利用ください。<br>※Java Script 設定方法は<a href="http://ichiba.faq.rakuten.co.jp/cgi-bin/rakuten_www.cfg/php/enduser/std_adp.php?p_faqid=154">楽天市場お問い合わせQ&amp;A</a>をご覧ください。</p> </noscript> <!-- contents --> <div id="str-contents"> <p class="topic-path"><a href="https://toto.rakuten.co.jp/">トップ</a> &gt; <a href="/toto/">toto</a> &gt; <a href="/toto/schedule/">toto販売スケジュール</a> &gt; 第923回totoくじ情報 </p> <div id="str-main"> <h1 class="hdg-l1-04"><span>totoくじ情報</span></h1> <h2 class="hdg-l2-04 extra"><span><span> 第923回 </span><span class="resultLink"><a href="/toto/schedule/">最新の販売スケジュール</a></span></span></h2> <div class="section-02"> <div id="totoBlock class="totoBlock"> <ul class="lotTypeList toto"> <li class="select"> toto </li> <li><a href="#minitotoBlockA">mini toto A組</a></li> <li><a href="#minitotoBlockB">mini toto B組</a></li> <li><a href="#totoGoal3Block">totoGOAL3</a></li> </ul> <div class="totoDetail"> <div class="totoDetailInner"> <h3 class="hdg-l3-03 extra"><span><span>販売予定/払戻日</span></span></h3> <table class="tbl-result-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">販売予定<br>結果発表</th> <th>販売開始日</th> <th>販売終了日</th> <th>結果発表確定日</th> </tr> <tr> <td>2017年4月15日(土)</td> <td>2017年4月22日(土)<br>(ネット13:50)</td> <td>2017年4月24日(月)</td> </tr> </table> <table class="tbl-basic-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">払戻日</th> <th>払戻開始日</th> <th>払戻期間</th> </tr> <tr> <td>2017年4月25日(火)</td> <td>2018年4月24日(火)</td> </tr> </table> <h3 class="hdg-l3-03 extra"><span><span>指定試合情報</span></span></h3> <table class="tbl-result border="1 cellspacing="0"> <thead> <tr> <th class="date">開催日</th> <th class="place">競技場</th> <th class="num">No</th> <th colspan="3 class="game">指定試合(ホームvsアウェイ)</th> </tr> </thead> <tbody> <tr> <td class="date">04/22</td> <td class="place">埼玉</td> <td class="num">1</td> <td class="home">浦和</td> <td class="vs">VS</td> <td class="away">札幌</td> </tr> <tr> <td class="date">04/22</td> <td class="place">中銀スタ</td> <td class="num">2</td> <td class="home">甲府</td> <td class="vs">VS</td> <td class="away">C大阪</td> </tr> <tr> <td class="date">04/22</td> <td class="place">Eスタ</td> <td class="num">3</td> <td class="home">広島</td> <td class="vs">VS</td> <td class="away">仙台</td> </tr> <tr> <td class="date">04/22</td> <td class="place">カシマ</td> <td class="num">4</td> <td class="home">鹿島</td> <td class="vs">VS</td> <td class="away">磐田</td> </tr> <tr> <td class="date">04/22</td> <td class="place">柏</td> <td class="num">5</td> <td class="home">柏</td> <td class="vs">VS</td> <td class="away">横浜M</td> </tr> <tr> <td class="date">04/22</td> <td class="place">デンカS</td> <td class="num">6</td> <td class="home">新潟</td> <td class="vs">VS</td> <td class="away">F東京</td> </tr> <tr> <td class="date">04/22</td> <td class="place">ベアスタ</td> <td class="num">7</td> <td class="home">鳥栖</td> <td class="vs">VS</td> <td class="away">神戸</td> </tr> <tr> <td class="date">04/22</td> <td class="place">パロ瑞穂</td> <td class="num">8</td> <td class="home">名古屋</td> <td class="vs">VS</td> <td class="away">山口</td> </tr> <tr> <td class="date">04/22</td> <td class="place">ニッパツ</td> <td class="num">9</td> <td class="home">横浜C</td> <td class="vs">VS</td> <td class="away">千葉</td> </tr> <tr> <td class="date">04/22</td> <td class="place">西京極</td> <td class="num">10</td> <td class="home">京都</td> <td class="vs">VS</td> <td class="away">松本</td> </tr> <tr> <td class="date">04/22</td> <td class="place">ニンスタ</td> <td class="num">11</td> <td class="home">愛媛</td> <td class="vs">VS</td> <td class="away">長崎</td> </tr> <tr> <td class="date">04/22</td> <td class="place">味スタ</td> <td class="num">12</td> <td class="home">東京V</td> <td class="vs">VS</td> <td class="away">群馬</td> </tr> <tr> <td class="date">04/22</td> <td class="place">町田</td> <td class="num">13</td> <td class="home">町田</td> <td class="vs">VS</td> <td class="away">徳島</td> </tr> </tbody> </table> </div> </div> </div> <div id="minitotoBlockA class="miniTotoBlock"> <ul class="lotTypeList minitoto"> <li><a href="#totoBlock">toto</a></li> <li class="select"> mini toto A組 </li> <li><a href="#minitotoBlockB">mini toto B組</a></li> <li><a href="#totoGoal3Block">totoGOAL3</a></li> </ul> <div class="miniTotoDetail"> <div class="miniTotoDetailInner"> <h3 class="hdg-l3-03 extra"><span><span>販売予定/払戻日</span></span></h3> <table class="tbl-result-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">販売予定<br>結果発表</th> <th>販売開始日</th> <th>販売終了日</th> <th>結果発表確定日</th> </tr> <tr> <td>2017年4月15日(土)</td> <td>2017年4月22日(土)<br>(ネット13:50)</td> <td>2017年4月24日(月)</td> </tr> </table> <table class="tbl-basic-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">払戻日</th> <th>払戻開始日</th> <th>払戻期間</th> </tr> <tr> <td>2017年4月25日(火)</td> <td>2018年4月24日(火)</td> </tr> </table> <h3 class="hdg-l3-03 extra"><span><span>指定試合情報</span></span></h3> <table class="tbl-result border="1 cellspacing="0"> <thead> <tr> <th class="date">開催日</th> <th class="place">競技場</th> <th class="num">No</th> <th colspan="3 class="game">指定試合(ホームvsアウェイ)</th> </tr> </thead> <tbody> <tr> <td class="date">04/22</td> <td class="place">埼玉</td> <td class="num">1</td> <td class="home">浦和</td> <td class="vs">VS</td> <td class="away">札幌</td> </tr> <tr> <td class="date">04/22</td> <td class="place">中銀スタ</td> <td class="num">2</td> <td class="home">甲府</td> <td class="vs">VS</td> <td class="away">C大阪</td> </tr> <tr> <td class="date">04/22</td> <td class="place">Eスタ</td> <td class="num">3</td> <td class="home">広島</td> <td class="vs">VS</td> <td class="away">仙台</td> </tr> <tr> <td class="date">04/22</td> <td class="place">カシマ</td> <td class="num">4</td> <td class="home">鹿島</td> <td class="vs">VS</td> <td class="away">磐田</td> </tr> <tr> <td class="date">04/22</td> <td class="place">柏</td> <td class="num">5</td> <td class="home">柏</td> <td class="vs">VS</td> <td class="away">横浜M</td> </tr> </tbody> </table> </div> </div> </div> <div id="minitotoBlockB class="miniTotoBlock"> <ul class="lotTypeList minitoto"> <li><a href="#totoBlock">toto</a></li> <li><a href="#minitotoBlockA">mini toto A組</a></li> <li class="select"> mini toto B組 </li> <li><a href="#totoGoal3Block">totoGOAL3</a></li> </ul> <div class="miniTotoDetail"> <div class="miniTotoDetailInner"> <h3 class="hdg-l3-03 extra"><span><span>販売予定/払戻日</span></span></h3> <table class="tbl-result-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">販売予定<br>結果発表</th> <th>販売開始日</th> <th>販売終了日</th> <th>結果発表確定日</th> </tr> <tr> <td>2017年4月15日(土)</td> <td>2017年4月22日(土)<br>(ネット13:50)</td> <td>2017年4月24日(月)</td> </tr> </table> <table class="tbl-basic-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">払戻日</th> <th>払戻開始日</th> <th>払戻期間</th> </tr> <tr> <td>2017年4月25日(火)</td> <td>2018年4月24日(火)</td> </tr> </table> <h3 class="hdg-l3-03 extra"><span><span>指定試合情報</span></span></h3> <table class="tbl-result border="1 cellspacing="0"> <thead> <tr> <th class="date">開催日</th> <th class="place">競技場</th> <th class="num">No</th> <th colspan="3 class="game">指定試合(ホームvsアウェイ)</th> </tr> </thead> <tbody> <tr> <td class="date">04/22</td> <td class="place">デンカS</td> <td class="num">1</td> <td class="home">新潟</td> <td class="vs">VS</td> <td class="away">F東京</td> </tr> <tr> <td class="date">04/22</td> <td class="place">ベアスタ</td> <td class="num">2</td> <td class="home">鳥栖</td> <td class="vs">VS</td> <td class="away">神戸</td> </tr> <tr> <td class="date">04/22</td> <td class="place">パロ瑞穂</td> <td class="num">3</td> <td class="home">名古屋</td> <td class="vs">VS</td> <td class="away">山口</td> </tr> <tr> <td class="date">04/22</td> <td class="place">ニッパツ</td> <td class="num">4</td> <td class="home">横浜C</td> <td class="vs">VS</td> <td class="away">千葉</td> </tr> <tr> <td class="date">04/22</td> <td class="place">西京極</td> <td class="num">5</td> <td class="home">京都</td> <td class="vs">VS</td> <td class="away">松本</td> </tr> </tbody> </table> </div> </div> </div> <div id="totoGoal3Block class="totoGoal3Block"> <ul class="lotTypeList totoGOAL"> <li><a href="#totoBlock">toto</a></li> <li><a href="#minitotoBlockA">mini toto A組</a></li> <li><a href="#minitotoBlockB">mini toto B組</a></li> <li class="select"> totoGOAL3 </li> </ul> <div class="totoGoal3Detail"> <div class="totoGoal3DetailInner"> <h3 class="hdg-l3-03 extra"><span><span>販売予定/払戻日</span></span></h3> <table class="tbl-result-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">販売予定<br>結果発表</th> <th>販売開始日</th> <th>販売終了日</th> <th>結果発表確定日</th> </tr> <tr> <td>2017年4月15日(土)</td> <td>2017年4月22日(土)<br>(ネット13:50)</td> <td>2017年4月24日(月)</td> </tr> </table> <table class="tbl-basic-day border="1 cellspacing="0"> <tr> <th rowspan="2 class="title">払戻日</th> <th>払戻開始日</th> <th>払戻期間</th> </tr> <tr> <td>2017年4月25日(火)</td> <td>2018年4月24日(火)</td> </tr> </table> <h3 class="hdg-l3-03 extra"><span><span>指定試合情報</span></span></h3> <table class="tbl-result border="1 cellspacing="0"> <thead> <tr> <th class="date">開催日</th> <th class="place">競技場</th> <th class="num">No</th> <th colspan="3 class="game">指定試合(ホームvsアウェイ)</th> </tr> </thead> <tbody> <tr> <td class="date">04/22</td> <td class="place">埼玉</td> <td class="num">1</td> <td class="home">浦和</td> <td class="vs">VS</td> <td class="away">札幌</td> </tr> <tr> <td class="date">04/22</td> <td class="place">中銀スタ</td> <td class="num">2</td> <td class="home">甲府</td> <td class="vs">VS</td> <td class="away">C大阪</td> </tr> <tr> <td class="date">04/22</td> <td class="place">柏</td> <td class="num">3</td> <td class="home">柏</td> <td class="vs">VS</td> <td class="away">横浜M</td> </tr> </tbody> </table> </div> </div> </div> <div class="extraBox"><span class="resultLink"><a href="/toto/schedule/">最新の販売スケジュール</a></span></div> </div> </div><!-- /str-main --> <div id="str-aside"> <div class="login"> <p class="btn-login"><a href="https://toto.rakuten.co.jp/member/registTop/?l-id=rightnavi_registtop"><img src="/shared/images/str-aside/btn-login-01.gif alt="利用登録 /></a></p> <p>楽天totoサービスを利用するには、楽天toto会員登録(無料)が必要です。</p> <ul class="btn-login-list"> <li><a href="https://toto.rakuten.co.jp/big/vote/bigChoiceSchedule/?l-id=rightnavi_big"><img src="/shared/images/str-aside/btn-big-01.gif alt="BIG購入 /></a></li> <li><a href="https://toto.rakuten.co.jp/big/omakase/bigReservationChoiceSchedule/?l-id=rightnavi_reservation"><img src="/shared/images/str-aside/btn-big-free-01.gif alt="おまかせBIG(予約登録) /></a></li> <li><a href="https://toto.rakuten.co.jp/toto/vote/totoChoiceSchedule/?l-id=rightnavi_toto"><img src="/shared/images/str-aside/btn-toto-01.gif alt="toto購入 /></a></li> <li><a href="https://toto.rakuten.co.jp/toto/omakase/totoReservationSetCondition/?l-id=rightnavi_omakasetoto"><img src="/shared/images/str-aside/btn-omakasetoto-01.gif alt="おまかせtoto(予約登録) /></a></li> </ul> <!-- /login --></div> <div class="box-01 toto-town"> <h2><img src="/shared/images/str-aside/hdg-01-01.gif alt="楽天toto売り場一覧 /></h2> <p><a href="/shoplist/?l-id=rightnavi_shoplist1"><img src="/shared/images/str-aside/img-tototown.gif alt="楽天toto売り場一覧 楽天totoタウン /></a></p> <p>楽天totoの売り場一覧は<a href="/shoplist/?l-id=rightnavi_shoplist2">楽天totoタウン</a>でチェック!過去の当せんデータも揃っています。</p> <!-- /toto-town --></div> <ul class="list-image-01"> <li><a href="/campaign/20170411/?l-id=rightnavi_cp1"><img src="/img/banner/bigchoice100/180x80.gif alt="【楽天toto】くじ購入で選べるBIGプレゼント!狙うは高額当せん金か当せんチャンスか? height="80 width="180 /></a></li> <li><a href="/campaign/20170331/?l-id=rightnavi_cp2"><img src="/img/banner/omakase_keep6/180x80.gif alt="【楽天toto】継続は力なり!「おまかせBIG」1ヶ月継続で現金最大6万円プレゼント! height="80 width="180 /></a></li> <li><a href="/program/omakase/?l-id=rightnavi_cp3"><img src="/shared/images/str-aside/img-bnr-pr-omakase.gif alt="自動購入!「おまかせBIG」ご優待!おまかせステージアッププログラム height="80 width="180 /></a></li> <!--<li><a href="/campaign/20170304b/?l-id=rightnavi_cp4"><img src="/img/banner/timesale/6oku_10bai/180x80.gif alt="【楽天toto】【39時間限定】全くじポイント10倍サンキューキャンペーン height="80 width="180 /></a></li>--> <!--<li><a href="http://event.rakuten.co.jp/group/groupday/vissel/ticket/?scid=wi_2016_toto_v2016groupday_toto_top target="_blank"><img src="/shared/images/str-aside/img-bnr-vissel-180x80.gif alt="楽天会員500名様に無料でサッカー観戦チケットプレゼント height="80 width="180 /></a></li>--> </ul> <div class="box-01 qr-code"> <h2><img src="/shared/images/str-aside/hdg-01-02.gif alt="モバイル版楽天toto /></h2> <p class="code">ケータイでtotoやBIGも購入できます。 <img src="/shared/images/str-aside/img-qr-mobile-02.gif alt=" /></p> <p><img src="/shared/images/str-aside/img-url-mobile-01.gif alt="https://m.toto.rakuten.co.jp/ /></p> <div class="other"> <ul class="list-socialmedia"> <li class="facebook"><a href="http://www.facebook.com/RakutenToto">楽天toto公式facebook</a></li> <li class="twitter"><a href="http://twitter.com/Rakuten_toto">楽天toto公式twitter</a></li> </ul> </div> <!-- footer --> <div id="grpRakutenLinkArea"><!-- ========== footer ========== --> <div class="rc-f-standard rc-f-liquid rc-f-custom00"> <div class="rc-f-section-content00"> <div class="rc-f-section-bar rc-f-first"> <div class="rc-f-inner"> <dl class="rc-f-dl-inline-box"> <dt class="rc-f-dl-title01 rc-f-text-em">楽天グループ</dt> <dd> <ul class="rc-f-list-inline"> <li><a href="http://www.rakuten.co.jp/sitemap/ class="rc-f-btn"><span>サービス一覧</span></a></li><li><a href="http://www.rakuten.co.jp/sitemap/inquiry.html class="rc-f-btn"><span>お問い合わせ一覧</span></a></li> </ul> </dd> </dl> </div> </div> <div class="rc-f-section-bar"> <div class="rc-f-inner"> <dl class="rc-f-dl-inline rc-f-block"> <dt class="rc-f-dl-title01">おすすめ</dt> <dd class="rc-f-text-strong id="grpRakutenRecommend"></dd> </dl> <ul class="rc-f-row rc-f-row-dot rc-f-row4"> <li class="rc-f-col rc-f-first"> <div class="rc-f-media rc-f-nav-item"> <div class="rc-f-media-head"><a href="http://news.www.infoseek.co.jp/sports/football/">Jリーグの試合結果をニュースで見る</a></div> <div class="rc-f-media-body">インフォシーク(ニュース)</div> </div> </li> <li class="rc-f-col"> <div class="rc-f-media rc-f-nav-item rc-f-nav-item-delimit"> <div class="rc-f-media-head"><a href="http://keiba.rakuten.co.jp">競馬もオンラインで楽しむ</a></div> <div class="rc-f-media-body">楽天競馬</div> </div> </li> <li class="rc-f-col"> <div class="rc-f-media rc-f-nav-item rc-f-nav-item-delimit"> <div class="rc-f-media-head"><a href="http://uranai.rakuten.co.jp/">自分の運勢を占ってみる</a></div> <div class="rc-f-media-body">楽天占い</div> </div> </li> <li class="rc-f-col"> <div class="rc-f-media rc-f-nav-item rc-f-nav-item-delimit"> <div class="rc-f-media-head"><a href="http://search.rakuten.co.jp/search/mall/%E9%96%8B%E9%81%8B%E3%82%A2%E3%82%A4%E3%83%86%E3%83%A0/%E5%8D%A0%E3%81%84%E3%83%BB%E9%96%8B%E9%81%8B%E3%83%BB%E9%A2%A8%E6%B0%B4%E3%83%BB%E3%83%91%E3%83%AF%E3%83%BC%E3%82%B9%E3%83%88%E3%83%BC%E3%83%B3-112132/s.1-sf.0-st.A-v.2">開運アイテムを購入する</a></div> <div class="rc-f-media-body">楽天市場</div> </div> </li> </ul> </div> </div><!-- /.rc-f-section-bar --> </div><!-- /.rc-f-section-content00 --> <div class="rc-f-section01"> <div class="rc-f-inner"> <ul class="rcf-list-inline rcf-list-block"> <li><a href="http://corp.rakuten.co.jp/ rel="nofollow">企業情報</a></li><li><a href="http://privacy.rakuten.co.jp/ rel="nofollow">個人情報保護方針</a></li><li><a href="http://corp.rakuten.co.jp/csr/">社会的責任[CSR]</a></li><li><a href="http://corp.rakuten.co.jp/careers/">採用情報</a></li> </ul> <p class="copyright">&copy; Rakuten, Inc.</p> </div> </div><!-- /.rc-f-section01 --> </div><!-- /.rc-f-standard --> <script type="text/javascript src="//jp.rakuten-static.com/1/js/grp/ftr/js/parm_selector_footer.js"></script> <!-- Google Remarketing tag --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 873995840; var google_custom_params = window.google_tag_params; var google_remarketing_only = true; /* ]]> */ </script> <script type="text/javascript src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1 width="1 style="border-style:none; alt=" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/873995840/?value=0&amp;guid=ON&amp;script=0"/> </div> </noscript> <!-- RAT tags For PC:--> <form class="ratForm name="ratForm id="ratForm style="display:none;"> <input type="hidden name="rat id="ratAccountId value="1020"> <input type="hidden name="rat id="ratServiceId value="1"> <input type="hidden name="rat id="ratServiceType value="toto"> <input type="hidden name="rat id="ratPageLayout value="pc"> </form> <script type="text/javascript src="//r.r10s.jp/com/rat/js/rat-main.js async defer></script> </div> </div> <!-- SiteCatalyst code Copyright Omniture, Inc. More info available at http://www.omniture.com --> <script type="text/javascript"><!-- if(typeof(s_account)=="undefined"){ var scHost=(("https:"==document.location.protocol)?"s":"") document.write(unescape("%3Cscript src='http"+scHost+"://jp.rakuten-static.com/1/js/anl/tto/s_code.js?20100601' type='text/javascript'%3E%3C/script%3E"))} //--></script> <script type="text/javascript"><!-- void(s.t())//--></script> <!-- End SiteCatalyst --> </body> </html>" """ }
apache-2.0
fc4688923365252f7049e5d2a9787348
46.410819
353
0.469426
2.952923
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/intentions/intentionUtil.kt
14
1008
// 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 org.jetbrains.plugins.groovy.annotator.intentions import com.intellij.psi.PsiElement /** * Appends [text] to the [builder] cutting length of [left] text from the start and length of [right] text from the end. */ internal fun appendTextBetween(builder: StringBuilder, text: String, left: PsiElement?, right: PsiElement?) { val start = left?.textLength ?: 0 val end = text.length - (right?.textLength ?: 0) builder.append(text, start, end) } /** * Appends text of elements to the [builder] between [start] and [stop]. * If [stop] is `null` then all siblings of [start] are processed. */ internal fun appendElements(builder: StringBuilder, start: PsiElement, stop: PsiElement) { var current: PsiElement? = start.nextSibling while (current !== null && current !== stop) { builder.append(current.text) current = current.nextSibling } }
apache-2.0
5abd6efa94fc9dd735fe3e0b94951b7b
39.32
140
0.722222
3.876923
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionFacadeWithDebugInfo.kt
2
9988
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.ResolverForProject import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments private class ResolutionFacadeWithDebugInfo( private val delegate: ResolutionFacade, private val creationPlace: CreationPlace ) : ResolutionFacade, ResolutionFacadeModuleDescriptorProvider { override fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor { return delegate.findModuleDescriptor(ideaModuleInfo) } override val project: Project get() = delegate.project override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext { return wrapExceptions({ ResolvingWhat(element, bodyResolveMode = bodyResolveMode) }) { delegate.analyze(element, bodyResolveMode) } } override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext { return wrapExceptions({ ResolvingWhat(elements = elements, bodyResolveMode = bodyResolveMode) }) { delegate.analyze(elements, bodyResolveMode) } } override fun analyzeWithAllCompilerChecks( element: KtElement, callback: DiagnosticSink.DiagnosticsCallback? ): AnalysisResult { return wrapExceptions({ ResolvingWhat(element) }) { delegate.analyzeWithAllCompilerChecks(element, callback) } } override fun analyzeWithAllCompilerChecks( elements: Collection<KtElement>, callback: DiagnosticSink.DiagnosticsCallback? ): AnalysisResult { return wrapExceptions({ ResolvingWhat(elements = elements) }) { delegate.analyzeWithAllCompilerChecks(elements, callback) } } override fun fetchWithAllCompilerChecks(element: KtElement): AnalysisResult? { return wrapExceptions({ ResolvingWhat(element = element) }) { delegate.fetchWithAllCompilerChecks(element) } } override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor { return wrapExceptions({ ResolvingWhat(declaration, bodyResolveMode = bodyResolveMode) }) { delegate.resolveToDescriptor(declaration, bodyResolveMode) } } override val moduleDescriptor: ModuleDescriptor get() = delegate.moduleDescriptor @FrontendInternals override fun <T : Any> getFrontendService(serviceClass: Class<T>): T { return wrapExceptions({ ResolvingWhat(serviceClass = serviceClass) }) { delegate.getFrontendService(serviceClass) } } override fun <T : Any> getIdeService(serviceClass: Class<T>): T { return wrapExceptions({ ResolvingWhat(serviceClass = serviceClass) }) { delegate.getIdeService(serviceClass) } } @FrontendInternals override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T { return wrapExceptions({ ResolvingWhat(element, serviceClass = serviceClass) }) { delegate.getFrontendService(element, serviceClass) } } @FrontendInternals override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? { return wrapExceptions({ ResolvingWhat(element, serviceClass = serviceClass) }) { delegate.tryGetFrontendService(element, serviceClass) } } override fun getResolverForProject(): ResolverForProject<out ModuleInfo> { return delegate.getResolverForProject() } @FrontendInternals override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T { return wrapExceptions({ ResolvingWhat(serviceClass = serviceClass, moduleDescriptor = moduleDescriptor) }) { delegate.getFrontendService(moduleDescriptor, serviceClass) } } private inline fun <R> wrapExceptions(resolvingWhat: () -> ResolvingWhat, body: () -> R): R { try { return body() } catch (e: Throwable) { if (e is ControlFlowException || e is IndexNotReadyException) { throw e } throw KotlinIdeaResolutionException(e, resolvingWhat(), creationPlace) } } } private class KotlinIdeaResolutionException( cause: Throwable, resolvingWhat: ResolvingWhat, creationPlace: CreationPlace ) : KotlinExceptionWithAttachments("Kotlin resolution encountered a problem while ${resolvingWhat.shortDescription()}", cause) { init { withAttachment("info.txt", buildString { append(resolvingWhat.description()) appendLine("---------------------------------------------") append(creationPlace.description()) }) for (element in resolvingWhat.elements.withIndex()) { withPsiAttachment("element${element.index}.kt", element.value) withPsiAttachment( "file${element.index}.kt", element.value.containingFile ) } } } private class CreationPlace( private val elements: Collection<KtElement>, private val moduleInfo: ModuleInfo?, private val settings: PlatformAnalysisSettings? ) { fun description() = buildString { appendLine("Resolver created for:") for (element in elements) { appendElement(element) } if (moduleInfo != null) { appendLine("Provided module info: $moduleInfo") } if (settings != null) { appendLine("Provided settings: $settings") } } } private class ResolvingWhat( val element: PsiElement? = null, val elements: Collection<PsiElement> = emptyList(), private val bodyResolveMode: BodyResolveMode? = null, private val serviceClass: Class<*>? = null, private val moduleDescriptor: ModuleDescriptor? = null ) { fun shortDescription() = serviceClass?.let { "getting service ${serviceClass.simpleName}" } ?: "analyzing ${(element ?: elements.firstOrNull())?.javaClass?.simpleName ?: ""}" fun description(): String { return buildString { appendLine("Failed performing task:") if (serviceClass != null) { appendLine("Getting service: ${serviceClass.name}") } else { append("Analyzing code") if (bodyResolveMode != null) { append(" in BodyResolveMode.$bodyResolveMode") } appendLine() } appendLine("Elements:") element?.let { appendElement(it) } for (element in elements) { appendElement(element) } if (moduleDescriptor != null) { appendLine("Provided module descriptor for module ${moduleDescriptor.getCapability(ModuleInfo.Capability)}") } } } } private fun StringBuilder.appendElement(element: PsiElement) { fun info(key: String, value: String?) { appendLine(" $key = $value") } appendLine("Element of type: ${element.javaClass.simpleName}:") if (element is PsiNamedElement) { info("name", element.name) } info("isValid", element.isValid.toString()) info("isPhysical", element.isPhysical.toString()) if (element is PsiFile) { info("containingFile.name", element.containingFile.name) } val moduleInfoResult = ifIndexReady { element.moduleInfoOrNull } info("moduleInfo", moduleInfoResult?.let { it.result?.toString() ?: "null" } ?: "<index not ready>") val moduleInfo = moduleInfoResult?.result if (moduleInfo != null) { info("moduleInfo.platform", moduleInfo.platform.toString()) } val virtualFile = element.containingFile?.virtualFile info("virtualFile", virtualFile?.name) if (virtualFile != null) { val moduleName = ifIndexReady { ModuleUtil.findModuleForFile(virtualFile, element.project)?.name ?: "null" }?.result info( "ideaModule", moduleName ?: "<index not ready>" ) } } private class IndexResult<T>(val result: T) private fun <T> ifIndexReady(body: () -> T): IndexResult<T>? = try { IndexResult(body()) } catch (e: IndexNotReadyException) { null } internal fun ResolutionFacade.createdFor( files: Collection<KtFile>, moduleInfo: ModuleInfo?, settings: PlatformAnalysisSettings ): ResolutionFacade { return ResolutionFacadeWithDebugInfo(this, CreationPlace(files, moduleInfo, settings)) }
apache-2.0
d254f9fa040740239ea8911ad3080c54
37.415385
158
0.685222
5.207508
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-fir/src/org/jetbrains/uast/kotlin/FirKotlinUastLanguagePlugin.kt
2
4285
// 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.uast.kotlin import com.intellij.lang.Language import com.intellij.openapi.components.ServiceManager import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.* import org.jetbrains.uast.DEFAULT_TYPES_LIST import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UastLanguagePlugin import org.jetbrains.uast.kotlin.FirKotlinConverter.convertDeclarationOrElement import org.jetbrains.uast.kotlin.psi.UastFakeLightPrimaryConstructor import org.jetbrains.uast.util.ClassSet import org.jetbrains.uast.util.ClassSetsWrapper class FirKotlinUastLanguagePlugin : UastLanguagePlugin { override val priority: Int = 10 override val language: Language get() = KotlinLanguage.INSTANCE override fun isFileSupported(fileName: String): Boolean { return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false) } private val PsiElement.isJvmElement: Boolean get() { val resolveProvider = ServiceManager.getService(project, FirKotlinUastResolveProviderService::class.java) return resolveProvider.isJvmElement(this) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { if (!element.isJvmElement) return null return convertDeclarationOrElement(element, parent, elementTypes(requiredType)) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { if (!element.isJvmElement) return null return convertDeclarationOrElement(element, null, elementTypes(requiredType)) } override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = when (uastTypes.size) { 0 -> getPossibleSourceTypes(UElement::class.java) 1 -> getPossibleSourceTypes(uastTypes.single()) else -> ClassSetsWrapper(Array(uastTypes.size) { getPossibleSourceTypes(uastTypes[it]) }) } @Suppress("UNCHECKED_CAST") override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? { if (!element.isJvmElement) return null val nonEmptyRequiredTypes = requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST) return convertDeclarationOrElement(element, null, nonEmptyRequiredTypes) as? T } @Suppress("UNCHECKED_CAST") override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> { if (!element.isJvmElement) return emptySequence() return when { element is KtFile -> FirKotlinConverter.convertKtFile(element, null, requiredTypes) as Sequence<T> element is KtClassOrObject -> FirKotlinConverter.convertClassOrObject(element, null, requiredTypes) as Sequence<T> element is KtProperty && !element.isLocal -> FirKotlinConverter.convertNonLocalProperty(element, null, requiredTypes) as Sequence<T> element is KtParameter -> FirKotlinConverter.convertParameter(element, null, requiredTypes) as Sequence<T> element is UastFakeLightPrimaryConstructor -> FirKotlinConverter.convertFakeLightConstructorAlternatives(element, null, requiredTypes) as Sequence<T> else -> sequenceOf(convertElementWithParent(element, requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)) as? T).filterNotNull() } } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { TODO("Not yet implemented") } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { TODO("Not yet implemented") } override fun isExpressionValueUsed(element: UExpression): Boolean { TODO("Not yet implemented") } }
apache-2.0
4bc5d033475ee06c4bf2d65522d878b6
43.635417
129
0.71902
5.059032
false
false
false
false
ktorio/ktor
ktor-io/common/src/io/ktor/utils/io/charsets/Encoding.kt
1
6098
package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* public expect abstract class Charset { public abstract fun newEncoder(): CharsetEncoder public abstract fun newDecoder(): CharsetDecoder public companion object { public fun forName(name: String): Charset public fun isSupported(charset: String): Boolean } } public expect val Charset.name: String // ----------------------------- ENCODER ------------------------------------------------------------------------------- public expect abstract class CharsetEncoder public expect val CharsetEncoder.charset: Charset @Deprecated( "Use writeText on Output instead.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith( "dst.writeText(input, fromIndex, toIndex, charset)", "io.ktor.utils.io.core.writeText" ) ) public fun CharsetEncoder.encode(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Output) { encodeToImpl(dst, input, fromIndex, toIndex) } public expect fun CharsetEncoder.encodeToByteArray( input: CharSequence, fromIndex: Int = 0, toIndex: Int = input.length ): ByteArray @Deprecated( "Internal API. Will be hidden in future releases. Use encodeToByteArray instead.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("encodeToByteArray(input, fromIndex, toIndex)") ) public fun CharsetEncoder.encodeToByteArrayImpl( input: CharSequence, fromIndex: Int = 0, toIndex: Int = input.length ): ByteArray { return encodeToByteArray(input, fromIndex, toIndex) } public expect fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) public fun CharsetEncoder.encode( input: CharSequence, fromIndex: Int = 0, toIndex: Int = input.length ): ByteReadPacket = buildPacket { encodeToImpl(this, input, fromIndex, toIndex) } public fun CharsetEncoder.encodeUTF8(input: ByteReadPacket): ByteReadPacket = buildPacket { encodeUTF8(input, this) } public fun CharsetEncoder.encode(input: CharArray, fromIndex: Int, toIndex: Int, dst: Output) { var start = fromIndex if (start >= toIndex) return dst.writeWhileSize(1) { view: Buffer -> val rc = encodeArrayImpl(input, start, toIndex, view) check(rc >= 0) start += rc when { start >= toIndex -> 0 rc == 0 -> 8 else -> 1 } } encodeCompleteImpl(dst) } // ----------------------------- DECODER ------------------------------------------------------------------------------- public expect abstract class CharsetDecoder /** * Decoder's charset it is created for. */ public expect val CharsetDecoder.charset: Charset public fun CharsetDecoder.decode(input: Input, max: Int = Int.MAX_VALUE): String = buildString(minOf(max.toLong(), input.sizeEstimate()).toInt()) { decode(input, this, max) } public expect fun CharsetDecoder.decode(input: Input, dst: Appendable, max: Int): Int public expect fun CharsetDecoder.decodeExactBytes(input: Input, inputLength: Int): String // ----------------------------- REGISTRY ------------------------------------------------------------------------------ public expect object Charsets { public val UTF_8: Charset public val ISO_8859_1: Charset } public expect open class MalformedInputException(message: String) : Throwable public class TooLongLineException(message: String) : MalformedInputException(message) // ----------------------------- INTERNALS ----------------------------------------------------------------------------- internal fun CharsetEncoder.encodeArrayImpl(input: CharArray, fromIndex: Int, toIndex: Int, dst: Buffer): Int { val length = toIndex - fromIndex return encodeImpl(CharArraySequence(input, fromIndex, length), 0, length, dst) } internal expect fun CharsetEncoder.encodeImpl(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Buffer): Int internal expect fun CharsetEncoder.encodeComplete(dst: Buffer): Boolean internal expect fun CharsetDecoder.decodeBuffer( input: Buffer, out: Appendable, lastBuffer: Boolean, max: Int = Int.MAX_VALUE ): Int internal fun CharsetEncoder.encodeToByteArrayImpl1( input: CharSequence, fromIndex: Int = 0, toIndex: Int = input.length ): ByteArray { var start = fromIndex if (start >= toIndex) return EmptyByteArray val single = ChunkBuffer.Pool.borrow() try { val rc = encodeImpl(input, start, toIndex, single) start += rc if (start == toIndex) { val result = ByteArray(single.readRemaining) single.readFully(result) return result } return buildPacket { appendSingleChunk(single.duplicate()) encodeToImpl(this, input, start, toIndex) }.readBytes() } finally { single.release(ChunkBuffer.Pool) } } internal fun Input.sizeEstimate(): Long = when (this) { is ByteReadPacket -> remaining else -> maxOf(remaining, 16) } private fun CharsetEncoder.encodeCompleteImpl(dst: Output): Int { var size = 1 var bytesWritten = 0 dst.writeWhile { view -> val before = view.writeRemaining if (encodeComplete(view)) { size = 0 } else { size++ } bytesWritten += before - view.writeRemaining size > 0 } return bytesWritten } internal fun CharsetEncoder.encodeToImpl( destination: Output, input: CharSequence, fromIndex: Int, toIndex: Int ): Int { var start = fromIndex if (start >= toIndex) return 0 var bytesWritten = 0 destination.writeWhileSize(1) { view: Buffer -> val before = view.writeRemaining val rc = encodeImpl(input, start, toIndex, view) check(rc >= 0) start += rc bytesWritten += before - view.writeRemaining when { start >= toIndex -> 0 rc == 0 -> 8 else -> 1 } } bytesWritten += encodeCompleteImpl(destination) return bytesWritten }
apache-2.0
12f73abcfbafdc9e330269a9dc1a7eb2
27.900474
120
0.625615
4.651411
false
false
false
false
chiclaim/android-sample
language-kotlin/kotlin-sample/kotlin-in-action/src/lambda/KotlinLambdaModifyVariable.kt
1
1723
package lambda /** * desc: 修改Lambda外部的变量 演示 * * Created by Chiclaim on 2018/09/22 */ //----forEach底层是通过iterator来遍历的,并不是通过内部类来实现的,所以可以修改lambda外面的变量 fun printGoods(prefix: String, goods: List<String>) { var count = 0 goods.forEach { goodName -> count++ println("$prefix $goodName") } println("goods count: $count") } //---- 下面的例子把Lambda赋值给变量inc,由于在lambda中没有使用额外的参数,底层是使用Function0来实现的 //在下面的lambda底层是通过匿名内部类来实现的,我们知道内部类是修改不了外面的变量的,那么它是如何修改外面的counter变量呢? //通过把外面的变量包装一层,修改的时候,通过包装对象来修改,然后返回修改后的变量值 //在Kotlin中通过Ref包装类,如果是整型则是IntRef,如果是复杂类型则是ObjectRef fun printCount() { var counter = 0 //把Lambda赋值给变量 val inc = { ++counter } println(inc()) } /* public static final void printCount() { final IntRef counter = new IntRef(); counter.element = 0; Function0 inc = (Function0)(new Function0() { public Object invoke() { return this.invoke(); } public final int invoke() { IntRef var10000 = counter; ++counter.element; return var10000.element; } }); int var2 = ((Number)inc.invoke()).intValue(); System.out.println(var2); } */ fun main(args: Array<String>) { printGoods("china", listOf("telephone", "tv")) printCount() }
apache-2.0
4a7db6d78572da80468ea0ea6bec7ea9
21
68
0.623199
3.096244
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ResponseConverter.kt
1
4215
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.contentnegotiation import io.ktor.http.* import io.ktor.http.content.* import io.ktor.serialization.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.utils.io.charsets.* private val NOT_ACCEPTABLE = HttpStatusCodeContent(HttpStatusCode.NotAcceptable) internal fun PluginBuilder<ContentNegotiationConfig>.convertResponseBody() = onCallRespond { call, subject -> if (subject is OutgoingContent) { LOGGER.trace("Skipping because body is already converted.") return@onCallRespond } if (pluginConfig.ignoredTypes.any { it.isInstance(subject) }) { LOGGER.trace("Skipping because the type is ignored.") return@onCallRespond } val responseType = call.response.responseType ?: return@onCallRespond val registrations = pluginConfig.registrations val checkAcceptHeader = pluginConfig.checkAcceptHeaderCompliance transformBody { val acceptHeader = call.parseAcceptHeader() val acceptItems: List<ContentTypeWithQuality> = [email protected] .acceptContributors .fold(acceptHeader) { result, contributor -> contributor(call, result) } .distinct() .sortedByQuality() val suitableConverters = if (acceptItems.isEmpty()) { // all converters are suitable since client didn't indicate what it wants registrations } else { // select converters that match specified Accept header, in order of quality acceptItems.flatMap { (contentType, _) -> registrations.filter { it.contentType.match(contentType) } }.distinct() } val acceptCharset = call.request.headers.suitableCharsetOrNull() // Pick the first one that can convert the subject successfully for (registration in suitableConverters) { val contentType = acceptCharset?.let { charset -> registration.contentType.withCharset(charset) } val result = registration.converter.serializeNullable( contentType = contentType ?: registration.contentType, charset = acceptCharset ?: Charsets.UTF_8, typeInfo = responseType, value = subject.takeIf { it != NullBody } ) if (result == null) { LOGGER.trace("Can't convert body $subject with ${registration.converter}") continue } val transformedContent = transformDefaultContent(call, result) if (transformedContent == null) { LOGGER.trace("Can't convert body $subject with ${registration.converter}") continue } if (checkAcceptHeader && !checkAcceptHeader(acceptItems, transformedContent.contentType)) { LOGGER.trace( "Can't send content with ${transformedContent.contentType} to client " + "because it is not acceptable" ) return@transformBody NOT_ACCEPTABLE } return@transformBody transformedContent } LOGGER.trace( "No suitable content converter found for response type ${responseType.type}" + " and body $subject" ) return@transformBody subject } } /** * Returns a list of content types sorted by the quality, number of asterisks, and number of parameters. * @see parseAndSortContentTypeHeader */ private fun List<ContentTypeWithQuality>.sortedByQuality(): List<ContentTypeWithQuality> = sortedWith( compareByDescending<ContentTypeWithQuality> { it.quality }.thenBy { val contentType = it.contentType var asterisks = 0 if (contentType.contentType == "*") { asterisks += 2 } if (contentType.contentSubtype == "*") { asterisks++ } asterisks }.thenByDescending { it.contentType.parameters.size } )
apache-2.0
183acd87f818acc828fb8086ee00574e
36.633929
119
0.638671
5.072202
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/stb/src/templates/kotlin/stb/templates/stb_image_write.kt
4
9816
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package stb.templates import org.lwjgl.generator.* import stb.* val stb_image_write = "STBImageWrite".nativeClass(Module.STB, prefix = "STBI", prefixMethod = "stbi_") { includeSTBAPI( """#include "lwjgl_malloc.h" #define STBIW_MALLOC(sz) org_lwjgl_malloc(sz) #define STBIW_REALLOC(p,sz) org_lwjgl_realloc(p,sz) #define STBIW_FREE(p) org_lwjgl_free(p) #define STBIW_ASSERT(x) #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_STATIC #ifdef LWJGL_WINDOWS #define STBIW_WINDOWS_UTF8 #define STBI_MSC_SECURE_CRT #endif #include "stb_image_write.h"""") documentation = """ Native bindings to stb_image_write.h from the ${url("https://github.com/nothings/stb", "stb library")}. <h3>ABOUT</h3> This header file is a library for writing images to C stdio. The PNG output is not optimal; it is 20-50% larger than the file written by a decent optimizing implementation; though providing a custom zlib compress function (see #zlib_compress()) can mitigate that. This library is designed for source code compactness and simplicity, not optimal image file size or run-time performance. <h3>USAGE</h3> There are five functions, one for each image file format: ${codeBlock(""" int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); int stbi_write_hdr(char const *filename, int w, int h, int comp, const void *data); int stbi_write_jpg(char const *filename, int w, int h, int comp, const float *data, int quality); void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically""")} There are also five equivalent functions that use an arbitrary write function. You are expected to open/close your file-equivalent before and after calling these: ${codeBlock(""" int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);""")} where the callback is: ${codeBlock(""" void stbi_write_func(void *context, void *data, int size);""")} You can configure it with these global variables: ${codeBlock(""" int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode""")} The functions create an image file defined by the parameters. The image is a rectangle of pixels stored from left-to-right, top-to-bottom. Each pixel contains {@code comp} channels of data stored interleaved with 8-bits per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is {@code w} pixels wide and {@code h} pixels tall. The {@code *data} pointer points to the first byte of the top-left-most pixel. """ val write = intb( "write_png", """ Writes a PNR image file. PNG creates output files with the same number of components as the input. PNG supports writing rectangles of data even when the bytes storing rows of data are not consecutive in memory (e.g. sub-rectangles of a larger image), by supplying the stride between the beginning of adjacent rows. The other formats do not. (Thus you cannot write a native-format BMP through the BMP writer, both because it is in BGR order and because it may have padding at the end of the line.) PNG allows you to set the deflate compression level by setting the global variable #write_png_compression_level() (it defaults to 8). """, charUTF8.const.p("filename", "the image file path"), int("w", "the image width, in pixels"), int("h", "the image height, in pixels"), int("comp", "the number of channels in each pixel"), Check("(stride_in_bytes != 0 ? stride_in_bytes : w * comp) * h")..void.const.p("data", "the image data"), int("stride_in_bytes", "the distance in bytes from the first byte of a row of pixels to the first byte of the next row of pixels"), returnDoc = "1 on success, 0 on failure" ) macro..Address..int.p( "write_png_compression_level", "Returns the address of the global variable {@code stbi_write_png_compression_level}.", void() ) macro..Address..int.p( "write_force_png_filter", "Returns the address of the global variable {@code stbi_write_force_png_filter}.", void() ) macro..Address..stbi_zlib_compress.p( "zlib_compress", """ Returns the address of the global variable {@code stbi_zlib_compress}. The address of an ##STBIZlibCompress instance may be set to this variable, in order to override the Zlib compression implementation. """, void() ) intb( "write_bmp", """ Writes a BMP image file. The BMP format expands Y to RGB in the file format and does not output alpha. """, write["filename"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), returnDoc = "1 on success, 0 on failure" ) intb( "write_tga", """ Writes a TGA image file. TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed data, set the global variable {@code stbi_write_tga_with_rle} to 0. The variable can be accessed with #write_tga_with_rle(). """, write["filename"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), returnDoc = "1 on success, 0 on failure" ) macro..Address..int.p( "write_tga_with_rle", "Returns the address of the global variable {@code stbi_write_tga_with_rle}.", void() ) val write_hdr = intb( "write_hdr", """ Writes an HDR image file. HDR expects linear float data. Since the format is always 32-bit rgb(e) data, alpha (if provided) is discarded, and for monochrome data it is replicated across all three channels. """, write["filename"], write["w"], write["h"], write["comp"], Check("w * h * comp")..float.const.p("data", "the image data"), returnDoc = "1 on success, 0 on failure" ) val write_jpg = intb( "write_jpg", """ Writes a JPEG image file. JPEG does ignore alpha channels in input data; quality is between 1 and 100. Higher quality looks better but results in a bigger image. JPEG baseline (no JPEG progressive). """, write["filename"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), int("quality", "the compression quality"), returnDoc = "1 on success, 0 on failure" ) val write_to_func = intb( "write_png_to_func", "Callback version of #write_png().", stbi_write_func("func", "the callback function"), nullable..opaque_p("context", "a context that will be passed to {@code func}"), write["w"], write["h"], write["comp"], write["data"], write["stride_in_bytes"], returnDoc = "1 on success, 0 on failure" ) intb( "write_bmp_to_func", "Callback version of #write_bmp().", write_to_func["func"], write_to_func["context"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), returnDoc = "1 on success, 0 on failure" ) intb( "write_tga_to_func", "Callback version of #write_tga().", write_to_func["func"], write_to_func["context"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), returnDoc = "1 on success, 0 on failure" ) intb( "write_hdr_to_func", "Callback version of #write_hdr().", write_to_func["func"], write_to_func["context"], write["w"], write["h"], write["comp"], write_hdr["data"], returnDoc = "1 on success, 0 on failure" ) int( "write_jpg_to_func", "Callback version of #write_jpg().", write_to_func["func"], write_to_func["context"], write["w"], write["h"], write["comp"], Check("w * h * comp")..void.const.p("data", "the image data"), write_jpg["quality"], returnDoc = "1 on success, 0 on failure" ) void( "flip_vertically_on_write", "Configures if the written image should flipped vertically.", intb("flip_boolean", "true to flip data vertically") ) }
bsd-3-clause
6dd0e098966ff49741c50d7affde2c98
34.959707
159
0.608191
3.768138
false
false
false
false
google/android-fhir
contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/barcodedetection/BarcodeProcessor.kt
1
4931
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.barcodedetection import android.animation.ValueAnimator import androidx.annotation.MainThread import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.InputInfo import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.Utils.getBarcodeScanningClient import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.CameraReticleAnimator import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.FrameProcessorBase import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.GraphicOverlay import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.WorkflowModel import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.WorkflowModel.WorkflowState import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.settings.PreferenceUtils import com.google.android.gms.tasks.Task import com.google.mlkit.vision.barcode.Barcode import com.google.mlkit.vision.common.InputImage import java.io.IOException import timber.log.Timber /** A processor to run the barcode detector. */ class BarcodeProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) : FrameProcessorBase<List<Barcode>>() { private val scanner = getBarcodeScanningClient() private val cameraReticleAnimator: CameraReticleAnimator = CameraReticleAnimator(graphicOverlay) override fun detectInImage(image: InputImage): Task<List<Barcode>> = scanner.process(image) @MainThread override fun onSuccess( inputInfo: InputInfo, results: List<Barcode>, graphicOverlay: GraphicOverlay ) { if (!workflowModel.isCameraLive) return Timber.d("Barcode result size: ${results.size}") // Picks the barcode, if exists, that covers the center of graphic overlay. val barcodeInCenter = results.firstOrNull { barcode -> val boundingBox = barcode.boundingBox ?: return@firstOrNull false val box = graphicOverlay.translateRect(boundingBox) box.contains(graphicOverlay.width / 2f, graphicOverlay.height / 2f) } graphicOverlay.clear() if (barcodeInCenter == null) { cameraReticleAnimator.start() graphicOverlay.add(BarcodeReticleGraphic(graphicOverlay, cameraReticleAnimator)) workflowModel.setWorkflowState(WorkflowState.DETECTING) } else { cameraReticleAnimator.cancel() val sizeProgress = PreferenceUtils.getProgressToMeetBarcodeSizeRequirement(graphicOverlay, barcodeInCenter) if (sizeProgress < 1) { // Barcode in the camera view is too small, so prompt user to move camera closer. graphicOverlay.add(BarcodeConfirmingGraphic(graphicOverlay, barcodeInCenter)) workflowModel.setWorkflowState(WorkflowState.CONFIRMING) } else { // Barcode size in the camera view is sufficient. if (PreferenceUtils.shouldDelayLoadingBarcodeResult(graphicOverlay.context)) { val loadingAnimator = createLoadingAnimator(graphicOverlay, barcodeInCenter) loadingAnimator.start() graphicOverlay.add(BarcodeLoadingGraphic(graphicOverlay, loadingAnimator)) workflowModel.setWorkflowState(WorkflowState.SEARCHING) } else { workflowModel.setWorkflowState(WorkflowState.DETECTED) workflowModel.detectedBarcode.setValue(barcodeInCenter) } } } graphicOverlay.invalidate() } private fun createLoadingAnimator( graphicOverlay: GraphicOverlay, barcode: Barcode ): ValueAnimator { val endProgress = 1.1f return ValueAnimator.ofFloat(0f, endProgress).apply { duration = 2000 addUpdateListener { if ((animatedValue as Float).compareTo(endProgress) >= 0) { graphicOverlay.clear() workflowModel.setWorkflowState(WorkflowState.SEARCHED) workflowModel.detectedBarcode.setValue(barcode) } else { graphicOverlay.invalidate() } } } } override fun onFailure(e: Exception) { Timber.e("Barcode detection failed!", e) } override fun stop() { super.stop() try { scanner.close() } catch (e: IOException) { Timber.e("Failed to close barcode detector!", e) } } }
apache-2.0
29a9c90cc86bd45e8e612bcab598c864
38.766129
108
0.744677
4.536339
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/GroovyKeywordAnnotator.kt
1
2623
// 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.groovy.highlighter import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.project.DumbAware import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.lexer.TokenSets import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement /** * Groovy allows keywords to appear in various places such as FQNs, reference names, labels, etc. * Syntax highlighter highlights all of them since it's based on lexer, which has no clue which keyword is really a keyword. * This knowledge becomes available only after parsing. * * This annotator clears text attributes for elements which are not really keywords. */ class GroovyKeywordAnnotator : Annotator, DumbAware { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (shouldBeErased(element)) { holder.createInfoAnnotation(element, null).enforcedTextAttributes = TextAttributes.ERASE_MARKER } } } fun shouldBeErased(element: PsiElement): Boolean { val tokenType = element.node.elementType if (tokenType !in TokenSets.KEYWORDS) return false // do not touch other elements val parent = element.parent if (parent is GrArgumentLabel) { // don't highlight: print (void:'foo') return true } else if (PsiTreeUtil.getParentOfType(element, GrCodeReferenceElement::class.java) != null) { if (TokenSets.CODE_REFERENCE_ELEMENT_NAME_TOKENS.contains(tokenType)) { return true // it is allowed to name packages 'as', 'in', 'def' or 'trait' } } else if (tokenType === GroovyTokenTypes.kDEF && element.parent is GrAnnotationNameValuePair) { return true } else if (parent is GrReferenceExpression && element === parent.referenceNameElement) { if (tokenType === GroovyTokenTypes.kSUPER && parent.qualifier == null) return false if (tokenType === GroovyTokenTypes.kTHIS && parent.qualifier == null) return false return true // don't highlight foo.def } return false }
apache-2.0
697b28a6706161025d3c18e1c177b7e1
45.017544
140
0.77621
4.364393
false
false
false
false
theapache64/Mock-API
src/com/theah64/mock_api/database/Params.kt
1
6308
package com.theah64.mock_api.database import com.theah64.mock_api.models.Param import com.theah64.mock_api.models.Route import com.theah64.webengine.database.BaseTable import com.theah64.webengine.database.Connection import java.sql.SQLException import java.util.ArrayList /** * Created by theapache64 on 30/11/17. */ class Params private constructor() : BaseTable<Param>("params") { @Throws(SQLException::class) fun addParamsFromRoute(route: Route) { var error: String? = null val con = Connection.getConnection() try { addParams(con, route.id!!, route.params!!) } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) } @Throws(SQLException::class) fun addParams(con: java.sql.Connection, routeId: String, params: List<Param>) { //Move required params val reqInsQuery = "INSERT INTO params (name, route_id, is_required,data_type,default_value,description) VALUES (?,?,?,?,?,?);" val ps1 = con.prepareStatement(reqInsQuery) for (param in params) { ps1.setString(1, param.name) ps1.setString(2, routeId) ps1.setBoolean(3, param.isRequired) ps1.setString(4, param.dataType) ps1.setString(5, param.defaultValue) ps1.setString(6, param.description) ps1.executeUpdate() } ps1.close() } @Throws(SQLException::class) fun updateParams(con: java.sql.Connection, params: List<Param>) { //Move required params val updateQuery = "UPDATE params SET is_required = ? , data_type = ? , default_value = ? , description = ? WHERE route_id = ? AND name = ?" val ps1 = con.prepareStatement(updateQuery) for (param in params) { ps1.setBoolean(1, param.isRequired) ps1.setString(2, param.dataType) ps1.setString(3, param.defaultValue) ps1.setString(4, param.description) ps1.setString(5, param.routeId) ps1.setString(6, param.name) ps1.executeUpdate() } ps1.close() } override fun getAll(whereColumn: String, whereColumnValue: String): List<Param> { val con = Connection.getConnection() val params = ArrayList<Param>() val query = String.format("SELECT id, name ,route_id, is_required, data_type, default_value, description FROM params WHERE %s = ? ORDER BY is_required DESC", whereColumn) try { val ps = con.prepareStatement(query) ps.setString(1, whereColumnValue) val rs = ps.executeQuery() if (rs.first()) { do { val id = rs.getString(Params.COLUMN_ID) val name = rs.getString(Params.COLUMN_NAME) val routeId = rs.getString(COLUMN_ROUTE_ID) val defaultValue = rs.getString(COLUMN_DEFAULT_VALUE) val dataType = rs.getString(COLUMN_DATA_TYPE) val description = rs.getString(COLUMN_DESCRIPTION) val isRequired = rs.getBoolean(COLUMN_IS_REQUIRED) params.add(Param(id, name, routeId, dataType, defaultValue, description, isRequired)) } while (rs.next()) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } return params } internal fun updateParamFromRoute(route: Route) { //Get new params val newParams = route.params //Get all params val oldParams = getAll(COLUMN_ROUTE_ID, route.id!!) val deletedParams = ArrayList<Param>() val addedParams = ArrayList<Param>() val updatedParams = ArrayList<Param>() if (oldParams.isEmpty() && !newParams!!.isEmpty()) { addedParams.addAll(newParams) } else if (newParams!!.isEmpty() && !oldParams.isEmpty()) { deletedParams.addAll(oldParams) } else { //finding deleted params for (oldParam in oldParams) { if (!newParams.contains(oldParam)) { deletedParams.add(oldParam) } } //finding addedParmas for (newParam in newParams) { if (!oldParams.contains(newParam)) { addedParams.add(newParam) } else { updatedParams.add(newParam) } } } val con = Connection.getConnection() try { if (!deletedParams.isEmpty()) { //Delete params val delQuery = "DELETE FROM params WHERE route_id = ? AND name = ?;" val ps = con.prepareStatement(delQuery) for (delParam in deletedParams) { ps.setString(1, route.id) ps.setString(2, delParam.name) ps.executeUpdate() } ps.close() } if (!addedParams.isEmpty()) { addParams(con, route.id!!, addedParams) } if (!updatedParams.isEmpty()) { updateParams(con, updatedParams) } } catch (e: SQLException) { e.printStackTrace() } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } } companion object { const val COLUMN_ID = "id" const val COLUMN_NAME = "name" const val COLUMN_ROUTE_ID = "route_id" const val COLUMN_IS_REQUIRED = "is_required" const val COLUMN_DEFAULT_VALUE = "default_value" const val COLUMN_DESCRIPTION = "description" const val COLUMN_DATA_TYPE = "data_type" val instance = Params() } }
apache-2.0
1c1793aafe9e78ffc45a7bcd3ba60a71
29.621359
178
0.539949
4.451658
false
false
false
false
Madrapps/Pikolo
pikolo/src/main/java/com/madrapps/pikolo/RGBColorPicker.kt
1
7041
package com.madrapps.pikolo import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.util.AttributeSet import android.view.MotionEvent import com.madrapps.pikolo.components.ColorComponent import com.madrapps.pikolo.components.rgb.BlueComponent import com.madrapps.pikolo.components.rgb.GreenComponent import com.madrapps.pikolo.components.rgb.RedComponent import com.madrapps.pikolo.components.rgb.RgbMetrics import com.madrapps.pikolo.listeners.OnColorSelectionListener open class RGBColorPicker @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ColorPicker(context, attrs, defStyleAttr) { private val metrics = RgbMetrics(color = floatArrayOf(255f, 0f, 0f), density = resources.displayMetrics.density) private val redComponent: ColorComponent private val greenComponent: ColorComponent private val blueComponent: ColorComponent private val redRadiusOffset: Float private val greenRadiusOffset: Float private val blueRadiusOffset: Float override val color: Int get() = metrics.getColor() init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RGBColorPicker, defStyleAttr, 0) with(config) { val redArcLength = typedArray.getFloat(R.styleable.RGBColorPicker_red_arc_length, if (arcLength == 0f) 110f else arcLength) val redStartAngle = typedArray.getFloat(R.styleable.RGBColorPicker_red_start_angle, 30f) redComponent = RedComponent(metrics, paints, redArcLength, redStartAngle).also { it.fillWidth = typedArray.getDimension(R.styleable.RGBColorPicker_red_arc_width, arcWidth) it.strokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_red_stroke_width, strokeWidth) it.indicatorStrokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_red_indicator_stroke_width, indicatorStrokeWidth) it.indicatorStrokeColor = typedArray.getColor(R.styleable.RGBColorPicker_red_indicator_stroke_color, indicatorStrokeColor) it.strokeColor = typedArray.getColor(R.styleable.RGBColorPicker_red_stroke_color, strokeColor) it.indicatorRadius = typedArray.getDimension(R.styleable.RGBColorPicker_red_indicator_radius, indicatorRadius) } val greenArcLength = typedArray.getFloat(R.styleable.RGBColorPicker_green_arc_length, if (arcLength == 0f) 110f else arcLength) val greenStartAngle = typedArray.getFloat(R.styleable.RGBColorPicker_green_start_angle, 150f) greenComponent = GreenComponent(metrics, paints, greenArcLength, greenStartAngle).also { it.fillWidth = typedArray.getDimension(R.styleable.RGBColorPicker_green_arc_width, arcWidth) it.strokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_green_stroke_width, strokeWidth) it.indicatorStrokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_green_indicator_stroke_width, indicatorStrokeWidth) it.indicatorStrokeColor = typedArray.getColor(R.styleable.RGBColorPicker_green_indicator_stroke_color, indicatorStrokeColor) it.strokeColor = typedArray.getColor(R.styleable.RGBColorPicker_green_stroke_color, strokeColor) it.indicatorRadius = typedArray.getDimension(R.styleable.RGBColorPicker_green_indicator_radius, indicatorRadius) } val blueArcLength = typedArray.getFloat(R.styleable.RGBColorPicker_blue_arc_length, if (arcLength == 0f) 110f else arcLength) val blueStartAngle = typedArray.getFloat(R.styleable.RGBColorPicker_blue_start_angle, 270f) blueComponent = BlueComponent(metrics, paints, blueArcLength, blueStartAngle).also { it.fillWidth = typedArray.getDimension(R.styleable.RGBColorPicker_blue_arc_width, arcWidth) it.strokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_blue_stroke_width, config.strokeWidth) it.indicatorStrokeWidth = typedArray.getDimension(R.styleable.RGBColorPicker_blue_indicator_stroke_width, indicatorStrokeWidth) it.indicatorStrokeColor = typedArray.getColor(R.styleable.RGBColorPicker_blue_indicator_stroke_color, indicatorStrokeColor) it.strokeColor = typedArray.getColor(R.styleable.RGBColorPicker_blue_stroke_color, strokeColor) it.indicatorRadius = typedArray.getDimension(R.styleable.RGBColorPicker_blue_indicator_radius, indicatorRadius) } redRadiusOffset = typedArray.getDimension(R.styleable.RGBColorPicker_red_radius_offset, if (radiusOffset == 0f) dp(25f) else radiusOffset) greenRadiusOffset = typedArray.getDimension(R.styleable.RGBColorPicker_green_radius_offset, if (radiusOffset == 0f) dp(25f) else radiusOffset) blueRadiusOffset = typedArray.getDimension(R.styleable.RGBColorPicker_blue_radius_offset, if (radiusOffset == 0f) dp(25f) else radiusOffset) } typedArray.recycle() } override fun onDraw(canvas: Canvas) { redComponent.drawComponent(canvas) greenComponent.drawComponent(canvas) blueComponent.drawComponent(canvas) } override fun onSizeChanged(width: Int, height: Int, oldW: Int, oldH: Int) { val minimumSize = if (width > height) height else width val padding = (paddingLeft + paddingRight + paddingTop + paddingBottom) / 4f val outerRadius = minimumSize.toFloat() / 2f - padding redComponent.setRadius(outerRadius, redRadiusOffset) greenComponent.setRadius(outerRadius, greenRadiusOffset) blueComponent.setRadius(outerRadius, blueRadiusOffset) metrics.centerX = width / 2f metrics.centerY = height / 2f redComponent.updateComponent(redComponent.angle) greenComponent.updateComponent(greenComponent.angle) blueComponent.updateComponent(blueComponent.angle) } override fun onTouchEvent(event: MotionEvent): Boolean { var isTouched = true if (!redComponent.onTouchEvent(event)) { if (!greenComponent.onTouchEvent(event)) { isTouched = blueComponent.onTouchEvent(event) } } invalidate() return isTouched } override fun setColorSelectionListener(listener: OnColorSelectionListener) { redComponent.setColorSelectionListener(listener) greenComponent.setColorSelectionListener(listener) blueComponent.setColorSelectionListener(listener) } override fun setColor(color: Int) { val red = Color.red(color).toFloat() metrics.color[0] = red redComponent.updateAngle(red) val green = Color.green(color).toFloat() metrics.color[1] = green greenComponent.updateAngle(green) val blue = Color.blue(color).toFloat() metrics.color[2] = blue blueComponent.updateAngle(blue) invalidate() } }
apache-2.0
0d376ee0a1314c40f2792696e3108fec
53.589147
167
0.725607
4.513462
false
false
false
false
arturbosch/sonar-kotlin
src/main/kotlin/io/gitlab/arturbosch/detekt/sonar/sensor/IssueReporter.kt
1
2293
package io.gitlab.arturbosch.detekt.sonar.sensor import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.sonar.foundation.logger import io.gitlab.arturbosch.detekt.sonar.rules.excludedDuplicates import io.gitlab.arturbosch.detekt.sonar.rules.ruleKeyLookup import org.sonar.api.batch.fs.InputFile import org.sonar.api.batch.sensor.SensorContext import org.sonar.api.batch.sensor.issue.NewIssue class IssueReporter( private val result: Detektion, private val context: SensorContext ) { private val fileSystem = context.fileSystem() private val baseDir = fileSystem.baseDir() fun run() { for ((ruleSet, findings) in result.findings) { logger.info("RuleSet: $ruleSet - ${findings.size}") findings.forEach(this::reportIssue) } } private fun reportIssue(issue: Finding) { if (issue.id in excludedDuplicates) { return } if (issue.startPosition.line < 0) { logger.info("Invalid location for ${issue.compactWithSignature()}.") return } val pathOfIssue = baseDir.resolveSibling(issue.location.file) val inputFile = fileSystem.inputFile(fileSystem.predicates().`is`(pathOfIssue)) if (inputFile != null) { ruleKeyLookup[issue.id]?.let { val newIssue = context.newIssue() .forRule(it) .primaryLocation(issue, inputFile) newIssue.save() } ?: logger.warn("Could not find rule key for detekt rule ${issue.id} (${issue.compactWithSignature()}).") } else { logger.info("No file found for ${issue.location.file}") } } private fun NewIssue.primaryLocation(finding: Finding, inputFile: InputFile): NewIssue { val line = finding.startPosition.line val metricMessages = finding.metrics .joinToString(" ") { "${it.type} ${it.value} is greater than the threshold ${it.threshold}." } val newIssueLocation = newLocation() .on(inputFile) .at(inputFile.selectLine(line)) .message("${finding.issue.description} $metricMessages") return this.at(newIssueLocation) } }
lgpl-3.0
7495e67d8ad0e2ab16b87f14f5c5c6f8
37.864407
118
0.648059
4.31015
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/JComponentEditorProvider.kt
1
2539
// 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.fileEditor.impl import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorPolicy import com.intellij.openapi.fileEditor.FileEditorProvider import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFile import javax.swing.JComponent /** * To open any of your JComponent descendant, call * <pre>{@code * JComponentEditorProvider.openEditor(project, "Title", jComponent) * }</pre> * * To customize Editor tab icon, you can, provide a custom fileType * <pre>{@code * val fileType = JComponentFileType() * JComponentEditorProvider.openEditor(project, "Title", jComponent, fileType) * }</pre> */ class JComponentEditorProvider : FileEditorProvider, DumbAware { override fun createEditor(project: Project, file: VirtualFile): FileEditor { val fileEditor = file.getUserData(EDITOR_KEY) return if (fileEditor != null) { fileEditor } else { val component = file.getUserData(JCOMPONENT_KEY) ?: error("JCOMPONENT_KEY key is null while creating JComponentFileEditor.") val newEditor = JComponentFileEditor(file, component) file.putUserData(EDITOR_KEY, newEditor) newEditor } } override fun accept(project: Project, file: VirtualFile) = isJComponentEditor(file) override fun getEditorTypeId() = "jcomponent-editor" override fun getPolicy() = FileEditorPolicy.HIDE_DEFAULT_EDITOR companion object { private val JCOMPONENT_KEY: Key<JComponent> = Key.create("jcomponent.editor.jcomponent") private val EDITOR_KEY: Key<FileEditor> = Key.create("jcomponent.editor.fileeditor") fun openEditor(project: Project, @NlsContexts.DialogTitle title: String, component: JComponent, fileType: FileType = JComponentFileType.INSTANCE): Array<FileEditor> { val file = LightVirtualFile(title, fileType, "") file.putUserData(JCOMPONENT_KEY, component) return FileEditorManager.getInstance(project).openFile(file, true) } @JvmStatic fun isJComponentEditor(file: VirtualFile): Boolean = file.getUserData(JCOMPONENT_KEY) != null } }
apache-2.0
fd137578b114f67d4cb4514f04384375
39.301587
130
0.760929
4.35506
false
false
false
false
square/okhttp
okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsRecordCodec.kt
2
3855
/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you under the Apache License, version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package okhttp3.dnsoverhttps import java.io.EOFException import java.net.InetAddress import java.net.UnknownHostException import okio.Buffer import okio.ByteString import okio.utf8Size /** * Trivial Dns Encoder/Decoder, basically ripped from Netty full implementation. */ internal object DnsRecordCodec { private const val SERVFAIL = 2 private const val NXDOMAIN = 3 const val TYPE_A = 0x0001 const val TYPE_AAAA = 0x001c private const val TYPE_PTR = 0x000c private val ASCII = Charsets.US_ASCII fun encodeQuery(host: String, type: Int): ByteString = Buffer().apply { writeShort(0) // query id writeShort(256) // flags with recursion writeShort(1) // question count writeShort(0) // answerCount writeShort(0) // authorityResourceCount writeShort(0) // additional val nameBuf = Buffer() val labels = host.split('.').dropLastWhile { it.isEmpty() } for (label in labels) { val utf8ByteCount = label.utf8Size() require(utf8ByteCount == label.length.toLong()) { "non-ascii hostname: $host" } nameBuf.writeByte(utf8ByteCount.toInt()) nameBuf.writeUtf8(label) } nameBuf.writeByte(0) // end nameBuf.copyTo(this, 0, nameBuf.size) writeShort(type) writeShort(1) // CLASS_IN }.readByteString() @Throws(Exception::class) fun decodeAnswers(hostname: String, byteString: ByteString): List<InetAddress> { val result = mutableListOf<InetAddress>() val buf = Buffer() buf.write(byteString) buf.readShort() // query id val flags = buf.readShort().toInt() and 0xffff require(flags shr 15 != 0) { "not a response" } val responseCode = flags and 0xf if (responseCode == NXDOMAIN) { throw UnknownHostException("$hostname: NXDOMAIN") } else if (responseCode == SERVFAIL) { throw UnknownHostException("$hostname: SERVFAIL") } val questionCount = buf.readShort().toInt() and 0xffff val answerCount = buf.readShort().toInt() and 0xffff buf.readShort() // authority record count buf.readShort() // additional record count for (i in 0 until questionCount) { skipName(buf) // name buf.readShort() // type buf.readShort() // class } for (i in 0 until answerCount) { skipName(buf) // name val type = buf.readShort().toInt() and 0xffff buf.readShort() // class @Suppress("UNUSED_VARIABLE") val ttl = buf.readInt().toLong() and 0xffffffffL // ttl val length = buf.readShort().toInt() and 0xffff if (type == TYPE_A || type == TYPE_AAAA) { val bytes = ByteArray(length) buf.read(bytes) result.add(InetAddress.getByAddress(bytes)) } else { buf.skip(length.toLong()) } } return result } @Throws(EOFException::class) private fun skipName(source: Buffer) { // 0 - 63 bytes var length = source.readByte().toInt() if (length < 0) { // compressed name pointer, first two bits are 1 // drop second byte of compression offset source.skip(1) } else { while (length > 0) { // skip each part of the domain name source.skip(length.toLong()) length = source.readByte().toInt() } } } }
apache-2.0
657907a9af24c3e8e2fa47b3fa252d79
29.595238
100
0.667445
4.028213
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/gradle/code-insight-common/src/org/jetbrains/kotlin/idea/gradleCodeInsightCommon/KotlinWithGradleConfigurator.kt
1
14780
// 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.gradleCodeInsightCommon import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix import com.intellij.ide.actions.OpenFileAction import com.intellij.openapi.application.runReadAction import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.WritingAccessProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.gradle.util.GradleVersion import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.projectStructure.ModuleSourceRootGroup import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.extensions.gradle.* import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleConstants.GRADLE_PLUGIN_ID import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleConstants.GROUP_ID import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersionOrDefault import org.jetbrains.kotlin.idea.framework.ui.ConfigureDialogWithModulesAndVersion import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.projectConfiguration.LibraryJarDescriptor import org.jetbrains.kotlin.idea.projectConfiguration.getJvmStdlibArtifactId import org.jetbrains.kotlin.idea.quickfix.AbstractChangeFeatureSupportLevelFix import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtFile abstract class KotlinWithGradleConfigurator : KotlinProjectConfigurator { override fun getStatus(moduleSourceRootGroup: ModuleSourceRootGroup): ConfigureKotlinStatus { val module = moduleSourceRootGroup.baseModule if (!isApplicable(module)) { return ConfigureKotlinStatus.NON_APPLICABLE } if (moduleSourceRootGroup.sourceRootModules.all(::hasAnyKotlinRuntimeInScope)) { return ConfigureKotlinStatus.CONFIGURED } val buildFiles = runReadAction { listOf( module.getBuildScriptPsiFile(), module.project.getTopLevelBuildScriptPsiFile() ).filterNotNull() } if (buildFiles.isEmpty()) { return ConfigureKotlinStatus.NON_APPLICABLE } if (buildFiles.none { it.isConfiguredByAnyGradleConfigurator() }) { return ConfigureKotlinStatus.CAN_BE_CONFIGURED } return ConfigureKotlinStatus.BROKEN } private fun PsiFile.isConfiguredByAnyGradleConfigurator(): Boolean { @Suppress("DEPRECATION") val extensions = Extensions.getExtensions(KotlinProjectConfigurator.EP_NAME) return extensions .filterIsInstance<KotlinWithGradleConfigurator>() .any { it.isFileConfigured(this) } } protected open fun isApplicable(module: Module): Boolean = module.buildSystemType == BuildSystemType.Gradle protected open fun getMinimumSupportedVersion() = "1.0.0" protected fun PsiFile.isKtDsl() = this is KtFile private fun isFileConfigured(buildScript: PsiFile): Boolean { val manipulator = GradleBuildScriptSupport.findManipulator(buildScript) ?: return false return with(manipulator) { isConfiguredWithOldSyntax(kotlinPluginName) || isConfigured(getKotlinPluginExpression(buildScript.isKtDsl())) } } @JvmSuppressWildcards override fun configure(project: Project, excludeModules: Collection<Module>) { val dialog = ConfigureDialogWithModulesAndVersion(project, this, excludeModules, getMinimumSupportedVersion()) dialog.show() if (!dialog.isOK) return val collector = configureSilently(project, dialog.modulesToConfigure, IdeKotlinVersion.get(dialog.kotlinVersion)) collector.showNotification() } private fun configureSilently(project: Project, modules: List<Module>, version: IdeKotlinVersion): NotificationMessageCollector { return project.executeCommand(KotlinIdeaGradleBundle.message("command.name.configure.kotlin")) { val collector = NotificationMessageCollector.create(project) val changedFiles = configureWithVersion(project, modules, version, collector) for (file in changedFiles) { OpenFileAction.openFile(file.virtualFile, project) } collector } } fun configureWithVersion( project: Project, modulesToConfigure: List<Module>, kotlinVersion: IdeKotlinVersion, collector: NotificationMessageCollector ): HashSet<PsiFile> { val filesToOpen = HashSet<PsiFile>() val buildScript = project.getTopLevelBuildScriptPsiFile() if (buildScript != null && canConfigureFile(buildScript)) { val isModified = configureBuildScript(buildScript, true, kotlinVersion, collector) if (isModified) { filesToOpen.add(buildScript) } } for (module in modulesToConfigure) { val file = module.getBuildScriptPsiFile() if (file != null && canConfigureFile(file)) { configureModule(module, file, false, kotlinVersion, collector, filesToOpen) } else { showErrorMessage( project, KotlinIdeaGradleBundle.message("error.text.cannot.find.build.gradle.file.for.module", module.name) ) } } return filesToOpen } open fun configureModule( module: Module, file: PsiFile, isTopLevelProjectFile: Boolean, version: IdeKotlinVersion, collector: NotificationMessageCollector, filesToOpen: MutableCollection<PsiFile> ) { val isModified = configureBuildScript(file, isTopLevelProjectFile, version, collector) if (isModified) { filesToOpen.add(file) } } private fun configureModuleBuildScript(file: PsiFile, version: IdeKotlinVersion): Boolean { val sdk = ModuleUtil.findModuleForPsiElement(file)?.let { ModuleRootManager.getInstance(it).sdk } val jvmTarget = getJvmTarget(sdk, version) return GradleBuildScriptSupport.getManipulator(file).configureModuleBuildScript( kotlinPluginName, getKotlinPluginExpression(file.isKtDsl()), getStdlibArtifactName(sdk, version), version, jvmTarget ) } protected open fun getStdlibArtifactName(sdk: Sdk?, version: IdeKotlinVersion) = getJvmStdlibArtifactId(sdk, version) protected open fun getJvmTarget(sdk: Sdk?, version: IdeKotlinVersion): String? = null protected abstract val kotlinPluginName: String protected abstract fun getKotlinPluginExpression(forKotlinDsl: Boolean): String protected open fun addElementsToFile( file: PsiFile, isTopLevelProjectFile: Boolean, version: IdeKotlinVersion ): Boolean { if (!isTopLevelProjectFile) { var wasModified = GradleBuildScriptSupport.getManipulator(file).configureProjectBuildScript(kotlinPluginName, version) wasModified = wasModified or configureModuleBuildScript(file, version) return wasModified } return false } private fun configureBuildScript( file: PsiFile, isTopLevelProjectFile: Boolean, version: IdeKotlinVersion, collector: NotificationMessageCollector ): Boolean { val isModified = file.project.executeWriteCommand(KotlinIdeaGradleBundle.message("command.name.configure.0", file.name), null) { val isModified = addElementsToFile(file, isTopLevelProjectFile, version) CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(file) isModified } val virtualFile = file.virtualFile if (virtualFile != null && isModified) { collector.addMessage(KotlinIdeaGradleBundle.message("text.was.modified", virtualFile.path)) } return isModified } override fun updateLanguageVersion( module: Module, languageVersion: String?, apiVersion: String?, requiredStdlibVersion: ApiVersion, forTests: Boolean ) { val runtimeUpdateRequired = getRuntimeLibraryVersion(module)?.apiVersion?.let { runtimeVersion -> runtimeVersion < requiredStdlibVersion } ?: false if (runtimeUpdateRequired) { Messages.showErrorDialog( module.project, KotlinIdeaGradleBundle.message("error.text.this.language.feature.requires.version", requiredStdlibVersion), KotlinIdeaGradleBundle.message("title.update.language.version") ) return } val element = changeLanguageVersion(module, languageVersion, apiVersion, forTests) element?.let { OpenFileDescriptor(module.project, it.containingFile.virtualFile, it.textRange.startOffset).navigate(true) } } override fun changeGeneralFeatureConfiguration( module: Module, feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ) { val sinceVersion = feature.sinceApiVersion if (state != LanguageFeature.State.DISABLED && getRuntimeLibraryVersionOrDefault(module).apiVersion < sinceVersion) { Messages.showErrorDialog( module.project, KotlinIdeaGradleBundle.message("error.text.support.requires.version", feature.presentableName, sinceVersion), AbstractChangeFeatureSupportLevelFix.getFixText(state, feature.presentableName) ) return } val element = changeFeatureConfiguration(module, feature, state, forTests) if (element != null) { OpenFileDescriptor(module.project, element.containingFile.virtualFile, element.textRange.startOffset).navigate(true) } } override fun addLibraryDependency( module: Module, element: PsiElement, library: ExternalLibraryDescriptor, libraryJarDescriptor: LibraryJarDescriptor, scope: DependencyScope ) { val scope = OrderEntryFix.suggestScopeByLocation(module, element) addKotlinLibraryToModule(module, scope, library) } companion object { @NonNls const val CLASSPATH = "classpath \"$GROUP_ID:$GRADLE_PLUGIN_ID:\$kotlin_version\"" fun getGroovyDependencySnippet(artifactName: String, scope: String, withVersion: Boolean, gradleVersion: GradleVersion): String { val updatedScope = gradleVersion.scope(scope) val versionStr = if (withVersion) ":\$kotlin_version" else "" return "$updatedScope \"org.jetbrains.kotlin:$artifactName$versionStr\"" } fun getGroovyApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'" fun addKotlinLibraryToModule(module: Module, scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor) { val buildScript = module.getBuildScriptPsiFile() ?: return if (!canConfigureFile(buildScript)) { return } GradleBuildScriptSupport.getManipulator(buildScript).addKotlinLibraryToModuleBuildScript(module, scope, libraryDescriptor) buildScript.virtualFile?.let { NotificationMessageCollector.create(buildScript.project) .addMessage(KotlinIdeaGradleBundle.message("text.was.modified", it.path)) .showNotification() } } fun changeFeatureConfiguration( module: Module, feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ) = changeBuildGradle(module) { GradleBuildScriptSupport.getManipulator(it).changeLanguageFeatureConfiguration(feature, state, forTests) } fun changeLanguageVersion(module: Module, languageVersion: String?, apiVersion: String?, forTests: Boolean) = changeBuildGradle(module) { buildScriptFile -> val manipulator = GradleBuildScriptSupport.getManipulator(buildScriptFile) var result: PsiElement? = null if (languageVersion != null) { result = manipulator.changeLanguageVersion(languageVersion, forTests) } if (apiVersion != null) { result = manipulator.changeApiVersion(apiVersion, forTests) } result } private fun changeBuildGradle(module: Module, body: (PsiFile) -> PsiElement?): PsiElement? = module.getBuildScriptPsiFile() ?.takeIf { canConfigureFile(it) } ?.let { it.project.executeWriteCommand(KotlinIdeaGradleBundle.message("change.build.gradle.configuration"), null) { body(it) } } fun getKotlinStdlibVersion(module: Module): String? = module.getBuildScriptPsiFile()?.let { GradleBuildScriptSupport.getManipulator(it).getKotlinStdlibVersion() } private fun canConfigureFile(file: PsiFile): Boolean = WritingAccessProvider.isPotentiallyWritable(file.virtualFile, null) private fun showErrorMessage(project: Project, @Nls message: String?) { Messages.showErrorDialog( project, "<html>" + KotlinIdeaGradleBundle.message("text.couldn.t.configure.kotlin.gradle.plugin.automatically") + "<br/>" + (if (message != null) "$message<br/>" else "") + "<br/>${KotlinIdeaGradleBundle.message("text.see.manual.installation.instructions")}</html>", KotlinIdeaGradleBundle.message("title.configure.kotlin.gradle.plugin") ) } } }
apache-2.0
a018d3d189ca44bc1efc36c4dcf7ad48
41.34957
137
0.691137
5.59213
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/helpers/CallableMetadataProvider.kt
1
10718
// 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.completion.contributors.helpers import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.KtTypeProjection import org.jetbrains.kotlin.analysis.api.components.buildClassType import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.analysis.api.KtStarTypeProjection import org.jetbrains.kotlin.types.Variance internal object CallableMetadataProvider { class CallableMetadata( val kind: CallableKind, /** * The index of the matched receiver. This number makes completion prefer candidates that are available from the innermost receiver * when all other things are equal. Explicit receiver is pushed to the end because if explicit receiver does not match, the entry * would not have showed up in the first place. * * For example, consider the code below * * ``` * class Foo { // receiver 2 * fun String.f1() { // receiver 1 * fun Int.f2() { // receiver 0 * length // receiver index = 1 * listOf("").size // receiver index = 3 (explicit receiver is added to the end) * "".f1() // receiver index = 3 (explicit receiver is honored over implicit (dispatch) receiver) * } * } * } * ``` */ val receiverIndex: Int? ) { companion object { val local = CallableMetadata(CallableKind.Local, null) val globalOrStatic = CallableMetadata(CallableKind.GlobalOrStatic, null) } } sealed class CallableKind(private val index: Int) : Comparable<CallableKind> { object Local : CallableKind(0) // local non_extension object ThisClassMember : CallableKind(1) object BaseClassMember : CallableKind(2) object ThisTypeExtension : CallableKind(3) object BaseTypeExtension : CallableKind(4) object GlobalOrStatic : CallableKind(5) // global non_extension object TypeParameterExtension : CallableKind(6) class ReceiverCastRequired(val fullyQualifiedCastType: String) : CallableKind(7) override fun compareTo(other: CallableKind): Int = this.index - other.index } fun KtAnalysisSession.getCallableMetadata( context: WeighingContext, symbol: KtSymbol, substitutor: KtSubstitutor ): CallableMetadata? { if (symbol !is KtCallableSymbol) return null if (symbol is KtSyntheticJavaPropertySymbol) { return getCallableMetadata(context, symbol.javaGetterSymbol, substitutor) } val overriddenSymbols = symbol.getDirectlyOverriddenSymbols() if (overriddenSymbols.isNotEmpty()) { val weights = overriddenSymbols .mapNotNull { callableWeightByReceiver(it, context, substitutor, returnCastRequiredOnReceiverMismatch = false) } .takeUnless { it.isEmpty() } ?: symbol.getAllOverriddenSymbols().map { callableWeightBasic(context, it, substitutor) } return weights.minByOrNull { it.kind } } return callableWeightBasic(context, symbol, substitutor) } private fun KtAnalysisSession.callableWeightBasic( context: WeighingContext, symbol: KtCallableSymbol, substitutor: KtSubstitutor ): CallableMetadata { callableWeightByReceiver(symbol, context, substitutor, returnCastRequiredOnReceiverMismatch = true)?.let { return it } return when (symbol.getContainingSymbol()) { null, is KtPackageSymbol, is KtClassifierSymbol -> CallableMetadata.globalOrStatic else -> CallableMetadata.local } } private fun KtAnalysisSession.callableWeightByReceiver( symbol: KtCallableSymbol, context: WeighingContext, substitutor: KtSubstitutor, returnCastRequiredOnReceiverMismatch: Boolean ): CallableMetadata? { val actualExplicitReceiverType = context.explicitReceiver?.let { getReferencedClassTypeInCallableReferenceExpression(it) ?: it.getKtType() } val actualImplicitReceiverTypes = context.implicitReceiver.map { it.type } val expectedExtensionReceiverType = symbol.receiverType?.let { substitutor.substitute(it) } val weightBasedOnExtensionReceiver = expectedExtensionReceiverType?.let { receiverType -> // If a symbol expects an extension receiver, then either // * the call site explicitly specifies the extension receiver , or // * the call site specifies no receiver. // In other words, in this case, an explicit receiver can never be a dispatch receiver. callableWeightByReceiver(symbol, actualExplicitReceiverType?.let { listOf(it) } ?: actualImplicitReceiverTypes, receiverType, returnCastRequiredOnReceiverMismatch ) } if (returnCastRequiredOnReceiverMismatch && weightBasedOnExtensionReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnExtensionReceiver // In Fir, a local function takes its containing function's dispatch receiver as its dispatch receiver. But we don't consider a // local function as a class member. Hence, here we return null so that it's handled by other logic. if (symbol.callableIdIfNonLocal == null) return null val expectedDispatchReceiverType = (symbol as? KtCallableSymbol)?.getDispatchReceiverType() val weightBasedOnDispatchReceiver = expectedDispatchReceiverType?.let { receiverType -> callableWeightByReceiver( symbol, actualImplicitReceiverTypes + listOfNotNull(actualExplicitReceiverType), receiverType, returnCastRequiredOnReceiverMismatch ) } if (returnCastRequiredOnReceiverMismatch && weightBasedOnDispatchReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnDispatchReceiver return weightBasedOnExtensionReceiver ?: weightBasedOnDispatchReceiver } /** * Return the type from the referenced class if this explicit receiver is a receiver in a callable reference expression. For example, * in the following code, `String` is such a receiver. And this method should return the `String` type in this case. * ``` * val l = String::length * ``` */ private fun KtAnalysisSession.getReferencedClassTypeInCallableReferenceExpression(explicitReceiver: KtExpression): KtType? { val callableReferenceExpression = explicitReceiver.getParentOfType<KtCallableReferenceExpression>(strict = true) ?: return null if (callableReferenceExpression.lhs != explicitReceiver) return null val symbol = when (explicitReceiver) { is KtDotQualifiedExpression -> explicitReceiver.selectorExpression?.mainReference?.resolveToSymbol() is KtNameReferenceExpression -> explicitReceiver.mainReference.resolveToSymbol() else -> return null } if (symbol !is KtClassLikeSymbol) return null return buildClassType(symbol) { repeat(symbol.typeParameters.size) { argument(KtStarTypeProjection(token)) } } } private fun KtAnalysisSession.callableWeightByReceiver( symbol: KtCallableSymbol, actualReceiverTypes: List<KtType>, expectedReceiverType: KtType, returnCastRequiredOnReceiverTypeMismatch: Boolean ): CallableMetadata? { if (expectedReceiverType is KtFunctionType) return null var bestMatchIndex: Int? = null var bestMatchWeightKind: CallableKind? = null for ((i, actualReceiverType) in actualReceiverTypes.withIndex()) { val weightKind = callableWeightKindByReceiverType(symbol, actualReceiverType, expectedReceiverType) if (weightKind != null) { if (bestMatchWeightKind == null || weightKind < bestMatchWeightKind) { bestMatchWeightKind = weightKind bestMatchIndex = i } } } // TODO: FE1.0 has logic that uses `null` for receiverIndex if the symbol matches every actual receiver in order to "prevent members // of `Any` to show up on top". But that seems hacky and can cause collateral damage if the implicit receivers happen to implement // some common interface. So that logic is left out here for now. We can add it back in future if needed. if (bestMatchWeightKind == null) { return if (returnCastRequiredOnReceiverTypeMismatch) CallableMetadata(CallableKind.ReceiverCastRequired(expectedReceiverType.render(position = Variance.INVARIANT)), null) else null } return CallableMetadata(bestMatchWeightKind, bestMatchIndex) } private fun KtAnalysisSession.callableWeightKindByReceiverType( symbol: KtCallableSymbol, actualReceiverType: KtType, expectedReceiverType: KtType, ): CallableKind? = when { actualReceiverType isEqualTo expectedReceiverType -> when { isExtensionCallOnTypeParameterReceiver(symbol) -> CallableKind.TypeParameterExtension symbol.isExtension -> CallableKind.ThisTypeExtension else -> CallableKind.ThisClassMember } actualReceiverType isSubTypeOf expectedReceiverType -> when { symbol.isExtension -> CallableKind.BaseTypeExtension else -> CallableKind.BaseClassMember } else -> null } private fun KtAnalysisSession.isExtensionCallOnTypeParameterReceiver(symbol: KtCallableSymbol): Boolean { val originalSymbol = symbol.originalOverriddenSymbol val receiverParameterType = originalSymbol?.receiverType as? KtTypeParameterType ?: return false val parameterTypeOwner = receiverParameterType.symbol.getContainingSymbol() ?: return false return parameterTypeOwner == originalSymbol } }
apache-2.0
f2b55a41cacbb432de4593cde5c7abdd
48.855814
164
0.688561
5.765465
false
false
false
false
StepicOrg/stepik-android
app/src/debug/java/org/stepik/android/view/debug/ui/fragment/DebugFragment.kt
1
5616
package org.stepik.android.view.debug.ui.fragment import android.os.Bundle import android.view.View import android.widget.RadioButton import android.widget.Toast import androidx.appcompat.widget.AppCompatTextView import androidx.core.view.get import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.util.copyTextToClipboard import org.stepik.android.presentation.debug.DebugFeature import org.stepik.android.presentation.debug.DebugViewModel import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.app.presentation.redux.container.ReduxView import ru.nobird.android.view.redux.ui.extension.reduxViewModel import javax.inject.Inject import android.content.Intent import android.content.Context import androidx.core.view.isVisible import by.kirich1409.viewbindingdelegate.viewBinding import org.stepic.droid.databinding.FragmentDebugBinding import org.stepik.android.view.debug.ui.activity.InAppPurchasesActivity import org.stepik.android.view.debug.ui.dialog.SplitTestsDialogFragment import ru.nobird.android.view.base.ui.extension.showIfNotExists class DebugFragment : Fragment(R.layout.fragment_debug), ReduxView<DebugFeature.State, DebugFeature.Action.ViewAction> { companion object { fun newInstance(): Fragment = DebugFragment() } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val debugViewModel: DebugViewModel by reduxViewModel(this) { viewModelFactory } private val viewStateDelegate = ViewStateDelegate<DebugFeature.State>() private val debugBinding: FragmentDebugBinding by viewBinding(FragmentDebugBinding::bind) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) debugBinding.appBarLayoutBinding.viewCenteredToolbarBinding.centeredToolbarTitle.setText(R.string.debug_toolbar_title) initViewStateDelegate() debugViewModel.onNewMessage(DebugFeature.Message.InitMessage()) debugBinding.debugFcmTokenValue.setOnLongClickListener { val textToCopy = (it as AppCompatTextView).text.toString() requireContext().copyTextToClipboard( textToCopy = textToCopy, toastMessage = getString(R.string.copied_to_clipboard_toast) ) true } debugBinding.debugEndpointRadioGroup.setOnCheckedChangeListener { group, checkedId -> val checkedRadioButton = group.findViewById<RadioButton>(checkedId) val position = group.indexOfChild(checkedRadioButton) debugViewModel.onNewMessage(DebugFeature.Message.RadioButtonSelectionMessage(position)) } debugBinding.debugApplySettingsAction.setOnClickListener { debugViewModel.onNewMessage(DebugFeature.Message.ApplySettingsMessage) } debugBinding.debugLoadingError.tryAgain.setOnClickListener { debugViewModel.onNewMessage(DebugFeature.Message.InitMessage(forceUpdate = true)) } debugBinding.debugSplitTests.setOnClickListener { SplitTestsDialogFragment .newInstance() .showIfNotExists(childFragmentManager, SplitTestsDialogFragment.TAG) } debugBinding.debugPurchases.setOnClickListener { val intent = InAppPurchasesActivity.createIntent(requireContext()) startActivity(intent) } } private fun injectComponent() { App.component() .debugComponentBuilder() .build() .inject(this) } private fun initViewStateDelegate() { viewStateDelegate.addState<DebugFeature.State.Idle>() viewStateDelegate.addState<DebugFeature.State.Loading>(debugBinding.debugProgressBar.loadProgressbarOnEmptyScreen) viewStateDelegate.addState<DebugFeature.State.Error>(debugBinding.debugLoadingError.errorNoConnection) viewStateDelegate.addState<DebugFeature.State.Content>(debugBinding.debugContent) } override fun onAction(action: DebugFeature.Action.ViewAction) { if (action is DebugFeature.Action.ViewAction.RestartApplication) { Toast.makeText(requireContext(), R.string.debug_restarting_message, Toast.LENGTH_SHORT).show() view?.postDelayed({ triggerApplicationRestart(requireContext()) }, 1500) } } override fun render(state: DebugFeature.State) { viewStateDelegate.switchState(state) if (state is DebugFeature.State.Content) { debugBinding.debugFcmTokenValue.text = state.fcmToken setRadioButtonSelection(state.endpointConfigSelection) debugBinding.debugApplySettingsAction.isVisible = state.currentEndpointConfig.ordinal != state.endpointConfigSelection } } private fun triggerApplicationRestart(context: Context) { val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) val componentName = intent?.component val mainIntent = Intent.makeRestartActivityTask(componentName) context.startActivity(mainIntent) Runtime.getRuntime().exit(0) } private fun setRadioButtonSelection(itemPosition: Int) { val targetRadioButton = debugBinding.debugEndpointRadioGroup[itemPosition] as RadioButton targetRadioButton.isChecked = true } }
apache-2.0
48bd0483c31b26b5ea40328d67b6fe44
41.233083
130
0.745192
5.1101
false
false
false
false
square/okio
okio/src/jvmMain/kotlin/okio/CipherSink.kt
1
4090
/* * Copyright (C) 2020 Square, Inc. and others. * * 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 okio import java.io.IOException import javax.crypto.Cipher class CipherSink( private val sink: BufferedSink, val cipher: Cipher ) : Sink { private val blockSize = cipher.blockSize private var closed = false init { // Require block cipher require(blockSize > 0) { "Block cipher required $cipher" } } @Throws(IOException::class) override fun write(source: Buffer, byteCount: Long) { checkOffsetAndCount(source.size, 0, byteCount) check(!closed) { "closed" } var remaining = byteCount while (remaining > 0) { val size = update(source, remaining) remaining -= size } } private fun update(source: Buffer, remaining: Long): Int { val head = source.head!! var size = minOf(remaining, head.limit - head.pos).toInt() val buffer = sink.buffer // Shorten input until output is guaranteed to fit within a segment var outputSize = cipher.getOutputSize(size) while (outputSize > Segment.SIZE) { if (size <= blockSize) { // Bug: For AES-GCM on Android `update` method never outputs any data // As a consequence, `getOutputSize` just keeps increasing indefinitely after each update // When that happens, the fallback is to perform the update operation without using a pre-allocated segment sink.write(cipher.update(source.readByteArray(remaining))) return remaining.toInt() } size -= blockSize outputSize = cipher.getOutputSize(size) } val s = buffer.writableSegment(outputSize) val ciphered = cipher.update(head.data, head.pos, size, s.data, s.limit) s.limit += ciphered buffer.size += ciphered // We allocated a tail segment, but didn't end up needing it. Recycle! if (s.pos == s.limit) { buffer.head = s.pop() SegmentPool.recycle(s) } sink.emitCompleteSegments() // Mark those bytes as read. source.size -= size head.pos += size if (head.pos == head.limit) { source.head = head.pop() SegmentPool.recycle(head) } return size } override fun flush() = sink.flush() override fun timeout() = sink.timeout() @Throws(IOException::class) override fun close() { if (closed) return closed = true var thrown = doFinal() try { sink.close() } catch (e: Throwable) { if (thrown == null) thrown = e } if (thrown != null) throw thrown } private fun doFinal(): Throwable? { val outputSize = cipher.getOutputSize(0) if (outputSize == 0) return null if (outputSize > Segment.SIZE) { // Bug: For AES-GCM on Android `update` method never outputs any data // As a consequence, `doFinal` returns the fully encrypted data, which may be arbitrarily large // When that happens, the fallback is to perform the `doFinal` operation without using a pre-allocated segment try { sink.write(cipher.doFinal()) } catch (t: Throwable) { return t } return null } var thrown: Throwable? = null val buffer = sink.buffer // For block cipher, output size cannot exceed block size in doFinal val s = buffer.writableSegment(outputSize) try { val ciphered = cipher.doFinal(s.data, s.limit) s.limit += ciphered buffer.size += ciphered } catch (e: Throwable) { thrown = e } if (s.pos == s.limit) { buffer.head = s.pop() SegmentPool.recycle(s) } return thrown } }
apache-2.0
9291f03ea7ddf1c8e4d7d851b5a73a39
26.823129
116
0.652812
4.049505
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/viewholder/TransferDetailViewHolder.kt
1
3567
/* * Copyright (C) 2021 Veli Tasalı * * 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.monora.uprotocol.client.android.viewholder import android.view.View import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.LiveData import androidx.recyclerview.widget.RecyclerView import org.monora.uprotocol.client.android.database.model.TransferDetail import org.monora.uprotocol.client.android.databinding.ListTransferBinding import org.monora.uprotocol.client.android.viewmodel.content.TransferDetailContentViewModel import org.monora.uprotocol.client.android.viewmodel.content.TransferStateContentViewModel import org.monora.uprotocol.client.android.viewmodel.content.TransferStateFeederViewModel class TransferDetailViewHolder( private val gibSubscriberListener: (detail: TransferDetail) -> LiveData<TransferStateContentViewModel>, private val clickListener: (TransferDetail, ClickType) -> Unit, private val binding: ListTransferBinding, ) : RecyclerView.ViewHolder(binding.root), LifecycleOwner { // FIXME: 7/28/21 ViewHolder lifecycle isn't called when user leaves the activity private val lifecycleRegistry = LifecycleRegistry(this).apply { currentState = Lifecycle.State.INITIALIZED } fun onAppear() { lifecycleRegistry.currentState = Lifecycle.State.CREATED lifecycleRegistry.currentState = Lifecycle.State.STARTED lifecycleRegistry.currentState = Lifecycle.State.RESUMED } fun onDisappear() { lifecycleRegistry.currentState = Lifecycle.State.STARTED lifecycleRegistry.currentState = Lifecycle.State.CREATED } fun onDestroy() { // FIXME: 7/28/21 Recycled views are still being used for some reason and destroyed state is not reusable //lifecycleRegistry.currentState = Lifecycle.State.DESTROYED } fun bind(transferDetail: TransferDetail) { binding.viewModel = TransferDetailContentViewModel(transferDetail) binding.feederModel = TransferStateFeederViewModel(gibSubscriberListener(transferDetail)) binding.lifecycleOwner = this binding.container.setOnClickListener { clickListener(transferDetail, ClickType.Default) } binding.rejectButton.setOnClickListener { clickListener(transferDetail, ClickType.Reject) } val toggleListener = View.OnClickListener { clickListener(transferDetail, ClickType.ToggleTask) } binding.acceptButton.setOnClickListener(toggleListener) binding.toggleButton.setOnClickListener(toggleListener) binding.executePendingBindings() } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } enum class ClickType { Default, ToggleTask, Reject, } }
gpl-2.0
53e27d8d7cf6738732fe01d958b4ac15
39.988506
113
0.754066
5.001403
false
false
false
false
Szewek/FL
src/main/java/szewek/fl/network/FLNetUtilServer.kt
1
914
package szewek.fl.network import net.minecraft.entity.player.EntityPlayer import net.minecraft.network.INetHandler import net.minecraft.network.NetHandlerPlayServer import net.minecraft.util.IThreadListener import net.minecraft.util.Tuple import net.minecraftforge.fml.common.network.internal.FMLProxyPacket import net.minecraftforge.fml.relauncher.Side class FLNetUtilServer private constructor() : FLNetUtil { override fun preprocess(p: FMLProxyPacket, s: Side): Tuple<IThreadListener, EntityPlayer>? { val h = p.handler() as NetHandlerPlayServer? if (h != null) { val ep = h.player val itl = ep.server if (itl != null) return Tuple(itl, ep) } return null } override fun decode(msg: FLNetMsg, p: EntityPlayer, s: Side) = msg.srvmsg(p) override fun check(h: INetHandler) = if (h is NetHandlerPlayServer) Side.SERVER else null companion object { val THIS = FLNetUtilServer() } }
mit
5e0b7e988a6092682b8b0c25a104a5e1
28.483871
93
0.761488
3.311594
false
false
false
false
leafclick/intellij-community
platform/statistics/src/com/intellij/internal/statistic/local/ActionsLocalSummary.kt
1
1937
// 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.internal.statistic.local import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.XMap @State(name = "ActionsLocalSummary", storages = [ Storage("actionSummary.xml", roamingType = RoamingType.DISABLED), Storage("actions_summary.xml", deprecated = true) ]) internal class ActionsLocalSummary : SimplePersistentStateComponent<ActionsLocalSummaryState>(ActionsLocalSummaryState()) { companion object { val instance: ActionsLocalSummary get() = ApplicationManager.getApplication().getService(ActionsLocalSummary::class.java) } fun updateActionsSummary(actionId: String) { state.updateActionsSummary(actionId) } } internal class ActionsLocalSummaryState : BaseState() { internal class ActionSummary { @Attribute @JvmField var times = 0 @Attribute @JvmField var last = System.currentTimeMillis() } @get:XMap val data by map<String, ActionSummary>() internal fun updateActionsSummary(actionId: String) { val summary = data.getOrPut(actionId) { ActionSummary() } summary.last = System.currentTimeMillis() summary.times++ incrementModificationCount() } } private class ActionsLocalSummaryListener : AnActionListener { override fun beforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { ActionsLocalSummary.instance.updateActionsSummary(event.actionManager.getId(action) ?: action.javaClass.name) } }
apache-2.0
c699a29d1a94205c98c5264fafe36be8
34.888889
140
0.783686
4.818408
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/boxingOptimization/boxedPrimitivesAreEqual.kt
4
440
inline fun eq(a: Any, b: Any) = a == b inline fun ne(a: Any, b: Any) = a != b val ONE = 1 val ONEL = 1L fun box(): String { return when { eq(ONE, 2) -> "Fail 1" !eq(ONE, 1) -> "Fail 2" !ne(ONE, 2) -> "Fail 3" ne(ONE, 1) -> "Fail 4" eq(ONEL, 42L) -> "Fail 1L" !eq(ONEL, 1L) -> "Fail 2L" !ne(ONEL, 42L) -> "Fail 3L" ne(ONEL, 1L) -> "Fail 4L" else -> "OK" } }
apache-2.0
5b155d60f8832d841e5897ee16680f88
20
38
0.427273
2.458101
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/unwrap/KotlinFunctionParameterUnwrapper.kt
5
1186
// 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.codeInsight.unwrap import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class KotlinFunctionParameterUnwrapper(key: String) : KotlinUnwrapRemoveBase(key) { override fun isApplicableTo(element: PsiElement): Boolean { if (element !is KtCallExpression) return false if (element.valueArguments.size != 1) return false val argument = element.parent as? KtValueArgument ?: return false if (argument.getStrictParentOfType<KtCallExpression>() == null) return false return true } override fun doUnwrap(element: PsiElement?, context: Context?) { val function = element as? KtCallExpression ?: return val argument = element.valueArguments.firstOrNull()?.getArgumentExpression() ?: return context?.extractFromExpression(argument, function) context?.delete(function) } }
apache-2.0
bd5620120f793895e830c72b23c947c2
42.925926
158
0.747892
4.840816
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/MapFromDialog.kt
5
5596
// 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.refactoring.extractMethod.newImpl import com.intellij.codeInsight.CodeInsightUtil import com.intellij.codeInsight.generation.GenerateMembersUtil import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.util.NlsContexts import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.codeStyle.VariableKind import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl import com.intellij.psi.search.LocalSearchScope import com.intellij.refactoring.extractMethod.ExtractMethodDialog import com.intellij.refactoring.extractMethod.InputVariables import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.Nls import java.util.* object MapFromDialog { fun mapFromDialog(extractOptions: ExtractOptions, @NlsContexts.DialogTitle title: String, helpId: String): ExtractOptions? { val dialog = createDialog(extractOptions, title, helpId) val isOk = dialog.showAndGet() if (isOk){ return ExtractMethodPipeline.remap(extractOptions, dialog.chosenParameters, dialog.chosenMethodName, dialog.isMakeStatic, dialog.visibility, dialog.isChainedConstructor, dialog.returnType) } else { return null } } private fun createDialog(extractOptions: ExtractOptions, @NlsContexts.DialogTitle refactoringName: String, helpId: String): ExtractMethodDialog { val project = extractOptions.project val returnType = extractOptions.dataOutput.type val thrownExceptions = extractOptions.thrownExceptions.toTypedArray() val isStatic = extractOptions.isStatic val typeParameters = extractOptions.typeParameters val targetClass = extractOptions.anchor.containingClass val elements = extractOptions.elements.toTypedArray() val nullability = extractOptions.dataOutput.nullability.takeIf { ExtractMethodHelper.isNullabilityAvailable(extractOptions) } val analyzer = CodeFragmentAnalyzer(extractOptions.elements) val staticOptions = ExtractMethodPipeline.withForcedStatic(analyzer, extractOptions) val canBeStatic = ExtractMethodPipeline.withForcedStatic(analyzer, extractOptions) != null val canBeChainedConstructor = ExtractMethodPipeline.canBeConstructor(analyzer) val factory = PsiElementFactory.getInstance(project) val variables = extractOptions.inputParameters .map { factory.createVariableDeclarationStatement(it.name, it.type, null, it.references.first().context) } .map { declaration -> declaration.declaredElements[0] as PsiVariable } val parameterNames = extractOptions.inputParameters.map { it.name }.toSet() val fields = staticOptions?.inputParameters.orEmpty() .filterNot { it.name in parameterNames }.map { factory.createField(it.name, it.type) }.toSet() val inputVariables = InputVariables( variables, extractOptions.project, LocalSearchScope(extractOptions.elements.toTypedArray()), false, fields ) val typeParameterList = PsiElementFactory.getInstance(extractOptions.project).createTypeParameterList() typeParameters.forEach { typeParameterList.add(it) } val methodNames = ExtractMethodHelper.guessMethodName(extractOptions) return object: ExtractMethodDialog(project, targetClass, inputVariables, returnType, typeParameterList, thrownExceptions, isStatic, canBeStatic, canBeChainedConstructor, refactoringName, helpId, nullability, elements, {0}) { override fun areTypesDirected() = true override fun suggestMethodNames(): Array<String> { return methodNames.toTypedArray() } override fun isVoidReturn(): Boolean = false override fun findOccurrences(): Array<PsiExpression> { return when (val dataOutput = extractOptions.dataOutput) { is DataOutput.VariableOutput -> CodeInsightUtil.findReferenceExpressions(extractOptions.anchor, dataOutput.variable) is DataOutput.ExpressionOutput -> dataOutput.returnExpressions.toTypedArray() else -> emptyArray() } } override fun isOutputVariable(variable: PsiVariable): Boolean { return (extractOptions.dataOutput as? DataOutput.VariableOutput)?.variable == variable } override fun checkMethodConflicts(conflicts: MultiMap<PsiElement, String>) { super.checkMethodConflicts(conflicts) val parameters = chosenParameters val vars: MutableMap<String, PsiLocalVariable> = HashMap() for (element in elements) { element.accept(object : JavaRecursiveElementWalkingVisitor() { override fun visitLocalVariable(variable: PsiLocalVariable) { super.visitLocalVariable(variable) vars[variable.name] = variable } override fun visitClass(aClass: PsiClass) {} }) } for (parameter in parameters) { val paramName = parameter.name val variable = vars[paramName] if (variable != null) { conflicts.putValue(variable, JavaRefactoringBundle.message("extract.method.conflict.variable", paramName)) } } } override fun hasPreviewButton() = false } } }
apache-2.0
4c0da3068d51e99cbb32cd362782744a
47.669565
147
0.739099
5.220149
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/java/src/service/resolve/GradleTaskContainerContributor.kt
6
2603
// 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 org.jetbrains.plugins.gradle.service.resolve import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_TASK_CONTAINER import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.getName import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties class GradleTaskContainerContributor : NonCodeMembersContributor() { override fun getParentClassName(): String? = GRADLE_API_TASK_CONTAINER override fun processDynamicElements(qualifierType: PsiType, aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (qualifierType !is GradleProjectAwareType) return val processProperties = processor.shouldProcessProperties() val processMethods = processor.shouldProcessMethods() if (!processProperties && !processMethods) { return } val file = place.containingFile ?: return val data = GradleExtensionsContributor.getExtensionsFor(file) ?: return val name = processor.getName(state) val tasks = if (name == null) data.tasksMap.values else listOf(data.tasksMap[name] ?: return) if (tasks.isEmpty()) return val manager = file.manager val closureType = createType(GROOVY_LANG_CLOSURE, file) for (task in tasks) { val taskType = createType(task.typeFqn, file) if (processProperties) { val property = GradleTaskProperty(task, file) if (!processor.execute(property, state)) return } if (processMethods) { val method = GrLightMethodBuilder(manager, task.name).apply { returnType = taskType addParameter("configuration", closureType) } if (!processor.execute(method, state)) return } } } }
apache-2.0
b5161e3837bab7abc896367b8992f46b
42.383333
140
0.719939
4.724138
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/client/google/run/android/CreateAndroidInstrumentationTest.kt
1
2702
package ftl.client.google.run.android import com.google.testing.model.AndroidInstrumentationTest import com.google.testing.model.FileReference import com.google.testing.model.ManualSharding import com.google.testing.model.ShardingOption import com.google.testing.model.TestTargetsForShard import com.google.testing.model.UniformSharding import flank.common.logLn import ftl.api.ShardChunks import ftl.api.TestMatrixAndroid internal fun createAndroidInstrumentationTest( config: TestMatrixAndroid.Type.Instrumentation ) = AndroidInstrumentationTest().apply { appApk = FileReference().setGcsPath(config.appApkGcsPath) testApk = FileReference().setGcsPath(config.testApkGcsPath) testRunnerClass = config.testRunnerClass orchestratorOption = config.orchestratorOption }.setupTestTargets( disableSharding = config.disableSharding, testShards = config.testShards, numUniformShards = config.numUniformShards, keepTestTargetsEmpty = config.keepTestTargetsEmpty, testTargetsForShard = config.testTargetsForShard ) internal fun AndroidInstrumentationTest.setupTestTargets( disableSharding: Boolean, testShards: ShardChunks, numUniformShards: Int?, keepTestTargetsEmpty: Boolean, testTargetsForShard: ShardChunks ) = apply { when { keepTestTargetsEmpty -> { testTargets = emptyList() } disableSharding -> { testTargets = testShards.flatten() } else -> { shardingOption = ShardingOption().apply { if (numUniformShards != null) { testTargets = testShards.flatten() val safeNumUniformShards = if (testTargets.size > numUniformShards) numUniformShards else { logLn("WARNING: num-uniform-shards ($numUniformShards) is higher than number of test cases (${testTargets.size}) from ${testApk.gcsPath}") testTargets.size } uniformSharding = UniformSharding().setNumShards(safeNumUniformShards) } else { manualSharding = createManualSharding(testTargetsForShard, testShards) } } } } } private fun createManualSharding(testFlagForShard: ShardChunks, testShards: ShardChunks) = if (testFlagForShard.isNotEmpty()) { ManualSharding().setTestTargetsForShard( testFlagForShard.map { TestTargetsForShard().setTestTargets(it) } ) } else { ManualSharding().setTestTargetsForShard( testShards.map { TestTargetsForShard().setTestTargets(it) } ) }
apache-2.0
69277e766af8a595ff3fe773a880bf46
36.527778
162
0.676536
4.757042
false
true
false
false
kohesive/kohesive-iac
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/TemplateBuilder.kt
1
5325
package uy.kohesive.iac.model.aws.cloudformation import com.amazonaws.AmazonWebServiceRequest import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import uy.kohesive.iac.model.aws.AwsTypes import uy.kohesive.iac.model.aws.ParameterizedValue import uy.kohesive.iac.model.aws.cloudformation.processing.TemplateProcessor import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy class TemplateBuilder( val context: CloudFormationContext, val description: String? = null, val version: String = "2010-09-09" ) { companion object { val JSON = jacksonObjectMapper() .setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy()) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) } fun build(): JsonNode { val nameToDependsOnNames = context.dependsOn.map { entry -> val sourceName = context.getNameStrict(entry.key) val targetNames = entry.value.map { targetObj -> context.getNameStrict(targetObj) }.distinct() sourceName to targetNames }.toMap() val rawTemplate = Template( Description = description, AWSTemplateFormatVersion = version, Parameters = context.variables.mapValues { varEntry -> varEntry.value.toCFParameter() }, Mappings = context.mappings.map { it.key to it.value.map }.toMap(), Resources = context.objectsToNames.toList().groupBy(Pair<Any, String>::second).mapValues { it.value.map { it.first } }.mapValues { val name = it.key val objectsWithSameName = it.value objectsWithSameName.firstOrNull { obj -> (obj as? AmazonWebServiceRequest)?.let { request -> AwsTypes.isCreationRequestClass(request::class) } ?: false }?.let { creationRequest -> val awsType = AwsTypes.fromClass(creationRequest::class) val amazonWebServiceRequest = creationRequest as AmazonWebServiceRequest ResourcePropertyBuilders.getBuilder(awsType)?.takeIf { it.canBuildFrom(amazonWebServiceRequest) }?.let { resourceBuilder -> Resource( Type = awsType.type, Properties = resourceBuilder.buildResource( amazonWebServiceRequest, objectsWithSameName ), DependsOn = nameToDependsOnNames[name]?.let { dependOnNames -> if (dependOnNames.size == 1) { dependOnNames[0] } else { dependOnNames } } ) } } }.filterValues { it != null }.mapValues { it.value!! }, Outputs = context.outputs.map { it.logicalId to Output( Value = it.value, Description = it.description ) }.toMap() ) val templateTree = JSON.valueToTree<ObjectNode>(rawTemplate) TemplateProcessor(context).process(templateTree) return templateTree } } data class Template( var AWSTemplateFormatVersion: String?, var Description: String?, var Parameters: Map<String, Parameter> = emptyMap(), var Mappings: Map<String, Any> = emptyMap(), var Resources: Map<String, Resource> = emptyMap(), val Outputs: Map<String, Output> = emptyMap() ) data class Output( val Description: String?, val Value: String ) data class Parameter( var Description: String?, var Type: String, var Default: String?, var MinLength: String?, var MaxLength: String?, var AllowedValues: List<String>?, var AllowedPattern: String?, var ConstraintDescription: String? ) interface ResourceProperties @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class CloudFormationType(val value: String) @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class CloudFormationTypes data class Resource( var Type: String, var Properties: ResourceProperties? = null, val DependsOn: Any?, // String or List<String> var Metadata: Map<String, Any>? = emptyMap() ) fun ParameterizedValue<out Any>.toCFParameter(): Parameter = Parameter( Description = description, Type = type.cloudFormationName, AllowedPattern = allowedPattern?.pattern, AllowedValues = allowedValues, ConstraintDescription = constraintDescription, Default = defaultValue, MaxLength = allowedLength?.endInclusive?.toString(), MinLength = allowedLength?.start?.toString() )
mit
e81031a3ee8fb5e80a5faaac73ab8e0d
36.244755
102
0.594366
5.298507
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/SoundFileLoader.kt
1
3212
package com.habitrpg.android.habitica.helpers import android.annotation.SuppressLint import android.content.Context import android.os.Environment import com.habitrpg.android.habitica.HabiticaBaseApplication import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okio.Okio import java.io.File import java.io.IOException // based on http://stackoverflow.com/questions/29838565/downloading-files-using-okhttp-okio-and-rxjava class SoundFileLoader(private val context: Context) { private val client: OkHttpClient = OkHttpClient() private val externalCacheDir: String? get() { val cacheDir = HabiticaBaseApplication.getInstance(context)?.getExternalFilesDir(Environment.DIRECTORY_NOTIFICATIONS) return cacheDir?.path } @SuppressLint("SetWorldReadable", "ObsoleteSdkInt", "ReturnCount") fun download(files: List<SoundFile>): Single<List<SoundFile>> { return Observable.fromIterable(files) .flatMap({ audioFile -> val file = File(getFullAudioFilePath(audioFile)) if (file.exists() && file.length() > 5000) { // Important, or else the MediaPlayer can't access this file file.setReadable(true, false) audioFile.file = file return@flatMap Observable.just(audioFile) } val fileObservable = Observable.create<SoundFile> { sub -> val request = Request.Builder().url(audioFile.webUrl).build() val response: Response try { response = client.newCall(request).execute() if (!response.isSuccessful) { throw IOException() } } catch (io: IOException) { sub.onComplete() return@create } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { try { val sink = Okio.buffer(Okio.sink(file)) sink.writeAll(response.body()!!.source()) sink.flush() sink.close() } catch (io: IOException) { sub.onComplete() return@create } file.setReadable(true, false) audioFile.file = file sub.onNext(audioFile) sub.onComplete() } } fileObservable.subscribeOn(Schedulers.io()) }, 5) .toList() } private fun getFullAudioFilePath(soundFile: SoundFile): String = externalCacheDir + File.separator + soundFile.filePath }
gpl-3.0
52c7f72f1a70a15969b533629c88bfec
40.727273
129
0.524284
5.695035
false
false
false
false
viartemev/requestmapper
src/main/kotlin/com/viartemev/requestmapper/RequestMappingItemProvider.kt
1
5266
package com.viartemev.requestmapper import com.intellij.ide.util.gotoByName.* import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.CollectConsumer import com.intellij.util.Processor import com.intellij.util.SmartList import com.intellij.util.SynchronizedCollectConsumer import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.FindSymbolParameters import com.intellij.util.indexing.IdFilter import com.viartemev.requestmapper.model.Path import com.viartemev.requestmapper.model.PopupPath import com.viartemev.requestmapper.model.RequestedUserPath import kotlin.text.MatchResult import kotlin.text.contains import kotlin.text.isEmpty import kotlin.text.split open class RequestMappingItemProvider : ChooseByNameItemProvider { override fun filterNames( base: ChooseByNameViewModel, names: Array<out String>, pattern: String ): MutableList<String> { return java.util.ArrayList() } override fun filterElements( base: ChooseByNameViewModel, pattern: String, everywhere: Boolean, cancelled: ProgressIndicator, consumer: Processor<Any> ): Boolean { if (base.project != null) { base.project!!.putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern) } val idFilter: IdFilter? = null val searchScope = FindSymbolParameters.searchScopeFor(base.project, everywhere) val parameters = FindSymbolParameters(pattern, pattern, searchScope, idFilter) val namesList = getSortedResults(base, pattern, cancelled, parameters) cancelled.checkCanceled() return processByNames(base, everywhere, cancelled, consumer, namesList, parameters) } companion object { private fun getSortedResults( base: ChooseByNameViewModel, pattern: String, indicator: ProgressIndicator, parameters: FindSymbolParameters ): List<String> { if (pattern.isEmpty() && !base.canShowListForEmptyPattern()) { return emptyList() } val namesList: MutableList<String> = ArrayList() val collect: CollectConsumer<String> = SynchronizedCollectConsumer(namesList) val model = base.model if (model is ChooseByNameModelEx) { indicator.checkCanceled() model.processNames( { sequence: String? -> indicator.checkCanceled() if (matches(sequence, pattern)) { collect.consume(sequence) return@processNames true } return@processNames false }, parameters ) } namesList.sortWith(compareBy { PopupPath(it) }) indicator.checkCanceled() return namesList } private fun processByNames( base: ChooseByNameViewModel, everywhere: Boolean, indicator: ProgressIndicator, consumer: Processor<Any>, namesList: List<String>, parameters: FindSymbolParameters ): Boolean { val sameNameElements: MutableList<Any> = SmartList() val qualifierMatchResults: MutableMap<Any, MatchResult> = ContainerUtil.newIdentityTroveMap() val model = base.model for (name in namesList) { indicator.checkCanceled() val elements = if (model is ContributorsBasedGotoByModel) model.getElementsByName(name, parameters, indicator) else model.getElementsByName(name, everywhere, parameters.completePattern) if (elements.size > 1) { sameNameElements.clear() qualifierMatchResults.clear() for (element in elements) { indicator.checkCanceled() sameNameElements.add(element) } if (!ContainerUtil.process(sameNameElements, consumer)) return false } else if (elements.size == 1) { if (!consumer.process(elements[0])) return false } } return true } fun matches(name: String?, pattern: String): Boolean { if (name == null) { return false } return try { if (pattern == "/") { true } else if (!pattern.contains('/')) { val (method, path) = name.split(" ", limit = 2) path.contains(pattern) || method.contains(pattern, ignoreCase = true) } else { val popupPath = PopupPath(name) val requestedUserPath = RequestedUserPath(pattern) Path.isSubpathOf( popupPath.toPath(), requestedUserPath.toPath() ) } } catch (e: Exception) { false // no matches appears valid result for "bad" pattern } } } }
mit
a265fb0f6b4d55b55e5ac33c9947670f
36.884892
201
0.581086
5.401026
false
false
false
false
android/packager-manager-samples
CodeTransparencyKotlin/app/src/main/java/com/example/codetransparencyverification/CodeTransparencyChecker.kt
1
8937
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.codetransparencyverification import android.content.pm.PackageInfo import android.os.Build import com.google.common.hash.Hashing import com.google.common.io.ByteSource import com.google.common.io.ByteStreams import com.google.common.io.CharStreams import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.jose4j.jwa.AlgorithmConstraints import org.jose4j.jwa.AlgorithmConstraints.ConstraintType import org.jose4j.jws.AlgorithmIdentifiers import org.jose4j.jws.JsonWebSignature import org.jose4j.lang.JoseException import java.io.IOException import java.io.InputStreamReader import java.security.cert.X509Certificate import java.util.zip.ZipEntry import java.util.zip.ZipFile /** Class for verifying code transparency for a given package. */ object CodeTransparencyChecker { private const val CODE_TRANSPARENCY_FILE_ENTRY_PATH = "META-INF/code_transparency_signed.jwt" /** * Checks code transparency for the given [PackageInfo] and returns [TransparencyCheckResult]. */ fun checkCodeTransparency(packageInfo: PackageInfo): TransparencyCheckResult { var result = TransparencyCheckResult() try { val keyCertificates: List<String> = getApkSigningKeyCertificates(packageInfo) result = result.copy(apkSigningKeyCertificateFingerprints = keyCertificates) val baseApkPath: String = packageInfo.applicationInfo.sourceDir val codeTransparencyJws: JsonWebSignature = getCodeTransparencyJws(baseApkPath) val transparencyKeyCertFingerPrint: String = checkCodeTransparencySignature(codeTransparencyJws) result = result.copy( isTransparencySignatureVerified = true, transparencyKeyCertificateFingerprint = transparencyKeyCertFingerPrint ) val codeRelatedFilesFromTransparencyFile: Map<String, CodeRelatedFile> = Json.decodeFromString<CodeRelatedFiles>(codeTransparencyJws.unverifiedPayload) .files.associateBy { codeRelatedFile -> codeRelatedFile.sha256 } val splitApkPaths = packageInfo.splitApkPaths.map { path -> baseApkPath + path } val modifiedFiles: List<String> = findModifiedFiles(splitApkPaths, codeRelatedFilesFromTransparencyFile) result = result.copy(isFileContentsVerified = modifiedFiles.isEmpty()) } catch (e: Exception) { result = result.copy(errorMessage = e.message) } return result } private fun getApkSigningKeyCertificates(packageInfo: PackageInfo): List<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { if (packageInfo.signingInfo.hasMultipleSigners()) { throw AssertionError( "Play App Signing does not support multiple signers." ) } else { packageInfo.signingInfo.signingCertificateHistory.map { signature -> getCertificateFingerprint(signature.toByteArray()) } } } else { packageInfo.signatures.map { signature -> getCertificateFingerprint(signature.toByteArray()) } } private fun getCertificateFingerprint(certificate: X509Certificate): String = getCertificateFingerprint(certificate.encoded) private fun getCertificateFingerprint(encodedCertificate: ByteArray): String = getCertificateFingerprintBytes(encodedCertificate).joinToString(":") { byte -> byte.toString(16) } private fun getCertificateFingerprintBytes(encodedCertificate: ByteArray): ByteArray = ByteSource.wrap(encodedCertificate).hash(Hashing.sha256()).asBytes() private fun getCodeTransparencyJws(baseApkPath: String): JsonWebSignature = ZipFile(baseApkPath).use { baseApkFile -> val transparencyFileEntry: ZipEntry = baseApkFile.getEntry(CODE_TRANSPARENCY_FILE_ENTRY_PATH) ?: throw RuntimeException( "Installed base APK does not contain code transparency file." ) val serializedJwt: String = getSerializedCodeTransparencyJws(baseApkFile, transparencyFileEntry) ?: throw RuntimeException("Error parsing the code transparency file.") try { JsonWebSignature.fromCompactSerialization(serializedJwt) as JsonWebSignature } catch (e: JoseException) { throw RuntimeException( "Error constructing JsonWebSignature from compact serialization." ) } } private fun getSerializedCodeTransparencyJws( baseApkFile: ZipFile, codeTransparencyEntry: ZipEntry ): String? = try { baseApkFile.getInputStream(codeTransparencyEntry).use { inputStream -> CharStreams.toString(InputStreamReader(inputStream)) } } catch (e: IOException) { null } private fun checkCodeTransparencySignature(jws: JsonWebSignature): String = try { val publicKeyCert: X509Certificate = jws.leafCertificateHeaderValue jws.key = publicKeyCert.publicKey jws.setAlgorithmConstraints( AlgorithmConstraints( ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_USING_SHA256 ) ) if (jws.verifySignature()) { getCertificateFingerprint(jws.leafCertificateHeaderValue) } else { throw RuntimeException("Code transparency signature is invalid.") } } catch (e: Exception) { throw RuntimeException("Encountered error while verifying code transparency signature.") } private fun findModifiedFiles( installedApkPaths: List<String>, codeRelatedFilesFromTransparencyFile: Map<String, CodeRelatedFile> ): List<String> = installedApkPaths.flatMap { installedApkPath -> ZipFile(installedApkPath).use { apk -> findModifiedDexFiles(apk, codeRelatedFilesFromTransparencyFile) + findModifiedNativeLibraries(apk, codeRelatedFilesFromTransparencyFile) } } private fun findModifiedDexFiles( apk: ZipFile, codeRelatedFilesFromTransparencyFile: Map<String, CodeRelatedFile> ): List<String> = apk.entries() .toList() .filter { entry -> entry.isDexFile } .filter { entry -> val fileHash: String = getFileHash(apk, entry) !codeRelatedFilesFromTransparencyFile.containsKey(fileHash) || codeRelatedFilesFromTransparencyFile[fileHash]?.type != CodeRelatedFile.Type.DEX }.map { entry -> entry.name } private fun findModifiedNativeLibraries( apk: ZipFile, codeRelatedFilesFromTransparencyFile: Map<String, CodeRelatedFile> ): List<String> = apk.entries() .toList() .filter { entry -> entry.isNativeLibrary } .filter { entry -> val fileHash: String = getFileHash(apk, entry) !codeRelatedFilesFromTransparencyFile.containsKey(fileHash) || codeRelatedFilesFromTransparencyFile[fileHash]?.type != CodeRelatedFile.Type.NATIVE_LIBRARY || // For native libraries path to the file in the APK is known at code transparency // file generation time. This is not true for dex files, so APK path should not be // checked for them. codeRelatedFilesFromTransparencyFile[fileHash]?.apkPath != entry.name }.map { entry -> entry.name } private val ZipEntry.isDexFile: Boolean get() = name.endsWith(".dex") private val ZipEntry.isNativeLibrary: Boolean get() = name.endsWith(".so") private fun getFileHash(apkFile: ZipFile, zipEntry: ZipEntry): String = apkFile.getInputStream(zipEntry).use { inputStream -> ByteSource.wrap(ByteStreams.toByteArray(inputStream)) .hash(Hashing.sha256()) .toString() } private val PackageInfo.splitApkPaths: List<String> get() = applicationInfo.splitSourceDirs?.toList() ?: emptyList() }
apache-2.0
46ae93d775668b7d2075e948938cb0ec
41.35545
98
0.672485
5.052007
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/fragment/OthersBookmarkFragment.kt
1
5874
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.presentation.widget.fragment import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.Binds import dagger.android.AndroidInjector import dagger.android.support.DaggerFragment import dagger.android.support.FragmentKey import dagger.multibindings.IntoMap import io.reactivex.disposables.CompositeDisposable import me.rei_m.hbfavmaterial.R import me.rei_m.hbfavmaterial.databinding.FragmentOthersBookmarkBinding import me.rei_m.hbfavmaterial.di.ForFragment import me.rei_m.hbfavmaterial.presentation.helper.Navigator import me.rei_m.hbfavmaterial.presentation.helper.SnackbarFactory import me.rei_m.hbfavmaterial.presentation.widget.adapter.BookmarkListAdapter import me.rei_m.hbfavmaterial.viewmodel.widget.adapter.di.BookmarkListItemViewModelModule import me.rei_m.hbfavmaterial.viewmodel.widget.fragment.OthersBookmarkFragmentViewModel import me.rei_m.hbfavmaterial.viewmodel.widget.fragment.di.OthersBookmarkFragmentViewModelModule import javax.inject.Inject /** * 特定のユーザーのブックマークを一覧で表示するFragment. */ class OthersBookmarkFragment : DaggerFragment() { companion object { private const val ARG_USER_ID = "ARG_USER_ID" /** * 他人のブックマークを表示する * * @userId: 表示対象のユーザーのID. * @return Fragment */ fun newInstance(userId: String) = OthersBookmarkFragment().apply { arguments = Bundle().apply { putString(ARG_USER_ID, userId) } } } @Inject lateinit var navigator: Navigator @Inject lateinit var viewModelFactory: OthersBookmarkFragmentViewModel.Factory @Inject lateinit var injector: BookmarkListAdapter.Injector private lateinit var binding: FragmentOthersBookmarkBinding private lateinit var viewModel: OthersBookmarkFragmentViewModel private lateinit var adapter: BookmarkListAdapter private var disposable: CompositeDisposable? = null private var footerView: View? = null private val userId: String by lazy { requireNotNull(arguments?.getString(ARG_USER_ID)) { "Arguments is NULL $ARG_USER_ID" } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory).get(OthersBookmarkFragmentViewModel::class.java) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentOthersBookmarkBinding.inflate(inflater, container, false) binding.viewModel = viewModel adapter = BookmarkListAdapter(context!!, injector, viewModel.bookmarkList) binding.listView.adapter = adapter return binding.root } override fun onDestroyView() { adapter.releaseCallback() footerView = null super.onDestroyView() } override fun onResume() { super.onResume() disposable = CompositeDisposable() disposable?.addAll(viewModel.hasNextPageUpdatedEvent.subscribe { if (it) { if (footerView == null) { footerView = View.inflate(binding.listView.context, R.layout.list_fotter_loading, null) binding.listView.addFooterView(footerView) } } else { if (footerView != null) { binding.listView.removeFooterView(footerView) footerView = null } } }, viewModel.onItemClickEvent.subscribe { navigator.navigateToBookmark(it) }, viewModel.onRaiseGetNextPageErrorEvent.subscribe { SnackbarFactory(binding.root).create(R.string.message_error_network).show() }, viewModel.onRaiseRefreshErrorEvent.subscribe { SnackbarFactory(binding.root).create(R.string.message_error_network).show() }) } override fun onPause() { disposable?.dispose() disposable = null super.onPause() } @ForFragment @dagger.Subcomponent(modules = arrayOf( OthersBookmarkFragmentViewModelModule::class, BookmarkListItemViewModelModule::class)) interface Subcomponent : AndroidInjector<OthersBookmarkFragment> { @dagger.Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<OthersBookmarkFragment>() { abstract fun viewModelModule(module: OthersBookmarkFragmentViewModelModule): Builder override fun seedInstance(instance: OthersBookmarkFragment) { viewModelModule(OthersBookmarkFragmentViewModelModule(instance.userId)) } } } @dagger.Module(subcomponents = arrayOf(Subcomponent::class)) abstract inner class Module { @Binds @IntoMap @FragmentKey(OthersBookmarkFragment::class) internal abstract fun bind(builder: Subcomponent.Builder): AndroidInjector.Factory<out Fragment> } }
apache-2.0
467bcc8329ee31b50fe9b74b26294892
34.913043
116
0.704773
4.879325
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/WhenToIfIntention.kt
3
4041
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.combineWhenConditions import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isFalseConstant import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>( KtWhenExpression::class.java, KotlinBundle.lazyMessage("replace.when.with.if") ), LowPriorityAction { override fun applicabilityRange(element: KtWhenExpression): TextRange? { val entries = element.entries if (entries.isEmpty()) return null val lastEntry = entries.last() if (entries.any { it != lastEntry && it.isElse }) return null if (entries.all { it.isElse }) return null // 'when' with only 'else' branch is not supported if (element.subjectExpression is KtProperty) return null if (!lastEntry.isElse) { val bindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL_WITH_CFA) if (bindingContext == BindingContext.EMPTY || element.isUsedAsExpression(bindingContext)) return null } return element.whenKeyword.textRange } override fun applyTo(element: KtWhenExpression, editor: Editor?) { val commentSaver = CommentSaver(element) val factory = KtPsiFactory(element) val isTrueOrFalseCondition = element.isTrueOrFalseCondition() val ifExpression = factory.buildExpression { val entries = element.entries for ((i, entry) in entries.withIndex()) { if (i > 0) { appendFixedText("else ") } val branch = entry.expression if (entry.isElse || (isTrueOrFalseCondition && i == 1)) { appendExpression(branch) } else { val condition = factory.combineWhenConditions(entry.conditions, element.subjectExpression) appendFixedText("if (") appendExpression(condition) appendFixedText(")") if (branch is KtIfExpression) { appendFixedText("{ ") } appendExpression(branch) if (branch is KtIfExpression) { appendFixedText(" }") } } if (i != entries.lastIndex) { appendFixedText("\n") } } } val result = element.replace(ifExpression) commentSaver.restore(result) } private fun KtWhenExpression.isTrueOrFalseCondition(): Boolean { val entries = this.entries if (entries.size != 2) return false val first = entries[0]?.conditionExpression() ?: return false val second = entries[1]?.conditionExpression() ?: return false return first.isTrueConstant() && second.isFalseConstant() || first.isFalseConstant() && second.isTrueConstant() } private fun KtWhenEntry.conditionExpression(): KtExpression? { return (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression } }
apache-2.0
a0e3775957299a7acdda8fce956f9589
44.920455
158
0.667409
5.446092
false
false
false
false
ursjoss/sipamato
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/keyword/KeywordListPageTest.kt
1
5248
package ch.difty.scipamato.core.web.keyword import ch.difty.scipamato.core.entity.keyword.KeywordDefinition import ch.difty.scipamato.core.entity.keyword.KeywordTranslation import ch.difty.scipamato.core.web.common.BasePageTest import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable import io.mockk.confirmVerified import io.mockk.every import io.mockk.verify import org.apache.wicket.markup.html.form.Form import org.apache.wicket.markup.html.link.Link import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test @Suppress("SameParameterValue", "PrivatePropertyName") internal class KeywordListPageTest : BasePageTest<KeywordListPage>() { private val kt1_de = KeywordTranslation(1, "de", "Name1", 1) private val kt1_en = KeywordTranslation(2, "en", "name1", 1) private val kt1_fr = KeywordTranslation(3, "fr", "nom1", 1) private val kd1 = KeywordDefinition(1, "de", "nameOverride", 1, kt1_de, kt1_en, kt1_fr) private val kt2_en = KeywordTranslation(5, "en", "name2", 1) private val kt2_fr = KeywordTranslation(6, "fr", "nom2", 1) private val kt2_de = KeywordTranslation(4, "de", "Name2", 1) private val kd2 = KeywordDefinition(2, "de", 1, kt2_de, kt2_en, kt2_fr) private val results: List<KeywordDefinition> = listOf(kd1, kd2) override fun setUpHook() { every { keywordServiceMock.countByFilter(any()) } returns results.size every { keywordServiceMock.findPageOfEntityDefinitions(any(), any()) } returns results.iterator() } @AfterEach fun tearDown() { confirmVerified(keywordServiceMock) } override fun makePage(): KeywordListPage = KeywordListPage(null) override val pageClass: Class<KeywordListPage> get() = KeywordListPage::class.java override fun assertSpecificComponents() { assertFilterForm("filterPanel:filterForm") val headers = arrayOf("Translations", "Search Override") val values = arrayOf("DE: 'Name1'; EN: 'name1'; FR: 'nom1'".replace("'", "&#039;"), "nameOverride") assertResultTable("resultPanel:results", headers, values) verify { keywordServiceMock.countByFilter(any()) } verify { keywordServiceMock.findPageOfEntityDefinitions(any(), any()) } } private fun assertFilterForm(b: String) { tester.assertComponent(b, Form::class.java) assertLabeledTextField(b, "name") tester.assertComponent("$b:newKeyword", BootstrapAjaxButton::class.java) } private fun assertResultTable(b: String, labels: Array<String>, values: Array<String>) { tester.assertComponent(b, BootstrapDefaultDataTable::class.java) assertHeaderColumns(b, labels) assertTableValuesOfRow(b, 1, COLUMN_ID_WITH_LINK, values) } private fun assertHeaderColumns(b: String, labels: Array<String>) { var idx = 0 labels.forEach { label -> tester.assertLabel( "$b:topToolbars:toolbars:2:headers:${++idx}:header:orderByLink:header_body:label", label ) } } private fun assertTableValuesOfRow(b: String, rowIdx: Int, colIdxAsLink: Int?, values: Array<String>) { if (colIdxAsLink != null) tester.assertComponent("$b:body:rows:$rowIdx:cells:$colIdxAsLink:cell:link", Link::class.java) var colIdx = 1 for (value in values) tester.assertLabel( "$b:body:rows:$rowIdx:cells:$colIdx:cell${if (colIdxAsLink != null && colIdx++ == colIdxAsLink) ":link:label" else ""}", value ) } @Test fun clickingOnKeywordTitle_forwardsToKeywordEditPage_withModelLoaded() { tester.startPage(pageClass) tester.clickLink("resultPanel:results:body:rows:1:cells:$COLUMN_ID_WITH_LINK:cell:link") tester.assertRenderedPage(KeywordEditPage::class.java) // verify the keywords were loaded into the target page tester.assertModelValue("form:translationsPanel:translations:1:name", "Name1") tester.assertModelValue("form:translationsPanel:translations:2:name", "name1") tester.assertModelValue("form:translationsPanel:translations:3:name", "nom1") verify { keywordServiceMock.countByFilter(any()) } verify { keywordServiceMock.findPageOfEntityDefinitions(any(), any()) } } @Test fun clickingNewKeyword_forwardsToKeywordEditPage() { val kt_en = KeywordTranslation(1, "en", "kt_en", 1) val kd = KeywordDefinition(1, "en", 1, kt_en) every { keywordServiceMock.newUnpersistedKeywordDefinition() } returns kd tester.startPage(pageClass) tester.assertRenderedPage(pageClass) val formTester = tester.newFormTester("filterPanel:filterForm") formTester.submit("newKeyword") tester.assertRenderedPage(KeywordEditPage::class.java) verify { keywordServiceMock.countByFilter(any()) } verify { keywordServiceMock.findPageOfEntityDefinitions(any(), any()) } verify { keywordServiceMock.newUnpersistedKeywordDefinition() } } companion object { private const val COLUMN_ID_WITH_LINK = 1 } }
gpl-3.0
769de860bceaba5af0fe31cefd83a983
43.474576
136
0.693026
3.987842
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt
1
2562
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.MESSAGE_FOR_YIELD_BEFORE_LAMBDA class UnsupportedYieldFix(psiElement: PsiElement) : KotlinQuickFixAction<PsiElement>(psiElement), CleanupFix { override fun getFamilyName(): String = KotlinBundle.message("migrate.unsupported.yield.syntax") override fun getText(): String = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { val psiElement = element ?: return val psiFactory = KtPsiFactory(project) if (psiElement is KtCallExpression) { val ktExpression = (psiElement as KtCallElement).calleeExpression ?: return // Add after "yield" reference in call psiElement.addAfter(psiFactory.createCallArguments("()"), ktExpression) } if (psiElement.node.elementType == KtTokens.IDENTIFIER) { psiElement.replace(psiFactory.createIdentifier("`yield`")) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { if (diagnostic.psiElement.text != "yield") return null val message = Errors.YIELD_IS_RESERVED.cast(diagnostic).a if (message == MESSAGE_FOR_YIELD_BEFORE_LAMBDA) { // Identifier -> Expression -> Call (normal call) or Identifier -> Operation Reference -> Binary Expression (for infix usage) val grand = diagnostic.psiElement.parent.parent if (grand is KtBinaryExpression || grand is KtCallExpression) { return UnsupportedYieldFix(grand) } } else { return UnsupportedYieldFix(diagnostic.psiElement) } return null } } }
apache-2.0
d204dbb131305338ff26f3052012c93c
44.767857
158
0.709992
4.974757
false
false
false
false
stupacki/MultiFunctions
multi-functions/src/main/kotlin/io/multifunctions/MultiForEach.kt
1
1916
package io.multifunctions import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad /** * Performs the given [action] on each [Pair] element. */ public inline infix fun <A, B> Iterable<Pair<A?, B?>>.forEach(action: (A?, B?) -> Unit) = forEach { (first, second) -> action(first, second) } /** * Performs the given [action] on each [Triple] element. */ public inline infix fun <A, B, C> Iterable<Triple<A?, B?, C?>>.forEach(action: (A?, B?, C?) -> Unit) = forEach { (first, second, third) -> action(first, second, third) } /** * Performs the given [action] on each [Quad] element. */ public inline infix fun <A, B, C, D> Iterable<Quad<A?, B?, C?, D?>>.forEach(action: (A?, B?, C?, D?) -> Unit) = forEach { (first, second, third, fourth) -> action(first, second, third, fourth) } /** * Performs the given [action] on each [Penta] element. */ public inline infix fun <A, B, C, D, E> Iterable<Penta<A?, B?, C?, D?, E?>>.forEach(action: (A?, B?, C?, D?, E?) -> Unit) = forEach { (first, second, third, fourth, fifth) -> action(first, second, third, fourth, fifth) } /** * Performs the given [action] on each [Hexa] element. */ public inline infix fun <A, B, C, D, E, F> Iterable<Hexa<A?, B?, C?, D?, E?, F?>>.forEach(action: (A?, B?, C?, D?, E?, F?) -> Unit) = forEach { (first, second, third, fourth, fifth, sixth) -> action(first, second, third, fourth, fifth, sixth) } /** * Performs the given [action] on each [Hepta] element. */ public inline infix fun <A, B, C, D, E, F, G> Iterable<Hepta<A?, B?, C?, D?, E?, F?, G?>>.forEach( action: (A?, B?, C?, D?, E?, F?, G?) -> Unit ) = forEach { (first, second, third, fourth, fifth, sixth, seventh) -> action(first, second, third, fourth, fifth, sixth, seventh) }
apache-2.0
6d3833016999895c6f21b490fc3719e1
33.214286
133
0.596033
3.151316
false
false
false
false
kotlinx/kotlinx.html
src/commonMain/kotlin/filter-consumer.kt
1
2665
package kotlinx.html.consumers import kotlinx.html.* import org.w3c.dom.events.* object PredicateResults { val PASS = PredicateResult.PASS val SKIP = PredicateResult.SKIP val DROP = PredicateResult.DROP } enum class PredicateResult { PASS, SKIP, DROP } private class FilterTagConsumer<T>(val downstream: TagConsumer<T>, val predicate: (Tag) -> PredicateResult) : TagConsumer<T> { private var currentLevel = 0 private var skippedLevels = HashSet<Int>() private var dropLevel: Int? = null override fun onTagStart(tag: Tag) { currentLevel++ if (dropLevel == null) { when (predicate(tag)) { PredicateResult.PASS -> downstream.onTagStart(tag) PredicateResult.SKIP -> skippedLevels.add(currentLevel) PredicateResult.DROP -> dropLevel = currentLevel } } } override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) { throw UnsupportedOperationException("this filter doesn't support attribute change") } override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) { throw UnsupportedOperationException("this filter doesn't support attribute change") } override fun onTagEnd(tag: Tag) { if (canPassCurrentLevel()) { downstream.onTagEnd(tag) } skippedLevels.remove(currentLevel) if (dropLevel == currentLevel) { dropLevel = null } currentLevel-- } override fun onTagContent(content: CharSequence) { if (canPassCurrentLevel()) { downstream.onTagContent(content) } } override fun onTagContentEntity(entity: Entities) { if (canPassCurrentLevel()) { downstream.onTagContentEntity(entity) } } override fun onTagContentUnsafe(block: Unsafe.() -> Unit) { if (canPassCurrentLevel()) { downstream.onTagContentUnsafe(block) } } private fun canPassCurrentLevel() = dropLevel == null && currentLevel !in skippedLevels override fun onTagError(tag: Tag, exception: Throwable) { if (canPassCurrentLevel()) { downstream.onTagError(tag, exception) } } override fun onTagComment(content: CharSequence) { if (canPassCurrentLevel()) { downstream.onTagComment(content) } } override fun finalize(): T = downstream.finalize() } fun <T> TagConsumer<T>.filter(predicate: PredicateResults.(Tag) -> PredicateResult): TagConsumer<T> = FilterTagConsumer(this) { PredicateResults.predicate(it) }.delayed()
apache-2.0
7043f0614181872837f3fe6b970c0b30
27.666667
109
0.638274
4.501689
false
false
false
false
GunoH/intellij-community
plugins/editorconfig/src/org/editorconfig/language/schema/parser/handlers/impl/EditorConfigDeclarationDescriptorParseHandler.kt
16
2085
// 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.schema.parser.handlers.impl import com.google.gson.JsonObject import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.DOCUMENTATION import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.ID import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.NEEDS_REFERENCES import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.REQUIRED import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.TYPE import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaException import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaParser import org.editorconfig.language.schema.parser.handlers.EditorConfigDescriptorParseHandlerBase class EditorConfigDeclarationDescriptorParseHandler : EditorConfigDescriptorParseHandlerBase() { override val requiredKeys = listOf(TYPE, ID) override val optionalKeys = super.optionalKeys + listOf(NEEDS_REFERENCES, REQUIRED) override fun doHandle(jsonObject: JsonObject, parser: EditorConfigJsonSchemaParser): EditorConfigDescriptor { val rawId = jsonObject[ID] if (!rawId.isJsonPrimitive) { throw EditorConfigJsonSchemaException(jsonObject) } val id = rawId.asString val documentation = tryGetString(jsonObject, DOCUMENTATION) val deprecation = tryGetString(jsonObject, EditorConfigJsonSchemaConstants.DEPRECATION) val needsReferences = tryGetBoolean(jsonObject, NEEDS_REFERENCES) ?: true val required = tryGetBoolean(jsonObject, REQUIRED) ?: false return EditorConfigDeclarationDescriptor(id, needsReferences, required, documentation, deprecation) } }
apache-2.0
0bd45ead1696b7cdb6ca9535198b163e
58.571429
140
0.844604
5.265152
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddMemberToSupertypeFix.kt
2
13026
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.IconManager import com.intellij.util.PlatformIcons import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.AddMemberToSupertypeFix.MemberData import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.modalityModifier import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.Icon abstract class AddMemberToSupertypeFix(element: KtCallableDeclaration, private val candidateMembers: List<MemberData>) : KotlinQuickFixAction<KtCallableDeclaration>(element), LowPriorityAction { class MemberData(val signaturePreview: String, val sourceCode: String, val targetClass: KtClass) init { assert(candidateMembers.isNotEmpty()) } abstract val kind: String abstract val icon: Icon override fun getText(): String = candidateMembers.singleOrNull()?.let { actionName(it) } ?: KotlinBundle.message("fix.add.member.supertype.text", kind) override fun getFamilyName() = KotlinBundle.message("fix.add.member.supertype.family", kind) override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor?, file: KtFile) { CommandProcessor.getInstance().runUndoTransparentAction { if (candidateMembers.size == 1 || editor == null || !editor.component.isShowing) { addMember(candidateMembers.first(), project) } else { JBPopupFactory.getInstance().createListPopup(createMemberPopup(project)).showInBestPositionFor(editor) } } } private fun addMember(memberData: MemberData, project: Project) { project.executeWriteCommand(KotlinBundle.message("fix.add.member.supertype.progress", kind)) { element?.removeDefaultParameterValues() val classBody = memberData.targetClass.getOrCreateBody() val memberElement: KtCallableDeclaration = KtPsiFactory(project).createDeclaration(memberData.sourceCode) memberElement.copyAnnotationEntriesFrom(element) val insertedMemberElement = classBody.addBefore(memberElement, classBody.rBrace) as KtCallableDeclaration ShortenReferences.DEFAULT.process(insertedMemberElement) val modifierToken = insertedMemberElement.modalityModifier()?.node?.elementType as? KtModifierKeywordToken ?: return@executeWriteCommand if (insertedMemberElement.implicitModality() == modifierToken) { RemoveModifierFixBase(insertedMemberElement, modifierToken, true).invoke() } } } private fun KtCallableDeclaration.removeDefaultParameterValues() { valueParameters.forEach { it.defaultValue?.delete() it.equalsToken?.delete() } } private fun KtCallableDeclaration.copyAnnotationEntriesFrom(member: KtCallableDeclaration?) { member?.annotationEntries?.reversed()?.forEach { addAnnotationEntry(it) } } private fun createMemberPopup(project: Project): ListPopupStep<*> { return object : BaseListPopupStep<MemberData>(KotlinBundle.message("fix.add.member.supertype.choose.type"), candidateMembers) { override fun isAutoSelectionEnabled() = false override fun onChosen(selectedValue: MemberData, finalChoice: Boolean): PopupStep<*>? { if (finalChoice) { addMember(selectedValue, project) } return PopupStep.FINAL_CHOICE } override fun getIconFor(value: MemberData) = icon override fun getTextFor(value: MemberData) = actionName(value) } } @Nls private fun actionName(memberData: MemberData): String = KotlinBundle.message( "fix.add.member.supertype.add.to", memberData.signaturePreview, memberData.targetClass.name.toString() ) } abstract class AddMemberToSupertypeFactory : KotlinSingleIntentionActionFactory() { protected fun getCandidateMembers(memberElement: KtCallableDeclaration): List<MemberData> { val descriptors = generateCandidateMembers(memberElement) return descriptors.mapNotNull { createMemberData(it, memberElement) } } abstract fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? private fun generateCandidateMembers(memberElement: KtCallableDeclaration): List<CallableMemberDescriptor> { val memberDescriptor = memberElement.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableMemberDescriptor ?: return emptyList() val containingClass = memberDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList() // TODO: filter out impossible supertypes (for example when argument's type isn't visible in a superclass). return getKotlinSourceSuperClasses(containingClass).map { generateMemberSignatureForType(memberDescriptor, it) } } private fun getKotlinSourceSuperClasses(classDescriptor: ClassDescriptor): List<ClassDescriptor> { val supertypes = classDescriptor.defaultType.supertypes().toMutableList().sortSubtypesFirst() return supertypes.mapNotNull { type -> type.constructor.declarationDescriptor.safeAs<ClassDescriptor>().takeIf { it !is JavaClassDescriptor && it !is DeserializedClassDescriptor } } } private fun MutableList<KotlinType>.sortSubtypesFirst(): List<KotlinType> { val typeChecker = KotlinTypeChecker.DEFAULT for (i in 1 until size) { val currentType = this[i] for (j in 0 until i) { if (typeChecker.isSubtypeOf(currentType, this[j])) { this.removeAt(i) this.add(j, currentType) break } } } return this } private fun generateMemberSignatureForType( memberDescriptor: CallableMemberDescriptor, typeDescriptor: ClassDescriptor ): CallableMemberDescriptor { // TODO: support for generics. val modality = if (typeDescriptor.kind == ClassKind.INTERFACE || typeDescriptor.modality == Modality.SEALED) { Modality.ABSTRACT } else { typeDescriptor.modality } return memberDescriptor.copy( typeDescriptor, modality, memberDescriptor.visibility, CallableMemberDescriptor.Kind.DECLARATION, /* copyOverrides = */ false ) } } class AddFunctionToSupertypeFix private constructor(element: KtNamedFunction, functions: List<MemberData>) : AddMemberToSupertypeFix(element, functions) { override val kind: String = "function" override val icon: Icon = IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Function) companion object : AddMemberToSupertypeFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val functionElement = diagnostic.psiElement as? KtNamedFunction ?: return null val candidateFunctions = getCandidateMembers(functionElement) return if (candidateFunctions.isNotEmpty()) AddFunctionToSupertypeFix(functionElement, candidateFunctions) else null } override fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? { val classDescriptor = memberDescriptor.containingDeclaration as ClassDescriptor val project = memberElement.project var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.withNoAnnotations().withDefaultValueOption(project).render(memberDescriptor) if (classDescriptor.kind != ClassKind.INTERFACE && memberDescriptor.modality != Modality.ABSTRACT) { val returnType = memberDescriptor.returnType sourceCode += if (returnType == null || !KotlinBuiltIns.isUnit(returnType)) { val bodyText = getFunctionBodyTextFromTemplate( project, TemplateKind.FUNCTION, memberDescriptor.name.asString(), memberDescriptor.returnType?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } ?: "Unit", classDescriptor.importableFqName ) "{\n$bodyText\n}" } else { "{}" } } val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor) as? KtClass ?: return null return MemberData( IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withDefaultValueOption(project).render(memberDescriptor), sourceCode, targetClass ) } } } class AddPropertyToSupertypeFix private constructor(element: KtProperty, properties: List<MemberData>) : AddMemberToSupertypeFix(element, properties) { override val kind: String = "property" override val icon: Icon = PlatformIcons.PROPERTY_ICON companion object : AddMemberToSupertypeFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val propertyElement = diagnostic.psiElement as? KtProperty ?: return null val candidateProperties = getCandidateMembers(propertyElement) return if (candidateProperties.isNotEmpty()) AddPropertyToSupertypeFix(propertyElement, candidateProperties) else null } override fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? { val classDescriptor = memberDescriptor.containingDeclaration as ClassDescriptor val signaturePreview = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(memberDescriptor) var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.withNoAnnotations().render(memberDescriptor) val initializer = memberElement.safeAs<KtProperty>()?.initializer if (classDescriptor.kind == ClassKind.CLASS && classDescriptor.modality == Modality.OPEN && initializer != null) { sourceCode += " = ${initializer.text}" } val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(memberElement.project, classDescriptor) as? KtClass ?: return null return MemberData(signaturePreview, sourceCode, targetClass) } } } private fun DescriptorRenderer.withNoAnnotations(): DescriptorRenderer { return withOptions { modifiers -= DescriptorRendererModifier.ANNOTATIONS } } private fun DescriptorRenderer.withDefaultValueOption(project: Project): DescriptorRenderer { return withOptions { this.defaultParameterValueRenderer = { OptionalParametersHelper.defaultParameterValueExpression(it, project)?.text ?: error("value parameter renderer shouldn't be called when there is no value to render") } } }
apache-2.0
e2e25133a21e62cbf52ed0f958d90bab
47.608209
141
0.714494
5.535912
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/BaseKotlinConverter.kt
1
35486
// 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.uast.kotlin import com.intellij.openapi.components.ServiceManager import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.* import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink import org.jetbrains.kotlin.kdoc.psi.impl.KDocName import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.expressions.UInjectionHost import org.jetbrains.uast.internal.UElementAlternative import org.jetbrains.uast.internal.accommodate import org.jetbrains.uast.internal.alternative import org.jetbrains.uast.kotlin.psi.* @ApiStatus.Internal interface BaseKotlinConverter { val languagePlugin: UastLanguagePlugin fun unwrapElements(element: PsiElement?): PsiElement? = when (element) { is KtValueArgumentList -> unwrapElements(element.parent) is KtValueArgument -> unwrapElements(element.parent) is KtDeclarationModifierList -> unwrapElements(element.parent) is KtContainerNode -> unwrapElements(element.parent) is KtSimpleNameStringTemplateEntry -> unwrapElements(element.parent) is PsiParameterList -> unwrapElements(element.parent) is KtTypeArgumentList -> unwrapElements(element.parent) is KtTypeProjection -> unwrapElements(element.parent) is KtTypeElement -> unwrapElements(element.parent) is KtSuperTypeList -> unwrapElements(element.parent) is KtFinallySection -> unwrapElements(element.parent) is KtAnnotatedExpression -> unwrapElements(element.parent) is KtWhenConditionWithExpression -> unwrapElements(element.parent) is KDocLink -> unwrapElements(element.parent) is KDocSection -> unwrapElements(element.parent) is KDocTag -> unwrapElements(element.parent) else -> element } fun convertAnnotation( annotationEntry: KtAnnotationEntry, givenParent: UElement? ): UAnnotation { return KotlinUAnnotation(annotationEntry, givenParent) } fun convertDeclaration( element: PsiElement, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UElement? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, givenParent) } fun <P : PsiElement, K : KtElement> buildKt(ktElement: K, ctor: (P, K, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, ktElement, givenParent) } fun <P : PsiElement, K : KtElement> buildKtOpt(ktElement: K?, ctor: (P, K?, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, ktElement, givenParent) } fun Array<out Class<out UElement>>.convertToUField(original: PsiField, kotlinOrigin: KtElement?): UElement? = if (original is PsiEnumConstant) el<UEnumConstant>(buildKtOpt(kotlinOrigin, ::KotlinUEnumConstant)) else el<UField>(buildKtOpt(kotlinOrigin, ::KotlinUField)) return with(requiredTypes) { when (element) { is KtLightMethod -> { el<UMethod>(build(KotlinUMethod::create)) } is UastFakeLightMethod -> { el<UMethod> { val ktFunction = element.original if (ktFunction.isLocal) convertDeclaration(ktFunction, givenParent, requiredTypes) else KotlinUMethodWithFakeLightDelegate(ktFunction, element, givenParent) } } is UastFakeLightPrimaryConstructor -> { convertFakeLightConstructorAlternatives(element, givenParent, requiredTypes).firstOrNull() } is KtLightClass -> { when (element.kotlinOrigin) { is KtEnumEntry -> el<UEnumConstant> { convertEnumEntry(element.kotlinOrigin as KtEnumEntry, givenParent) } else -> el<UClass> { KotlinUClass.create(element, givenParent) } } } is KtLightField -> { convertToUField(element, element.kotlinOrigin) } is KtLightFieldForSourceDeclarationSupport -> { // KtLightFieldForDecompiledDeclaration is not a KtLightField convertToUField(element, element.kotlinOrigin) } is KtLightParameter -> { el<UParameter>(buildKtOpt(element.kotlinOrigin, ::KotlinUParameter)) } is UastKotlinPsiParameter -> { el<UParameter>(buildKt(element.ktParameter, ::KotlinUParameter)) } is UastKotlinPsiParameterBase<*> -> { el<UParameter> { element.ktOrigin.safeAs<KtTypeReference>()?.let { convertReceiverParameter(it) } } } is UastKotlinPsiVariable -> { el<ULocalVariable>(buildKt(element.ktElement, ::KotlinULocalVariable)) } is KtEnumEntry -> { el<UEnumConstant> { convertEnumEntry(element, givenParent) } } is KtClassOrObject -> { convertClassOrObject(element, givenParent, this).firstOrNull() } is KtFunction -> { if (element.isLocal) { el<ULambdaExpression> { val parent = element.parent if (parent is KtLambdaExpression) { KotlinULambdaExpression(parent, givenParent) // your parent is the ULambdaExpression } else if (element.name.isNullOrEmpty()) { createLocalFunctionLambdaExpression(element, givenParent) } else { val uDeclarationsExpression = createLocalFunctionDeclaration(element, givenParent) val localFunctionVar = uDeclarationsExpression.declarations.single() as KotlinLocalFunctionUVariable localFunctionVar.uastInitializer } } } else { el<UMethod> { val lightMethod = LightClassUtil.getLightClassMethod(element) if (lightMethod != null) convertDeclaration(lightMethod, givenParent, requiredTypes) else { val ktLightClass = getLightClassForFakeMethod(element) ?: return null KotlinUMethodWithFakeLightDelegate(element, ktLightClass, givenParent) } } } } is KtPropertyAccessor -> { el<UMethod> { val lightMethod = LightClassUtil.getLightClassAccessorMethod(element) ?: return null convertDeclaration(lightMethod, givenParent, requiredTypes) } } is KtProperty -> { if (element.isLocal) { convertPsiElement(element, givenParent, requiredTypes) } else { convertNonLocalProperty(element, givenParent, requiredTypes).firstOrNull() } } is KtParameter -> { convertParameter(element, givenParent, this).firstOrNull() } is KtFile -> { convertKtFile(element, givenParent, this).firstOrNull() } is FakeFileForLightClass -> { el<UFile> { KotlinUFile(element.navigationElement, languagePlugin) } } is KtAnnotationEntry -> { el<UAnnotation>(build(::convertAnnotation)) } is KtCallExpression -> { if (requiredTypes.isAssignableFrom(KotlinUNestedAnnotation::class.java) && !requiredTypes.isAssignableFrom(UCallExpression::class.java) ) { el<UAnnotation> { KotlinUNestedAnnotation.create(element, givenParent) } } else null } is KtLightElementBase -> { element.kotlinOrigin?.let { convertDeclarationOrElement(it, givenParent, requiredTypes) } } is KtDelegatedSuperTypeEntry -> { el<KotlinSupertypeDelegationUExpression> { KotlinSupertypeDelegationUExpression(element, givenParent) } } else -> null } } } fun convertDeclarationOrElement( element: PsiElement, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>> ): UElement? { return if (element is UElement) element else convertDeclaration(element, givenParent, expectedTypes) ?: convertPsiElement(element, givenParent, expectedTypes) } fun convertKtFile( element: KtFile, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return requiredTypes.accommodate( // File alternative { KotlinUFile(element, languagePlugin) }, // Facade alternative { element.findFacadeClass()?.let { KotlinUClass.create(it, givenParent) } } ) } fun convertClassOrObject( element: KtClassOrObject, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { val ktLightClass = element.toLightClass() ?: return emptySequence() val uClass = KotlinUClass.create(ktLightClass, givenParent) return requiredTypes.accommodate( // Class alternative { uClass }, // Object alternative primaryConstructor@{ val primaryConstructor = element.primaryConstructor ?: return@primaryConstructor null uClass.methods.asSequence() .filter { it.sourcePsi == primaryConstructor } .firstOrNull() } ) } fun convertFakeLightConstructorAlternatives( original: UastFakeLightPrimaryConstructor, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return expectedTypes.accommodate( alternative { convertDeclaration(original.original, givenParent, expectedTypes) as? UClass }, alternative { KotlinConstructorUMethod(original.original, original, original.original, givenParent) } ) } private fun getLightClassForFakeMethod(original: KtFunction): KtLightClass? { if (original.isLocal) return null return getContainingLightClass(original) } private fun convertToPropertyAlternatives( methods: LightClassUtil.PropertyAccessorsPsiMethods?, givenParent: UElement? ): Array<UElementAlternative<*>> { return if (methods != null) arrayOf( alternative { methods.backingField?.let { KotlinUField(it, getKotlinMemberOrigin(it), givenParent) } }, alternative { methods.getter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } }, alternative { methods.setter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } } ) else emptyArray() } fun convertNonLocalProperty( property: KtProperty, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return requiredTypes.accommodate( *convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(property), givenParent) ) } fun convertJvmStaticMethod( function: KtFunction, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { val functions = LightClassUtil.getLightClassMethods(function) return requiredTypes.accommodate( *functions.map { alternative { convertDeclaration(it, null, arrayOf(UMethod::class.java)) as? UMethod } }.toTypedArray() ) } fun convertParameter( element: KtParameter, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> = requiredTypes.accommodate( alternative uParam@{ val lightMethod = when (val ownerFunction = element.ownerFunction) { is KtFunction -> LightClassUtil.getLightClassMethod(ownerFunction) ?: getLightClassForFakeMethod(ownerFunction) ?.takeIf { !it.isAnnotationType } ?.let { UastFakeLightMethod(ownerFunction, it) } is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethod(ownerFunction) else -> null } ?: return@uParam null val lightParameter = lightMethod.parameterList.parameters.find { it.name == element.name } ?: return@uParam null KotlinUParameter(lightParameter, element, givenParent) }, alternative catch@{ val uCatchClause = element.parent?.parent?.safeAs<KtCatchClause>()?.toUElementOfType<UCatchClause>() ?: return@catch null uCatchClause.parameters.firstOrNull { it.sourcePsi == element } }, *convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(element), givenParent) ) private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? { return LightClassUtil.getLightClassBackingField(original)?.let { psiField -> if (psiField is KtLightField && psiField is PsiEnumConstant) { KotlinUEnumConstant(psiField, psiField.kotlinOrigin, givenParent) } else { null } } } private fun convertReceiverParameter(receiver: KtTypeReference): UParameter? { val call = (receiver.parent as? KtCallableDeclaration) ?: return null if (call.receiverTypeReference != receiver) return null return call.toUElementOfType<UMethod>()?.uastParameters?.firstOrNull() } fun forceUInjectionHost(): Boolean fun convertExpression( expression: KtExpression, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UExpression? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return { @Suppress("UNCHECKED_CAST") ctor(expression as P, givenParent) } } return with(requiredTypes) { when (expression) { is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration)) is KtDestructuringDeclaration -> expr<UDeclarationsExpression> { val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression) declarationsExpression.apply { val tempAssignment = KotlinULocalVariable( UastKotlinPsiVariable.create(expression, declarationsExpression), expression, declarationsExpression ) val destructuringAssignments = expression.entries.mapIndexed { i, entry -> val psiFactory = KtPsiFactory(expression.project) val initializer = psiFactory.createAnalyzableExpression( "${tempAssignment.name}.component${i + 1}()", expression.containingFile ) initializer.destructuringDeclarationInitializer = true KotlinULocalVariable( UastKotlinPsiVariable.create(entry, tempAssignment.javaPsi, declarationsExpression, initializer), entry, declarationsExpression ) } declarations = listOf(tempAssignment) + destructuringAssignments } } is KtStringTemplateExpression -> { when { forceUInjectionHost() || requiredTypes.contains(UInjectionHost::class.java) -> { expr<UInjectionHost> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) } } expression.entries.isEmpty() -> { expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, givenParent, "") } } expression.entries.size == 1 -> { convertStringTemplateEntry(expression.entries[0], givenParent, requiredTypes) } else -> { expr<KotlinStringTemplateUPolyadicExpression> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) } } } } is KtCollectionLiteralExpression -> expr<UCallExpression>(build(::KotlinUCollectionLiteralExpression)) is KtConstantExpression -> expr<ULiteralExpression>(build(::KotlinULiteralExpression)) is KtLabeledExpression -> expr<ULabeledExpression>(build(::KotlinULabeledExpression)) is KtParenthesizedExpression -> expr<UParenthesizedExpression>(build(::KotlinUParenthesizedExpression)) is KtBlockExpression -> expr<UBlockExpression> { if (expression.parent is KtFunctionLiteral && expression.parent.parent is KtLambdaExpression && givenParent !is KotlinULambdaExpression ) { KotlinULambdaExpression(expression.parent.parent as KtLambdaExpression, givenParent).body } else KotlinUBlockExpression(expression, givenParent) } is KtReturnExpression -> expr<UReturnExpression>(build(::KotlinUReturnExpression)) is KtThrowExpression -> expr<UThrowExpression>(build(::KotlinUThrowExpression)) is KtTryExpression -> expr<UTryExpression>(build(::KotlinUTryExpression)) is KtBreakExpression -> expr<UBreakExpression>(build(::KotlinUBreakExpression)) is KtContinueExpression -> expr<UContinueExpression>(build(::KotlinUContinueExpression)) is KtDoWhileExpression -> expr<UDoWhileExpression>(build(::KotlinUDoWhileExpression)) is KtWhileExpression -> expr<UWhileExpression>(build(::KotlinUWhileExpression)) is KtForExpression -> expr<UForEachExpression>(build(::KotlinUForEachExpression)) is KtWhenExpression -> expr<USwitchExpression>(build(::KotlinUSwitchExpression)) is KtIfExpression -> expr<UIfExpression>(build(::KotlinUIfExpression)) is KtBinaryExpressionWithTypeRHS -> expr<UBinaryExpressionWithType>(build(::KotlinUBinaryExpressionWithType)) is KtIsExpression -> expr<UBinaryExpressionWithType>(build(::KotlinUTypeCheckExpression)) is KtArrayAccessExpression -> expr<UArrayAccessExpression>(build(::KotlinUArrayAccessExpression)) is KtThisExpression -> expr<UThisExpression>(build(::KotlinUThisExpression)) is KtSuperExpression -> expr<USuperExpression>(build(::KotlinUSuperExpression)) is KtCallableReferenceExpression -> expr<UCallableReferenceExpression>(build(::KotlinUCallableReferenceExpression)) is KtClassLiteralExpression -> expr<UClassLiteralExpression>(build(::KotlinUClassLiteralExpression)) is KtObjectLiteralExpression -> expr<UObjectLiteralExpression>(build(::KotlinUObjectLiteralExpression)) is KtDotQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUQualifiedReferenceExpression)) is KtSafeQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUSafeQualifiedExpression)) is KtSimpleNameExpression -> expr<USimpleNameReferenceExpression>(build(::KotlinUSimpleReferenceExpression)) is KtCallExpression -> expr<UCallExpression>(build(::KotlinUFunctionCallExpression)) is KtBinaryExpression -> { if (expression.operationToken == KtTokens.ELVIS) { expr<UExpressionList>(build(::createElvisExpression)) } else { expr<UBinaryExpression>(build(::KotlinUBinaryExpression)) } } is KtPrefixExpression -> expr<UPrefixExpression>(build(::KotlinUPrefixExpression)) is KtPostfixExpression -> expr<UPostfixExpression>(build(::KotlinUPostfixExpression)) is KtClassOrObject -> expr<UDeclarationsExpression> { expression.toLightClass()?.let { lightClass -> KotlinUDeclarationsExpression(givenParent).apply { declarations = listOf(KotlinUClass.create(lightClass, this)) } } ?: UastEmptyExpression(givenParent) } is KtLambdaExpression -> expr<ULambdaExpression>(build(::KotlinULambdaExpression)) is KtFunction -> { if (expression.name.isNullOrEmpty()) { expr<ULambdaExpression>(build(::createLocalFunctionLambdaExpression)) } else { expr<UDeclarationsExpression>(build(::createLocalFunctionDeclaration)) } } is KtAnnotatedExpression -> { expression.baseExpression ?.let { convertExpression(it, givenParent, requiredTypes) } ?: expr<UExpression>(build(::UnknownKotlinExpression)) } else -> expr<UExpression>(build(::UnknownKotlinExpression)) } } } fun convertStringTemplateEntry( entry: KtStringTemplateEntry, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UExpression? { return with(requiredTypes) { if (entry is KtStringTemplateEntryWithExpression) { expr<UExpression> { convertOrEmpty(entry.expression, givenParent) } } else { expr<ULiteralExpression> { if (entry is KtEscapeStringTemplateEntry) KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue) else KotlinStringULiteralExpression(entry, givenParent) } } } } fun convertVariablesDeclaration( psi: KtVariableDeclaration, parent: UElement? ): UDeclarationsExpression { val declarationsExpression = parent as? KotlinUDeclarationsExpression ?: psi.parent.toUElementOfType<UDeclarationsExpression>() as? KotlinUDeclarationsExpression ?: KotlinUDeclarationsExpression( null, parent, psi ) val parentPsiElement = parent?.javaPsi //TODO: looks weird. mb look for the first non-null `javaPsi` in `parents` ? val variable = KotlinUAnnotatedLocalVariable( UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), psi, declarationsExpression ) { annotationParent -> psi.annotationEntries.map { convertAnnotation(it, annotationParent) } } return declarationsExpression.apply { declarations = listOf(variable) } } fun convertWhenCondition( condition: KtWhenCondition, givenParent: UElement?, requiredType: Array<out Class<out UElement>> ): UExpression? { return with(requiredType) { when (condition) { is KtWhenConditionInRange -> expr<UBinaryExpression> { KotlinCustomUBinaryExpression(condition, givenParent).apply { leftOperand = KotlinStringUSimpleReferenceExpression("it", this) operator = when { condition.isNegated -> KotlinBinaryOperators.NOT_IN else -> KotlinBinaryOperators.IN } rightOperand = convertOrEmpty(condition.rangeExpression, this) } } is KtWhenConditionIsPattern -> expr<UBinaryExpression> { KotlinCustomUBinaryExpressionWithType(condition, givenParent).apply { operand = KotlinStringUSimpleReferenceExpression("it", this) operationKind = when { condition.isNegated -> KotlinBinaryExpressionWithTypeKinds.NEGATED_INSTANCE_CHECK else -> UastBinaryExpressionWithTypeKind.InstanceCheck.INSTANCE } typeReference = condition.typeReference?.let { val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java) KotlinUTypeReferenceExpression(it, this) { service.resolveToType(it, this, boxed = true) ?: UastErrorType } } } } is KtWhenConditionWithExpression -> condition.expression?.let { convertExpression(it, givenParent, requiredType) } else -> expr<UExpression> { UastEmptyExpression(givenParent) } } } } fun convertPsiElement( element: PsiElement?, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UElement? { if (element == null) return null fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, givenParent) } return with(requiredTypes) { when (element) { is KtParameterList -> { el<UDeclarationsExpression> { val declarationsExpression = KotlinUDeclarationsExpression(null, givenParent, null) declarationsExpression.apply { declarations = element.parameters.mapIndexed { i, p -> KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), p, this) } } } } is KtClassBody -> { el<UExpressionList>(build(KotlinUExpressionList.Companion::createClassBody)) } is KtCatchClause -> { el<UCatchClause>(build(::KotlinUCatchClause)) } is KtVariableDeclaration -> { if (element is KtProperty && !element.isLocal) { convertNonLocalProperty(element, givenParent, this).firstOrNull() } else { el<UVariable> { convertVariablesDeclaration(element, givenParent).declarations.singleOrNull() } ?: expr<UDeclarationsExpression> { convertExpression(element, givenParent, requiredTypes) } } } is KtExpression -> { convertExpression(element, givenParent, requiredTypes) } is KtLambdaArgument -> { element.getLambdaExpression()?.let { convertExpression(it, givenParent, requiredTypes) } } is KtLightElementBase -> { when (val expression = element.kotlinOrigin) { is KtExpression -> convertExpression(expression, givenParent, requiredTypes) else -> el<UExpression> { UastEmptyExpression(givenParent) } } } is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> { el<ULiteralExpression>(build(::KotlinStringULiteralExpression)) } is KtStringTemplateEntry -> { element.expression?.let { convertExpression(it, givenParent, requiredTypes) } ?: expr<UExpression> { UastEmptyExpression(givenParent) } } is KtWhenEntry -> { el<USwitchClauseExpressionWithBody>(build(::KotlinUSwitchEntry)) } is KtWhenCondition -> { convertWhenCondition(element, givenParent, requiredTypes) } is KtTypeReference -> { requiredTypes.accommodate( alternative { KotlinUTypeReferenceExpression(element, givenParent) }, alternative { convertReceiverParameter(element) } ).firstOrNull() } is KtConstructorDelegationCall -> { el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) } } is KtSuperTypeCallEntry -> { el<UExpression> { (element.getParentOfType<KtClassOrObject>(true)?.parent as? KtObjectLiteralExpression) ?.toUElementOfType<UExpression>() ?: KotlinUFunctionCallExpression(element, givenParent) } } is KtImportDirective -> { el<UImportStatement>(build(::KotlinUImportStatement)) } is PsiComment -> { el<UComment>(build(::UComment)) } is KDocName -> { if (element.getQualifier() == null) el<USimpleNameReferenceExpression> { element.lastChild?.let { psiIdentifier -> KotlinStringUSimpleReferenceExpression(psiIdentifier.text, givenParent, element, element) } } else el<UQualifiedReferenceExpression>(build(::KotlinDocUQualifiedReferenceExpression)) } is LeafPsiElement -> { when { element.elementType in identifiersTokens -> { if (element.elementType != KtTokens.OBJECT_KEYWORD || element.getParentOfType<KtObjectDeclaration>(false)?.nameIdentifier == null ) el<UIdentifier>(build(::KotlinUIdentifier)) else null } element.elementType in KtTokens.OPERATIONS && element.parent is KtOperationReferenceExpression -> { el<UIdentifier>(build(::KotlinUIdentifier)) } element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression -> { el<UIdentifier> { UIdentifier( element, KotlinUCollectionLiteralExpression(element.parent as KtCollectionLiteralExpression, null) ) } } else -> null } } else -> null } } } fun createVarargsHolder( arguments: Collection<ValueArgument>, parent: UElement?, ): UExpressionList = KotlinUExpressionList(null, UastSpecialExpressionKind.VARARGS, parent).apply { expressions = arguments.map { convertOrEmpty(it.getArgumentExpression(), parent) } } fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression { return expression?.let { convertExpression(it, parent, DEFAULT_EXPRESSION_TYPES_LIST) } ?: UastEmptyExpression(parent) } fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? { return if (expression != null) convertExpression(expression, parent, DEFAULT_EXPRESSION_TYPES_LIST) else null } fun KtPsiFactory.createAnalyzableExpression(text: String, context: PsiElement): KtExpression = createAnalyzableProperty("val x = $text", context).initializer ?: error("Failed to create expression from text: '$text'") fun KtPsiFactory.createAnalyzableProperty(text: String, context: PsiElement): KtProperty = createAnalyzableDeclaration(text, context) fun <TDeclaration : KtDeclaration> KtPsiFactory.createAnalyzableDeclaration(text: String, context: PsiElement): TDeclaration { val file = createAnalyzableFile("dummy.kt", text, context) val declarations = file.declarations assert(declarations.size == 1) { "${declarations.size} declarations in $text" } @Suppress("UNCHECKED_CAST") return declarations.first() as TDeclaration } }
apache-2.0
e2769009826d1081487d386f67e726e4
47.744505
137
0.572874
6.70306
false
false
false
false
GunoH/intellij-community
plugins/kotlin/plugin-updater/src/org/jetbrains/kotlin/idea/update/GooglePluginUpdateVerifier.kt
4
6497
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.update import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.PluginNode import com.intellij.openapi.diagnostic.Logger import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin import java.io.IOException import java.net.URL import java.util.* import javax.xml.bind.JAXBContext import javax.xml.bind.JAXBException import javax.xml.bind.annotation.* class GooglePluginUpdateVerifier : PluginUpdateVerifier() { override val verifierName: String get() = KotlinPluginUpdaterBundle.message("update.name.android.studio") // Verifies if a plugin can be installed in Android Studio 3.2+. // Currently used only by KotlinPluginUpdater. override fun verify(pluginDescriptor: IdeaPluginDescriptor): PluginVerifyResult? { val pluginVersion = KotlinIdePlugin.version if (pluginDescriptor.pluginId != KotlinIdePlugin.id || KotlinIdePlugin.isPostProcessed) { return null } else if (KotlinIdePlugin.isPreRelease) { return PluginVerifyResult.accept() } try { val url = URL(METADATA_FILE_URL) val stream = url.openStream() val context = JAXBContext.newInstance(PluginCompatibility::class.java) val unmarshaller = context.createUnmarshaller() val pluginCompatibility = unmarshaller.unmarshal(stream) as PluginCompatibility val release = getRelease(pluginCompatibility) ?: return PluginVerifyResult.decline(KotlinPluginUpdaterBundle.message("update.reason.text.no.verified.versions.for.this.build")) return if (release.plugins().any { KOTLIN_PLUGIN_ID == it.id && pluginVersion == it.version }) { PluginVerifyResult.accept() } else { PluginVerifyResult.decline(KotlinPluginUpdaterBundle.message("update.reason.text.version.to.be.verified")) } } catch (e: Exception) { LOG.info("Exception when verifying plugin ${pluginDescriptor.pluginId.idString} version $pluginVersion", e) return when (e) { is IOException -> { val message = KotlinPluginUpdaterBundle.message("update.reason.text.unable.to.connect.to.compatibility.verification.repository") PluginVerifyResult.decline(message) } is JAXBException -> { val message = KotlinPluginUpdaterBundle.message("update.reason.text.unable.to.parse.compatibility.verification.metadata") PluginVerifyResult.decline(message) } else -> { val message = KotlinPluginUpdaterBundle.message("update.reason.text.exception.during.verification", e.message.toString()) PluginVerifyResult.decline(message) } } } } private fun getRelease(pluginCompatibility: PluginCompatibility): StudioRelease? { for (studioRelease in pluginCompatibility.releases()) { if (buildInRange(studioRelease.name, studioRelease.sinceBuild, studioRelease.untilBuild)) { return studioRelease } } return null } private fun buildInRange(name: String?, sinceBuild: String?, untilBuild: String?): Boolean { val descriptor = PluginNode() descriptor.name = name descriptor.sinceBuild = sinceBuild descriptor.untilBuild = untilBuild return PluginManagerCore.isCompatible(descriptor) } companion object { private const val KOTLIN_PLUGIN_ID = "org.jetbrains.kotlin" private const val METADATA_FILE_URL = "https://dl.google.com/android/studio/plugins/compatibility.xml" private val LOG = Logger.getInstance(GooglePluginUpdateVerifier::class.java) private fun PluginCompatibility.releases() = studioRelease ?: emptyArray() private fun StudioRelease.plugins() = ideaPlugin ?: emptyArray() @XmlRootElement(name = "plugin-compatibility") @XmlAccessorType(XmlAccessType.FIELD) class PluginCompatibility { @XmlElement(name = "studio-release") var studioRelease: Array<StudioRelease>? = null override fun toString(): String { return "PluginCompatibility(studioRelease=${Arrays.toString(studioRelease)})" } } @XmlAccessorType(XmlAccessType.FIELD) class StudioRelease { @XmlAttribute(name = "until-build") var untilBuild: String? = null @XmlAttribute(name = "since-build") var sinceBuild: String? = null @XmlAttribute var name: String? = null @XmlAttribute var channel: String? = null @XmlElement(name = "idea-plugin") var ideaPlugin: Array<IdeaPlugin>? = null override fun toString(): String { return "StudioRelease(" + "untilBuild=$untilBuild, name=$name, ideaPlugin=${Arrays.toString(ideaPlugin)}, " + "sinceBuild=$sinceBuild, channel=$channel" + ")" } } @XmlAccessorType(XmlAccessType.FIELD) class IdeaPlugin { @XmlAttribute var id: String? = null @XmlAttribute var sha256: String? = null @XmlAttribute var channel: String? = null @XmlAttribute var version: String? = null @XmlElement(name = "idea-version") var ideaVersion: IdeaVersion? = null override fun toString(): String { return "IdeaPlugin(id=$id, sha256=$sha256, ideaVersion=$ideaVersion, channel=$channel, version=$version)" } } @XmlAccessorType(XmlAccessType.FIELD) class IdeaVersion { @XmlAttribute(name = "until-build") var untilBuild: String? = null @XmlAttribute(name = "since-build") var sinceBuild: String? = null override fun toString(): String { return "IdeaVersion(untilBuild=$untilBuild, sinceBuild=$sinceBuild)" } } } }
apache-2.0
996660f2f229784d7e61acda155b5e2c
40.647436
158
0.629829
4.940684
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/UiDslShowcaseAction.kt
2
4066
// 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.internal.ui.uiDslShowcase import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.dsl.builder.Align import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBEmptyBorder import java.awt.Dimension import javax.swing.JComponent import kotlin.reflect.KFunction import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.javaMethod private const val BASE_URL = "https://github.com/JetBrains/intellij-community/blob/master/platform/platform-impl/" private val DEMOS = arrayOf( ::demoBasics, ::demoRowLayout, ::demoComponentLabels, ::demoComments, ::demoComponents, ::demoGaps, ::demoGroups, ::demoAvailability, ::demoBinding, ::demoTips ) internal class UiDslShowcaseAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { UiDslShowcaseDialog(e.project, templatePresentation.text).show() } } private class UiDslShowcaseDialog(val project: Project?, dialogTitle: String) : DialogWrapper(project, null, true, IdeModalityType.MODELESS, false) { init { title = dialogTitle init() } override fun createCenterPanel(): JComponent { val result = JBTabbedPane() result.minimumSize = Dimension(400, 300) result.preferredSize = Dimension(800, 600) for (demo in DEMOS) { addDemo(demo, result) } return result } private fun addDemo(demo: KFunction<DialogPanel>, tabbedPane: JBTabbedPane) { val annotation = demo.findAnnotation<Demo>() if (annotation == null) { throw Exception("Demo annotation is missed for ${demo.name}") } val content = panel { row { label("<html>Description: ${annotation.description}") } val simpleName = "src/${demo.javaMethod!!.declaringClass.name}".replace('.', '/') val fileName = (simpleName.substring(0..simpleName.length - 3) + ".kt") row { link("View source") { if (!openInIdeaProject(fileName)) { BrowserUtil.browse(BASE_URL + fileName) } } }.bottomGap(BottomGap.MEDIUM) val args = demo.parameters.associateBy( { it }, { when (it.name) { "parentDisposable" -> myDisposable else -> null } } ) val dialogPanel = demo.callBy(args) if (annotation.scrollbar) { row { dialogPanel.border = JBEmptyBorder(10) scrollCell(dialogPanel) .align(Align.FILL) .resizableColumn() }.resizableRow() } else { row { cell(dialogPanel) .align(AlignX.FILL) .resizableColumn() } } } tabbedPane.add(annotation.title, content) } private fun openInIdeaProject(fileName: String): Boolean { if (project == null) { return false } val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.findModuleByName("intellij.platform.ide.impl") if (module == null) { return false } for (contentRoot in module.rootManager.contentRoots) { val file = contentRoot.findFileByRelativePath(fileName) if (file?.isValid == true) { OpenFileDescriptor(project, file).navigate(true) return true } } return false } }
apache-2.0
f97abfada0ad6a1730475c1aa8127fd5
28.042857
120
0.684702
4.353319
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/unifier/equivalence/declarations/localCallables/localExtensionFunctions.kt
13
571
// DISABLE-ERRORS class A(val n: Int) fun test() { <selection>fun <T: A> foo(t: T): Int { fun A.a(n: Int): Int = this.n + n fun A.b(n: Int): Int = this.n - n return t.n + A(1).a(2) - A(2).b(1) }</selection> fun <U: A> foo(u: U): Int { fun A.x(m: Int): Int = n + m fun A.y(n: Int): Int = this.n - n return u.n + A(1).x(2) - A(2).y(1) } fun <V: A> foo(v: V): Int { fun A.a(n: Int): Int = this.n + n fun A.b(n: Int): Int = this.n + n return v.n + A(1).a(2) - A(2).b(1) } }
apache-2.0
205092c908cf85d70c7ec079e3e1999f
21.88
42
0.423818
2.321138
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/status/GitAheadBehindCount.kt
1
1268
package zielu.gittoolbox.status import com.intellij.vcs.log.Hash internal data class GitAheadBehindCount constructor( val ahead: RevListCount, val behind: RevListCount ) { fun status(): Status = ahead.status fun isNotZero(): Boolean { return if (status() == Status.SUCCESS) { ahead.value != 0 || behind.value != 0 } else { false } } fun isNotZeroBehind(): Boolean { return if (status() == Status.SUCCESS) { behind.value != 0 } else { false } } companion object { private val cancel = GitAheadBehindCount(RevListCount.cancel(), RevListCount.cancel()) private val failure = GitAheadBehindCount(RevListCount.failure(), RevListCount.failure()) private val noRemote = GitAheadBehindCount(RevListCount.noRemote(), RevListCount.noRemote()) @JvmStatic fun success( ahead: Int, aheadHash: Hash?, behind: Int, behindHash: Hash? ): GitAheadBehindCount { return GitAheadBehindCount(RevListCount(aheadHash, ahead), RevListCount(behindHash, behind)) } @JvmStatic fun cancel(): GitAheadBehindCount = cancel @JvmStatic fun failure(): GitAheadBehindCount = failure @JvmStatic fun noRemote(): GitAheadBehindCount = noRemote } }
apache-2.0
e31ef886fe23c4560336fe395c440dbe
23.384615
98
0.672713
4.025397
false
false
false
false
Phakx/AdventOfCode
2017/src/main/kotlin/dayeight/Dayeight.kt
1
3565
package main.kotlin.dayeight import java.io.File import java.net.URLDecoder class Dayeight{ var allTimeHigh = 0 fun solve(){ val input = File(load_file()).readLines() val regex = "(\\w+)\\s(\\w+)\\s(-?\\d+)\\s(\\w+)\\s(\\w+)\\s([<,>,=,!]+)\\s(-?\\d+)" val valueMap = mutableMapOf<String, Int>() input.forEach({ line -> val toRegex = regex.toRegex() val matches = toRegex.find(line)!!.groupValues val register = matches.elementAt(1) val registerValue = valueMap.getOrPut(register) { 0 } val instruction = matches.elementAt(2) val instructionValue = matches.elementAt(3).toInt() val decisionRegister = matches.elementAt(5) val decisionRegisterValue = valueMap.getOrPut(decisionRegister) { 0 } val decisionOperator = matches.elementAt(6) val decisionValue = matches.elementAt(7).toInt() when (decisionOperator) { ">" -> { if(decisionRegisterValue > decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } "<" -> { if(decisionRegisterValue < decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } "!=" -> { if(decisionRegisterValue != decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } "==" -> { if(decisionRegisterValue == decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } "<=" -> { if(decisionRegisterValue <= decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } ">=" -> { if(decisionRegisterValue >= decisionValue){ val result = processInstruction(instruction, registerValue, instructionValue) valueMap[register] = result } } } }) println("Part 1: ${valueMap.values.max()}") println("Part 2: $allTimeHigh") } private fun processInstruction(instruction: String, registerValue: Int, instructionValue: Int): Int { var registerValue1 = registerValue if (instruction == "inc") { registerValue1 += instructionValue } else if (instruction == "dec") { registerValue1 -= instructionValue } if (registerValue1 > allTimeHigh){ allTimeHigh = registerValue1 } return registerValue1 } private fun load_file(): String? { val resource = this::class.java.classLoader.getResource("dayeight" + File.separator + "input") return URLDecoder.decode(resource.file, "UTF-8") } } fun main(args : Array<String>){ val solver = Dayeight() solver.solve() }
mit
342064159a4e613985420da3fdc9f9b1
36.93617
105
0.518934
5.189229
false
false
false
false
simonnorberg/dmach
app/src/main/java/net/simno/dmach/patch/PatchScreen.kt
1
8674
package net.simno.dmach.patch import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.navigation.NavController import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemsIndexed import net.simno.dmach.R import net.simno.dmach.core.DarkMediumText import net.simno.dmach.core.TextButton import net.simno.dmach.data.Patch import net.simno.dmach.theme.AppTheme @Composable fun PatchScreen( navController: NavController, viewModel: PatchViewModel ) { val state by viewModel.viewState.collectAsState() val patches = viewModel.patches.collectAsLazyPagingItems() LaunchedEffect(state.finish) { if (state.finish) { navController.navigateUp() } } Patch( state = state, patches = patches, onAction = viewModel::onAction ) } @Composable private fun Patch( state: ViewState, patches: LazyPagingItems<Patch>, onAction: (Action) -> Unit ) { val onSurface = MaterialTheme.colorScheme.onSurface val onSurfaceVariant = MaterialTheme.colorScheme.onSurfaceVariant val paddingLarge = AppTheme.dimens.PaddingLarge val paddingSmall = AppTheme.dimens.PaddingSmall val buttonLarge = AppTheme.dimens.ButtonLarge Column( modifier = Modifier .fillMaxSize() .systemBarsPadding() .navigationBarsPadding() .safeDrawingPadding() ) { Row( modifier = Modifier .fillMaxWidth() .wrapContentHeight() ) { if (state.title.isNotEmpty()) { val keyboardController = LocalSoftwareKeyboardController.current var title by remember { mutableStateOf(state.title) } BasicTextField( value = title, onValueChange = { title = it.take(50) }, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) .fillMaxWidth() .wrapContentHeight() .padding(paddingLarge), textStyle = MaterialTheme.typography.bodyMedium.copy( color = MaterialTheme.colorScheme.primary ), singleLine = true, keyboardOptions = KeyboardOptions.Default.copy( capitalization = KeyboardCapitalization.None, autoCorrect = false, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() if (title.isNotBlank()) { onAction(SavePatchAction(title)) } } ) ) TextButton( text = stringResource(R.string.patch_save), selected = false, modifier = Modifier .wrapContentSize() .padding(paddingLarge), textPadding = PaddingValues(paddingLarge), onClick = { keyboardController?.hide() if (title.isNotBlank()) { onAction(SavePatchAction(title)) } } ) } } Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = paddingLarge, vertical = paddingSmall), ) { DarkMediumText( text = stringResource(R.string.patch_name).uppercase(), modifier = Modifier.weight(1f) ) DarkMediumText( text = stringResource(R.string.patch_swing).uppercase(), modifier = Modifier.defaultMinSize(minWidth = buttonLarge), textAlign = TextAlign.End ) DarkMediumText( text = stringResource(R.string.patch_bpm).uppercase(), modifier = Modifier.defaultMinSize(minWidth = buttonLarge), textAlign = TextAlign.End ) } LazyColumn { itemsIndexed(patches) { index, patch -> if (patch != null) { val background = when { index % 2 == 0 -> onSurface else -> onSurfaceVariant } Row( modifier = Modifier .fillMaxWidth() .background(background) .combinedClickable( onClick = { onAction(SelectPatchAction(patch.title)) }, onLongClick = { if (patches.itemCount > 1) { onAction(DeletePatchAction(patch.title)) } } ) .padding(paddingLarge) ) { DarkMediumText( text = patch.title, modifier = Modifier.weight(1f) ) DarkMediumText( text = patch.swing.toString(), modifier = Modifier.defaultMinSize(minWidth = buttonLarge), textAlign = TextAlign.End ) DarkMediumText( text = patch.tempo.toString(), modifier = Modifier.defaultMinSize(minWidth = buttonLarge), textAlign = TextAlign.End ) } } } } } when { state.showDelete -> { PatchDialog( text = stringResource(R.string.delete_patch, state.title), confirmText = R.string.delete, onDismiss = { onAction(DismissAction) }, onConfirm = { onAction(ConfirmDeleteAction) } ) } state.showOverwrite -> { PatchDialog( text = stringResource(R.string.overwrite_patch, state.title), confirmText = R.string.overwrite, onDismiss = { onAction(DismissAction) }, onConfirm = { onAction(ConfirmOverwriteAction) } ) } } }
gpl-3.0
6e2349a0c4a08bdb81b7240d20b834da
38.788991
87
0.549343
5.982069
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/statistics/StatisticsFragmentViewModel.kt
1
12630
package sk.styk.martin.apkanalyzer.ui.statistics import android.view.MenuItem import androidx.appcompat.widget.Toolbar import androidx.lifecycle.* import com.github.mikephil.charting.data.BarData import com.github.mikephil.charting.data.BarDataSet import com.github.mikephil.charting.data.BarEntry import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.formatter.IAxisValueFormatter import com.github.mikephil.charting.interfaces.datasets.IBarDataSet import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.manager.appanalysis.LocalApplicationStatisticManager import sk.styk.martin.apkanalyzer.manager.appanalysis.MAX_SDK_VERSION import sk.styk.martin.apkanalyzer.manager.navigationdrawer.NavigationDrawerModel import sk.styk.martin.apkanalyzer.manager.resources.ResourcesManager import sk.styk.martin.apkanalyzer.model.statistics.StatisticsData import sk.styk.martin.apkanalyzer.util.ColorInfo import sk.styk.martin.apkanalyzer.util.TextInfo import sk.styk.martin.apkanalyzer.util.components.DialogComponent import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent import javax.inject.Inject import kotlin.math.roundToInt private const val LOADING_STATE = 0 private const val DATA_STATE = 1 typealias PackageName = String @HiltViewModel class StatisticsFragmentViewModel @Inject constructor( private val navigationDrawerModel: NavigationDrawerModel, private val localApplicationStatisticManager: LocalApplicationStatisticManager, private val resourcesManager: ResourcesManager, private val dispatcherProvider: DispatcherProvider, ) : ViewModel(), Toolbar.OnMenuItemClickListener { private val viewStateLiveData = MutableLiveData(LOADING_STATE) val viewState: LiveData<Int> = viewStateLiveData.distinctUntilChanged() private val loadingProgressLiveData = MutableLiveData<Int>() val loadingProgress: LiveData<Int> = loadingProgressLiveData private val loadingProgressMaxLiveData = MutableLiveData<Int>() val loadingProgressMax: LiveData<Int> = loadingProgressMaxLiveData private val statisticDataLiveData = MutableLiveData<StatisticsDataWithCharts>() val statisticData: LiveData<StatisticsDataWithCharts> = statisticDataLiveData private val showDialogEvent = SingleLiveEvent<DialogComponent>() val showDialog: LiveData<DialogComponent> = showDialogEvent private val showAppListEvent = SingleLiveEvent<List<PackageName>>() val showAppList: LiveData<List<PackageName>> = showAppListEvent private val analysisResultsExpandedLiveData = MutableLiveData(true) val analysisResultsExpanded: LiveData<Boolean> = analysisResultsExpandedLiveData private val minSdkExpandedLiveData = MutableLiveData(false) val minSdkExpanded: LiveData<Boolean> = minSdkExpandedLiveData private val targetSdkExpandedLiveData = MutableLiveData(false) val targetSdkExpanded: LiveData<Boolean> = targetSdkExpandedLiveData private val installLocationExpandedLiveData = MutableLiveData(false) val installLocationExpanded: LiveData<Boolean> = installLocationExpandedLiveData private val signAlgorithmExpandedLiveData = MutableLiveData(false) val signAlgorithmExpanded: LiveData<Boolean> = signAlgorithmExpandedLiveData private val appSourceExpandedLiveData = MutableLiveData(false) val appSourceExpanded: LiveData<Boolean> = appSourceExpandedLiveData private val appSizeExpandedLiveData = MutableLiveData(false) val appSizeExpanded: LiveData<Boolean> = appSizeExpandedLiveData private val activitiesExpandedLiveData = MutableLiveData(false) val activitiesExpanded: LiveData<Boolean> = activitiesExpandedLiveData private val servicesExpandedLiveData = MutableLiveData(false) val servicesExpanded: LiveData<Boolean> = servicesExpandedLiveData private val providersExpandedLiveData = MutableLiveData(false) val providersExpanded: LiveData<Boolean> = providersExpandedLiveData private val receiversExpandedLiveData = MutableLiveData(false) val receiversExpanded: LiveData<Boolean> = receiversExpandedLiveData private val usedPermissionsExpandedLiveData = MutableLiveData(false) val usedPermissionsExpanded: LiveData<Boolean> = usedPermissionsExpandedLiveData private val definedPermissionsExpandedLiveData = MutableLiveData(false) val definedPermissionsExpanded: LiveData<Boolean> = definedPermissionsExpandedLiveData init { viewModelScope.launch { localApplicationStatisticManager.loadStatisticsData() .flowOn(dispatcherProvider.default()) .collect { when (it) { is LocalApplicationStatisticManager.StatisticsLoadingStatus.Loading -> { loadingProgressLiveData.value = it.currentProgress loadingProgressMaxLiveData.value = it.totalProgress viewStateLiveData.value = LOADING_STATE } is LocalApplicationStatisticManager.StatisticsLoadingStatus.Data -> { val data = withContext(dispatcherProvider.default()) { StatisticsDataWithCharts( statisticsData = it.data, minSdkChartData = getBarSdkData(it.data.minSdk), targetSdkChartData = getBarSdkData(it.data.targetSdk), installLocationChartData = getBarData(it.data.installLocation), appSourceChartData = getBarData(it.data.appSource), signAlgorithChartData = getBarData(it.data.signAlgorithm) ) } statisticDataLiveData.value = data viewStateLiveData.value = DATA_STATE } } } } } fun onNavigationClick() = viewModelScope.launch { navigationDrawerModel.openDrawer() } fun showDetail(title: String, message: String) { showDialogEvent.value = DialogComponent(TextInfo.from(title), TextInfo.from(message), TextInfo.from(R.string.close)) } fun onChartMarkerClick(chartEntry: Entry) { val packageNames = chartEntry.data as? List<PackageName> ?: return showAppListEvent.value = packageNames } fun toggleAnalysisResultExpanded() { analysisResultsExpandedLiveData.value = analysisResultsExpandedLiveData.value?.not() } fun toggleMinSdkExpanded() { minSdkExpandedLiveData.value = minSdkExpandedLiveData.value?.not() } fun toggleTargetSdkExpanded() { targetSdkExpandedLiveData.value = targetSdkExpandedLiveData.value?.not() } fun toggleInstallLocationExpanded() { installLocationExpandedLiveData.value = installLocationExpandedLiveData.value?.not() } fun toggleSignAlgorithmExpanded() { signAlgorithmExpandedLiveData.value = signAlgorithmExpandedLiveData.value?.not() } fun toggleAppSourceExpanded() { appSourceExpandedLiveData.value = appSourceExpandedLiveData.value?.not() } fun toggleAppSizeExpanded() { appSizeExpandedLiveData.value = appSizeExpandedLiveData.value?.not() } fun toggleActivitiesExpanded() { activitiesExpandedLiveData.value = activitiesExpandedLiveData.value?.not() } fun toggleServicesExpanded() { servicesExpandedLiveData.value = servicesExpandedLiveData.value?.not() } fun toggleReceiversExpanded() { receiversExpandedLiveData.value = receiversExpandedLiveData.value?.not() } fun toggleProvidersExpanded() { providersExpandedLiveData.value = providersExpandedLiveData.value?.not() } fun toggleUsedPermissionsExpanded() { usedPermissionsExpandedLiveData.value = usedPermissionsExpandedLiveData.value?.not() } fun toggleDefinedPermissionsExpanded() { definedPermissionsExpandedLiveData.value = definedPermissionsExpandedLiveData.value?.not() } override fun onMenuItemClick(item: MenuItem?): Boolean { return when (item?.itemId) { R.id.action_expand_all -> { setAllExpanded(true) true } R.id.action_collapse_all -> { setAllExpanded(false) true } else -> false } } private fun setAllExpanded(isExpanded: Boolean) { analysisResultsExpandedLiveData.value = isExpanded minSdkExpandedLiveData.value = isExpanded targetSdkExpandedLiveData.value = isExpanded installLocationExpandedLiveData.value = isExpanded signAlgorithmExpandedLiveData.value = isExpanded appSourceExpandedLiveData.value = isExpanded appSizeExpandedLiveData.value = isExpanded activitiesExpandedLiveData.value = isExpanded servicesExpandedLiveData.value = isExpanded providersExpandedLiveData.value = isExpanded receiversExpandedLiveData.value = isExpanded usedPermissionsExpandedLiveData.value = isExpanded definedPermissionsExpandedLiveData.value = isExpanded } private fun getBarSdkData( map: Map<Int, List<String>>, columnColor: ColorInfo = ColorInfo.fromColor(R.color.graph_bar), selectedColumnColor: ColorInfo = ColorInfo.fromColor(R.color.secondary), ): BarDataHolder { val values = ArrayList<BarEntry>(map.size) val axisValues = ArrayList<String>(map.size) var index = 0f for (sdk in 1..MAX_SDK_VERSION) { if (map[sdk] == null) continue val applicationCount = map[sdk]?.size ?: 0 values.add(BarEntry(index++, applicationCount.toFloat(), map[sdk])) axisValues.add(sdk.toString()) } return BarDataHolder( BarData(listOf<IBarDataSet>( BarDataSet(values, "mLabel") .apply { color = resourcesManager.getColor(columnColor) highLightColor = resourcesManager.getColor(selectedColumnColor) highLightAlpha = 255 valueTextColor = color isHighlightEnabled = true })) ) { i, _ -> axisValues[i.roundToInt()] } } private fun getBarData(map: Map<*, List<String>>, columnColor: ColorInfo = ColorInfo.fromColor(R.color.graph_bar), selectedColumnColor: ColorInfo = ColorInfo.fromColor(R.color.secondary), ): BarDataHolder { val values = mutableListOf<BarEntry>() val axisValues = mutableListOf<String>() var index = 1f for ((key, value) in map) { values.add(BarEntry(index++, value.size.toFloat(), value)) axisValues.add(key.toString()) } return BarDataHolder( BarData(listOf<IBarDataSet>( BarDataSet(values, "mLabel") .apply { color = resourcesManager.getColor(columnColor) highLightColor = resourcesManager.getColor(selectedColumnColor) highLightAlpha = 255 valueTextColor = color isHighlightEnabled = true })) ) { i, _ -> axisValues[i.roundToInt() - 1] } } data class BarDataHolder( val data: BarData, val valueFormatter: IAxisValueFormatter) data class StatisticsDataWithCharts( val statisticsData: StatisticsData, val minSdkChartData: BarDataHolder, val targetSdkChartData: BarDataHolder, val installLocationChartData: BarDataHolder, val appSourceChartData: BarDataHolder, val signAlgorithChartData: BarDataHolder ) }
gpl-3.0
9ce9e963833c5b5b7f4a05b71d6bce7c
41.244147
124
0.668092
5.413631
false
false
false
false
ognev-zair/Kotlin-AgendaCalendarView
kotlin-agendacalendarview/src/main/java/com/ognev/kotlin/agendacalendarview/utils/BusProvider.kt
1
746
package com.ognev.kotlin.agendacalendarview.utils import rx.Observable import rx.subjects.PublishSubject import rx.subjects.SerializedSubject class BusProvider { private val mBus = SerializedSubject<Any, Any>(PublishSubject.create()) // endregion // region Public methods fun send(`object`: Any) { mBus.onNext(`object`) } fun toObserverable(): Observable<Any> { return mBus } companion object { var mInstance: BusProvider? = null // region Constructors val instance: BusProvider get() { if (mInstance == null) { mInstance = BusProvider() } return mInstance!! } } }
apache-2.0
db144e311a3f096580fa6294cced39fc
18.128205
75
0.580429
4.940397
false
false
false
false
wuan/bo-android
app/src/main/java/org/blitzortung/android/data/provider/standard/DataBuilder.kt
1
3509
/* Copyright 2015 Andreas Würl 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.blitzortung.android.data.provider.standard import org.blitzortung.android.data.beans.* import org.blitzortung.android.util.TimeFormat import org.json.JSONArray import org.json.JSONException import org.json.JSONObject internal class DataBuilder { fun createDefaultStrike(referenceTimestamp: Long, jsonArray: JSONArray): Strike { try { return DefaultStrike( timestamp = referenceTimestamp - 1000 * jsonArray.getInt(0), longitude = jsonArray.getDouble(1), latitude = jsonArray.getDouble(2), lateralError = jsonArray.getDouble(3), altitude = 0, amplitude = jsonArray.getDouble(4).toFloat(), stationCount = jsonArray.getInt(5).toShort()) } catch (e: JSONException) { throw IllegalStateException("error with JSON format while parsing strike data", e) } } @Throws(JSONException::class) fun createRasterParameters(response: JSONObject, baselength: Int): RasterParameters { return RasterParameters( longitudeStart = response.getDouble("x0"), latitudeStart = response.getDouble("y1"), longitudeDelta = response.getDouble("xd"), latitudeDelta = response.getDouble("yd"), longitudeBins = response.getInt("xc"), latitudeBins = response.getInt("yc"), baselength = baselength) } @Throws(JSONException::class) fun createRasterElement(rasterParameters: RasterParameters, referenceTimestamp: Long, jsonArray: JSONArray): RasterElement { return RasterElement( timestamp = referenceTimestamp + 1000 * jsonArray.getInt(3), longitude = rasterParameters.getCenterLongitude(jsonArray.getInt(0)), latitude = rasterParameters.getCenterLatitude(jsonArray.getInt(1)), multiplicity = jsonArray.getInt(2) ) } fun createStation(jsonArray: JSONArray): Station { val name : String val longitude : Double val latitude : Double var offlineSince = Station.OFFLINE_SINCE_NOT_SET try { name = jsonArray.getString(1) longitude = jsonArray.getDouble(3) latitude = jsonArray.getDouble(4) if (jsonArray.length() >= 6) { val offlineSinceString = jsonArray.getString(5) if (offlineSinceString.isNotEmpty()) { offlineSince = TimeFormat.parseTimeWithMilliseconds(offlineSinceString) } } } catch (e: JSONException) { throw IllegalStateException("error with JSON format while parsing participants data") } return Station(name = name, longitude = longitude, latitude = latitude, offlineSince = offlineSince) } }
apache-2.0
610098eebcf2b2d51e7628dc6479b1fd
38.41573
128
0.641106
5.128655
false
false
false
false
aucd29/crypto
library/src/test/java/net/sarangnamu/common/crypto/ExampleUnitTest.kt
1
3723
package net.sarangnamu.common.crypto import android.util.Log import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun test_des() { System.out.println("==\ntest des\n==") val key = "key!!!@@" // des는 key 가 8개 val data = "Hello World" val params = Crypto.Params().apply { des() key(key) this.data = data } val hex = Crypto().encrypt(params) System.out.println("encrypted : $hex") hex?.let { params.data = it val str = Crypto().decrypt(params) System.out.println("decrypted : ${str.toString()}") assertEquals(data, str) } } @Test fun test_blowfish() { System.out.println("==\ntest blowfish\n==") val data = "Hello World" val params = Crypto.Params().apply { blowfish() keyGen() this.data = data } System.out.println("generated key : ${params.key.encoded.toHexString()}") val hex = Crypto().encrypt(params) System.out.println("encrypted : $hex") hex?.let { params.data = it val str = Crypto().decrypt(params) System.out.println("decrypted : ${str.toString()}") assertEquals(data, str) } } @Test fun test_rsa() { System.out.println("==\ntest rsa\n==") val data = "Hello World" val params = Crypto.RsaParams().apply { this.data = data } val pub = params.publicKeyString() System.out.println("public key : ${pub}") val encrypted = Crypto().encrypt(params) System.out.println("encrypted : ${encrypted}") encrypted?.let { params.data = encrypted val decrypted = Crypto().decrypt(params) System.out.println("decrypted : ${decrypted}") assertEquals(decrypted, "Hello World") } ?: assert(true) } @Test fun test_aes() { System.out.println("==\ntest aes\n==") val data = "Hello World" val params = Crypto.Params().apply { aes() keyGen(128) this.data = data } System.out.println("generated key : ${params.key.encoded.toHexString()}") val encrypted = Crypto().encrypt(params) System.out.println("encrypted : $encrypted") encrypted?.let { params.data = it val decrypted = Crypto().decrypt(params) System.out.println("decrypted : ${decrypted}") assertEquals(decrypted, "Hello World") } } @Test fun test_md5() { System.out.println("==\ntest md5\n==") val data = "hello world" val md5Str = data.md5() System.out.println("md5 : $md5Str") assertEquals(md5Str, "5eb63bbbe01eeed093cb22bb8f5acdc3".toUpperCase()) } @Test fun test_sha1() { System.out.println("==\ntest sha1\n==") val data = "hello world" val sha1 = data.sha1() System.out.println("sha1 : $sha1") assertEquals(sha1, "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed".toUpperCase()) } @Test fun test_sha256() { System.out.println("==\ntest sha-256\n==") val data = "hello world" val sha256 = data.sha256() System.out.println("sha256 : $sha256") assertEquals(sha256, "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9".toUpperCase()) } }
apache-2.0
aec99a457649317d77a61901a6e43fa9
24.993007
110
0.549906
3.871875
false
true
false
false
myunusov/sofarc
sofarc-core/src/main/kotlin/org/maxur/sofarc/core/service/grizzly/WebServerGrizzlyImpl.kt
1
5128
@file:Suppress("unused") package org.maxur.sofarc.core.service.grizzly import org.glassfish.grizzly.http.server.HttpServer import org.glassfish.grizzly.http.server.ServerConfiguration import org.glassfish.hk2.api.ServiceLocator import org.glassfish.jersey.ServiceLocatorProvider import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory import org.jvnet.hk2.annotations.Service import org.maxur.sofarc.core.annotation.Value import org.maxur.sofarc.core.rest.RestResourceConfig import org.maxur.sofarc.core.service.WebServer import org.maxur.sofarc.core.service.grizzly.config.StaticContent import org.maxur.sofarc.core.service.grizzly.config.WebAppConfig import org.maxur.sofarc.core.service.hk2.DSL.cfg import org.slf4j.Logger import org.slf4j.LoggerFactory import org.slf4j.bridge.SLF4JBridgeHandler import javax.inject.Inject import javax.ws.rs.core.Feature import javax.ws.rs.core.FeatureContext /** * The Grizzly Embedded Web Server Adapter * * @param config resource configuration * * * @param locator service locator (hk2) * * @author myunusov * @version 1.0 * @since <pre>12.06.2017</pre> */ @Service(name = "Grizzly") open class WebServerGrizzlyImpl @Inject constructor( @Value(key = "webapp") val webConfig: WebAppConfig, val config: RestResourceConfig, val locator: ServiceLocator ) : WebServer(webConfig.url) { companion object { val log: Logger = LoggerFactory.getLogger(WebServer::class.java) } private lateinit var httpServer: HttpServer override val name: String get() { val cfg = httpServer.serverConfiguration return "${cfg.name} '${cfg.httpServerName}-${cfg.httpServerVersion}'" } override fun logEntries() { log.info("Entries:") val cfg = httpServer.serverConfiguration cfg.httpHandlersWithMapping.forEach { (_, regs) -> run { for (reg in regs) { val basePath = "${webConfig.url}${reg.contextPath}" when { reg.contextPath == "/docs" && webConfig.withSwaggerUi -> log.info("$basePath/index.html?url=/api/swagger.json") reg.contextPath == "/hal" && webConfig.withHalBrowser -> log.info("$basePath/#/api/service") else -> log.info("$basePath/") } } regs.filter { it.contextPath == "/docs" }.forEach { } } } } override fun launch() { makeLoggerBridge() val result = httpServer() makeStaticHandlers(result.serverConfiguration) httpServer = result } override fun shutdown() { httpServer.shutdownNow() } private fun httpServer(): HttpServer { val server = GrizzlyHttpServerFactory.createHttpServer(webConfig.apiUri, config, locator) val result = server result.serverConfiguration.isPassTraceRequest = true result.serverConfiguration.defaultQueryEncoding = Charsets.UTF_8 return result } private fun makeStaticHandlers(serverConfiguration: ServerConfiguration) { webConfig.staticContent.forEach { serverConfiguration.addHttpHandler( StaticHttpHandler(it), "/${it.normalisePath}" ) } if (webConfig.withHalBrowser) { addSwaggerUi(serverConfiguration) } if (webConfig.withSwaggerUi) { addHalBrowser(serverConfiguration) } } private fun addHalBrowser(serverConfiguration: ServerConfiguration) { val doc = StaticContent( arrayOf("/META-INF/resources/webjars/swagger-ui/3.0.14/"), "/docs", "index.html" ) serverConfiguration.addHttpHandler( CLStaticHttpHandler(WebServerGrizzlyImpl::class.java.getClassLoader(), doc), doc.normalisePath ) } private fun addSwaggerUi(serverConfiguration: ServerConfiguration) { val hal = StaticContent( arrayOf("/META-INF/resources/webjars/hal-browser/3325375/"), "/hal", "browser.html" ) serverConfiguration.addHttpHandler( CLStaticHttpHandler(WebServerGrizzlyImpl::class.java.getClassLoader(), hal), hal.normalisePath ) } private fun makeLoggerBridge() { SLF4JBridgeHandler.removeHandlersForRootLogger() SLF4JBridgeHandler.install() } override fun clone(key: String?): WebServerGrizzlyImpl { if (key == null) return this return WebServerGrizzlyImpl(cfg(key).asClass(WebAppConfig::class.java).get(), config, locator) } /** * service locator feature */ private class ServiceLocatorFeature : Feature { override fun configure(context: FeatureContext): Boolean { ServiceLocatorProvider.getServiceLocator(context) return true } } }
apache-2.0
9eef1249b45364e5686b68fae5db4026
30.660494
102
0.63202
4.514085
false
true
false
false
gradle/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/Combinators.kt
2
11054
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.configurationcache.serialization import org.gradle.configurationcache.extensions.uncheckedCast import org.gradle.configurationcache.extensions.useToRun import org.gradle.configurationcache.problems.DocumentationSection import org.gradle.configurationcache.problems.StructuredMessageBuilder import org.gradle.internal.classpath.ClassPath import org.gradle.internal.classpath.DefaultClassPath import org.gradle.internal.serialize.BaseSerializerFactory import org.gradle.internal.serialize.Decoder import org.gradle.internal.serialize.Encoder import org.gradle.internal.serialize.Serializer import java.io.File import java.io.ObjectInputStream import java.io.ObjectOutputStream import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext import kotlin.coroutines.startCoroutine import kotlin.coroutines.suspendCoroutine internal fun <T> singleton(value: T): Codec<T> = SingletonCodec(value) internal inline fun <reified T : Any> unsupported( documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes ): Codec<T> = codec( encode = { value -> logUnsupported("serialize", T::class, value.javaClass, documentationSection) }, decode = { logUnsupported("deserialize", T::class, documentationSection) null } ) internal inline fun <reified T : Any> unsupported( description: String, documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes ) = unsupported<T>(documentationSection) { text(description) } internal inline fun <reified T : Any> unsupported( documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes, noinline unsupportedMessage: StructuredMessageBuilder ): Codec<T> = codec( encode = { logUnsupported("serialize", documentationSection, unsupportedMessage) }, decode = { logUnsupported("deserialize", documentationSection, unsupportedMessage) null } ) internal fun <T> codec( encode: suspend WriteContext.(T) -> Unit, decode: suspend ReadContext.() -> T? ): Codec<T> = object : Codec<T> { override suspend fun WriteContext.encode(value: T) = encode(value) override suspend fun ReadContext.decode(): T? = decode() } internal inline fun <reified T> IsolateContext.ownerService() = ownerService(T::class.java) internal fun <T> IsolateContext.ownerService(serviceType: Class<T>) = isolate.owner.service(serviceType) internal fun <T : Any> reentrant(codec: Codec<T>): Codec<T> = object : Codec<T> { var encodeCall: EncodeFrame<T>? = null var decodeCall: DecodeFrame<T?>? = null override suspend fun WriteContext.encode(value: T) { when (encodeCall) { null -> { encodeCall = EncodeFrame(value, null) encodeLoop(coroutineContext) } else -> suspendCoroutine<Unit> { k -> encodeCall = EncodeFrame(value, k) } } } override suspend fun ReadContext.decode(): T? = when { immediateMode -> { codec.run { decode() } } decodeCall == null -> { decodeCall = DecodeFrame(null) decodeLoop(coroutineContext) } else -> suspendCoroutine { k -> decodeCall = DecodeFrame(k) } } private fun WriteContext.encodeLoop(coroutineContext: CoroutineContext) { do { val call = encodeCall!! suspend { codec.run { encode(call.value) } }.startCoroutine( Continuation(coroutineContext) { when (val k = call.k) { null -> { encodeCall = null it.getOrThrow() } else -> k.resumeWith(it) } } ) } while (encodeCall != null) } private fun ReadContext.decodeLoop(coroutineContext: CoroutineContext): T? { var result: T? = null do { val call = decodeCall!! suspend { codec.run { decode() } }.startCoroutine( Continuation(coroutineContext) { when (val k = call.k) { null -> { decodeCall = null result = it.getOrThrow() } else -> k.resumeWith(it) } } ) } while (decodeCall != null) return result } } private class DecodeFrame<T>(val k: Continuation<T>?) private data class EncodeFrame<T>(val value: T, val k: Continuation<Unit>?) private data class SingletonCodec<T>( private val singleton: T ) : Codec<T> { override suspend fun WriteContext.encode(value: T) = Unit override suspend fun ReadContext.decode(): T? = singleton } internal data class SerializerCodec<T>(val serializer: Serializer<T>) : Codec<T> { override suspend fun WriteContext.encode(value: T) = serializer.write(this, value) override suspend fun ReadContext.decode(): T = serializer.read(this) } internal fun WriteContext.writeClassArray(values: Array<Class<*>>) { writeArray(values) { writeClass(it) } } internal fun ReadContext.readClassArray(): Array<Class<*>> = readArray { readClass() } internal suspend fun ReadContext.readList(): List<Any?> = readList { read() } internal inline fun <T : Any?> ReadContext.readList(readElement: () -> T): List<T> = readCollectionInto({ size -> ArrayList(size) }) { readElement() } internal suspend fun WriteContext.writeCollection(value: Collection<*>) { writeCollection(value) { write(it) } } internal suspend fun <T : MutableCollection<Any?>> ReadContext.readCollectionInto(factory: (Int) -> T): T = readCollectionInto(factory) { read() } internal suspend fun WriteContext.writeMap(value: Map<*, *>) { writeSmallInt(value.size) writeMapEntries(value) } internal suspend fun WriteContext.writeMapEntries(value: Map<*, *>) { for (entry in value.entries) { write(entry.key) write(entry.value) } } internal suspend fun <T : MutableMap<Any?, Any?>> ReadContext.readMapInto(factory: (Int) -> T): T { val size = readSmallInt() val items = factory(size) readMapEntriesInto(items, size) return items } internal suspend fun <K, V, T : MutableMap<K, V>> ReadContext.readMapEntriesInto(items: T, size: Int) { @Suppress("unchecked_cast") for (i in 0 until size) { val key = read() as K val value = read() as V items[key] = value } } internal fun Encoder.writeClassPath(classPath: ClassPath) { writeCollection(classPath.asFiles) { writeFile(it) } } internal fun Decoder.readClassPath(): ClassPath { val size = readSmallInt() val builder = DefaultClassPath.builderWithExactSize(size) for (i in 0 until size) { builder.add(readFile()) } return builder.build() } internal fun Encoder.writeFile(file: File?) { BaseSerializerFactory.FILE_SERIALIZER.write(this, file) } internal fun Decoder.readFile(): File = BaseSerializerFactory.FILE_SERIALIZER.read(this) internal fun Encoder.writeStrings(strings: Collection<String>) { writeCollection(strings) { writeString(it) } } internal fun Decoder.readStrings(): List<String> = readCollectionInto({ size -> ArrayList(size) }) { readString() } internal inline fun <T> Encoder.writeCollection(collection: Collection<T>, writeElement: (T) -> Unit) { writeSmallInt(collection.size) for (element in collection) { writeElement(element) } } internal inline fun Decoder.readCollection(readElement: () -> Unit) { val size = readSmallInt() for (i in 0 until size) { readElement() } } internal inline fun <T, C : MutableCollection<T>> Decoder.readCollectionInto( containerForSize: (Int) -> C, readElement: () -> T ): C { val size = readSmallInt() val container = containerForSize(size) for (i in 0 until size) { container.add(readElement()) } return container } internal inline fun <T : Any?> WriteContext.writeArray(array: Array<T>, writeElement: (T) -> Unit) { writeClass(array.javaClass.componentType) writeSmallInt(array.size) for (element in array) { writeElement(element) } } internal inline fun <T : Any?> ReadContext.readArray(readElement: () -> T): Array<T> { val componentType = readClass() val size = readSmallInt() val array: Array<T> = java.lang.reflect.Array.newInstance(componentType, size).uncheckedCast() for (i in 0 until size) { array[i] = readElement() } return array } fun <E : Enum<E>> Encoder.writeEnum(value: E) { writeSmallInt(value.ordinal) } inline fun <reified E : Enum<E>> Decoder.readEnum(): E = readSmallInt().let { ordinal -> enumValues<E>()[ordinal] } fun Encoder.writeShort(value: Short) { BaseSerializerFactory.SHORT_SERIALIZER.write(this, value) } fun Decoder.readShort(): Short = BaseSerializerFactory.SHORT_SERIALIZER.read(this) fun Encoder.writeFloat(value: Float) { BaseSerializerFactory.FLOAT_SERIALIZER.write(this, value) } fun Decoder.readFloat(): Float = BaseSerializerFactory.FLOAT_SERIALIZER.read(this) fun Encoder.writeDouble(value: Double) { BaseSerializerFactory.DOUBLE_SERIALIZER.write(this, value) } fun Decoder.readDouble(): Double = BaseSerializerFactory.DOUBLE_SERIALIZER.read(this) inline fun <reified T : Any> ReadContext.readClassOf(): Class<out T> = readClass().asSubclass(T::class.java) /** * Workaround for serializing JDK types with complex/opaque state on Java 17+. * * **IMPORTANT** Should be avoided for composite/container types as all components would be serialized * using Java serialization. */ internal fun WriteContext.encodeUsingJavaSerialization(value: Any) { ObjectOutputStream(outputStream).useToRun { writeObject(value) } } internal fun ReadContext.decodeUsingJavaSerialization(): Any? = ObjectInputStream(inputStream).readObject()
apache-2.0
5e36b74612d9ebe8ac82b87d9134c401
24.528868
102
0.656052
4.281177
false
false
false
false
ColaGom/KtGitCloner
src/main/kotlin/nlp/PreProcessor.kt
1
6862
package nlp import common.KEY_COMMENT import common.KEY_SOURCE import common.Stopwords import data.SourceFile import org.tartarus.snowball.ext.englishStemmer class PreProcessor(var raw: String) { companion object { val regComment = Regex("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)") val regComment2 = Regex("/\\*(?:.|[\\r\\n])*?\\*/") val regAnnotate = Regex("@.*\\b") val regNonAlphanum = Regex("[^a-zA-Z]") val regCamelCase = Regex(String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])(\\B)", "(?<=[^A-Z])(?=[A-Z])(\\B)", "(?<=[A-Za-z])(?=[^A-Za-z])(\\B)" )) val regHtml = Regex("<[^>]*>") } fun toSourceFile(path : String): SourceFile { var wordMap: HashMap<String, HashMap<String, Int>> = hashMapOf() var srcLen = 0 var comLen = 0 var strComment = "" var strSource = "" val matcher = regComment.toPattern().matcher(raw) while (matcher.find()) { val str = matcher.group(); if (!str.contains("license", true) && !str.contains("copyright", true)) { strComment += str + " "; } } strSource = regComment.replace(raw, ""); srcLen = strSource.length comLen = strComment.length strSource = regAnnotate.replace(strSource, "") strSource = regNonAlphanum.replace(strSource, " ") strSource = regCamelCase.replace(strSource, " ") strComment = regAnnotate.replace(strComment, "") strComment = regHtml.replace(strComment, "") strComment = regNonAlphanum.replace(strComment, " ") strComment = regCamelCase.replace(strComment, " ") val stemmer = englishStemmer() val srcFreqMap : HashMap<String, Int> = hashMapOf() val comFreqMap : HashMap<String, Int> = hashMapOf() strSource.toLowerCase().split(" ").filter { it.length > 2 && it.length < 20 && !Stopwords.instance.contains(it) }.toList().forEach { stemmer.setCurrent(it) stemmer.stem() val key = stemmer.current if(srcFreqMap.containsKey(key)) srcFreqMap.set(key, srcFreqMap.get(key)!! + 1) else srcFreqMap.put(key, 1) } strComment.toLowerCase().split(" ").filter { it.length > 2 && it.length < 20 && !Stopwords.instance.contains(it) }.toList().forEach { stemmer.setCurrent(it) stemmer.stem() val key = stemmer.current if(comFreqMap.containsKey(key)) comFreqMap.set(key, comFreqMap.get(key)!! + 1) else comFreqMap.put(key, 1) } wordMap.put(KEY_SOURCE, srcFreqMap) wordMap.put(KEY_COMMENT, comFreqMap) return SourceFile(path, comLen, srcLen, wordMap) } fun step1() { // avoid to overflow if (raw.length > 2000) { val sub: String = raw.substring(0, 1000); if (regComment.find(sub)?.value?.toLowerCase()?.contains("license") == true) raw = regComment.replaceFirst(sub, "") + raw.substring(1000) } else { if (regComment.find(raw)?.value?.toLowerCase()?.contains("license") == true) raw = regComment.replaceFirst(raw, "") } } fun splitLargeStr(splen: Int, str: String): List<String> { var result: MutableList<String> = mutableListOf() var current = 0 while (true) { var find = false for (i in splen + current downTo current + 1) { if (str[i - 1] == '\r' && str[i] == '\n') { result.add(str.substring(current, i)) current = i find = true break } } if (!find && current + splen < str.length) { result.add(str.substring(current, current + splen)) current += splen } if (str.length - current <= splen) { result.add(str.substring(current)) break } } return result } fun run2(): HashMap<String, List<String>> { var result: HashMap<String, List<String>> = hashMapOf() var strComment = "" var strSource = "" val matcher = regComment.toPattern().matcher(raw) while (matcher.find()) { val str = matcher.group(); if (!str.contains("license", true) && !str.contains("copyright", true)) { strComment += str + " "; } } strSource = regComment.replace(raw, ""); strSource = regAnnotate.replace(strSource, "") strSource = regNonAlphanum.replace(strSource, " ") strSource = regCamelCase.replace(strSource, " ") strComment = regAnnotate.replace(strComment, "") strComment = regHtml.replace(strComment, "") strComment = regNonAlphanum.replace(strComment, " ") strComment = regCamelCase.replace(strComment, " ") result.put(KEY_SOURCE, strSource.toLowerCase().split(" ").filter { it.length > 2 && !Stopwords.instance.contains(it) }.toMutableList()) result.put(KEY_COMMENT, strComment.toLowerCase().split(" ").filter { it.length > 2 && !Stopwords.instance.contains(it) }.toMutableList()) return result; } fun run(): List<String> { var result: MutableList<String> = mutableListOf() var strComment = "" var strSource = "" step1(); // regComment.findAll(raw).forEach { // strComment += it.value // } // strSource = regComment.replace(raw, "") // if (raw.length < 10000) { // regComment.findAll(raw).forEach { // strComment += it.value // } // strSource = regComment.replace(raw, "") // } else { // splitLargeStr(3000, raw).forEach({ // // regComment.findAll(it).forEach { // strComment += it.value // } // // strSource += regComment.replace(it, "") + " " // }) // } // val mr = regComment2.find(raw)?.value // do { // val mr = regComment2.find(raw)?.value // // if (mr == null) // break // else { // strComment += mr // raw = regComment2.replace(raw, "") // } // } while (true) // raw = regAnnotate.replace(raw, "") raw = regHtml.replace(raw, "") raw = regNonAlphanum.replace(raw, " ") raw = regCamelCase.replace(raw, " ") return raw.toLowerCase().split(" ").filter { it.length > 2 && !Stopwords.instance.contains(it) }.toMutableList() } }
apache-2.0
d362868b3690bf49cb9ebbb14e45661c
31.367925
145
0.518508
3.912201
false
false
false
false
PaleoCrafter/BitReplicator
src/main/kotlin/de/mineformers/bitreplicator/util/Rays.kt
1
7198
package de.mineformers.bitreplicator.util import net.minecraft.entity.Entity import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.RayTraceResult import net.minecraft.util.math.Vec3d import java.lang.Math.max import java.lang.Math.min import javax.vecmath.Matrix4f import javax.vecmath.Vector4f /** * A collection of utility functions to deal with ray tracing. */ object Rays { /** * Performs a ray trace on a collection of boxes from an entity's eyes, * returns the index of the first one hit, `-1` otherwise. */ fun rayTraceBoxes(entity: Entity, boxes: List<AxisAlignedBB>) = rayTraceBoxes(Rendering.getEyePosition(entity, Rendering.partialTicks), entity.getLook(Rendering.partialTicks), boxes) /** * Performs a ray trace on a collection of boxes, returns the index of the first one hit, `-1` otherwise. */ fun rayTraceBoxes(origin: Vec3d, dir: Vec3d, boxes: List<AxisAlignedBB>) = boxes.mapIndexed { i, box -> Pair(i, rayTraceBox(origin, dir, box)) } .filter { it.second != null } .minBy { it.second!!.hitVec.squareDistanceTo(origin) }?.first ?: -1 /** * Performs a ray-box intersection from an entity's eyes. */ fun rayTraceBox(entity: Entity, box: AxisAlignedBB) = rayTraceBox(Rendering.getEyePosition(entity, Rendering.partialTicks), entity.getLook(Rendering.partialTicks), box) /** * Fast Ray-Box Intersection * from "Graphics Gems", Academic Press, 1990 * * Original is in C * * @author Andrew Woo */ fun rayTraceBox(origin: Vec3d, dir: Vec3d, box: AxisAlignedBB): RayTraceResult? { var t1: Double var t2: Double var tmin = Double.NEGATIVE_INFINITY var tmax = Double.POSITIVE_INFINITY var closestPoint = Vec3d(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE) var face = EnumFacing.NORTH for (i in 0..2) { t1 = (box.min[i] - origin[i]) / dir[i] t2 = (box.max[i] - origin[i]) / dir[i] if (t1 >= 0) { val p = origin + t1 * dir if (box.contains(p) && p.squareDistanceTo(origin) < closestPoint.squareDistanceTo(origin)) { closestPoint = p face = EnumFacing.VALUES[((2 * i + 4) % 6)] } } if (t2 >= 0) { val p = origin + t2 * dir if (box.contains(p) && p.squareDistanceTo(origin) < closestPoint.squareDistanceTo(origin)) { closestPoint = p face = EnumFacing.VALUES[((2 * i + 5) % 6)] } } tmin = max(tmin, min(t1, t2)) tmax = min(tmax, max(t1, t2)) } if (tmax > max(.0, tmin)) { return RayTraceResult(origin + dir * max(.0, tmin), face) } return null } /** * Sends a ray though a quad from an entity's eyes, optionally applying some transformations to it beforehand. * If there was a result, it will be returned in coordinates local to the quad, i.e. with the inverse * of the transformations applied. */ fun rayTraceQuad(entity: Entity, vertices: List<Vec3d>, transformations: Matrix4f? = null, epsilon: Double = 1e-6) = rayTraceQuad(Rendering.getEyePosition(entity, Rendering.partialTicks), entity.getLook(Rendering.partialTicks), vertices, transformations, epsilon) /** * Sends a ray though a quad, optionally applying some transformations to it beforehand. * If there was a result, it will be returned in coordinates local to the quad, i.e. with the inverse * of the transformations applied. */ fun rayTraceQuad(origin: Vec3d, dir: Vec3d, vertices: List<Vec3d>, transformations: Matrix4f? = null, epsilon: Double = 1e-6): Vec3d? { val quad = if (transformations != null) { // Transform all vertices vertices.map { val v = Vector4f(it.x.toFloat(), it.y.toFloat(), it.z.toFloat(), 1f) transformations.transform(v) Vec3d(v.x.toDouble(), v.y.toDouble(), v.z.toDouble()) } } else { vertices } // Intersect with both triangles making up the quad val hit = Rays.moellerTrumbore(origin, dir, quad[0], quad[1], quad[2], epsilon) ?: Rays.moellerTrumbore(origin, dir, quad[0], quad[2], quad[3], epsilon) if (hit != null && transformations != null) { val invertedMatrix = Matrix4f(transformations) invertedMatrix.invert() val v = Vector4f(hit.x.toFloat(), hit.y.toFloat(), hit.z.toFloat(), 1f) invertedMatrix.transform(v) return Vec3d(v.x.toDouble(), v.y.toDouble(), v.z.toDouble()) } else { return hit } } /** * Performs a Möller-Trumbore intersection on a triangle from an entity's eyes and * returns the position on the triangle that was hit, or `null` if there is no intersection. * Ignores the winding of the triangle, i.e. does not support backface culling. */ fun moellerTrumbore(entity: Entity, v1: Vec3d, v2: Vec3d, v3: Vec3d, epsilon: Double = 1e-6) = moellerTrumbore(Rendering.getEyePosition(entity, Rendering.partialTicks), entity.getLook(Rendering.partialTicks), v1, v2, v3, epsilon) /** * Performs a Möller-Trumbore intersection on a triangle and returns the position on the triangle that was hit, * or `null` if there is no intersection. * Ignores the winding of the triangle, i.e. does not support backface culling. */ fun moellerTrumbore(origin: Vec3d, dir: Vec3d, v1: Vec3d, v2: Vec3d, v3: Vec3d, epsilon: Double = 1e-6): Vec3d? { // Edges with v1 adjacent to them val e1 = v2 - v1 val e2 = v3 - v1 // Required for determinant and calculation of u val p = dir.crossProduct(e2) val det = e1.dotProduct(p) // Make sure determinant isn't near zero, otherwise we lie in the triangle's plane if (det > -epsilon && det < epsilon) { return null } // Distance from v1 to origin val t = origin - v1 // Calculate u parameter and check whether it's in the triangle's bounds val u = t.dotProduct(p) / det if (u < 0 || u > 1) { return null } // Calculate v parameter and check whether it's in the triangle's bounds val q = t.crossProduct(e1) val v = dir.dotProduct(q) / det if (v < 0 || u + v > 1) { return null } // Actual intersection test val d = e2.dotProduct(q) / det if (d > epsilon) { // u and v are barycentric coordinates on the triangle, convert them to "normal" ones return v1 + u * e1 + v * e2 } return null } }
mit
cca7091ce1eabf4667715bc320d8f67a
39.432584
120
0.583936
3.883432
false
false
false
false
ethauvin/kobalt
src/test/kotlin/com/beust/kobalt/TestModule.kt
1
1700
package com.beust.kobalt import com.beust.kobalt.api.KobaltContext import com.beust.kobalt.app.MainModule import com.beust.kobalt.internal.ILogger import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.internal.KobaltSettingsXml import com.beust.kobalt.maven.LocalRepo import com.beust.kobalt.maven.aether.KobaltMavenResolver import com.beust.kobalt.misc.kobaltLog import com.google.common.eventbus.EventBus import com.google.inject.Provider import com.google.inject.Scopes import java.io.File val LOCAL_CACHE = File(SystemProperties.homeDir + File.separatorChar + ".kobalt-test") val TEST_KOBALT_SETTINGS = KobaltSettings(KobaltSettingsXml()).apply { localCache = LOCAL_CACHE } class TestLocalRepo: LocalRepo(TEST_KOBALT_SETTINGS) class TestModule : MainModule(Args(), TEST_KOBALT_SETTINGS) { override fun configureTest() { val localRepo = TestLocalRepo() bind(LocalRepo::class.java).toInstance(localRepo) // val localAether = Aether(LOCAL_CACHE, TEST_KOBALT_SETTINGS, EventBus()) val testResolver = KobaltMavenResolver(KobaltSettings(KobaltSettingsXml()), Args(), TestLocalRepo(), EventBus()) bind(KobaltMavenResolver::class.java).to(testResolver) bind(KobaltContext::class.java).toProvider(Provider<KobaltContext> { KobaltContext(args).apply { resolver = testResolver logger = object: ILogger { override fun log(tag: CharSequence, level: Int, message: CharSequence, newLine: Boolean) { kobaltLog(1, "TestLog: [$tag $level] " + message) } } } }).`in`(Scopes.SINGLETON) } }
apache-2.0
14cff73b451ebe399ed7a2b3c3131579
39.47619
120
0.701765
4.218362
false
true
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/ui/ViewEventActivityNoRecents.kt
1
33663
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.ui import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.format.DateUtils import android.view.View import android.widget.* import com.github.quarck.calnotify.app.* import com.github.quarck.calnotify.calendar.* import com.github.quarck.calnotify.dismissedeventsstorage.EventDismissType import com.github.quarck.calnotify.eventsstorage.EventsStorage //import com.github.quarck.calnotify.logs.Logger import com.github.quarck.calnotify.maps.MapsIntents import com.github.quarck.calnotify.quiethours.QuietHoursManager import com.github.quarck.calnotify.textutils.EventFormatter import com.github.quarck.calnotify.textutils.EventFormatterInterface import com.github.quarck.calnotify.utils.* import java.util.* import com.github.quarck.calnotify.* import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.permissions.PermissionsManager import android.content.res.ColorStateList import android.os.Build import android.os.Handler import android.support.v4.content.ContextCompat import android.text.method.ScrollingMovementMethod // TODO: add repeating rule and calendar name somewhere on the snooze activity enum class ViewEventActivityStateCode(val code: Int) { Normal(0), CustomSnoozeOpened(1), SnoozeUntilOpenedDatePicker(2), SnoozeUntilOpenedTimePicker(3); companion object { fun fromInt(v: Int): ViewEventActivityStateCode { return values()[v]; } } } data class ViewEventActivityState( var state: ViewEventActivityStateCode = ViewEventActivityStateCode.Normal, var timeAMillis: Long = 0L, var timeBMillis: Long = 0L ) { fun toBundle(bundle: Bundle) { bundle.putInt(KEY_STATE_CODE, state.code) bundle.putLong(KEY_TIME_A, timeAMillis) bundle.putLong(KEY_TIME_B, timeBMillis) } companion object { fun fromBundle(bundle: Bundle): ViewEventActivityState { val code = bundle.getInt(KEY_STATE_CODE, 0) val timeA = bundle.getLong(KEY_TIME_A, 0L) val timeB = bundle.getLong(KEY_TIME_B, 0L) return ViewEventActivityState(ViewEventActivityStateCode.fromInt(code), timeA, timeB) } const val KEY_STATE_CODE = "code" const val KEY_TIME_A = "timeA" const val KEY_TIME_B = "timeB" } } class ViewEventById(private val context: Context, internal var eventId: Long) : Runnable { override fun run() { CalendarIntents.viewCalendarEvent(context, eventId) } } class ViewEventByEvent(private val context: Context, internal var event: EventAlertRecord) : Runnable { override fun run() { CalendarIntents.viewCalendarEvent(context, event) } } open class ViewEventActivityNoRecents : AppCompatActivity() { var state = ViewEventActivityState() lateinit var event: EventAlertRecord lateinit var calendar: CalendarRecord lateinit var snoozePresets: LongArray lateinit var settings: Settings lateinit var formatter: EventFormatterInterface val calendarReloadManager: CalendarReloadManagerInterface = CalendarReloadManager val calendarProvider: CalendarProviderInterface = CalendarProvider val handler = Handler() // var snoozeAllIsChange = false var snoozeFromMainActivity = false val snoozePresetControlIds = intArrayOf( R.id.snooze_view_snooze_present1, R.id.snooze_view_snooze_present2, R.id.snooze_view_snooze_present3, R.id.snooze_view_snooze_present4, R.id.snooze_view_snooze_present5, R.id.snooze_view_snooze_present6 ) val snoozePresentQuietTimeReminderControlIds = intArrayOf( R.id.snooze_view_snooze_present1_quiet_time_notice, R.id.snooze_view_snooze_present2_quiet_time_notice, R.id.snooze_view_snooze_present3_quiet_time_notice, R.id.snooze_view_snooze_present4_quiet_time_notice, R.id.snooze_view_snooze_present5_quiet_time_notice, R.id.snooze_view_snooze_present6_quiet_time_notice ) var baselineIds = intArrayOf( R.id.snooze_view_snooze_present1_quiet_time_notice_baseline, R.id.snooze_view_snooze_present2_quiet_time_notice_baseline, R.id.snooze_view_snooze_present3_quiet_time_notice_baseline, R.id.snooze_view_snooze_present4_quiet_time_notice_baseline, R.id.snooze_view_snooze_present5_quiet_time_notice_baseline, R.id.snooze_view_snooze_present6_quiet_time_notice_baseline ) private val undoManager by lazy { UndoManager } // These dialog controls moved here so saveInstanceState could store current time selection var customSnooze_TimeIntervalPickerController: TimeIntervalPickerController? = null var snoozeUntil_DatePicker: DatePicker? = null var snoozeUntil_TimePicker: TimePicker? = null lateinit var calendarNameTextView: TextView lateinit var calendarAccountTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!PermissionsManager.hasAllCalendarPermissions(this)) { finish() return } if (savedInstanceState != null) state = ViewEventActivityState.fromBundle(savedInstanceState) setContentView(R.layout.activity_view) val currentTime = System.currentTimeMillis() settings = Settings(this) formatter = EventFormatter(this) // Populate event details val eventId = intent.getLongExtra(Consts.INTENT_EVENT_ID_KEY, -1) val instanceStartTime = intent.getLongExtra(Consts.INTENT_INSTANCE_START_TIME_KEY, -1L) //snoozeAllIsChange = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_IS_CHANGE, false) snoozeFromMainActivity = intent.getBooleanExtra(Consts.INTENT_SNOOZE_FROM_MAIN_ACTIVITY, false) find<Toolbar?>(R.id.toolbar)?.visibility = View.GONE // load event if it is not a "snooze all" EventsStorage(this).use { db -> var dbEvent = db.getEvent(eventId, instanceStartTime) if (dbEvent != null) { val eventDidChange = calendarReloadManager.reloadSingleEvent(this, db, dbEvent, calendarProvider, null) if (eventDidChange) { val newDbEvent = db.getEvent(eventId, instanceStartTime) if (newDbEvent != null) { dbEvent = newDbEvent } else { DevLog.error(LOG_TAG, "ViewActivity: cannot find event after calendar reload, event $eventId, inst $instanceStartTime") } } } if (dbEvent == null) { DevLog.error(LOG_TAG, "ViewActivity started for non-existing eveng id $eventId, st $instanceStartTime") finish() return } event = dbEvent } calendar = calendarProvider.getCalendarById(this, event.calendarId) ?: calendarProvider.createCalendarNotFoundCal(this) calendarNameTextView = findOrThrow<TextView>(R.id.view_event_calendar_name) calendarNameTextView.text = calendar.displayName calendarAccountTextView = findOrThrow<TextView>(R.id.view_event_calendar_account) calendarAccountTextView.text = calendar.accountName snoozePresets = settings.snoozePresets // remove "MM minutes before event" snooze presents for "Snooze All" // and when event time has passed already if (event.displayedStartTime < currentTime) snoozePresets = snoozePresets.filter { it > 0L }.toLongArray() val isQuiet = QuietHoursManager(this).isInsideQuietPeriod( settings, snoozePresets.map { it -> currentTime + it }.toLongArray()) // Populate snooze controls for ((idx, id) in snoozePresetControlIds.withIndex()) { val snoozeLable = findOrThrow<TextView>(id); val quietTimeNotice = findOrThrow<TextView>(snoozePresentQuietTimeReminderControlIds[idx]) val quietTimeNoticeBaseline = findOrThrow<TextView>(baselineIds[idx]) if (idx < snoozePresets.size) { snoozeLable.text = formatPreset(snoozePresets[idx]) snoozeLable.visibility = View.VISIBLE; quietTimeNoticeBaseline.visibility = View.VISIBLE if (isQuiet[idx]) quietTimeNotice.visibility = View.VISIBLE else quietTimeNotice.visibility = View.GONE } else { snoozeLable.visibility = View.GONE; quietTimeNotice.visibility = View.GONE quietTimeNoticeBaseline.visibility = View.GONE } } // need to hide these guys val showCustomSnoozeVisibility = View.VISIBLE findOrThrow<TextView>(R.id.snooze_view_snooze_custom).visibility = showCustomSnoozeVisibility val snoozeCustom = find<TextView?>(R.id.snooze_view_snooze_until) if (snoozeCustom != null) snoozeCustom.visibility = showCustomSnoozeVisibility val location = event.location; if (location != "") { findOrThrow<View>(R.id.snooze_view_location_layout).visibility = View.VISIBLE; val locationView = findOrThrow<TextView>(R.id.snooze_view_location) locationView.text = location; locationView.setOnClickListener { MapsIntents.openLocation(this, event.location) } } val title = findOrThrow<TextView>(R.id.snooze_view_title) title.text = if (event.title.isNotEmpty()) event.title else this.resources.getString(R.string.empty_title); val (line1, line2) = formatter.formatDateTimeTwoLines(event); val dateTimeFirstLine = findOrThrow<TextView>(R.id.snooze_view_event_date_line1) val dateTimeSecondLine = findOrThrow<TextView>(R.id.snooze_view_event_date_line2) dateTimeFirstLine.text = line1; if (line2.isEmpty()) dateTimeSecondLine.visibility = View.GONE else dateTimeSecondLine.text = line2; dateTimeFirstLine.isClickable = false dateTimeSecondLine.isClickable = false title.isClickable = false title.setMovementMethod(ScrollingMovementMethod()) title.post { val y = title.getLayout()?.getLineTop(0) if (y != null) title.scrollTo(0, y) } title.setTextIsSelectable(true) if (event.desc.isNotEmpty() && !settings.snoozeHideEventDescription) { // Show the event desc findOrThrow<RelativeLayout>(R.id.layout_event_description).visibility = View.VISIBLE findOrThrow<TextView>(R.id.snooze_view_event_description).text = event.desc } var color: Int = event.color.adjustCalendarColor() if (color == 0) color = ContextCompat.getColor(this, R.color.primary) val colorDrawable = ColorDrawable(color) findOrThrow<RelativeLayout>(R.id.snooze_view_event_details_layout).background = colorDrawable if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = color.scaleColor(0.7f) } // val shouldOfferMove = (!event.isRepeating) && (DateTimeUtils.isUTCTodayOrInThePast(event.startTime)) val shouldOfferMove = (DateTimeUtils.isUTCTodayOrInThePast(event.startTime)) if (shouldOfferMove) { findOrThrow<RelativeLayout>(R.id.snooze_reschedule_layout).visibility = View.VISIBLE if (event.isRepeating) { findOrThrow<TextView>(R.id.snooze_reschedule_for).text = getString(R.string.change_event_time_repeating_event) } } else { find<View?>(R.id.snooze_view_inter_view_divider)?.visibility = View.GONE } if (event.snoozedUntil != 0L) { findOrThrow<TextView>(R.id.snooze_snooze_for).text = resources.getString(R.string.change_snooze_to) } val nextReminderLayout: RelativeLayout? = find<RelativeLayout>(R.id.layout_next_reminder) val nextReminderText: TextView? = find<TextView>(R.id.snooze_view_next_reminder) if (nextReminderLayout != null && nextReminderText != null) { val nextReminder = calendarProvider.getNextEventReminderTime(this, event) if (nextReminder != 0L) { nextReminderLayout.visibility = View.VISIBLE nextReminderText.visibility = View.VISIBLE val format = this.resources.getString(R.string.next_reminder_fmt) nextReminderText.text = format.format(formatter.formatTimePoint(nextReminder)) } } val fab = findOrThrow<FloatingActionButton>(R.id.floating_edit_button) if (!calendar.isReadOnly) { if (!event.isRepeating && !settings.alwaysUseExternalEditor) { fab.setOnClickListener { _ -> val intent = Intent(this, EditEventActivity::class.java) intent.putExtra(EditEventActivity.EVENT_ID, event.eventId) startActivity(intent) finish() } } else { fab.setOnClickListener { _ -> CalendarIntents.viewCalendarEvent(this, event) finish() } } val states = arrayOf(intArrayOf(android.R.attr.state_enabled), // enabled intArrayOf(android.R.attr.state_pressed) // pressed ) val colors = intArrayOf( event.color.adjustCalendarColor(false), event.color.adjustCalendarColor(true) ) fab.backgroundTintList = ColorStateList(states, colors) } else { fab.visibility = View.GONE } val menuButton = find<ImageView?>(R.id.snooze_view_menu) menuButton?.setOnClickListener { showDismissEditPopup(menuButton) } ApplicationController.cleanupEventReminder(this) restoreState(state) } fun showDismissEditPopup(v: View) { val popup = PopupMenu(this, v) val inflater = popup.menuInflater inflater.inflate(R.menu.snooze, popup.menu) val menuItem = popup.menu.findItem(R.id.action_delete_event) if (menuItem != null) { menuItem.isVisible = !event.isRepeating } val menuItemMute = popup.menu.findItem(R.id.action_mute_event) if (menuItemMute != null) { menuItemMute.isVisible = !event.isMuted && !event.isTask } val menuItemUnMute = popup.menu.findItem(R.id.action_unmute_event) if (menuItemUnMute != null) { menuItemUnMute.isVisible = event.isMuted } if (event.isTask) { val menuItemDismiss = popup.menu.findItem(R.id.action_dismiss_event) val menuItemDone = popup.menu.findItem(R.id.action_done_event) if (menuItemDismiss != null && menuItemDone != null) { menuItemDismiss.isVisible = false menuItemDone.isVisible = true } } /* <item android:id="@+id/action_mute_event" android:title="@string/mute_notification" android:visible="false" /> <item android:id="@+id/action_unmute_event" android:title="@string/un_mute_notification" android:visible="false" />*/ popup.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_dismiss_event, R.id.action_done_event -> { ApplicationController.dismissEvent(this, EventDismissType.ManuallyDismissedFromActivity, event) undoManager.addUndoState( UndoState(undo = Runnable { ApplicationController.restoreEvent(applicationContext, event) })) finish() true } R.id.action_delete_event -> { AlertDialog.Builder(this) .setMessage(getString(R.string.delete_event_question)) .setCancelable(false) .setPositiveButton(android.R.string.yes) { _, _ -> DevLog.info(LOG_TAG, "Deleting event ${event.eventId} per user request") val success = ApplicationController.dismissAndDeleteEvent( this, EventDismissType.ManuallyDismissedFromActivity, event ) if (success) { undoManager.addUndoState( UndoState(undo = Runnable { ApplicationController.restoreEvent(applicationContext, event) })) } finish() } .setNegativeButton(R.string.cancel) { _, _ -> } .create() .show() true } R.id.action_mute_event -> { ApplicationController.toggleMuteForEvent(this, event.eventId, event.instanceStartTime, 0) event.isMuted = true true } R.id.action_unmute_event -> { ApplicationController.toggleMuteForEvent(this, event.eventId, event.instanceStartTime, 1) event.isMuted = false true } R.id.action_open_in_calendar -> { CalendarIntents.viewCalendarEvent(this, event) finish() true } else -> false } } popup.show() } private fun formatPreset(preset: Long): String { val num: Long val unit: String val presetSeconds = preset / 1000L; if (presetSeconds == 0L) return resources.getString(R.string.until_event_time) if (presetSeconds % Consts.DAY_IN_SECONDS == 0L) { num = presetSeconds / Consts.DAY_IN_SECONDS; unit = if (num != 1L) resources.getString(R.string.days) else resources.getString(R.string.day) } else if (presetSeconds % Consts.HOUR_IN_SECONDS == 0L) { num = presetSeconds / Consts.HOUR_IN_SECONDS; unit = if (num != 1L) resources.getString(R.string.hours) else resources.getString(R.string.hour) } else { num = presetSeconds / Consts.MINUTE_IN_SECONDS; unit = if (num != 1L) resources.getString(R.string.minutes) else resources.getString(R.string.minute) } if (num <= 0) { val beforeEventString = resources.getString(R.string.before_event) return "${-num} $unit $beforeEventString" } return "$num $unit" } @Suppress("unused", "UNUSED_PARAMETER") fun onButtonCancelClick(v: View?) { finish(); } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonEventDetailsClick(v: View?) { CalendarIntents.viewCalendarEvent(this, event) } private fun snoozeEvent(snoozeDelay: Long) { DevLog.debug(LOG_TAG, "Snoozing event id ${event.eventId}, snoozeDelay=${snoozeDelay / 1000L}") val result = ApplicationController.snoozeEvent(this, event.eventId, event.instanceStartTime, snoozeDelay); if (result != null) { result.toast(this) } finish() } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonSnoozeClick(v: View?) { if (v == null) return for ((idx, id) in snoozePresetControlIds.withIndex()) { if (id == v.id) { snoozeEvent(snoozePresets[idx]); break; } } } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) when (state.state) { ViewEventActivityStateCode.Normal -> { } ViewEventActivityStateCode.CustomSnoozeOpened -> { state.timeAMillis = customSnooze_TimeIntervalPickerController?.intervalMilliseconds ?: 0L } ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker -> { val datePicker = snoozeUntil_DatePicker if (datePicker != null) { datePicker.clearFocus() val date = Calendar.getInstance() date.set(datePicker.year, datePicker.month, datePicker.dayOfMonth, 0, 0, 0) state.timeAMillis = date.timeInMillis state.timeBMillis = event?.snoozedUntil ?: 0L } } ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker -> { val timePicker = snoozeUntil_TimePicker if (timePicker != null) { timePicker.clearFocus() val time = Calendar.getInstance() time.timeInMillis = state.timeAMillis time.set(Calendar.HOUR_OF_DAY, timePicker.hourCompat) time.set(Calendar.MINUTE, timePicker.minuteCompat) state.timeBMillis = time.timeInMillis } } } // val intervalMilliseconds = customSnooze_TimeIntervalPickerController?.intervalMilliseconds ?: 0L state.toBundle(outState) } private fun restoreState(state: ViewEventActivityState) { when (state.state) { ViewEventActivityStateCode.Normal -> { } ViewEventActivityStateCode.CustomSnoozeOpened -> { customSnoozeShowDialog(state.timeAMillis) } ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker -> { snoozeUntilShowDatePickerDialog(state.timeAMillis, state.timeBMillis) } ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker -> { snoozeUntilShowTimePickerDialog(state.timeAMillis, state.timeBMillis) } } } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonCustomSnoozeClick(v: View?) { customSnoozeShowSimplifiedDialog(persistentState.lastCustomSnoozeIntervalMillis) } fun customSnoozeShowSimplifiedDialog(initialTimeValue: Long) { val intervalNames: Array<String> = this.resources.getStringArray(R.array.default_snooze_intervals) val intervalValues = this.resources.getIntArray(R.array.default_snooze_intervals_seconds_values) val builder = AlertDialog.Builder(this) val adapter = ArrayAdapter<String>(this, R.layout.simple_list_item_medium) adapter.addAll(intervalNames.toMutableList()) builder.setCancelable(true) builder.setAdapter(adapter) { _, which -> if (which in 0..intervalValues.size-1) { val intervalSeconds = intervalValues[which].toLong() if (intervalSeconds != -1L) { snoozeEvent(intervalSeconds * 1000L) } else { customSnoozeShowDialog(initialTimeValue) } } } builder.show() } fun customSnoozeShowDialog(initialTimeValue: Long) { val dialogView = this.layoutInflater.inflate(R.layout.dialog_interval_picker, null); val timeIntervalPicker = TimeIntervalPickerController(dialogView, R.string.snooze_for, 0, false) timeIntervalPicker.intervalMilliseconds = initialTimeValue state.state = ViewEventActivityStateCode.CustomSnoozeOpened customSnooze_TimeIntervalPickerController = timeIntervalPicker val builder = AlertDialog.Builder(this) builder.setView(dialogView) builder.setPositiveButton(R.string.snooze) { _: DialogInterface?, _: Int -> val intervalMilliseconds = timeIntervalPicker.intervalMilliseconds this.persistentState.lastCustomSnoozeIntervalMillis = intervalMilliseconds snoozeEvent(intervalMilliseconds) state.state = ViewEventActivityStateCode.Normal customSnooze_TimeIntervalPickerController = null } builder.setNegativeButton(R.string.cancel) { _: DialogInterface?, _: Int -> state.state = ViewEventActivityStateCode.Normal customSnooze_TimeIntervalPickerController = null } builder.create().show() } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonSnoozeUntilClick(v: View?) { snoozeUntilShowDatePickerDialog(event.snoozedUntil, event.snoozedUntil) } fun inflateDatePickerDialog() = layoutInflater?.inflate(R.layout.dialog_date_picker, null) fun inflateTimePickerDialog() = layoutInflater?.inflate(R.layout.dialog_time_picker, null) fun snoozeUntilShowDatePickerDialog(initialValueForDate: Long, initialValueForTime: Long) { val dialogDate = inflateDatePickerDialog() ?: return val datePicker = dialogDate.findOrThrow<DatePicker>(R.id.datePickerCustomSnooze) state.state = ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker snoozeUntil_DatePicker = datePicker if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val firstDayOfWeek = Settings(this).firstDayOfWeek if (firstDayOfWeek != -1) snoozeUntil_DatePicker?.firstDayOfWeek = firstDayOfWeek } if (initialValueForDate != 0L) { val cal = Calendar.getInstance() cal.timeInMillis = initialValueForDate val year = cal.get(Calendar.YEAR) val month = cal.get(Calendar.MONTH) val day = cal.get(Calendar.DAY_OF_MONTH) snoozeUntil_DatePicker?.updateDate(year, month, day) } val builder = AlertDialog.Builder(this) builder.setView(dialogDate) builder.setPositiveButton(R.string.next) { _: DialogInterface?, _: Int -> datePicker.clearFocus() val date = Calendar.getInstance() date.set(datePicker.year, datePicker.month, datePicker.dayOfMonth, 0, 0, 0) snoozeUntilShowTimePickerDialog(date.timeInMillis, initialValueForTime) } builder.setNegativeButton(R.string.cancel) { _: DialogInterface?, _: Int -> state.state = ViewEventActivityStateCode.Normal snoozeUntil_DatePicker = null } builder.create().show() } fun snoozeUntilShowTimePickerDialog(currentDateSelection: Long, initialTimeValue: Long) { val date = Calendar.getInstance() date.timeInMillis = currentDateSelection val dialogTime = inflateTimePickerDialog() ?: return val timePicker: TimePicker = dialogTime.findOrThrow<TimePicker>(R.id.timePickerCustomSnooze) timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(this)) state.state = ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker state.timeAMillis = currentDateSelection snoozeUntil_TimePicker = timePicker snoozeUntil_DatePicker = null if (initialTimeValue != 0L) { val cal = Calendar.getInstance() cal.timeInMillis = initialTimeValue timePicker.hourCompat = cal.get(Calendar.HOUR_OF_DAY) timePicker.minuteCompat = cal.get(Calendar.MINUTE) } val title = dialogTime.findOrThrow<TextView>(R.id.textViewSnoozeUntilDate) title.text = String.format( resources.getString(R.string.choose_time), DateUtils.formatDateTime(this, date.timeInMillis, DateUtils.FORMAT_SHOW_DATE)) val builder = AlertDialog.Builder(this) builder.setView(dialogTime) builder.setPositiveButton(R.string.snooze) { _: DialogInterface?, _: Int -> state.state = ViewEventActivityStateCode.Normal snoozeUntil_TimePicker = null timePicker.clearFocus() // grab time from timePicker + date picker date.set(Calendar.HOUR_OF_DAY, timePicker.hourCompat) date.set(Calendar.MINUTE, timePicker.minuteCompat) val snoozeFor = date.timeInMillis - System.currentTimeMillis() + Consts.ALARM_THRESHOLD if (snoozeFor > 0L) { snoozeEvent(snoozeFor) } else { // Selected time is in the past AlertDialog.Builder(this) .setTitle(R.string.selected_time_is_in_the_past) .setNegativeButton(R.string.cancel) { _: DialogInterface?, _: Int -> } .create() .show() } } builder.setNegativeButton(R.string.cancel) { _: DialogInterface?, _: Int -> state.state = ViewEventActivityStateCode.Normal snoozeUntil_TimePicker = null } builder.create().show() } fun reschedule(addTime: Long) { DevLog.info(LOG_TAG, "Moving event ${event.eventId} by ${addTime / 1000L} seconds, isRepeating = ${event.isRepeating}"); if (!event.isRepeating) { val moved = ApplicationController.moveEvent(this, event, addTime) if (moved) { // Show if (Settings(this).viewAfterEdit) { handler.postDelayed({ CalendarIntents.viewCalendarEvent(this, event) finish() }, 100) } else { SnoozeResult(SnoozeType.Moved, event.startTime, 0L).toast(this) // terminate ourselves finish(); } } else { DevLog.info(LOG_TAG, "snooze: Failed to move event ${event.eventId} by ${addTime / 1000L} seconds") } } else { val newEventId = ApplicationController.moveAsCopy(this, calendar, event, addTime) if (newEventId != -1L) { // Show if (Settings(this).viewAfterEdit) { handler.postDelayed({ CalendarIntents.viewCalendarEvent(this, newEventId) finish() }, 100) } else { SnoozeResult(SnoozeType.Moved, event.startTime, 0L).toast(this) // terminate ourselves finish(); } } else { DevLog.info(LOG_TAG, "snooze: Failed to move event ${event.eventId} by ${addTime / 1000L} seconds") } } } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonRescheduleClick(v: View?) { if (v == null) return when (v.id) { R.id.snooze_view_reschedule_present1 -> reschedule(Consts.HOUR_IN_SECONDS * 1000L) R.id.snooze_view_reschedule_present2 -> reschedule(Consts.DAY_IN_SECONDS * 1000L) R.id.snooze_view_reschedule_present3 -> reschedule(Consts.DAY_IN_SECONDS * 7L * 1000L) R.id.snooze_view_reschedule_present4 -> reschedule(Consts.DAY_IN_SECONDS * 28L * 1000L) } } @Suppress("unused", "UNUSED_PARAMETER") fun OnButtonRescheduleCustomClick(v: View?) { } companion object { private const val LOG_TAG = "ActivitySnooze" const val CUSTOM_SNOOZE_SNOOZE_FOR_IDX = 0 const val CUSTOM_SNOOZE_SNOOZE_UNTIL_IDX = 1 } }
gpl-3.0
83fad2a183f04be0efd458ea62de1d47
35.75
143
0.608353
4.724632
false
false
false
false
saru95/DSA
Kotlin/MergeSort.kt
1
1920
import java.util.* class MergeSort { private fun merge(a: IntArray, low: Int, high: Int) { val mid = (low + high) / 2 var i = low var j = mid + 1 val c = IntArray(high - low + 1) var k = 0 while (i <= mid && j <= high) { if (a[i] <= a[j]) { c[k] = a[i] i++ k++ } else { c[k] = a[j] j++ k++ } } while (i <= mid) { c[k] = a[i] k++ i++ } while (j <= high) { c[k] = a[j] k++ j++ } i = low while (i <= high) { a[i] = c[i - low] i++ } } fun mergesort(a: IntArray, low: Int, high: Int) { if (low >= high) return else { val mid = (low + high) / 2 mergesort(a, low, mid) mergesort(a, mid + 1, high) merge(a, low, high) } } fun print(a: IntArray, n: Int) { var i = 0 i = 0 while (i < n) { System.out.print(a[i].toString() + " ") i++ } } companion object { fun main(args: Array<String>) { val inputSize = Scanner(System.`in`) System.out.println("Enter number of elements:") val size = inputSize.nextInt() val inputElements = Scanner(System.`in`) val a = IntArray(size) for (i in 0 until size) { System.out.println("Enter the element " + (i + 1) + ":") a[i] = inputElements.nextInt() } inputSize.close() inputElements.close() val mergeSort = MergeSort() mergeSort.mergesort(a, 0, size - 1) mergeSort.print(a, size) } } }
mit
57a0d8354c69fb863334dcc6e67d1749
23.0125
72
0.375521
3.847695
false
false
false
false
signed/intellij-community
platform/projectModel-api/src/com/intellij/util/io/path.kt
1
6062
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime import java.util.* fun Path.exists() = Files.exists(this) fun Path.createDirectories(): Path = Files.createDirectories(this) /** * Opposite to Java, parent directories will be created */ fun Path.outputStream(): OutputStream { parent?.createDirectories() return Files.newOutputStream(this) } fun Path.inputStream(): InputStream = Files.newInputStream(this) fun Path.inputStreamIfExists(): InputStream? { try { return inputStream() } catch (e: NoSuchFileException) { return null } } /** * Opposite to Java, parent directories will be created */ fun Path.createSymbolicLink(target: Path): Path { parent?.createDirectories() Files.createSymbolicLink(this, target) return this } fun Path.delete() { val attributes = basicAttributesIfExists() ?: return try { if (attributes.isDirectory) { deleteRecursively() } else { Files.delete(this) } } catch (e: Exception) { FileUtil.delete(toFile()) } } fun Path.deleteWithParentsIfEmpty(root: Path, isFile: Boolean = true): Boolean { var parent = if (isFile) this.parent else null try { delete() } catch (e: NoSuchFileException) { return false } // remove empty directories while (parent != null && parent != root) { try { // must be only Files.delete, but not our delete (Files.delete throws DirectoryNotEmptyException) Files.delete(parent) } catch (e: IOException) { break } parent = parent.parent } return true } private fun Path.deleteRecursively() = Files.walkFileTree(this, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { try { Files.delete(file) } catch (e: Exception) { FileUtil.delete(file.toFile()) } return FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { try { Files.delete(dir) } catch (e: Exception) { FileUtil.delete(dir.toFile()) } return FileVisitResult.CONTINUE } }) fun Path.lastModified(): FileTime = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') val Path.parentSystemIndependentPath: String get() = parent!!.toString().replace(File.separatorChar, '/') fun Path.readBytes(): ByteArray = Files.readAllBytes(this) fun Path.readText(): String = readBytes().toString(Charsets.UTF_8) fun Path.readChars() = inputStream().reader().readCharSequence(size().toInt()) fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data) fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) fun Path.write(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { outputStream().use { it.write(data, offset, size) } return this } fun Path.writeSafe(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp") tempFile.write(data, offset, size) try { Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } catch (e: IOException) { LOG.warn(e) FileUtil.rename(tempFile.toFile(), this.toFile()) } return this } fun Path.writeSafe(outConsumer: (OutputStream) -> Unit): Path { val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp") tempFile.outputStream().use(outConsumer) try { Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } catch (e: IOException) { LOG.warn(e) FileUtil.rename(tempFile.toFile(), this.toFile()) } return this } fun Path.write(data: String): Path { parent?.createDirectories() Files.write(this, data.toByteArray()) return this } fun Path.size() = Files.size(this) fun Path.basicAttributesIfExists(): BasicFileAttributes? { try { return Files.readAttributes(this, BasicFileAttributes::class.java) } catch (ignored: NoSuchFileException) { return null } } fun Path.sizeOrNull() = basicAttributesIfExists()?.size() ?: -1 fun Path.isHidden() = Files.isHidden(this) fun Path.isDirectory() = Files.isDirectory(this) fun Path.isFile() = Files.isRegularFile(this) fun Path.move(target: Path): Path = Files.move(this, target, StandardCopyOption.REPLACE_EXISTING) /** * Opposite to Java, parent directories will be created */ fun Path.createFile() { parent?.createDirectories() Files.createFile(this) } inline fun <R> Path.directoryStreamIfExists(task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this).use(task) } catch (ignored: NoSuchFileException) { } return null } inline fun <R> Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this, filter).use(task) } catch (ignored: NoSuchFileException) { } return null } private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil")
apache-2.0
9213688353d5e8bd38053810cf788ef1
25.827434
137
0.710657
3.954338
false
false
false
false
esafirm/android-image-picker
imagepicker/src/test/java/com/esafirm/imagepicker/Should.kt
1
506
package com.esafirm.imagepicker import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo infix fun <T> T.shouldBe(value: Any?) = should(equalTo(value)) infix fun <T> T.shouldNot(value: Any?) = should(equalTo(value).not()) infix fun <T> T.shouldBe(matcher: Matcher<T>) = should(matcher) infix fun <T> T.shouldNot(matcher: Matcher<T>) = should(matcher.not()) private infix fun <T> T.should(matcher: Matcher<T>) = assertThat(this, matcher)
mit
dfea2172c64c70f991e6d2d573bb0986
41.25
79
0.756917
3.373333
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/client/xprops/view/renderer.kt
1
2758
package at.cpickl.gadsu.client.xprops.view import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.xprops.model.* import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.view.Fields import at.cpickl.gadsu.view.components.EditorRendererSwitchable import at.cpickl.gadsu.view.components.panels.FormPanel import com.google.common.eventbus.EventBus import java.awt.Component import java.awt.GridBagConstraints import java.util.* import javax.swing.ImageIcon class CPropsRenderer( private val fields: Fields<Client>, private val bus: EventBus ) { companion object { private val log = LOG(javaClass) } private val xpropToCPropView: HashMap<XProp, CPropView> = HashMap() val allSwitchables: List<EditorRendererSwitchable> get() = xpropToCPropView.values.toList() fun addXProp(xprop: XProp, form: FormPanel) { log.trace("addXProp(xprop={}, form", xprop) val ui = buildCPropUI(xprop) xpropToCPropView.put(xprop, ui) form.addFormInput(xprop.label, ui.toComponent(), ui.fillType, ui.icon) } fun updateFields(client: Client) { xpropToCPropView.forEach { _, ui -> ui.updateValue(client) } } fun readCProps(): CProps { val cprops = HashMap<XProp, CProp>() xpropToCPropView.forEach { xprop, ui -> val cprop = ui.toCProp() if (cprop.isValueOrNoteSet) { cprops.put(xprop, cprop) } } return CProps(cprops) } private fun buildCPropUI(xprop: XProp): CPropView { return xprop.onType(object: XPropTypeCallback<CPropView> { override fun onEnum(xprop: XPropEnum): CPropView { val iconResource = javaClass.getResource(xprop.resourcePath()) ?: throw GadsuException("Please create an icon for property '${xprop.label}' located at: ${xprop.resourcePath()}") val icon = ImageIcon(iconResource) val view = CPropEnumView(icon, xprop, bus) // got no view name yet, as no tests yet ;) fields.register(view) return view } }) } private fun XPropEnum.resourcePath() = "/gadsu/images/tcm_props/${this.key}.png" } interface CPropView : EditorRendererSwitchable { // keep it this way fun updateValue(value: Client) fun toComponent(): Component fun toCProp(): CProp val fillType: GridBagFill val icon: ImageIcon? } enum class GridBagFill(val swingId: Int) { None(GridBagConstraints.NONE), Horizontal(GridBagConstraints.HORIZONTAL), Vertical(GridBagConstraints.VERTICAL), Both(GridBagConstraints.BOTH) }
apache-2.0
29918cf70ff4f7824fffcccb32a9ba81
29.988764
138
0.658811
3.841226
false
false
false
false
christophpickl/gadsu
src/test/kotlin/at/cpickl/gadsu/view/labels_test.kt
1
4435
package at.cpickl.gadsu.view import at.cpickl.gadsu.global.GadsuSystemProperty import at.cpickl.gadsu.testinfra.Expects import at.cpickl.gadsu.view.language.Buttons import at.cpickl.gadsu.view.language.Labels import at.cpickl.gadsu.view.language.LabelsLanguageFinder import at.cpickl.gadsu.view.language.Language import at.cpickl.gadsu.view.language.LanguageException import at.cpickl.gadsu.view.language.Languages import at.cpickl.gadsu.view.language.Tabs import at.cpickl.gadsu.view.language.TestLabels import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.testng.Assert import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.BeforeMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test import java.util.Locale @Test class LanguageTest { private var oldLocale: Locale? = null private var oldOverrideLanguage: String? = null @BeforeClass fun storeOldState() { oldLocale = Locale.getDefault() oldOverrideLanguage = GadsuSystemProperty.overrideLanguage.getOrNull() } @BeforeMethod fun resetState() { GadsuSystemProperty.overrideLanguage.clear() defaultLocale(Locale.KOREAN) } @AfterClass fun cleanupAfterYourself() { if (oldOverrideLanguage == null) { GadsuSystemProperty.overrideLanguage.clear() } else { GadsuSystemProperty.overrideLanguage.set(oldOverrideLanguage!!) } defaultLocale(oldLocale!!) } @DataProvider(name = "defaultLocaleProvider") fun defaultLocaleProvider(): Array<Array<out Any>> = arrayOf( arrayOf(Locale.GERMAN, "DE"), // arrayOf(Locale.ENGLISH, "EN"), arrayOf(Locale.ITALIAN, "DE") // default to DE ) @Test(dataProvider = "defaultLocaleProvider") fun `change default locale`(locale: Locale, expected: String) { defaultLocale(locale) assertInitLang(expected) } fun `override language vis system property`() { overrideLang("DE") assertInitLang("DE") // overrideLang("EN") // assertInitLang("EN") Expects.expect( type = LanguageException::class, messageContains = "ABC", action = { overrideLang("ABC") initLang() }) } private fun assertInitLang(expected: String) { assertThat(initLang().id, equalTo(expected)) } private fun initLang() = Languages._initLanguage() private fun overrideLang(value: String) { GadsuSystemProperty.overrideLanguage.set(value) } private fun defaultLocale(locale: Locale) { Locale.setDefault(locale) } } @Test class LabelsTest { @DataProvider(name = "labelAndLang") fun labelAndLang(): Array<Array<Any>> = arrayOf( arrayOf(Buttons::class.java as Any, "DE" as Any, Labels.Buttons_DE as Any) // arrayOf(Buttons::class.java as Any, "EN" as Any, Labels.Buttons_EN as Any) // arrayOf(Tabs::class.java as Any, Language.DE as Any, Labels.Tabs_DE as Any), // arrayOf(Tabs::class.java as Any, Language.EN as Any, Labels.Tabs_EN as Any) ) @Test(dataProvider = "labelAndLang") fun `find LABEL for LANGUAGE`(requestType: Class<Any>, requestLanguage: String, expected: Any) { assertLabel(requestType, requestLanguage, expected) } fun `find for not existing language, defaults to DE`() { assertLabel(Tabs::class.java, "XXX", Labels.Tabs_DE) assertLabel(Buttons::class.java, "XXX", Labels.Buttons_DE) } fun `find for not existing label, throws exception`() { Expects.expect( type = LanguageException::class, action = { find(TestLabels::class.java, "DE") } ) } private fun assertLabel(requestType: Class<out Any>, requestLanguage: String, expected: Any) { val actual = find(requestType, requestLanguage) Assert.assertTrue(actual === expected, "Expected: $expected, Actual: $actual") } private fun find(requestType: Class<out Any>, requestLanguage: String): Any { val lang = Language.byId(requestLanguage) ?: throw AssertionError("Invalid language ID '${requestLanguage}'!") return LabelsLanguageFinder.findForLanguage(requestType, lang) } }
apache-2.0
105bc593a2a38062b82c0ddc8e5dd3a7
31.372263
118
0.670575
4.23187
false
true
false
false
peterholak/mogul
native/src/mogul/react/Component.kt
2
3031
package mogul.react import mogul.react.injection.ServiceContainer interface Updater { fun queueUpdate() } abstract class Component<out PropTypes> { private var hackyProps: PropTypes? = null private lateinit var hackyChildren: List<Element> protected lateinit var updater: Updater val props get() = hackyProps!! // This hack is here to hide the implementation details from users who implement components // - if only Kotlin had some construct to easily auto-inherit the default constructor... open internal fun createInstance(props: Any, children: List<Element>, updater: Updater) { @Suppress("UNCHECKED_CAST") hackyProps = props as PropTypes hackyChildren = children this.updater = updater } @Suppress("UNCHECKED_CAST") open internal fun updateProps(newProps: Any) { // TODO: this should only update the props that have changed (maybe to preserve some identity semantics?) hackyProps = newProps as PropTypes } fun forceUpdate() { updater.queueUpdate() } abstract fun render(): Element } abstract class ComponentDecorator<out PropTypes>(val inner: Component<PropTypes>) : Component<PropTypes>() { override fun createInstance(props: Any, children: List<Element>, updater: Updater) { super.createInstance(props, children, updater) inner.createInstance(props, children, updater) } override fun updateProps(newProps: Any) { super.updateProps(newProps) inner.updateProps(newProps) } override fun render(): Element = inner.render() } abstract class StatefulComponent<out PropTypes, StateType> : Component<PropTypes>() { val state: StateType get() = currentState ?: initialState abstract val initialState: StateType private var currentState: StateType? = null fun setState(newState: StateType) { currentState = newState updater.queueUpdate() } } typealias ComponentConstructor = (container: ServiceContainer) -> Component<*> //val stringType = ElementType("string") // This is because Kotlin Native currently doesn't support much reflection, otherwise Component::class could be used. class ElementType(val name: String, val constructComponent: ComponentConstructor? = null) { override fun toString(): String { return name + if (constructComponent != null) " (C)" else "" } fun isComponent() = constructComponent != null } data class Element( val type: ElementType, val props: Any, val children: List<Element> = emptyList() ) // Something like this should also be available for DOM-backed elements class InstantiatedElement( val type: ElementType, val props: Any, val children: List<InstantiatedElement>, val instance: Any, val change: Change? ) sealed class Change class Add : Change() class Modify(val oldProps: Any) : Change() // TODO: clean this up class Replace(val oldInstance: Any, val oldComponent: InstantiatedElement? = null) : Change()
mit
b91bce7b9fb2e495991fc91606a62481
29.928571
117
0.703398
4.557895
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/volume/preparation/volumemanagement/GivenAnUnsetMaxVolume/WhenSettingTheVolumeToOne.kt
2
1123
package com.lasthopesoftware.bluewater.client.playback.file.volume.preparation.volumemanagement.GivenAnUnsetMaxVolume import com.lasthopesoftware.bluewater.client.playback.file.NoTransformVolumeManager import com.lasthopesoftware.bluewater.client.playback.file.volume.preparation.MaxFileVolumeManager import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import org.assertj.core.api.Assertions import org.junit.BeforeClass import org.junit.Test class WhenSettingTheVolumeToOne { companion object { private var volumeManager: NoTransformVolumeManager? = null private var returnedVolume = 0f @JvmStatic @BeforeClass fun before() { volumeManager = NoTransformVolumeManager() val maxFileVolumeManager = MaxFileVolumeManager(volumeManager!!) returnedVolume = maxFileVolumeManager.setVolume(1f).toFuture().get()!! } } @Test fun thenThePlaybackHandlerVolumeIsSetToTheMaxVolume() { Assertions.assertThat(volumeManager!!.volume.toFuture().get()).isEqualTo(1F) } @Test fun thenTheReturnedVolumeIsSetToTheMaxVolume() { Assertions.assertThat(returnedVolume).isEqualTo(1f) } }
lgpl-3.0
df612bae5f587e8b455cadacb5e3c46c
32.029412
117
0.820125
3.996441
false
true
false
false
jitsi/jitsi-videobridge
jvb-api/jvb-api-common/src/main/kotlin/org/jitsi/videobridge/api/types/SupportedApiVersions.kt
2
2549
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.api.types /** * An enum representing an API versions. The value is a ordinal value to * denote the version in a monotonically-increasing order, such that versions * can be compared. */ enum class ApiVersion(val value: Int) { V1(1); override fun toString(): String = "v$value" companion object { private val valueMap = values().associateBy { "v${it.value}" } /** * Get an [ApiVersion] instance from a [String] formatted as: * v<API VERSION NUMBER> */ fun fromString(versionStr: String): ApiVersion? = valueMap.getOrDefault(versionStr, null) } } @Suppress("unused", "MemberVisibilityCanBePrivate") data class SupportedApiVersions(val supportedVersions: List<ApiVersion>) { constructor(vararg versions: ApiVersion) : this(versions.toList()) fun supports(apiVersion: ApiVersion): Boolean = supportedVersions.contains(apiVersion) /** * Return the maximum supported [ApiVersion] supported by both this * [SupportedApiVersions] instance and [other], or null if there is * no intersection. */ fun maxSupported(other: SupportedApiVersions): ApiVersion? = supportedVersions.sorted().find(other::supports) fun intersect(other: SupportedApiVersions): SupportedApiVersions = SupportedApiVersions(supportedVersions.intersect(other.supportedVersions).toList()) // So we can add extensions to it companion object } /** * Serialize to a [String] which can be placed in the JVB's presence */ fun SupportedApiVersions.toPresenceString(): String = supportedVersions.joinToString(separator = ",") /** * Deserialize from a presence [String] into a [SupportedApiVersions] instance. */ fun SupportedApiVersions.Companion.fromPresenceString(str: String): SupportedApiVersions = SupportedApiVersions(str.split(",").mapNotNull(ApiVersion.Companion::fromString))
apache-2.0
aad6752bddc53bb2fb17e8cacb1b1ef2
34.402778
91
0.713221
4.456294
false
false
false
false
alxnns1/MobHunter
src/main/kotlin/com/alxnns1/mobhunter/Extensions.kt
1
2516
package com.alxnns1.mobhunter import com.alxnns1.mobhunter.entity.MHEntity import net.minecraft.entity.MobEntity import net.minecraft.inventory.container.Container import net.minecraft.item.crafting.IRecipe import net.minecraft.item.crafting.IRecipeType import net.minecraft.item.crafting.RecipeManager import net.minecraft.util.IntReferenceHolder import net.minecraft.util.ResourceLocation import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty fun RecipeManager.getRecipes(type: IRecipeType<*>): Map<ResourceLocation, IRecipe<*>> = this.recipes.getOrElse(type, { emptyMap() }).toMap() fun <T> T.getMHScale(): Float where T : MHEntity, T : MobEntity = this.dataManager[this.getScaleKey()] fun Container.intReferenceHolder(): ReadWriteProperty<Container, Int> = IntReferenceHolderDelegate(this.trackInt(IntReferenceHolder.single())) fun Container.intArrayReferenceHolder(size: Int): ReadWriteProperty<Container, IntArray> = IntArrayReferenceHolderDelegate(Array(size) { this.trackInt(IntReferenceHolder.single()) }) fun Container.booleanArrayReferenceHolder(size: Int): ReadWriteProperty<Container, BooleanArray> = BooleanArrayReferenceHolderDelegate(Array(size) { this.trackInt(IntReferenceHolder.single()) }) class IntReferenceHolderDelegate(private val intReferenceHolder: IntReferenceHolder) : ReadWriteProperty<Container, Int> { override fun getValue(thisRef: Container, property: KProperty<*>): Int = intReferenceHolder.get() override fun setValue(thisRef: Container, property: KProperty<*>, value: Int) = intReferenceHolder.set(value) } class IntArrayReferenceHolderDelegate(private val intReferenceHolders: Array<out IntReferenceHolder>) : ReadWriteProperty<Container, IntArray> { override fun setValue(thisRef: Container, property: KProperty<*>, value: IntArray) = value.forEachIndexed { i, v -> intReferenceHolders[i].set(v) } override fun getValue(thisRef: Container, property: KProperty<*>): IntArray = IntArray(intReferenceHolders.size) { intReferenceHolders[it].get() } } class BooleanArrayReferenceHolderDelegate(private val intReferenceHolders: Array<out IntReferenceHolder>) : ReadWriteProperty<Container, BooleanArray> { override fun setValue(thisRef: Container, property: KProperty<*>, value: BooleanArray) = value.forEachIndexed { i, v -> intReferenceHolders[i].set(if (v) 1 else 0) } override fun getValue(thisRef: Container, property: KProperty<*>): BooleanArray = BooleanArray(intReferenceHolders.size) { intReferenceHolders[it].get() == 1 } }
gpl-2.0
7a1b7db72d84890069d8134d2402e443
52.531915
152
0.803259
4.151815
false
false
false
false
MichaelObi/PaperPlayer
app/src/main/java/xyz/michaelobi/paperplayer/presentation/player/playlist/PlaylistFragment.kt
1
4491
/* * MIT License * * Copyright (c) 2017 MIchael Obi * * 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 xyz.michaelobi.paperplayer.presentation.player.playlist import android.app.Dialog import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.appcompat.widget.Toolbar import android.view.View import android.widget.Toast import xyz.michaelobi.paperplayer.R import xyz.michaelobi.paperplayer.injection.Injector import xyz.michaelobi.paperplayer.playback.queue.QueueItem import xyz.michaelobi.paperplayer.playback.queue.QueueManager /** * PaperPlayer * Michael Obi * 22 05 2017 1:04 AM */ class PlaylistFragment : com.google.android.material.bottomsheet.BottomSheetDialogFragment(), PlaylistView { lateinit var playlistAdapter: PlaylistAdapter lateinit var rvPlaylist: androidx.recyclerview.widget.RecyclerView val queueManager: QueueManager = Injector.provideQueueManager() val presenter = PlaylistPresenter() override fun showList(items: MutableList<QueueItem>) { setUpPlaylist() playlistAdapter.setQueueItems(items) } override fun showLoading() {} override fun hideLoading() {} override fun showError(message: String) { Toast.makeText(activity, "An error occurred", Toast.LENGTH_SHORT).show() } override fun setupDialog(dialog: Dialog?, style: Int) { val view = View.inflate(activity, R.layout.bottomsheet_playlist, null) dialog?.setContentView(view) val toolbar = view.findViewById(R.id.toolbar) as Toolbar rvPlaylist = view.findViewById(R.id.rv_playlist) as androidx.recyclerview.widget.RecyclerView toolbar.setNavigationOnClickListener { dismiss() } toolbar.setTitle(R.string.playlist) val params = (view.parent as View).layoutParams as androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams val behavior = params.behavior (behavior as com.google.android.material.bottomsheet.BottomSheetBehavior<*>).state = com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED behavior.setBottomSheetCallback(object : com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { when (newState) { com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED, com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN -> { dismiss() } } } override fun onSlide(bottomSheet: View, slideOffset: Float) {} }) presenter.attachView(this) presenter.getAll() } private fun setUpPlaylist() { playlistAdapter = PlaylistAdapter() val currentPlayingIndex = queueManager.currentIndex val linearLayoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity) linearLayoutManager.scrollToPositionWithOffset(currentPlayingIndex, 20) with(rvPlaylist) { setHasFixedSize(true) layoutManager = linearLayoutManager adapter = playlistAdapter } } }
mit
4a3716133d41c39906a9d6231bfda61c
41.780952
174
0.738588
4.951488
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/Spinner.kt
1
1826
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.kotlin.widget import android.graphics.drawable.Drawable import androidx.annotation.ColorInt import androidx.annotation.LayoutRes import com.facebook.litho.Dimen import com.facebook.litho.ResourcesScope import com.facebook.litho.eventHandler import com.facebook.litho.sp import com.facebook.litho.widget.ItemSelectedEvent import com.facebook.litho.widget.Spinner /** Builder function for creating [SpinnerSpec] components. */ @Suppress("NOTHING_TO_INLINE", "FunctionName") inline fun ResourcesScope.Spinner( options: List<String>, selectedOption: String, @LayoutRes itemLayout: Int = android.R.layout.simple_dropdown_item_1line, selectedTextSize: Dimen = 16.sp, @ColorInt selectedTextColor: Int = 0xDE000000.toInt(), caret: Drawable? = null, noinline onItemSelected: (ItemSelectedEvent) -> Unit ): Spinner = Spinner.create(context) .options(options) .selectedOption(selectedOption) .itemLayout(itemLayout) .selectedTextColor(selectedTextColor) .selectedTextSizePx(selectedTextSize.toPixels().toFloat()) .caret(caret) .itemSelectedEventHandler(eventHandler(onItemSelected)) .build()
apache-2.0
b505458b253f4502b55225d81d4c870b
37.041667
77
0.748083
4.25641
false
false
false
false
google/horologist
sample/src/main/java/com/google/android/horologist/tile/SampleTileService.kt
1
1891
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.tile import androidx.wear.tiles.RequestBuilders.ResourcesRequest import androidx.wear.tiles.RequestBuilders.TileRequest import androidx.wear.tiles.ResourceBuilders.Resources import androidx.wear.tiles.TileBuilders.Tile import com.google.android.horologist.sample.R import com.google.android.horologist.tiles.SuspendingTileService import com.google.android.horologist.tiles.images.drawableResToImageResource class SampleTileService : SuspendingTileService() { private lateinit var renderer: SampleTileRenderer private var count = 0 override fun onCreate() { super.onCreate() renderer = SampleTileRenderer(this) } override suspend fun tileRequest(requestParams: TileRequest): Tile { if (requestParams.state?.lastClickableId == "click") { count++ } return renderer.renderTimeline(SampleTileRenderer.TileState(count), requestParams) } override suspend fun resourcesRequest(requestParams: ResourcesRequest): Resources { val imageResource = drawableResToImageResource(R.drawable.ic_uamp) return renderer.produceRequestedResources( SampleTileRenderer.ResourceState(imageResource), requestParams ) } }
apache-2.0
5872909f0105920fb7d6b3a45037c754
34.018519
90
0.748281
4.799492
false
false
false
false
xfournet/intellij-community
platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt
1
8181
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("ProjectUtil") package com.intellij.openapi.project import com.intellij.ide.DataManager import com.intellij.ide.highlighter.ProjectFileType import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.appSystemDir import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFilePathWrapper import com.intellij.openapi.wm.WindowManager import com.intellij.util.PathUtilRt import com.intellij.util.io.exists import com.intellij.util.io.sanitizeFileName import com.intellij.util.text.trimMiddle import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.function.Consumer import javax.swing.JComponent val Module.rootManager: ModuleRootManager get() = ModuleRootManager.getInstance(this) @JvmOverloads fun calcRelativeToProjectPath(file: VirtualFile, project: Project?, includeFilePath: Boolean = true, includeUniqueFilePath: Boolean = false, keepModuleAlwaysOnTheLeft: Boolean = false): String { if (file is VirtualFilePathWrapper && file.enforcePresentableName()) { return if (includeFilePath) file.presentablePath else file.name } val url = when { includeFilePath -> file.presentableUrl includeUniqueFilePath && project != null -> UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file) else -> file.name } return if (project == null) url else displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft) } fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file) /** * guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned */ @JvmOverloads fun guessProjectForContentFile(file: VirtualFile, fileType: FileType = FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence)): Project? { if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) { return null } val list = ProjectManager.getInstance().openProjects.filter { !it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file) } return list.firstOrNull { WindowManager.getInstance().getFrame(it)?.isActive ?: false } ?: list.firstOrNull() } fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean = ProjectCoreUtil.isProjectOrWorkspaceFile(file) fun guessCurrentProject(component: JComponent?): Project { var project: Project? = null if (component != null) { project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component)) } @Suppress("DEPRECATION") return project ?: ProjectManager.getInstance().openProjects.firstOrNull() ?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext) ?: ProjectManager.getInstance().defaultProject } inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T { val model = ModuleManager.getInstance(this).modifiableModel val result = model.task() runWriteAction { model.commit() } return result } fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean { return try { Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists() } catch (e: InvalidPathException) { false } } /** * Tries to guess the "main project directory" of the project. * * There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places, * and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project * directory"). This method should be preferred, although it can't provide perfect accuracy either. * * @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case. */ fun Project.guessProjectDir() : VirtualFile { if (isDefault) { throw IllegalStateException("Not applicable for default project") } val modules = ModuleManager.getInstance(this).modules val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name } module?.rootManager?.contentRoots?.firstOrNull()?.let { return it } return this.baseDir!! } fun Project.getProjectCacheFileName(forceNameUse: Boolean, hashSeparator: String): String { val presentableUrl = presentableUrl var name = if (forceNameUse || presentableUrl == null) { name } else { // lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests) PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } name = sanitizeFileName(name, isTruncate = false) // do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended). val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode()) // trim to avoid "File name too long" name = name.trimMiddle(Math.min(name.length, 255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false) return "$name$hashSeparator${locationHash}" } @JvmOverloads fun Project.getProjectCachePath(cacheName: String, forceNameUse: Boolean = false): Path { return getProjectCachePath(appSystemDir.resolve(cacheName), forceNameUse) } fun Project.getExternalConfigurationDir(): Path { return getProjectCachePath("external_build_system") } /** * Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed */ @JvmOverloads fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path { return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator)) } /** * Add one-time projectOpened listener. */ fun Project.runWhenProjectOpened(handler: Runnable) = runWhenProjectOpened(this) { handler.run() } /** * Add one-time first projectOpened listener. */ @JvmOverloads fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) = runWhenProjectOpened(project) { handler.accept(it) } /** * Add one-time projectOpened listener. */ inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) { val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(eventProject: Project) { if (project == null || project === eventProject) { connection.disconnect() handler(eventProject) } } }) }
apache-2.0
a13573ac43649d4b8602c39bcdeb844f
38.718447
160
0.755898
4.555122
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/ui/StartupDialogFragment.kt
1
5889
/* * Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.ui import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Dialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.PowerManager import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import com.etesync.syncadapter.BuildConfig import com.etesync.syncadapter.Constants import com.etesync.syncadapter.R import com.etesync.syncadapter.utils.HintManager import java.util.* class StartupDialogFragment : DialogFragment() { enum class Mode { BATTERY_OPTIMIZATIONS, DEVELOPMENT_VERSION, GOOGLE_PLAY_ACCOUNTS_REMOVED, VENDOR_SPECIFIC_BUGS } @TargetApi(Build.VERSION_CODES.M) @SuppressLint("BatteryLife") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { isCancelable = false val mode = Mode.valueOf(arguments!!.getString(ARGS_MODE)!!) when (mode) { StartupDialogFragment.Mode.BATTERY_OPTIMIZATIONS -> return AlertDialog.Builder(activity!!) .setTitle(R.string.startup_battery_optimization) .setMessage(R.string.startup_battery_optimization_message) .setPositiveButton(android.R.string.ok) { dialog, which -> } .setNeutralButton(R.string.startup_battery_optimization_disable) { dialog, which -> val intent = Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)) if (intent.resolveActivity(context!!.packageManager) != null) context!!.startActivity(intent) } .setNegativeButton(R.string.startup_dont_show_again) { dialog, which -> HintManager.setHintSeen(context!!, HINT_BATTERY_OPTIMIZATIONS, true) } .create() StartupDialogFragment.Mode.DEVELOPMENT_VERSION -> return AlertDialog.Builder(activity!!) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.startup_development_version) .setMessage(R.string.startup_development_version_message) .setPositiveButton(android.R.string.ok) { dialog, which -> } .setNeutralButton(R.string.startup_development_version_give_feedback) { dialog, which -> startActivity(Intent(Intent.ACTION_VIEW, Constants.feedbackUri)) } .create() StartupDialogFragment.Mode.VENDOR_SPECIFIC_BUGS -> return AlertDialog.Builder(activity!!) .setTitle(R.string.startup_vendor_specific_bugs) .setMessage(R.string.startup_vendor_specific_bugs_message) .setPositiveButton(android.R.string.ok) { dialog, which -> } .setNeutralButton(R.string.startup_vendor_specific_bugs_open_faq) { dialog, which -> WebViewActivity.openUrl(context!!, Constants.faqUri.buildUpon().encodedFragment("vendor-issues").build()) } .setNegativeButton(R.string.startup_dont_show_again) { dialog, which -> HintManager.setHintSeen(context!!, HINT_VENDOR_SPECIFIC_BUGS, true) } .create() } throw IllegalArgumentException(/* illegal mode argument */) } companion object { private val HINT_BATTERY_OPTIMIZATIONS = "BatteryOptimizations" private val HINT_VENDOR_SPECIFIC_BUGS = "VendorSpecificBugs" private val ARGS_MODE = "mode" fun getStartupDialogs(context: Context): Array<StartupDialogFragment> { val dialogs = LinkedList<StartupDialogFragment>() if (BuildConfig.VERSION_NAME.contains("-alpha") || BuildConfig.VERSION_NAME.contains("-beta") || BuildConfig.VERSION_NAME.contains("-rc")) dialogs.add(StartupDialogFragment.instantiate(Mode.DEVELOPMENT_VERSION)) // battery optimization whitelisting if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !HintManager.getHintSeen(context, HINT_BATTERY_OPTIMIZATIONS)) { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager? if (powerManager != null && !powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID)) dialogs.add(StartupDialogFragment.instantiate(Mode.BATTERY_OPTIMIZATIONS)) } // Vendor specific bugs val manu = Build.MANUFACTURER if (!HintManager.getHintSeen(context, HINT_BATTERY_OPTIMIZATIONS) && (manu.equals("Xiaomi", ignoreCase = true) || manu.equals("Huawei", ignoreCase = true)) && !Build.DISPLAY.contains("lineage")) { dialogs.add(StartupDialogFragment.instantiate(Mode.VENDOR_SPECIFIC_BUGS)) } Collections.reverse(dialogs) return dialogs.toTypedArray() } fun instantiate(mode: Mode): StartupDialogFragment { val frag = StartupDialogFragment() val args = Bundle(1) args.putString(ARGS_MODE, mode.name) frag.arguments = args return frag } private fun installedFrom(context: Context): String? { try { return context.packageManager.getInstallerPackageName(context.packageName) } catch (e: IllegalArgumentException) { return null } } } }
gpl-3.0
3365bf2bd23051db5fa46857366cbd09
46.853659
212
0.654604
4.762136
false
false
false
false
Shynixn/BlockBall
blockball-core/src/test/java/unittest/ArenaFileRepositoryTest.kt
1
7294
@file:Suppress("UNCHECKED_CAST") package unittest import com.github.shynixn.blockball.api.business.service.ConfigurationService import com.github.shynixn.blockball.api.business.service.LoggingService import com.github.shynixn.blockball.api.business.service.YamlSerializationService import com.github.shynixn.blockball.api.business.service.YamlService import com.github.shynixn.blockball.core.logic.business.service.LoggingUtilServiceImpl import com.github.shynixn.blockball.core.logic.business.service.YamlSerializationServiceImpl import com.github.shynixn.blockball.core.logic.persistence.entity.ArenaEntity import com.github.shynixn.blockball.core.logic.persistence.repository.ArenaFileRepository import org.apache.commons.io.FileUtils import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.Yaml import java.io.* import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.logging.Logger /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class ArenaFileRepositoryTest { /** * Given * multiple arena files * When * getall is called * Then * the arenas should be returned in correct order. */ @Test fun getAll_MultipleArenas_ShouldBeCorrectlyLoadable() { // Arrange val classUnderTest = createWithDependencies() // Act val arena1 = ArenaEntity() arena1.name = "10" classUnderTest.save(arena1) val arena2 = ArenaEntity() arena2.name = "1" classUnderTest.save(arena2) val arena3 = ArenaEntity() arena3.name = "2" classUnderTest.save(arena3) val arenas = classUnderTest.getAll() // Assert Assertions.assertEquals(3, arenas.size) Assertions.assertEquals("1", arenas[0].name) Assertions.assertEquals("2", arenas[1].name) Assertions.assertEquals("10", arenas[2].name) } /** * Given * a new arena * When * save is called * Then * an file with the correct amount of bytes should be created. */ @Test fun save_NewArenaEntity_ShouldBeCorrectlySaved() { // Arrange val arena = ArenaEntity() arena.name = "1" val classUnderTest = createWithDependencies() // Act classUnderTest.save(arena) val actualDataLength = FileUtils.readFileToString(File("build/repository-test/arena/arena_1.yml"), "UTF-8") // Assert Assertions.assertEquals(9542, actualDataLength.length) } /** * Given * an existing arena file * When * delete is called * Then * the file should be deleted. */ @Test fun delete_ExistingArenaFile_ShouldBeDeleted() { // Arrange val classUnderTest = createWithDependencies() val arena = ArenaEntity() arena.name = "1" classUnderTest.save(arena) // Act val fileExisted = File("build/repository-test/arena/arena_1.yml").exists() classUnderTest.delete(arena) val fileExistsNow = File("build/repository-test/arena/arena_1.yml").exists() // Assert Assertions.assertTrue(fileExisted) Assertions.assertFalse(fileExistsNow) } companion object { fun createWithDependencies( configurationService: ConfigurationService = MockedConfigurationService(), yamlSerializationService: YamlSerializationService = YamlSerializationServiceImpl(), loggingService: LoggingService = LoggingUtilServiceImpl(Logger.getAnonymousLogger()) ): ArenaFileRepository { return ArenaFileRepository(configurationService, yamlSerializationService, MockedYamlService(), loggingService) } } class MockedYamlService : YamlService { /** * Writes the given [content] to the given [path]. */ override fun write(path: Path, content: Map<String, Any?>) { val options = DumperOptions() options.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK options.isPrettyFlow = true val yaml = Yaml(options) OutputStreamWriter(FileOutputStream(path.toFile()), StandardCharsets.UTF_8).use { fw -> yaml.dump(content, fw) } } /** * Reads the content from the given [path]. */ override fun read(path: Path): Map<String, Any?> { return InputStreamReader(FileInputStream(path.toFile()), StandardCharsets.UTF_8).use { fr -> val yaml = Yaml() yaml.load(fr) as Map<String, Any?> } } } class MockedConfigurationService : ConfigurationService { /** * Opens an inputStream to the given resource name. */ override fun openResource(name: String): InputStream { throw IllegalArgumentException() } /** * Checks if the given [path] contains a value. */ override fun containsValue(path: String): Boolean { return true } /** * Reloads the config. */ override fun reload() { } private var path: Path = Paths.get("build/repository-test") init { if (Files.exists(path)) { FileUtils.deleteDirectory(path.toFile()) } Files.createDirectories(path) } /** * Gets the path to the folder where the application is allowed to store * save data. */ override val applicationDir: Path get() { return path } /** * Tries to load the config value from the given [path]. * Throws a [IllegalArgumentException] if the path could not be correctly * loaded. */ override fun <C> findValue(path: String): C { throw IllegalArgumentException() } } }
apache-2.0
465ada95595a55d3e68b62b85130766a
32.004525
123
0.642994
4.660703
false
true
false
false