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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/caching/FineGrainedEntityCache.kt | 1 | 10342 | // 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.base.util.caching
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.LowMemoryWatcher
import com.intellij.openapi.util.registry.Registry
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.WorkspaceEntity
import java.util.concurrent.ConcurrentHashMap
abstract class FineGrainedEntityCache<Key : Any, Value : Any>(protected val project: Project, cleanOnLowMemory: Boolean) : Disposable {
private val invalidationStamp = InvalidationStamp()
protected abstract val cache: MutableMap<Key, Value>
protected val logger = Logger.getInstance(javaClass)
init {
if (cleanOnLowMemory) {
@Suppress("LeakingThis")
LowMemoryWatcher.register(this::invalidate, this)
}
@Suppress("LeakingThis")
subscribe()
}
protected abstract fun <T> useCache(block: (MutableMap<Key, Value>) -> T): T
override fun dispose() {
invalidate()
}
abstract operator fun get(key: Key): Value
fun values(): Collection<Value> = useCache { it.values }
protected fun checkEntitiesIfRequired(cache: MutableMap<Key, Value>) {
if (isValidityChecksEnabled && invalidationStamp.isCheckRequired()) {
checkEntities(cache, CHECK_ALL)
}
}
protected fun checkKeyAndDisposeIllegalEntry(key: Key) {
if (isValidityChecksEnabled) {
try {
checkKeyValidity(key)
} catch (e: Throwable) {
useCache { cache ->
disposeIllegalEntry(cache, key)
}
logger.error(e)
}
}
}
protected open fun disposeIllegalEntry(cache: MutableMap<Key, Value>, key: Key) {
cache.remove(key)
}
protected fun putAll(map: Map<Key, Value>) {
if (isValidityChecksEnabled) {
for ((key, value) in map) {
checkKeyValidity(key)
checkValueValidity(value)
}
}
useCache { cache ->
for ((key, value) in map) {
cache.putIfAbsent(key, value)
}
}
}
protected fun invalidate() {
useCache { cache ->
doInvalidate(cache)
}
}
/**
* perform [cache] invalidation under the lock
*/
protected open fun doInvalidate(cache: MutableMap<Key, Value>) {
cache.clear()
}
protected fun invalidateKeysAndGetOutdatedValues(
keys: Collection<Key>,
validityCondition: ((Key, Value) -> Boolean)? = CHECK_ALL
): Collection<Value> = useCache { cache ->
doInvalidateKeysAndGetOutdatedValues(keys, cache).also {
invalidationStamp.incInvalidation()
checkEntities(cache, validityCondition)
}
}
protected open fun doInvalidateKeysAndGetOutdatedValues(keys: Collection<Key>, cache: MutableMap<Key, Value>): Collection<Value> {
return buildList {
for (key in keys) {
cache.remove(key)?.let(::add)
}
}
}
protected fun invalidateKeys(
keys: Collection<Key>,
validityCondition: ((Key, Value) -> Boolean)? = CHECK_ALL
) {
useCache { cache ->
for (key in keys) {
cache.remove(key)
}
invalidationStamp.incInvalidation()
checkEntities(cache, validityCondition)
}
}
/**
* @param condition is a condition to find entries those will be invalidated and removed from the cache
* @param validityCondition is a condition to find entries those have to be checked for their validity, see [checkKeyValidity] and [checkValueValidity]
*/
protected fun invalidateEntries(
condition: (Key, Value) -> Boolean,
validityCondition: ((Key, Value) -> Boolean)? = CHECK_ALL
) {
useCache { cache ->
val iterator = cache.entries.iterator()
while (iterator.hasNext()) {
val (key, value) = iterator.next()
if (condition(key, value)) {
iterator.remove()
}
}
invalidationStamp.incInvalidation()
checkEntities(cache, validityCondition)
}
}
private fun checkEntities(cache: MutableMap<Key, Value>, validityCondition: ((Key, Value) -> Boolean)?) {
if (isValidityChecksEnabled && validityCondition != null) {
var allEntriesChecked = true
val iterator = cache.entries.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (validityCondition(entry.key, entry.value)) {
try {
checkKeyConsistency(cache, entry.key)
checkValueValidity(entry.value)
} catch (e: Throwable) {
iterator.remove()
disposeEntry(cache, entry)
logger.error(e)
}
} else {
allEntriesChecked = false
}
}
additionalEntitiesCheck(cache)
if (allEntriesChecked) {
invalidationStamp.reset()
}
}
}
protected open fun additionalEntitiesCheck(cache: MutableMap<Key, Value>) = Unit
protected open fun disposeEntry(cache: MutableMap<Key, Value>, entry: MutableMap.MutableEntry<Key, Value>) = Unit
protected abstract fun subscribe()
protected abstract fun checkKeyValidity(key: Key)
protected open fun checkKeyConsistency(cache: MutableMap<Key, Value>, key: Key) = checkKeyValidity(key)
protected open fun checkValueValidity(value: Value) {}
/***
* In some cases it is not possible to validate all entries of the cache.
* That could result to the state when there are some invalid entries after a partial cache invalidation.
*
* InvalidationStamp is to address this problem:
* - currentCount is incremented any time when a partial cache invalidation happens
* - count is equal to number of partial cache invalidation WHEN all cache entries have been validated
*
* No checks are required when count is equal to currentCount.
*/
private class InvalidationStamp {
private var currentCount: Int = 0
private var count: Int = 0
fun isCheckRequired(): Boolean = currentCount > count
fun incInvalidation() {
currentCount++
}
fun reset() {
count = currentCount
}
}
companion object {
val CHECK_ALL: (Any, Any) -> Boolean = { _, _ -> true }
val isValidityChecksEnabled: Boolean by lazy {
Registry.`is`("kotlin.caches.fine.grained.entity.validation")
}
}
}
abstract class SynchronizedFineGrainedEntityCache<Key : Any, Value : Any>(project: Project, cleanOnLowMemory: Boolean = false) :
FineGrainedEntityCache<Key, Value>(project, cleanOnLowMemory) {
@Deprecated("Do not use directly", level = DeprecationLevel.ERROR)
override val cache: MutableMap<Key, Value> = HashMap()
private val lock = Any()
final override fun <T> useCache(block: (MutableMap<Key, Value>) -> T): T = synchronized(lock) {
@Suppress("DEPRECATION_ERROR")
cache.run(block)
}
override fun get(key: Key): Value {
checkKeyAndDisposeIllegalEntry(key)
useCache { cache ->
checkEntitiesIfRequired(cache)
cache[key]
}?.let { return it }
ProgressManager.checkCanceled()
val newValue = calculate(key)
if (isValidityChecksEnabled) {
checkValueValidity(newValue)
}
useCache { cache ->
cache.putIfAbsent(key, newValue)
}?.let { return it }
postProcessNewValue(key, newValue)
return newValue
}
/**
* it has to be a pure function w/o side effects as a value could be recalculated
*/
abstract fun calculate(key: Key): Value
/**
* side effect function on a newly calculated value
*/
open fun postProcessNewValue(key: Key, value: Value) {}
}
abstract class SynchronizedFineGrainedValueCache<Value : Any>(project: Project, cleanOnLowMemory: Boolean = false) :
SynchronizedFineGrainedEntityCache<Unit, Value>(project, cleanOnLowMemory) {
@Deprecated("Do not use directly", level = DeprecationLevel.ERROR)
override val cache: MutableMap<Unit, Value> = HashMap(1)
fun value(): Value = get(Unit)
abstract fun calculate(): Value
final override fun calculate(key: Unit): Value = calculate()
override fun checkKeyValidity(key: Unit) = Unit
}
abstract class LockFreeFineGrainedEntityCache<Key : Any, Value : Any>(project: Project, cleanOnLowMemory: Boolean) :
FineGrainedEntityCache<Key, Value>(project, cleanOnLowMemory) {
@Deprecated("Do not use directly", level = DeprecationLevel.ERROR)
override val cache: MutableMap<Key, Value> = ConcurrentHashMap()
final override fun <T> useCache(block: (MutableMap<Key, Value>) -> T): T {
@Suppress("DEPRECATION_ERROR")
return cache.run(block)
}
override fun get(key: Key): Value {
checkKeyAndDisposeIllegalEntry(key)
useCache { cache ->
checkEntitiesIfRequired(cache)
cache[key]
}?.let { return it }
ProgressManager.checkCanceled()
return useCache { cache ->
calculate(cache, key)
}
}
abstract fun calculate(cache: MutableMap<Key, Value>, key: Key): Value
}
fun <T : WorkspaceEntity> EntityChange<T>.oldEntity() = when (this) {
is EntityChange.Added -> null
is EntityChange.Removed -> entity
is EntityChange.Replaced -> oldEntity
}
fun <T : WorkspaceEntity> EntityChange<T>.newEntity() = when (this) {
is EntityChange.Added -> newEntity
is EntityChange.Removed -> null
is EntityChange.Replaced -> newEntity
} | apache-2.0 | 85ce9f1b0dcaf636ac6236e7b5f35856 | 31.731013 | 155 | 0.619513 | 4.750574 | false | false | false | false |
smmribeiro/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereContextFeaturesProvider.kt | 1 | 2884 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.internal.statistic.local.ActionsGlobalSummaryManager
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
internal class SearchEverywhereContextFeaturesProvider {
companion object {
private const val LOCAL_MAX_USAGE_COUNT_KEY = "maxUsage"
private const val LOCAL_MIN_USAGE_COUNT_KEY = "minUsage"
private const val LOCAL_MAX_USAGE_SE_COUNT_KEY = "maxUsageSE"
private const val LOCAL_MIN_USAGE_SE_COUNT_KEY = "minUsageSE"
private const val GLOBAL_MAX_USAGE_COUNT_KEY = "globalMaxUsage"
private const val GLOBAL_MIN_USAGE_COUNT_KEY = "globalMinUsage"
private const val OPEN_FILE_TYPES_KEY = "openFileTypes"
private const val NUMBER_OF_OPEN_EDITORS_KEY = "numberOfOpenEditors"
private const val IS_SINGLE_MODULE_PROJECT = "isSingleModuleProject"
}
fun getContextFeatures(project: Project?): Map<String, Any> {
val data = hashMapOf<String, Any>()
val localTotalStats = ApplicationManager.getApplication().getService(ActionsLocalSummary::class.java).getTotalStats()
val globalSummary = ApplicationManager.getApplication().getService(ActionsGlobalSummaryManager::class.java)
val globalTotalStats = globalSummary.totalSummary
val updatedGlobalTotalStats = globalSummary.updatedTotalSummary
val updatedGlobalStatsVersion = globalSummary.updatedStatisticsVersion
val versionPattern = "V$updatedGlobalStatsVersion"
data[LOCAL_MAX_USAGE_COUNT_KEY] = localTotalStats.maxUsageCount
data[LOCAL_MIN_USAGE_COUNT_KEY] = localTotalStats.minUsageCount
data[LOCAL_MAX_USAGE_SE_COUNT_KEY] = localTotalStats.maxUsageFromSearchEverywhere
data[LOCAL_MIN_USAGE_SE_COUNT_KEY] = localTotalStats.minUsageFromSearchEverywhere
data[GLOBAL_MAX_USAGE_COUNT_KEY] = globalTotalStats.maxUsageCount
data[GLOBAL_MIN_USAGE_COUNT_KEY] = globalTotalStats.minUsageCount
data[GLOBAL_MAX_USAGE_COUNT_KEY + versionPattern] = updatedGlobalTotalStats.maxUsageCount
data[GLOBAL_MIN_USAGE_COUNT_KEY + versionPattern] = updatedGlobalTotalStats.minUsageCount
project?.let {
if (project.isDisposed) {
return@let
}
val fem = FileEditorManager.getInstance(it)
data[OPEN_FILE_TYPES_KEY] = fem.openFiles.map { file -> file.fileType.name }.distinct()
data[NUMBER_OF_OPEN_EDITORS_KEY] = fem.allEditors.size
data[IS_SINGLE_MODULE_PROJECT] = ModuleManager.getInstance(it).modules.size == 1
}
return data
}
} | apache-2.0 | 5342457af06cb432e2fad1e7a79355c2 | 47.898305 | 158 | 0.774619 | 4.067701 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRFileEditorComponentFactory.kt | 1 | 9922 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.collaboration.async.CompletableFutureUtil.handleOnEdt
import com.intellij.collaboration.ui.SingleValueModel
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.update.UiNotifyConnector
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GHRepositoryPermissionLevel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.GHPRTimelineFileEditor
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHSubmittableTextFieldFactory
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHSubmittableTextFieldModel
import org.jetbrains.plugins.github.pullrequest.data.GHListLoader
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRCommentsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDetailsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider
import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.component.GHHandledErrorPanelModel
import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
internal class GHPRFileEditorComponentFactory(private val project: Project,
private val editor: GHPRTimelineFileEditor,
currentDetails: GHPullRequestShort) {
private val uiDisposable = Disposer.newDisposable().also {
Disposer.register(editor, it)
}
private val detailsModel = SingleValueModel(currentDetails)
private val errorModel = GHHandledErrorPanelModel(GithubBundle.message("pull.request.timeline.cannot.load"),
GHApiLoadingErrorHandler(project,
editor.securityService.account,
editor.timelineLoader::reset))
private val timelineModel = GHPRTimelineMergingModel()
private val reviewThreadsModelsProvider = GHPRReviewsThreadsModelsProviderImpl(editor.reviewData, uiDisposable)
init {
editor.detailsData.loadDetails(uiDisposable) {
it.handleOnEdt(uiDisposable) { pr, _ ->
if (pr != null) detailsModel.value = pr
}
}
editor.timelineLoader.addErrorChangeListener(uiDisposable) {
errorModel.error = editor.timelineLoader.error
}
errorModel.error = editor.timelineLoader.error
editor.timelineLoader.addDataListener(uiDisposable, object : GHListLoader.ListDataListener {
override fun onDataAdded(startIdx: Int) {
val loadedData = editor.timelineLoader.loadedData
timelineModel.add(loadedData.subList(startIdx, loadedData.size))
}
override fun onDataUpdated(idx: Int) {
val loadedData = editor.timelineLoader.loadedData
val item = loadedData[idx]
timelineModel.update(item)
}
override fun onDataRemoved(data: Any) {
if (data !is GHPRTimelineItem) return
timelineModel.remove(data)
}
override fun onAllDataRemoved() = timelineModel.removeAll()
})
timelineModel.add(editor.timelineLoader.loadedData)
}
fun create(): JComponent {
val mainPanel = Wrapper()
DataManager.registerDataProvider(mainPanel, DataProvider {
if (PlatformDataKeys.UI_DISPOSABLE.`is`(it)) uiDisposable else null
})
val header = GHPRTitleComponent.create(project, detailsModel, editor.detailsData)
val timeline = GHPRTimelineComponent(detailsModel,
timelineModel,
createItemComponentFactory(project, editor.detailsData, editor.commentsData, editor.reviewData,
reviewThreadsModelsProvider,
editor.avatarIconsProvider, editor.securityService.currentUser)).apply {
border = JBUI.Borders.empty(16, 0)
}
val errorPanel = GHHtmlErrorPanel.create(errorModel)
val timelineLoader = editor.timelineLoader
val loadingIcon = JLabel(AnimatedIcon.Default()).apply {
border = JBUI.Borders.empty(8, 0)
isVisible = timelineLoader.loading
}
timelineLoader.addLoadingStateChangeListener(uiDisposable) {
loadingIcon.isVisible = timelineLoader.loading
}
val timelinePanel = ScrollablePanel().apply {
isOpaque = false
border = JBUI.Borders.empty(24, 20)
val maxWidth = GHUIUtil.getPRTimelineWidth()
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill()
.flowY(),
AC().grow().gap("push"))
add(header, CC().growX().maxWidth("$maxWidth"))
add(timeline, CC().growX().minWidth(""))
val fullTimelineWidth = JBUIScale.scale(GHUIUtil.AVATAR_SIZE) + maxWidth
add(errorPanel, CC().hideMode(2).width("$fullTimelineWidth"))
add(loadingIcon, CC().hideMode(2).width("$fullTimelineWidth"))
if (editor.securityService.currentUserHasPermissionLevel(GHRepositoryPermissionLevel.READ)) {
val commentField = createCommentField(editor.commentsData,
editor.avatarIconsProvider,
editor.securityService.currentUser)
add(commentField, CC().growX().pushX().maxWidth("$fullTimelineWidth"))
}
}
val scrollPane = ScrollPaneFactory.createScrollPane(timelinePanel, true).apply {
isOpaque = false
viewport.isOpaque = false
verticalScrollBar.model.addChangeListener(object : ChangeListener {
private var firstScroll = true
override fun stateChanged(e: ChangeEvent) {
if (firstScroll && verticalScrollBar.value > 0) firstScroll = false
if (!firstScroll) {
if (timelineLoader.canLoadMore()) {
timelineLoader.loadMore()
}
}
}
})
}
UiNotifyConnector.doWhenFirstShown(scrollPane) {
timelineLoader.loadMore()
}
timelineLoader.addDataListener(uiDisposable, object : GHListLoader.ListDataListener {
override fun onAllDataRemoved() {
if (scrollPane.isShowing) timelineLoader.loadMore()
}
})
mainPanel.setContent(scrollPane)
val actionManager = ActionManager.getInstance()
actionManager.getAction("Github.PullRequest.Timeline.Update").registerCustomShortcutSet(scrollPane, uiDisposable)
val groupId = "Github.PullRequest.Timeline.Popup"
PopupHandler.installPopupMenu(scrollPane, groupId, groupId)
return mainPanel
}
private fun createCommentField(commentService: GHPRCommentsDataProvider,
avatarIconsProvider: GHAvatarIconsProvider,
currentUser: GHUser): JComponent {
val model = GHSubmittableTextFieldModel(project) {
commentService.addComment(EmptyProgressIndicator(), it)
}
return GHSubmittableTextFieldFactory(model).create(avatarIconsProvider, currentUser)
}
private fun createItemComponentFactory(project: Project,
detailsDataProvider: GHPRDetailsDataProvider,
commentsDataProvider: GHPRCommentsDataProvider,
reviewDataProvider: GHPRReviewDataProvider,
reviewThreadsModelsProvider: GHPRReviewsThreadsModelsProvider,
avatarIconsProvider: GHAvatarIconsProvider,
currentUser: GHUser)
: GHPRTimelineItemComponentFactory {
val selectInToolWindowHelper = GHPRSelectInToolWindowHelper(project, detailsModel.value)
val diffFactory = GHPRReviewThreadDiffComponentFactory(project, EditorFactory.getInstance())
val eventsFactory = GHPRTimelineEventComponentFactoryImpl(avatarIconsProvider)
return GHPRTimelineItemComponentFactory(project, detailsDataProvider, commentsDataProvider, reviewDataProvider,
avatarIconsProvider, reviewThreadsModelsProvider, diffFactory,
eventsFactory,
selectInToolWindowHelper, currentUser)
}
} | apache-2.0 | 2d8d12342594f310b4d9206fe8427dc8 | 45.153488 | 140 | 0.690486 | 5.317256 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/data/network/retrofit/callback/HttpErrorFunction.kt | 1 | 842 | package com.zwq65.unity.data.network.retrofit.callback
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.functions.Function
/**
* ================================================
* api返回数据异常统一处理方法类
* <p>
* Created by NIRVANA on 2018/02/05.
* Contact with <[email protected]>
* ================================================
*/
class HttpErrorFunction<T> : Function<Throwable, ObservableSource<T>> {
/**
* Applies this function to the given argument.
*
* @param throwable the function argument
* @return the function result
*/
override fun apply(throwable: Throwable): ObservableSource<T> {
//ExceptionEngine为处理异常的驱动器
return Observable.error(ExceptionHandler.handleException(throwable))
}
}
| apache-2.0 | bb48672aa04e2cf943c5b11a58733fa0 | 28.555556 | 76 | 0.62782 | 4.384615 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/server/ftp/FtpServer.kt | 1 | 21455 | package com.timepath.vfs.server.ftp
import com.timepath.vfs.MockFile
import com.timepath.vfs.SimpleVFile
import com.timepath.vfs.VFile
import com.timepath.vfs.provider.ProviderStub
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.logging.Level
import java.util.logging.Logger
import java.util.regex.Pattern
/**
* With reference to:
* http://cr.yp.to/ftp.html
* http://www.nsftools.com/tips/RawFTP.htm
* http://www.ipswitch.com/support/ws_ftp-server/guide/v5/a_ftpref3.html
* http://graham.main.nc.us/~bhammel/graham/ftp.html
* http://www.codeguru.com/csharp/csharp/cs_network/sockets/article.php/c7409/A-C-FTP-Server.htm
* Mounting requires CurlFtpFS
* $ mkdir mnt
* $ curlftpfs -o umask=0000,uid=1000,gid=1000,allow_other localhost:2121 mnt
* $ cd mnt
* $ ls -l
* $ cd ..
* $ fusermount -u mnt
* ncdu
* press 'a' for apparent size
*
* @author TimePath
*/
public class FtpServer
/**
* Creates a server on the specified address.
*
* @param port
* @param addr If null, listen on all available interfaces
* @throws java.io.IOException
*/
@throws(IOException::class) constructor
(private val port: Int = 2121, private var address: InetAddress? = null) : ProviderStub(), Runnable {
private val pool = Executors.newFixedThreadPool(10, object : ThreadFactory {
override fun newThread(r: Runnable): Thread {
val t = Executors.defaultThreadFactory().newThread(r)
t.setDaemon(false)
return t
}
})
private val nameComparator = object : Comparator<SimpleVFile> {
override fun compare(o1: SimpleVFile, o2: SimpleVFile): Int {
return o1.name compareTo o2.name
}
}
private var servsock: ServerSocket? = null
init {
bind()
}
throws(IOException::class)
private fun bind() {
if (address == null) {
address = InetAddress.getByName(null)
}
servsock = ServerSocket(port, 0, address)
}
override fun run() {
LOG.log(Level.INFO, "Listening on {0}:{1}", arrayOf<Any>(servsock!!.getInetAddress().getHostAddress(), servsock!!.getLocalPort()))
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
LOG.log(Level.INFO, "FTP server shutting down...")
}
})
while (true) {
// LOG.log(Level.INFO, "Waiting for client...");
try {
pool.submit(FTPConnection(servsock!!.accept()))
} catch (ex: IOException) {
LOG.log(Level.SEVERE, null, ex)
}
}
}
inner class FTPConnection (private val client: Socket) : Runnable {
private var data: Socket? = null
private var pasv: ServerSocket? = null
private var cwd = VFile.SEPARATOR
init {
LOG.log(Level.FINE, "{0} connected.", client)
}
override fun run() {
try {
val h = servsock!!.getInetAddress().getAddress()
val br = BufferedReader(InputStreamReader(client.getInputStream()))
val pw = PrintWriter(client.getOutputStream(), true)
out(pw, "220 Welcome")
var skip: Long = 0
while (!client.isClosed()) {
try {
val cmd = `in`(br)
if (cmd == null) {
break
} else if (cmd.toUpperCase().startsWith("GET")) {
out(pw, "This is an FTP server.")
break
}
if (cmd.toUpperCase().startsWith("USER")) {
out(pw, "331 Please specify the password.")
} else if (cmd.toUpperCase().startsWith("PASS")) {
out(pw, "230 Login successful.")
} else if (cmd.toUpperCase().startsWith("SYST")) {
out(pw, "215 UNIX Type: L8")
} else if (cmd.toUpperCase().startsWith("PWD")) {
val dirKnowable = true
if (dirKnowable) {
out(pw, "257 \"$cwd")
} else {
out(pw, "550 Error")
}
} else if (cmd.toUpperCase().startsWith("TYPE")) {
val c = cmd.charAt(5)
if (c == 'I') {
out(pw, "200 Switching to Binary mode.")
} else if (c == 'A') {
out(pw, "200 Switching to ASCII mode.")
}
} else if (cmd.toUpperCase().startsWith("PORT")) {
val args = cmd.substring(5).splitBy(",")
val sep = "."
val dataAddress = "${args[0]}$sep${args[1]}$sep${args[2]}$sep${args[3]}"
val dataPort = (Integer.parseInt(args[4]) * 256) + Integer.parseInt(args[5])
data = Socket(InetAddress.getByName(dataAddress), dataPort)
LOG.log(Level.INFO, "*** Data receiver: {0}", data)
out(pw, "200 PORT command successful.")
} else if (cmd.toUpperCase().startsWith("EPRT")) {
val payload = cmd.substring(5)
// String delimeter = "\\x" + Integer.toHexString((int)
// payload.charAt(0));
val delimeter = Pattern.quote(payload.charAt(0).toString())
val args = payload.substring(1).splitBy(delimeter)
val type = Integer.parseInt(args[0])
val dataAddress = args[1]
val dataPort = Integer.parseInt(args[2])
data = Socket(InetAddress.getByName(dataAddress), dataPort)
LOG.log(Level.INFO, "*** Data receiver: {0}", data)
out(pw, "200 PORT command successful.")
} else if (cmd.toUpperCase().startsWith("PASV")) {
pasv?.let {
it.close()
}
pasv = ServerSocket(0)
val p = intArrayOf(pasv!!.getLocalPort() / 256, pasv!!.getLocalPort() % 256)
val con = java.lang.String.format("%s,%s,%s,%s,%s,%s", h[0].toInt() and 255, h[1].toInt() and 255, h[2].toInt() and 255, h[3].toInt() and 255, p[0] and 255, p[1] and 255)
out(pw, "227 Entering Passive Mode ($con).")
} else if (cmd.toUpperCase().startsWith("EPSV")) {
pasv?.let {
it.close()
}
pasv = ServerSocket(0)
val p = pasv!!.getLocalPort()
out(pw, "229 Entering Extended Passive Mode (|||$p|).")
} else if (cmd.toUpperCase().startsWith("SIZE")) {
val req = cmd.substring(5)
val ch: String
ch = if (req.startsWith(VFile.SEPARATOR)) req else canonicalize("$cwd${VFile.SEPARATOR}$req")
val f = query(ch)
if ((f == null) || f.isDirectory) {
out(pw, "550 Could not get file size.")
} else {
out(pw, "213 ${f.length}")
}
} else if (cmd.toUpperCase().startsWith("MODE")) {
val modes = arrayOf("S", "B", "C")
val mode = cmd.substring(5)
val has = mode in modes
if (has) {
out(pw, "200 Mode set to $mode.")
} else {
out(pw, "504 Bad MODE command.")
}
} else if (cmd.toUpperCase().startsWith("CWD") || cmd.toUpperCase().startsWith("CDUP")) {
LOG.log(Level.FINE, "Changing from: {0}", cwd)
val ch: String
if (cmd.toUpperCase().startsWith("CDUP")) {
ch = canonicalize("$cwd/src/main")
} else {
var dir = canonicalize(cmd.substring(4))
if (!dir.endsWith(VFile.SEPARATOR)) {
dir += VFile.SEPARATOR
}
ch = if (dir.startsWith(VFile.SEPARATOR)) dir else canonicalize("$cwd${VFile.SEPARATOR}$dir")
}
val f = query(ch)
if ((f != null) && f.isDirectory) {
out(pw, "250 Directory successfully changed.")
cwd = ch
} else {
out(pw, "550 Failed to change directory.")
}
} else if (cmd.toUpperCase().startsWith("LIST")) {
out(pw, "150 Here comes the directory listing.")
pasv?.let {
data = it.accept()
}
val out = PrintWriter(data!!.getOutputStream(), true)
val v = query(cwd)
val files = LinkedList(v!!.list())
Collections.sort(files, nameComparator)
val executor = Executors.newCachedThreadPool()
val lines = arrayOfNulls<String>(files.size()).mapIndexed { i, s ->
executor.submit(object : Callable<String> {
override fun call() = toFTPString(files[i])
})
}.forEach {
out(out, it.get())
}
out.close()
out(pw, "226 Directory send OK.")
} else if (cmd.toUpperCase().startsWith("QUIT")) {
out(pw, "221 Goodbye")
break
} else if (cmd.toUpperCase().startsWith("MDTM")) {
val req = cmd.substring(5)
val ch: String
ch = if (req.startsWith(VFile.SEPARATOR)) req else canonicalize("$cwd${VFile.SEPARATOR}$req")
val f = query(ch)
val cal = Calendar.getInstance()
cal.setTimeInMillis(f!!.lastModified)
out(pw, "200 ${mdtm.format(cal.getTime())}")
} else if (cmd.toUpperCase().startsWith("REST")) {
skip = java.lang.Long.parseLong(cmd.substring(5))
out(pw, "350 Skipped $skip bytes")
} else if (cmd.toUpperCase().startsWith("RETR")) {
val toSkip = skip
skip = 0
val req = cmd.substring(5)
val ch: String
ch = if (req.startsWith(VFile.SEPARATOR)) req else canonicalize("$cwd${VFile.SEPARATOR}$req")
val f = query(ch)
if ((f != null) && !f.isDirectory) {
out(pw, "150 Opening BINARY mode data connection for file")
pasv?.let {
data = it.accept()
}
try {
val stream = f.openStream()!!
stream.skip(toSkip)
val os = data!!.getOutputStream()
// anonymous clients seem to request this much and then quit
val buf = ByteArray(131072)
val read: Int
while (true) {
read = stream.read(buf)
if (read < 0) break
os.write(buf, 0, read)
os.flush()
}
stream.close()
os.close()
} catch (se: SocketException) {
if (!("Connection reset" == se.getMessage() || "Broken pipe" == se.getMessage())) {
LOG.log(Level.SEVERE, "Error serving $ch", se)
}
break
}
out(pw, "226 File sent")
} else {
out(pw, "550 Failed to open file.")
}
} else if (cmd.toUpperCase().startsWith("DELE")) {
out(pw, "550 Permission denied.")
} else if (cmd.toUpperCase().startsWith("FEAT")) {
out(pw, "211-Features:")
val features = arrayOf("MDTM", "PASV")
Arrays.sort(features)
for (feature in features) {
out(pw, ' ' + feature)
}
out(pw, "211 end")
} else if (cmd.toUpperCase().startsWith("HELP")) {
out(pw, "214-Commands supported:")
out(pw, "MDTM PASV")
out(pw, "214 End")
} else if (cmd.toUpperCase().startsWith("SITE")) {
out(pw, "200 Nothing to see here")
} else if (cmd.toUpperCase().startsWith("RNFR")) {
// Rename file
val from = cmd.substring(5)
out(pw, "350 Okay")
val to = `in`(br)!!.substring(5)
out(pw, "250 Renamed")
} else if (cmd.toUpperCase().startsWith("MKD")) {
val folder = cmd.substring(4)
val f = query(folder)
if ((f != null) && f.isDirectory) {
out(pw, "550 Failed to create directory. (it exists)")
} else {
out(pw, "200 created directory.")
}
files.put(folder, MockFile(folder, null))
} else if (cmd.toUpperCase().startsWith("STOR")) {
// Upload file
val file = cmd.substring(5)
out(pw, "150 Entering Transfer Mode")
pasv?.let {
data = it.accept()
}
val `in` = BufferedReader(InputStreamReader(data!!.getInputStream()))
val out = PrintWriter(data!!.getOutputStream(), true)
var text = ""
`in`.forEachLine { line ->
LOG.log(Level.FINE, "=== {0}", line)
if (text.isEmpty()) {
text = line
} else {
text += "\r\n$line"
}
}
data!!.close()
val f = MockFile(file, text)
files.put(file, f)
fileModified(f)
LOG.log(Level.INFO, "***\r\n{0}", text)
out(pw, "226 File uploaded successfully")
} else if (cmd.toUpperCase().startsWith("NOOP")) {
out(pw, "200 NOOP ok.")
} else if (cmd.toUpperCase().startsWith("OPTS")) {
val args = cmd.toUpperCase().substring(5).splitBy(" ")
val opt = args[0]
val status = args[1]
out(pw, "200 $opt always $status.")
} else {
LOG.log(Level.WARNING, "Unsupported operation {0}", cmd)
out(pw, "502 ${cmd.splitBy(" ")[0]} not implemented.")
// out(pw, "500 Unknown command.");
}
} catch (ex: Exception) {
LOG.log(Level.SEVERE, null, ex)
break
}
}
client.close()
LOG.log(Level.FINE, "{0} closed.", client)
} catch (ex: IOException) {
Logger.getLogger(javaClass<FtpServer>().getName()).log(Level.SEVERE, null, ex)
}
}
private fun canonicalize(string: String): String {
@suppress("NAME_SHADOWING")
val string = when {
string.endsWith(VFile.SEPARATOR) -> string.substring(0, string.length() - 1)
else -> string
}
val split = string.splitBy(VFile.SEPARATOR)
val pieces = LinkedList<String>()
for (s in split) {
if (s.isEmpty()) {
} else if (".." == s) {
if (pieces.size() > 2) {
pieces.remove(pieces.size() - 1)
}
} else {
pieces.add(s)
}
}
val sb = StringBuilder()
for (s in pieces) {
sb.append(VFile.SEPARATOR).append(s)
}
val ret = sb.toString()
LOG.log(Level.FINE, ret)
return ret
}
}
companion object {
internal val LOG = Logger.getLogger(javaClass<FtpServer>().getName())
internal val mdtm = SimpleDateFormat("yyyyMMddhhmmss")
internal fun toFTPString(file: SimpleVFile): String {
var spec = '-' // TODO: links
val f = arrayOf(charArrayOf('r', '-', '-'), charArrayOf('r', '-', '-'), charArrayOf('r', '-', '-')) // RWX: User, Group, Everybody
if (file.isDirectory) {
spec = 'd'
f[0][1] = 'w'
f[0][2] = 'x'
}
val fileSize = file.length
val perms = "${spec.toString()}${f[0][0]}${f[0][1]}${f[0][2]}${f[1][0]}${f[1][1]}${f[1][2]}${f[2][0]}${f[2][1]}${f[2][2]}"
val sb = StringBuilder()
sb.append(perms)
sb.append(' ')
sb.append(java.lang.String.format("%4s", fileSize)) // >= 4 left
sb.append(' ')
sb.append(java.lang.String.format("%-8s", file.owner)) // >= 8 right
sb.append(' ')
sb.append(java.lang.String.format("%-8s", file.group)) // >= 8 right
sb.append(' ')
sb.append(java.lang.String.format("%8s", fileSize)) // >= 8 left
sb.append(' ')
val cal = Calendar.getInstance()
val y1 = cal[Calendar.YEAR]
cal.setTimeInMillis(file.lastModified)
val y2 = cal[Calendar.YEAR]
val sameYear = "MMM d HH:mm"
val diffYear = "MMM d yyyy"
val df = SimpleDateFormat(if ((y1 == y2)) sameYear else diffYear)
sb.append(df.format(cal.getTime()))
sb.append(' ')
sb.append(file.name)
return sb.toString()
}
throws(IOException::class)
internal fun `in`(`in`: BufferedReader): String? {
val s = `in`.readLine()
LOG.log(Level.FINE, "<<< {0}", s)
return s
}
internal fun out(out: PrintWriter, cmd: String) {
out.print("$cmd\r\n")
out.flush()
LOG.log(Level.FINE, ">>> {0}", cmd)
}
}
}
| artistic-2.0 | c2f79676c59980f26a45355b9da5b705 | 47.105381 | 198 | 0.411466 | 5.091362 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/command/ServiceCommand.kt | 1 | 2710 | package org.maxur.mserv.frame.command
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import org.maxur.mserv.core.command.Command
import org.maxur.mserv.frame.MicroService
import org.maxur.mserv.frame.service.MicroServiceBuilder
import javax.inject.Inject
import javax.validation.constraints.NotBlank
import javax.validation.constraints.Pattern
/** The service command */
@ApiModel(
value = "ServiceCommand",
description = "This class represents the service command"
)
@JsonDeserialize(using = ServiceCommandDeserializer::class)
abstract class ServiceCommand protected constructor(
/** The command type */
@ApiModelProperty(
dataType = "string",
name = "type",
value = "type of the command",
notes = "Type of the command",
required = true,
allowableValues = "stop, restart",
example = "restart"
)
@NotBlank
@Pattern(regexp = "^(stop|restart)$")
val type: String) : Command() {
companion object {
internal fun stop() = Stop()
internal fun restart() = Restart()
}
/** Stop Microservice Command */
class Stop : ServiceCommand {
/** The microservice */
@Inject
protected lateinit var service: MicroService
internal constructor() : super("stop")
constructor(service: MicroService) : this() {
this.service = service
}
/** {@inheritDoc} */
override fun run() {
post(service.stop())
}
}
/** Restart Microservice Command */
class Restart : ServiceCommand {
/** The microservice runner */
@Inject
private lateinit var builder: MicroServiceBuilder
/** The microservice */
@Inject
protected lateinit var service: MicroService
internal constructor() : super("restart")
constructor(service: MicroService, runner: MicroServiceBuilder) : this() {
this.service = service
this.builder = runner
}
/** {@inheritDoc} */
override fun run() {
post(service.stop())
post(builder.build().start())
}
}
/** Restart Microservice Command */
class Start : ServiceCommand {
/** The microservice runner */
@Inject
private lateinit var service: MicroService
internal constructor() : super("start")
constructor(service: MicroService) : this() {
this.service = service
}
/** {@inheritDoc} */
override fun run() {
post(service.start())
}
}
} | apache-2.0 | c2a337c21c224f422bd1e51940bc8c85 | 25.841584 | 82 | 0.614391 | 4.856631 | false | false | false | false |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/bookmarklist/BookmarkListFragment.kt | 1 | 2557 | package me.kirimin.mitsumine.bookmarklist
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.kirimin.mitsumine.R
import me.kirimin.mitsumine._common.domain.model.Bookmark
import me.kirimin.mitsumine.search.AbstractSearchActivity
import me.kirimin.mitsumine.feed.user.UserSearchActivity
import kotlinx.android.synthetic.main.fragment_bookmark_list.view.*
import me.kirimin.mitsumine.MyApplication
import me.kirimin.mitsumine._common.ui.BaseFragment
class BookmarkListFragment : BaseFragment(), BookmarkListView {
val presenter = BookmarkListPresenter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater.inflate(R.layout.fragment_bookmark_list, container, false)
return rootView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
presenter.view = this
presenter.onCreate(arguments!!.getSerializable("bookmarkList") as ArrayList<Bookmark>)
}
override fun initViews(bookmarks: List<Bookmark>) {
val view = view ?: return
val adapter = BookmarkListAdapter(context!!, presenter, arguments!!.getString("entryId"))
adapter.addAll(bookmarks)
view.listView.adapter = adapter
}
override fun startUserSearchActivity(userId: String) {
val intent = Intent(activity, UserSearchActivity::class.java)
intent.putExtras(AbstractSearchActivity.buildBundle(userId))
startActivity(intent)
}
override fun shareCommentLink(text: String) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(intent)
}
override fun showBrowser(url: String) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
override fun injection() {
(activity!!.application as MyApplication).getApplicationComponent().inject(this)
}
companion object {
fun newFragment(bookmarkList: List<Bookmark>, entryId: String): BookmarkListFragment {
val fragment = BookmarkListFragment()
val bundle = Bundle()
bundle.putSerializable("bookmarkList", ArrayList(bookmarkList))
bundle.putString("entryId", entryId)
fragment.arguments = bundle
return fragment
}
}
}
| apache-2.0 | 6e5248c330bb463f7971eccfbd2fa939 | 34.513889 | 115 | 0.717247 | 4.879771 | false | false | false | false |
intrigus/jtransc | jtransc-core/src/com/jtransc/ast/ast_ref.kt | 1 | 3948 | package com.jtransc.ast
import com.jtransc.error.invalidOp
import com.jtransc.error.noImpl
import kotlin.reflect.KProperty1
interface AstRef
interface AstMemberRef : AstRef {
val classRef: AstType.REF
val containingClass: FqName
val name: String
val memberType: AstType
}
fun AstMemberRef.getClass(program: AstProgram) = program[classRef]!!
fun AstMethodRef.getMethod(program: AstProgram) = program[this]
fun AstFieldRef.getField(program: AstProgram) = program[this]
inline fun <reified T1 : Any, reified T2 : Any> KProperty1<T1, T2>.ast(): AstFieldRef {
return AstFieldRef(T1::class.java.name.fqname, this.name, T2::class.java.ast())
}
inline fun <reified T: Any> Class<T>.ast(): AstType {
if (this.isPrimitive) {
noImpl("Not implemented " + T::class.java)
} else {
return AstType.REF(this.name.fqname)
}
}
object AstProgramRef : AstRef {
}
data class AstFieldRef(override val containingClass: FqName, override val name: String, val type: AstType) : AstMemberRef, FieldRef {
override val ref = this
override val classRef: AstType.REF by lazy { AstType.REF(containingClass) }
override val memberType: AstType = type
val containingTypeRef = AstType.REF(containingClass)
override fun hashCode() = containingClass.hashCode() + name.hashCode() + type.hashCode()
override fun toString() = "AstFieldRef(${containingClass.fqname},$name,${type.mangle()})"
//fun resolve(program: AstProgram): AstField = program[containingClass][this]
fun resolve(program: AstProgram): AstField = program[this]
}
data class AstMethodRef(override val containingClass: FqName, override val name: String, val type: AstType.METHOD) : AstMemberRef, MethodRef {
override val ref = this
override val classRef: AstType.REF by lazy { AstType.REF(containingClass) }
val withoutClass: AstMethodWithoutClassRef by lazy { AstMethodWithoutClassRef(this.name, this.type) }
val containingClassType: AstType.REF by lazy { AstType.REF(containingClass) }
override val memberType: AstType = type
val fid: String get() = "${containingClass.fqname}:$name:$desc"
val fidWildcard: String get() = "${containingClass.fqname}:$name:*"
val desc by lazy { type.desc }
val descWithoutRetval by lazy { type.desc2 }
val nameDesc by lazy { AstMethodWithoutClassRef(name, type) }
val nameDescStr by lazy { "$name$desc" }
val nameWithClass by lazy { "${containingClass.fqname}.${name}" }
val allClassRefs: List<AstType.REF> by lazy { type.getRefClasses() + classRef }
//fun resolve(program: AstProgram): AstMethod = program[containingClass].getMethodInAncestorsAndInterfaces(this.withoutClass) ?: invalidOp("Can't resolve method $this")
fun resolve(program: AstProgram): AstMethod = program[this]!!
override fun hashCode() = containingClass.hashCode() + name.hashCode() + type.hashCode()
override fun toString() = "AstMethodRef(${containingClass.fqname},$name,${type.desc})"
}
data class AstFieldWithoutClassRef(val name: String, val type: AstType)
data class AstFieldWithoutTypeRef(val containingClass: FqName, val name: String)
data class AstMethodWithoutClassRef(val name: String, val type: AstType.METHOD) {
val fid2: String get() = "$name:${type.mangle()}"
val fid2Wildcard: String get() = "$name:*"
val desc = type.desc
val descWithoutRetval = type.desc2
override fun toString() = "AstMethodWithoutClassRef($name,${type.desc})"
}
val AstMethodRef.methodDesc: AstMethodWithoutClassRef get() = AstMethodWithoutClassRef(this.name, this.type)
val AstMethodRef.withoutRetval: AstMethodRef get() {
return if (this.type.ret is AstType.UNKNOWN) this else AstMethodRef(containingClass, name, type.withoutRetval)
}
val AstFieldRef.withoutClass: AstFieldWithoutClassRef get() = AstFieldWithoutClassRef(this.name, this.type)
fun AstMethodRef.withClass(other: AstType.REF) = AstMethodRef(other.name, this.name, this.type)
fun AstMethodWithoutClassRef.withClass(containingClass: FqName): AstMethodRef = AstMethodRef(containingClass, this.name, this.type)
| apache-2.0 | 79b53887ca89475f9b02b539f0681684 | 42.866667 | 169 | 0.764944 | 3.628676 | false | false | false | false |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/models/parsers/BibleContentHandler.kt | 1 | 2526 | package com.claraboia.bibleandroid.models.parsers
import com.claraboia.bibleandroid.models.Bible
import com.claraboia.bibleandroid.models.Book
import com.claraboia.bibleandroid.models.Chapter
import com.claraboia.bibleandroid.models.Verse
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler
/**
* Created by lucas.batagliao on 12/07/2016.
*/
class BibleContentHandler : DefaultHandler() {
val Bible : Bible = Bible()
private var tempVal: String = ""
private var elementOn: Boolean = false
private var currentBook: Book? = null
private var currentChapter: Chapter? = null
private var currentVerse: Verse? = null
override fun startElement(uri: String?, localName: String?, qName: String?, atts: Attributes?) {
var tempVal = ""
if(localName.equals("bible", true)){
}
if (localName.equals("title", true)) {
elementOn = true
}
if (localName.equals("b", true)) { //book
currentBook = Book()
val order = Integer.parseInt(atts!!.getValue("o")) //order
currentBook!!.bookOrder = order
}
if (localName.equals("c", true)) { //chapter
currentChapter = Chapter()
val number = Integer.parseInt(atts!!.getValue("n")) //number
currentChapter!!.chapterOrder = number
}
if (localName.equals("v", true)) { //verse
elementOn = true
currentVerse = Verse()
val number = Integer.parseInt(atts!!.getValue("n")) //number
currentVerse!!.verseOrder = number
}
}
override fun characters(ch: CharArray?, start: Int, length: Int) {
if (elementOn) {
tempVal = String(ch as CharArray, start, length)
elementOn = false
}
}
override fun endElement(uri: String?, localName: String?, qName: String?) {
elementOn = false
if (localName.equals("title", true)) {
this.Bible.title = tempVal
}
if (localName.equals("b", true)) { //book
this.Bible.books.add(currentBook!!)
currentBook = null
}
if(localName.equals("c", true)) { //chapter
currentBook!!.chapters.add(currentChapter!!)
currentChapter = null
}
if(localName.equals("v", true)) { //verse
currentChapter!!.verses.add(currentVerse!!)
currentVerse!!.text = tempVal;
currentVerse = null
}
}
} | apache-2.0 | 2580f55a96d57aab5332af6f13e9b5c4 | 27.393258 | 100 | 0.592241 | 4.455026 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/util/extensions/ExceptionExtensions.kt | 1 | 9631 | @file:Suppress("unused")
package org.eurofurence.connavigator.util.extensions
import org.eurofurence.connavigator.services.AnalyticsService
import org.eurofurence.connavigator.util.Choice
import org.eurofurence.connavigator.util.Dispatcher
import org.eurofurence.connavigator.util.left
import org.eurofurence.connavigator.util.right
/**
* Utilities for handling exceptions with automatic analytics handling.
* Created by pazuzu on 4/10/17.
*/
/**
* Handler proxy, this callback is invoked on exceptions in [catchAlternative], [catchToNull] and [catchToFalse].
*/
val proxyException = Dispatcher<Throwable>().apply {
this += { _: Throwable -> /* pass */ }
}
/**
* Catches and dismisses an exception, should not be used but have it anyway.
* @param R Type of the return value
* @param block The block to execute
*/
inline fun <reified R> dismissExceptionIn(block: () -> R) {
try {
block()
} catch(_: Throwable) {
}
}
@kotlin.jvm.JvmName("blockUnit")
inline fun <reified T> block(noinline block: (T) -> Unit) = block
@kotlin.jvm.JvmName("blockReturn")
inline fun <reified T, reified U> block(noinline block: (T) -> U) = block
@kotlin.jvm.JvmName("handlerUnit")
fun block(block: (Unit) -> Unit) = block
@kotlin.jvm.JvmName("handlerReturn")
inline fun <reified U> block(noinline block: (Unit) -> U) = block
/**
* Catches an exception of type [E] in the receiver.
*
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
*/
inline infix fun <reified E : Throwable> (() -> Unit).catchHandle(handler: (E) -> Unit) {
try {
this()
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
}
}
/**
* Catches an exception of type [E] in the receiver. If the receiver succeeded, uses it's return value, otherwise
* uses the [handler]s return value.
*
* @param R Type of the shared return value
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
* @return Returns the return value of the receiver if no exception occurred, otherwise returns the handlers return
* value
*/
inline infix fun <reified R, reified E : Throwable> (() -> R).catchAlternative(handler: (E) -> R): R {
return try {
this()
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
}
}
/**
* Catches an exception of type [E] in the receiver. If the receiver succeeded, uses it's return value, otherwise
* returns null.
*
* @param R Type of the shared return value
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
* @return Returns the return value of the receiver if no exception occurred, otherwise returns null
* value
*/
inline infix fun <reified R, reified E : Throwable> (() -> R).catchToNull(handler: (E) -> Unit): R? {
return try {
this()
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
null
}
}
/**
* Catches an exception of type [E] in the [block]. If the [block] succeeded, uses it's return value, otherwise
* returns null. Exceptions are just handled by logging with [AnalyticsService].
*
* @param R Type of the shared return value
* @param E Type of the exception
* @param block The block to execute that might throw an exception
* @return Returns the return value of the [block] if no exception occurred, otherwise returns null
* value
*/
inline fun <reified R, reified E : Throwable> catchToNull(block: () -> R): R? {
return try {
block()
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
null
}
}
/**
* Catches an exception of type [E] in the receiver. If [R] is boolean, returns the result of the receiver if succeeded,
* otherwise returns true if the receiver succeeded.
*
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
* @return Returns true only if the receiver succeeded and returned true.
*/
inline infix fun <reified E : Throwable, reified R> (() -> R).catchToFalse(handler: (E) -> Unit): Boolean {
return try {
this() as? Boolean ?: true
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
false
}
}
/**
* Catches an exception of type [E] in the [block]. If [R] is boolean, returns the result of the [block] if succeeded,
* otherwise returns true if the [block] succeeded. Exceptions are just handled by logging with [proxyException].
*
* @param E Type of the exception
* @param block The block to execute that might throw an exception
* @return Returns true only if the [block] succeeded and returned true.
*/
inline fun <reified E : Throwable, reified R> catchToFalse(block: () -> R): Boolean {
return try {
block() as? Boolean ?: true
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
false
}
}
/**
* Catches an exception in the [block]. If [R] is boolean, returns the result of the [block] if succeeded, otherwise
* returns true if the [block] succeeded. Exceptions are just handled by logging with [proxyException].
*
* @param block The block to execute that might throw an exception
* @return Returns true only if the [block] succeeded.
*/
inline fun <reified R> catchToAnyFalse(block: () -> R): Boolean {
return try {
block() as? Boolean ?: true
} catch(t: Throwable) {
proxyException(t)
false
}
}
/**
* Catches an exception in the [block]. Returns true only if the [block] succeeded and returned true.
* Exceptions are just handled by logging with [proxyException].
*
* @param block The block to execute that might throw an exception
* @return Returns true only if the [block] succeeded and returned true.
*/
@kotlin.jvm.JvmName("catchToAnyFalseFromReturn")
inline fun catchToAnyFalse(block: () -> Boolean): Boolean {
return try {
block()
} catch(t: Throwable) {
proxyException(t)
false
}
}
/**
* Catches an exception of type [E] in the receiver. Returns a choice of either receivers return value or the
* exception itself on failure.
*
* @param R Type of the return value
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
* @return Returns a choice of either receivers return value or the exception itself on failure.
*/
inline infix fun <reified R, reified E : Throwable> (() -> R).catchToChoice(handler: (E) -> Unit): Choice<R, E> {
return try {
left(this())
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
right(t)
}
}
/**
* Catches an exception of type [E] in the [block]. Returns a choice of either [block]s return value or the
* exception itself on failure. Exceptions are just handled by logging with [proxyException].
*
* @param R Type of the return value
* @param E Type of the exception
* @param block The block to execute that might throw an exception
* @return Returns a choice of either [block]s return value or the exception itself on failure.
*/
inline fun <reified R, reified E : Throwable> catchToChoice(block: () -> R): Choice<R, E> {
return try {
left(block())
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
right(t)
}
}
/**
* Catches an exception of type [E] in the receiver. Returns the exception or null if succeeded.
*
* @param R Type of the return value
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @param handler The handler to execute on an exception
* @return Returns the exception or null if succeeded.
*/
inline infix fun <reified R, reified E : Throwable> (() -> R).catchToException(handler: (E) -> Unit): E? {
return try {
this()
null
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
handler(t)
t
}
}
/**
* Catches an exception of type [E] in the receiver. Returns the exception or null if succeeded.
*
* @param R Type of the return value
* @param E Type of the exception
* @receiver The block to execute that might throw an exception
* @return Returns the exception or null if succeeded.
*/
inline fun <reified R, reified E : Throwable> catchToException(block: () -> R): E? {
return try {
block()
null
} catch(t: Throwable) {
if (t !is E)
throw t
proxyException(t)
t
}
}
/**
* Substitute for [catchToException] for any exception that is thrown.
*/
inline fun <reified R> catchToAnyException(block: () -> R): Throwable? {
return catchToException(block)
}
/**
* Utility to write tests
*/
private infix fun Any?.shouldBe(value: Any?) {
if (this != value)
throw IllegalStateException("$this should be $value")
}
/**
* Utility to write tests
*/
private inline infix fun <reified R> R.shouldSatisfy(predicate: (R) -> Boolean) {
if (!predicate(this))
throw IllegalStateException("$this should satisfy condition")
}
| mit | c7f0cce4fc7cea6016809ed92e29b81d | 28.909938 | 120 | 0.656941 | 3.90077 | false | false | false | false |
handsomecode/smart-foosball | AndroidFoosballScoreboard/app/src/main/java/is/handsome/foosballscoreboard/ScoreboardDoubleView.kt | 2 | 3012 | package `is`.handsome.foosballscoreboard
import `is`.handsome.foosballscoreboard.ScoreboardItemView
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.widget.LinearLayout
public class ScoreboardDoubleView : LinearLayout {
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
firstDigit = ScoreboardItemView(context)
secondDigit = ScoreboardItemView(context)
touchSlop = ViewConfiguration.get(context).scaledTouchSlop * 5
init()
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes) {
firstDigit = ScoreboardItemView(context)
secondDigit = ScoreboardItemView(context)
touchSlop = ViewConfiguration.get(context).scaledTouchSlop * 5
init()
}
private var firstDigit: ScoreboardItemView
private var secondDigit: ScoreboardItemView
private var firstTap: PointF? = null
private var touchSlop: Int
public var currentValue: Int = 0
set(value) {
field = if (value > 0) value % 100 else 0
animateSwitch()
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (isEnabled && firstDigit.isEnabled && secondDigit.isEnabled) {
val motionEvent: MotionEvent = ev ?: return false
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
if (motionEvent.pointerCount > 1) return false
firstTap = PointF(motionEvent.rawX, motionEvent.rawY)
return true
}
MotionEvent.ACTION_UP -> {
if (firstTap == null) return false
if (firstTap!!.y - motionEvent.rawY > touchSlop) {
currentValue--
} else if (motionEvent.rawY - firstTap!!.y > touchSlop) {
currentValue++
}
}
}
}
return super.dispatchTouchEvent(ev)
}
public fun next() {
currentValue++
}
public fun reset() {
currentValue = 0
}
private fun animateSwitch() {
firstDigit.currentValue = currentValue / 10
secondDigit.currentValue = currentValue % 10
}
private fun init() {
initItem(firstDigit)
initItem(secondDigit)
}
private fun initItem(digit: ScoreboardItemView) {
digit.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT)
(digit.layoutParams as LinearLayout.LayoutParams).weight = 1f
addView(digit)
}
}
| apache-2.0 | fee5b977a9520b1931cb5327a1bda8d5 | 32.466667 | 115 | 0.631142 | 5.045226 | false | false | false | false |
wizardofos/Protozoo | extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/ColumnType.kt | 1 | 12444 | package org.jetbrains.exposed.sql
import org.jetbrains.exposed.dao.EntityID
import org.jetbrains.exposed.dao.IdTable
import org.jetbrains.exposed.sql.statements.DefaultValueMarker
import org.jetbrains.exposed.sql.vendors.SQLiteDialect
import org.jetbrains.exposed.sql.vendors.currentDialect
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat
import java.io.InputStream
import java.math.BigDecimal
import java.math.RoundingMode
import java.nio.ByteBuffer
import java.sql.Blob
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.util.*
import javax.sql.rowset.serial.SerialBlob
interface IColumnType {
var nullable: Boolean
fun sqlType(): String
fun valueFromDB(value: Any): Any = value
fun valueToString(value: Any?) : String = when (value) {
null -> {
if (!nullable) error("NULL in non-nullable column")
"NULL"
}
DefaultValueMarker -> "DEFAULT"
is Iterable<*> -> {
value.joinToString(","){ valueToString(it) }
}
else -> {
nonNullValueToString (value)
}
}
fun valueToDB(value: Any?): Any? = value?.let { notNullValueToDB(it) }
fun notNullValueToDB(value: Any): Any = value
fun nonNullValueToString(value: Any) : String = notNullValueToDB(value).toString()
fun readObject(rs: ResultSet, index: Int): Any? = rs.getObject(index)
fun setParameter(stmt: PreparedStatement, index: Int, value: Any?) {
stmt.setObject(index, value)
}
}
abstract class ColumnType(override var nullable: Boolean = false) : IColumnType {
override fun toString(): String = sqlType()
}
class AutoIncColumnType(val delegate: ColumnType, private val _autoincSeq: String) : IColumnType by delegate {
val autoincSeq : String? get() = if (currentDialect.needsSequenceToAutoInc) _autoincSeq else null
private fun resolveAutIncType(columnType: IColumnType) : String = when (columnType) {
is EntityIDColumnType<*> -> resolveAutIncType(columnType.idColumn.columnType)
is IntegerColumnType -> currentDialect.dataTypeProvider.shortAutoincType()
is LongColumnType -> currentDialect.dataTypeProvider.longAutoincType()
else -> error("Unsupported type $delegate for auto-increment")
}
override fun sqlType(): String = resolveAutIncType(delegate)
}
val IColumnType.isAutoInc: Boolean get() = this is AutoIncColumnType || (this is EntityIDColumnType<*> && idColumn.columnType.isAutoInc)
val Column<*>.autoIncSeqName : String? get() {
return (columnType as? AutoIncColumnType)?.autoincSeq
?: (columnType as? EntityIDColumnType<*>)?.idColumn?.autoIncSeqName
}
class EntityIDColumnType<T:Any>(val idColumn: Column<T>) : ColumnType(false) {
init {
assert(idColumn.table is IdTable<*>){"EntityId supported only for IdTables"}
}
override fun sqlType(): String = idColumn.columnType.sqlType()
override fun notNullValueToDB(value: Any): Any =
idColumn.columnType.notNullValueToDB(when (value) {
is EntityID<*> -> value.value
else -> value
})
override fun valueFromDB(value: Any): Any {
@Suppress("UNCHECKED_CAST")
return when (value) {
is EntityID<*> -> EntityID(value.value as T, idColumn.table as IdTable<T>)
else -> EntityID(idColumn.columnType.valueFromDB(value) as T, idColumn.table as IdTable<T>)
}
}
}
class CharacterColumnType : ColumnType() {
override fun sqlType(): String = "CHAR"
override fun valueFromDB(value: Any): Any = when(value) {
is Char -> value
is Number -> value.toInt().toChar()
is String -> value.single()
else -> error("Unexpected value of type Char: $value")
}
override fun notNullValueToDB(value: Any): Any = valueFromDB(value).toString()
override fun nonNullValueToString(value: Any): String = "'$value'"
}
class IntegerColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.shortType()
override fun valueFromDB(value: Any): Any = when(value) {
is Int -> value
is Number -> value.toInt()
else -> error("Unexpected value of type Int: $value")
}
}
class LongColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.longType()
override fun valueFromDB(value: Any): Any = when(value) {
is Long -> value
is Number -> value.toLong()
else -> error("Unexpected value of type Long: $value")
}
}
class DecimalColumnType(val precision: Int, val scale: Int): ColumnType() {
override fun sqlType(): String = "DECIMAL($precision, $scale)"
override fun valueFromDB(value: Any): Any {
val valueFromDB = super.valueFromDB(value)
return when (valueFromDB) {
is BigDecimal -> valueFromDB.setScale(scale, RoundingMode.HALF_EVEN)
is Double -> BigDecimal.valueOf(valueFromDB).setScale(scale, RoundingMode.HALF_EVEN)
is Int -> BigDecimal(valueFromDB)
is Long -> BigDecimal.valueOf(valueFromDB)
else -> valueFromDB
}
}
}
class EnumerationColumnType<T:Enum<T>>(val klass: Class<T>): ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.shortType()
override fun notNullValueToDB(value: Any): Any = when(value) {
is Int -> value
is Enum<*> -> value.ordinal
else -> error("$value is not valid for enum ${klass.name}")
}
override fun valueFromDB(value: Any): Any = when (value) {
is Number -> klass.enumConstants!![value.toInt()]
is Enum<*> -> value
else -> error("$value is not valid for enum ${klass.name}")
}
}
class EnumerationNameColumnType<T:Enum<T>>(val klass: Class<T>, length: Int): StringColumnType(length) {
override fun notNullValueToDB(value: Any): Any = when (value) {
is String -> value
is Enum<*> -> value.name
else -> error("$value is not valid for enum ${klass.name}")
}
override fun valueFromDB(value: Any): Any = when (value) {
is String -> klass.enumConstants!!.first { it.name == value }
is Enum<*> -> value
else -> error("$value is not valid for enum ${klass.name}")
}
}
private val DEFAULT_DATE_STRING_FORMATTER = DateTimeFormat.forPattern("YYYY-MM-dd").withLocale(Locale.ROOT)
private val DEFAULT_DATE_TIME_STRING_FORMATTER = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSSSSS").withLocale(Locale.ROOT)
private val SQLITE_DATE_TIME_STRING_FORMATTER = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss")
private val SQLITE_DATE_STRING_FORMATTER = ISODateTimeFormat.yearMonthDay()
class DateColumnType(val time: Boolean): ColumnType() {
override fun sqlType(): String = if (time) currentDialect.dataTypeProvider.dateTimeType() else "DATE"
override fun nonNullValueToString(value: Any): String {
if (value is String) return value
val dateTime = when (value) {
is DateTime -> value
is java.sql.Date -> DateTime(value.time)
is java.sql.Timestamp -> DateTime(value.time)
else -> error("Unexpected value: $value")
}
return if (time)
"'${DEFAULT_DATE_TIME_STRING_FORMATTER.print(dateTime.toDateTime(DateTimeZone.getDefault()))}'"
else
"'${DEFAULT_DATE_STRING_FORMATTER.print(dateTime)}'"
}
override fun valueFromDB(value: Any): Any = when(value) {
is DateTime -> value
is java.sql.Date -> DateTime(value.time)
is java.sql.Timestamp -> DateTime(value.time)
is Int -> DateTime(value.toLong())
is Long -> DateTime(value)
is String -> when {
currentDialect == SQLiteDialect && time -> SQLITE_DATE_TIME_STRING_FORMATTER.parseDateTime(value)
currentDialect == SQLiteDialect -> SQLITE_DATE_STRING_FORMATTER.parseDateTime(value)
else -> value
}
// REVIEW
else -> DEFAULT_DATE_TIME_STRING_FORMATTER.parseDateTime(value.toString())
}
override fun notNullValueToDB(value: Any): Any {
if (value is DateTime) {
val millis = value.millis
if (time) {
return java.sql.Timestamp(millis)
}
else {
return java.sql.Date(millis)
}
}
return value
}
}
open class StringColumnType(val length: Int = 255, val collate: String? = null): ColumnType() {
override fun sqlType(): String = buildString {
val colLength = [email protected]
append(when (colLength) {
in 1..255 -> "VARCHAR($colLength)"
else -> currentDialect.dataTypeProvider.textType()
})
if (collate != null) {
append(" COLLATE $collate")
}
}
val charactersToEscape = mapOf(
'\'' to "\'\'",
// '\"' to "\"\"", // no need to escape double quote as we put string in single quotes
'\r' to "\\r",
'\n' to "\\n")
override fun nonNullValueToString(value: Any): String = buildString {
append('\'')
value.toString().forEach {
append(charactersToEscape[it] ?: it)
}
append('\'')
}
override fun valueFromDB(value: Any): Any {
if (value is java.sql.Clob) {
return value.characterStream.readText()
}
return value
}
}
class BinaryColumnType(val length: Int) : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.binaryType(length)
// REVIEW
override fun valueFromDB(value: Any): Any {
if (value is java.sql.Blob) {
return value.binaryStream.readBytes()
}
return value
}
}
class BlobColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.blobType()
override fun nonNullValueToString(value: Any): String = "?"
override fun readObject(rs: ResultSet, index: Int): Any? {
return if (currentDialect.dataTypeProvider.blobAsStream)
rs.getBytes(index)?.let { SerialBlob(it) }
else
rs.getBlob(index)
}
override fun valueFromDB(value: Any): Any = when (value) {
is Blob -> value
is InputStream -> SerialBlob(value.readBytes())
is ByteArray -> SerialBlob(value)
else -> error("Unknown type for blob column :${value.javaClass}")
}
override fun setParameter(stmt: PreparedStatement, index: Int, value: Any?) {
if (currentDialect.dataTypeProvider.blobAsStream && value is InputStream) {
stmt.setBinaryStream(index, value, value.available())
} else {
super.setParameter(stmt, index, value)
}
}
override fun notNullValueToDB(value: Any): Any {
return if (currentDialect.dataTypeProvider.blobAsStream)
(value as? Blob)?.binaryStream ?: value
else
value
}
}
class BooleanColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.booleanType()
override fun valueFromDB(value: Any) = when (value) {
is Number -> value.toLong() != 0L
is String -> currentDialect.dataTypeProvider.booleanFromStringToBoolean(value)
else -> value.toString().toBoolean()
}
override fun nonNullValueToString(value: Any) = currentDialect.dataTypeProvider.booleanToStatementString(value as Boolean)
}
class UUIDColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.uuidType()
override fun notNullValueToDB(value: Any): Any = currentDialect.dataTypeProvider.uuidToDB(when (value) {
is UUID -> value
is String -> UUID.fromString(value)
is ByteArray -> ByteBuffer.wrap(value).let { UUID(it.long, it.long )}
else -> error("Unexpected value of type UUID: ${value.javaClass.canonicalName}")
})
override fun valueFromDB(value: Any): Any = when(value) {
is UUID -> value
is ByteArray -> ByteBuffer.wrap(value).let { b -> UUID(b.long, b.long) }
is String -> ByteBuffer.wrap(value.toByteArray()).let { b -> UUID(b.long, b.long) }
else -> error("Unexpected value of type UUID: $value")
}
}
| mit | 68e90cf28652aafd48f104adab8f0d93 | 34.758621 | 136 | 0.645291 | 4.2866 | false | false | false | false |
lena0204/Plattenspieler | musicServiceLibrary/src/main/java/com/lk/musicservicelibrary/main/MusicService.kt | 1 | 9370 | package com.lk.musicservicelibrary.main
import android.app.NotificationManager
import android.content.*
import android.media.AudioManager
import android.media.browse.MediaBrowser
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.os.Build
import android.os.Bundle
import android.service.media.MediaBrowserService
import android.util.Log
import androidx.core.content.getSystemService
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import com.lk.musicservicelibrary.R
import com.lk.musicservicelibrary.database.PlaylistRepository
import com.lk.musicservicelibrary.database.room.PlaylistRoomRepository
import com.lk.musicservicelibrary.models.*
import com.lk.musicservicelibrary.playback.PlaybackCallback
import com.lk.musicservicelibrary.system.*
import com.lk.musicservicelibrary.utils.SharedPrefsWrapper
/**
* Erstellt von Lena am 02.09.18.
* MediaBrowserService; zusammen mit PlaybackController (ControllerCallback)
* mögliche Controller-Aktionen: playFromId, play, pause, next, previous, stop, Command: addAll (als shuffle)
*/
class MusicService : MediaBrowserService(), Observer<Any> {
private val TAG = MusicService::class.java.simpleName
private val NOTIFICATION_ID = 9880
private lateinit var musicDataRepo: MusicDataRepository
private lateinit var playlistRepo: PlaylistRepository
private lateinit var session: MediaSession
private lateinit var sessionCallback: PlaybackCallback
private lateinit var notificationManager: NotificationManager
private lateinit var notificationBuilder: MusicNotificationBuilder
private lateinit var nbReceiver: NotificationActionReceiver
private var serviceStarted = false
companion object {
const val ACTION_MEDIA_PLAY = "com.lk.pl-ACTION_MEDIA_PLAY"
const val ACTION_MEDIA_PAUSE = "com.lk.pl-ACTION_MEDIA_PAUSE"
const val ACTION_MEDIA_NEXT = "com.lk.pl-ACTION_MEDIA_NEXT"
const val SHUFFLE_KEY = "shuffle"
const val QUEUE_KEY = "queue"
const val METADATA_KEY = "metadata"
var PLAYBACK_STATE = PlaybackState.STATE_STOPPED
}
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate")
initializeComponents()
registerBroadcastReceiver()
prepareSession()
registerPlaybackObserver()
}
// - - - Setup - - -
private fun initializeComponents() {
musicDataRepo = LocalMusicFileRepository(this.applicationContext)
playlistRepo = PlaylistRoomRepository(this.application)
sessionCallback = PlaybackCallback(musicDataRepo, playlistRepo, this.applicationContext)
notificationManager = this.getSystemService<NotificationManager>() as NotificationManager
notificationBuilder = MusicNotificationBuilder(this)
nbReceiver = NotificationActionReceiver(sessionCallback)
val am = this.getSystemService<AudioManager>() as AudioManager
// AudioFocusRequester.setup(sessionCallback.audioFocusChanged, am)
}
private fun registerBroadcastReceiver() {
val ifilter = IntentFilter()
ifilter.addAction(ACTION_MEDIA_PLAY)
ifilter.addAction(ACTION_MEDIA_PAUSE)
ifilter.addAction(ACTION_MEDIA_NEXT)
this.registerReceiver(nbReceiver, ifilter)
}
private fun prepareSession() {
session = MediaSession(applicationContext, TAG)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
session.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS)
}
session.setCallback(sessionCallback)
session.setQueueTitle(getString(R.string.queue_title))
sessionToken = session.sessionToken
}
private fun registerPlaybackObserver() {
sessionCallback.getPlaybackState().observeForever(this)
sessionCallback.getPlayingList().observeForever(this)
}
// - - - Media Browser capabilities - - -
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot {
if (this.packageName == clientPackageName) {
return BrowserRoot(MusicDataRepository.ROOT_ID, null)
}
return BrowserRoot("", null)
}
override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowser.MediaItem>>) {
when {
parentId == MusicDataRepository.ROOT_ID -> {
result.sendResult(musicDataRepo.queryAlbums().getMediaItemList())
}
parentId.contains("ALBUM-") -> {
result.sendResult(getTitles(parentId))
}
else -> Log.e(TAG, "No known parent ID")
}
}
private fun getTitles(albumId: String): MutableList<MediaBrowser.MediaItem> {
val id = albumId.replace("ALBUM-", "")
val playingList = musicDataRepo.queryTitlesByAlbumID(id)
sessionCallback.setQueriedMediaList(playingList)
return playingList.getMediaItemList()
}
// - - - Clean up - - -
override fun onUnbind(intent: Intent?): Boolean {
val bool = super.onUnbind(intent)
Log.v(TAG, "onUnbind")
val state = session.controller.playbackState?.state
if (state == PlaybackState.STATE_PAUSED) {
Log.d(TAG, "Playback paused ($state), so stop")
val metadata = MusicMetadata.createFromMediaMetadata(session.controller.metadata!!)
playlistRepo.savePlayingQueue(sessionCallback.getPlayingList().value!!, metadata)
sessionCallback.onStop()
}
return bool
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
sessionCallback.onStop()
this.unregisterReceiver(nbReceiver)
unregisterPlaybackObserver()
session.release()
session.isActive = false
}
private fun unregisterPlaybackObserver(){
sessionCallback.getPlayingList().removeObserver(this)
sessionCallback.getPlaybackState().removeObserver(this)
}
// - - - Changes handler - - -
override fun onChanged(update: Any?) {
if(update is MusicList) {
updatePlayingList(update)
} else if (update is PlaybackState) {
updatePlaybackState(update)
}
}
private fun updatePlayingList(playingList: MusicList) {
val playingTitle = playingList.getItemAtCurrentPlaying()
val shortQueue = getShortenedQueue(playingList)
if(playingTitle != null ){
playingTitle.nr_of_songs_left = shortQueue.count().toLong()
session.setMetadata(playingTitle.getMediaMetadata())
sendBroadcastForLightningLauncher(playingTitle)
}
session.setQueue(shortQueue.getQueueItemList())
}
private fun getShortenedQueue(playingList: MusicList) : MusicList {
val shortedQueue = MusicList()
val firstAfterPlaying = playingList.getCurrentPlaying() + 1
for (i in firstAfterPlaying until playingList.size()) {
shortedQueue.addItem(playingList.getItemAt(i))
}
return shortedQueue
}
private fun sendBroadcastForLightningLauncher(metadata: MusicMetadata) {
val track = bundleOf(
"title" to metadata.title,
"album" to metadata.album,
"artist" to metadata.artist)
val extras = bundleOf(
"track" to track,
"aaPath" to metadata.cover_uri)
this.sendBroadcast(Intent("com.lk.plattenspieler.metachanged").putExtras(extras))
}
private fun updatePlaybackState(state: PlaybackState) {
PLAYBACK_STATE = state.state
session.setPlaybackState(state)
adaptServiceToPlaybackState()
}
private fun adaptServiceToPlaybackState() {
when (PLAYBACK_STATE) {
PlaybackState.STATE_PLAYING -> adaptToPlayingPaused()
PlaybackState.STATE_PAUSED -> {
adaptToPlayingPaused()
this.stopForeground(false)
}
PlaybackState.STATE_STOPPED -> {
notificationManager.cancel(NOTIFICATION_ID)
stopService()
}
}
}
private fun adaptToPlayingPaused() {
val shuffleOn = SharedPrefsWrapper.readShuffle(applicationContext)
val metadata = if(session.controller.metadata != null) {
MusicMetadata.createFromMediaMetadata(session.controller.metadata!!)
} else {
MusicMetadata()
}
val noti = notificationBuilder.showNotification(PLAYBACK_STATE, metadata, shuffleOn)
if(PLAYBACK_STATE == PlaybackState.STATE_PLAYING){
startServiceIfNecessary()
this.startForeground(NOTIFICATION_ID, noti)
} else {
notificationManager.notify(NOTIFICATION_ID, noti)
}
}
private fun startServiceIfNecessary() {
if (!serviceStarted) {
this.startService(Intent(applicationContext,
com.lk.musicservicelibrary.main.MusicService::class.java))
Log.d(TAG, "started service")
serviceStarted = true
}
if (!session.isActive)
session.isActive = true
}
private fun stopService() {
Log.d(TAG, "stopService in service")
this.stopSelf()
serviceStarted = false
this.stopForeground(true)
}
} | gpl-3.0 | f581e5bff932e63010db2edb75ca9b7a | 36.630522 | 109 | 0.676486 | 4.765514 | false | false | false | false |
fython/shadowsocks-android | mobile/src/main/java/com/github/shadowsocks/utils/DirectBoot.kt | 1 | 1100 | package com.github.shadowsocks.utils
import android.annotation.TargetApi
import com.github.shadowsocks.App.Companion.app
import com.github.shadowsocks.bg.BaseService
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.database.ProfileManager
import com.github.shadowsocks.preference.DataStore
import java.io.File
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
@TargetApi(24)
object DirectBoot {
private val file = File(app.deviceContext.noBackupFilesDir, "directBootProfile")
fun getDeviceProfile(): Profile? = try {
ObjectInputStream(file.inputStream()).use { it.readObject() as Profile }
} catch (_: IOException) { null }
fun clean() {
file.delete()
File(app.deviceContext.noBackupFilesDir, BaseService.CONFIG_FILE).delete()
}
fun update() {
val profile = ProfileManager.getProfile(DataStore.profileId) // app.currentProfile will call this
if (profile == null) clean() else ObjectOutputStream(file.outputStream()).use { it.writeObject(profile) }
}
}
| gpl-3.0 | 4075576a066ceee070b11ce675563cc4 | 34.483871 | 113 | 0.75 | 4.280156 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut14/perspectiveInterpolation.kt | 2 | 3367 | package main.tut14
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import glNext.*
import main.framework.Framework
import main.framework.component.Mesh
import uno.gl.gl3
import uno.glm.MatrixStack
import uno.glsl.programOf
/**
* Created by elect on 28/03/17.
*/
fun main(args: Array<String>) {
PerspectiveInterpolation_().setup("Tutorial 14 - Perspective Interpolation")
}
class PerspectiveInterpolation_ : Framework() {
lateinit var smoothInterp: ProgramData
lateinit var linearInterp: ProgramData
lateinit var realHallway: Mesh
lateinit var fauxHallway: Mesh
var useFakeHallway = false
var useSmoothInterpolation = true
override fun init(gl: GL3) {
initializePrograms(gl)
realHallway = Mesh(gl, javaClass, "tut14/RealHallway.xml")
fauxHallway = Mesh(gl, javaClass, "tut14/FauxHallway.xml")
}
fun initializePrograms(gl: GL3) = with(gl) {
smoothInterp = ProgramData(gl, "smooth-vertex-colors")
linearInterp = ProgramData(gl, "no-correct-vertex-colors")
val zNear = 1.0f
val zFar = 1_000f
val persMatrix = MatrixStack()
persMatrix.perspective(60.0f, 1.0f, zNear, zFar)
glUseProgram(smoothInterp.theProgram)
glUniformMatrix4f(smoothInterp.cameraToClipMatrixUnif, persMatrix.top())
glUseProgram(linearInterp.theProgram)
glUniformMatrix4f(linearInterp.cameraToClipMatrixUnif, persMatrix.top())
glUseProgram()
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0.0f)
glClearBufferf(GL_DEPTH)
if (useSmoothInterpolation)
glUseProgram(smoothInterp.theProgram)
else
glUseProgram(linearInterp.theProgram)
if (useFakeHallway)
fauxHallway.render(gl)
else
realHallway.render(gl)
glUseProgram(0)
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_S -> {
useFakeHallway = !useFakeHallway
println(if (useFakeHallway) "Fake Hallway." else "Real Hallway.")
}
KeyEvent.VK_P -> {
useSmoothInterpolation = !useSmoothInterpolation
println(if (useSmoothInterpolation) "Perspective correct interpolation." else "Just linear interpolation")
}
KeyEvent.VK_SPACE -> window.gl3 {
realHallway.dispose(this)
fauxHallway.dispose(this)
realHallway = Mesh(this, javaClass, "tut14/RealHallway.xml")
fauxHallway = Mesh(this, javaClass, "tut14/FauxHallway.xml")
}
}
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(smoothInterp.theProgram, linearInterp.theProgram)
fauxHallway.dispose(gl)
realHallway.dispose(gl)
}
class ProgramData(gl: GL3, shader: String) {
val theProgram = programOf(gl, javaClass, "tut14", shader + ".vert", shader + ".frag")
val cameraToClipMatrixUnif = gl.glGetUniformLocation(theProgram, "cameraToClipMatrix")
}
} | mit | 4093b75f84a78c0a2d5a7c5523ecc174 | 27.786325 | 122 | 0.6436 | 4.008333 | false | false | false | false |
RyotaMurohoshi/snippets | kotlin/kotlin_playground/src/main/kotlin/sequence_example.kt | 1 | 1888 | package com.mrstar.kotlin_playground
fun listExample0() {
val list = listOf(1, 2, 3)
val result = list.map {
println("map $it")
it
}
println("--------")
for (it in result) println("for $it")
/*
map 1
map 2
map 3
--------
for 1
for 2
for 3
*/
}
fun listExample1() {
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val result = list
.map {
println("map $it")
it
}
.filter {
println("filter $it")
it % 2 == 0
}
.take(3)
println("--------")
for (it in result) println("for $it")
/*
map 1
map 2
map 3
map 4
map 5
map 6
map 7
map 8
map 9
filter 1
filter 2
filter 3
filter 4
filter 5
filter 6
filter 7
filter 8
filter 9
--------
for 2
for 4
for 6
*/
}
fun sequenceExample0() {
val list = listOf(1, 2, 3)
val result = list
.asSequence()
.map {
println("map $it")
it
}
println("--------")
for (it in result) println("for $it")
/*
--------
map 1
for 1
map 2
for 2
map 3
for 3
*/
}
fun sequenceExample1() {
val list = sequenceOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val result = list
.map {
println("map $it")
it
}
.filter {
println("filter $it")
it % 2 == 0
}
.take(3)
println("--------")
for (it in result) println("for $it")
/*
--------
map 1
filter 1
map 2
filter 2
for 2
map 3
filter 3
map 4
filter 4
for 4
map 5
filter 5
map 6
filter 6
for 6
*/
}
| mit | 81f3162409358429520d39e248dc3d02 | 13.635659 | 52 | 0.389301 | 3.783567 | false | false | false | false |
square/kotlinpoet | interop/javapoet/src/main/kotlin/com/squareup/kotlinpoet/javapoet/PoetInterop.kt | 1 | 1202 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.kotlinpoet.javapoet
/** Various JavaPoet and KotlinPoet representations of some common types. */
@OptIn(KotlinPoetJavaPoetPreview::class)
internal object PoetInterop {
internal val CN_JAVA_CHAR_SEQUENCE = JClassName.get("java.lang", "CharSequence")
internal val CN_JAVA_STRING = JClassName.get("java.lang", "String")
internal val CN_JAVA_LIST = JClassName.get("java.util", "List")
internal val CN_JAVA_SET = JClassName.get("java.util", "Set")
internal val CN_JAVA_MAP = JClassName.get("java.util", "Map")
internal val CN_JAVA_ENUM = JClassName.get("java.lang", "Enum")
}
| apache-2.0 | 6c60d041d0f785d1270c2e4e24917980 | 43.518519 | 82 | 0.738769 | 3.779874 | false | false | false | false |
Cardstock/Cardstock | src/test/kotlin/xyz/cardstock/cardstock/games/GameSpec.kt | 1 | 4005 | /*
* 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 xyz.cardstock.cardstock.games
import org.jetbrains.spek.api.Spek
import org.kitteh.irc.client.library.element.Channel
import org.kitteh.irc.client.library.element.User
import org.mockito.Matchers.anyString
import org.mockito.Matchers.eq
import org.mockito.Mockito.verify
import org.powermock.api.mockito.PowerMockito.*
import xyz.cardstock.cardstock.extensions.channel.antiPing
import xyz.cardstock.cardstock.implementations.DummyCardstock
import xyz.cardstock.cardstock.implementations.games.DummyGame
import xyz.cardstock.cardstock.implementations.players.DummyPlayer
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GameSpec : Spek({
fun makeChannel(nicknames: List<String>): Channel {
val channel = mock(Channel::class.java)
doNothing().`when`(channel).sendMessage(anyString())
`when`(channel.nicknames).thenReturn(nicknames)
return channel
}
fun makeUser(nickname: String): User {
val user = mock(User::class.java)
`when`(user.nick).thenReturn(nickname)
return user
}
given("a DummyGame") {
val cardstock = DummyCardstock()
val channel = makeChannel(listOf("Bert", "Ernie"))
val game = DummyGame(cardstock, channel)
on("accessing cardstock") {
val gameCardstock = game.cardstock
it("should be the same as it was constructed with") {
assertTrue(cardstock === gameCardstock)
}
}
on("accessing channel") {
val gameChannel = game.channel
it("should be the same as it was constructed with") {
assertTrue(channel === gameChannel)
}
}
on("sending a message") {
val message = "Hi, Bert!"
game.sendMessage(message)
it("should send the anti-pinged message to the channel") {
val antiPinged = channel.antiPing(message)
verify(channel).sendMessage(eq(antiPinged))
}
}
val user = makeUser("Bert")
on("getting a player that is not in the game") {
val player = game.getPlayer(user, false)
it("should return null") {
assertNull(player)
}
}
on("getting a player that is not in the game but should be created") {
val player = game.getPlayer(user, true)
it("should not be null") {
assertNotNull(player)
}
it("should be a DummyPlayer") {
assertTrue(player is DummyPlayer)
}
}
on("getting a player that is in the game") {
val player = game.getPlayer(user, false)
it("should not be null") {
assertNotNull(player)
}
it("should be a DummyPlayer") {
assertTrue(player is DummyPlayer)
}
}
on("removing that player by his user") {
game.removePlayer(user)
val size = game.players.size
it("should have a player count of 0") {
assertEquals(0, size)
}
it("should return null on getting the player") {
assertNull(game.getPlayer(user, false))
}
}
on("removing that player by his player") {
val player = game.getPlayer(user, true)!!
game.removePlayer(player)
val size = game.players.size
it("should have a player count of 0") {
assertEquals(0, size)
}
it("should return null on getting the player") {
assertNull(game.getPlayer(user, false))
}
}
}
})
| mpl-2.0 | d476348f251508bb631c5d95b597bbfa | 35.409091 | 78 | 0.59226 | 4.5 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/api/commands/Command.kt | 1 | 1282 | package net.perfectdreams.loritta.morenitta.api.commands
import net.perfectdreams.loritta.common.commands.CommandArguments
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.LorittaBot
open class Command<T : CommandContext>(
val loritta: LorittaBot,
val labels: List<String>,
val commandName: String,
val category: CommandCategory,
val descriptionKey: LocaleKeyData = MISSING_DESCRIPTION_KEY,
val description: ((BaseLocale) -> (String)) = {
it.get(descriptionKey)
},
val usage: CommandArguments,
val examplesKey: LocaleKeyData?,
val executor: (suspend T.() -> (Unit))
) {
companion object {
val MISSING_DESCRIPTION_KEY = LocaleKeyData("commands.missingDescription")
val SINGLE_IMAGE_EXAMPLES_KEY = LocaleKeyData("commands.category.images.singleImageExamples")
val TWO_IMAGES_EXAMPLES_KEY = LocaleKeyData("commands.category.images.twoImagesExamples")
}
var needsToUploadFiles = false
var hideInHelp = false
var canUseInPrivateChannel = false
var onlyOwner = false
var similarCommands: List<String> = listOf()
open val cooldown = 2_500
// var lorittaPermissions = listOf()
} | agpl-3.0 | c54f62565517875ba07ca286ef4dfcfb | 33.675676 | 95 | 0.790172 | 3.944615 | false | false | false | false |
signed/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/completion/StatisticsUpdate.kt | 1 | 5073 | /*
* 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.codeInsight.completion
import com.google.common.annotations.VisibleForTesting
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.featureStatistics.FeatureUsageTrackerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.event.DocumentAdapter
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.statistics.StatisticsInfo
import com.intellij.util.Alarm
/**
* @author peter
*/
class StatisticsUpdate
private constructor(private val myInfo: StatisticsInfo) : Disposable {
private var mySpared: Int = 0
override fun dispose() {}
fun addSparedChars(indicator: CompletionProgressIndicator, item: LookupElement, context: InsertionContext) {
val textInserted: String
if (context.offsetMap.containsOffset(CompletionInitializationContext.START_OFFSET) &&
context.offsetMap.containsOffset(InsertionContext.TAIL_OFFSET) &&
context.tailOffset >= context.startOffset) {
textInserted = context.document.immutableCharSequence.subSequence(context.startOffset, context.tailOffset).toString()
}
else {
textInserted = item.lookupString
}
val withoutSpaces = StringUtil.replace(textInserted, arrayOf(" ", "\t", "\n"), arrayOf("", "", ""))
var spared = withoutSpaces.length - indicator.lookup.itemPattern(item).length
val completionChar = context.completionChar
if (!LookupEvent.isSpecialCompletionChar(completionChar) && withoutSpaces.contains(completionChar.toString())) {
spared--
}
if (spared > 0) {
mySpared += spared
}
}
fun trackStatistics(context: InsertionContext) {
if (ourPendingUpdate !== this) {
return
}
if (!context.offsetMap.containsOffset(CompletionInitializationContext.START_OFFSET)) {
return
}
val document = context.document
val startOffset = context.startOffset
val tailOffset =
if (context.editor.selectionModel.hasSelection()) context.editor.selectionModel.selectionStart
else context.editor.caretModel.offset
if (startOffset < 0 || tailOffset <= startOffset) {
return
}
val marker = document.createRangeMarker(startOffset, tailOffset)
val listener = object : DocumentAdapter() {
override fun beforeDocumentChange(e: DocumentEvent) {
if (!marker.isValid || e.offset > marker.startOffset && e.offset < marker.endOffset) {
cancelLastCompletionStatisticsUpdate()
}
}
}
ourStatsAlarm.addRequest({
if (ourPendingUpdate === this) {
applyLastCompletionStatisticsUpdate()
}
}, 20 * 1000)
document.addDocumentListener(listener)
Disposer.register(this, Disposable {
document.removeDocumentListener(listener)
marker.dispose()
ourStatsAlarm.cancelAllRequests()
})
}
companion object {
private val ourStatsAlarm = Alarm(ApplicationManager.getApplication())
private var ourPendingUpdate: StatisticsUpdate? = null
init {
Disposer.register(ApplicationManager.getApplication(), Disposable { cancelLastCompletionStatisticsUpdate() })
}
@VisibleForTesting
@JvmStatic
fun collectStatisticChanges(item: LookupElement): StatisticsUpdate {
applyLastCompletionStatisticsUpdate()
val base = StatisticsWeigher.getBaseStatisticsInfo(item, null)
if (base === StatisticsInfo.EMPTY) {
return StatisticsUpdate(StatisticsInfo.EMPTY)
}
val update = StatisticsUpdate(base)
ourPendingUpdate = update
Disposer.register(update, Disposable { ourPendingUpdate = null })
return update
}
@JvmStatic
fun cancelLastCompletionStatisticsUpdate() {
ourPendingUpdate?.let { Disposer.dispose(it) }
assert(ourPendingUpdate == null)
}
@JvmStatic
fun applyLastCompletionStatisticsUpdate() {
ourPendingUpdate?.let {
it.myInfo.incUseCount()
(FeatureUsageTracker.getInstance() as FeatureUsageTrackerImpl).completionStatistics.registerInvocation(it.mySpared)
}
cancelLastCompletionStatisticsUpdate()
}
}
}
| apache-2.0 | 1c55e83b050aaa4e579197733ac5ceb8 | 34.475524 | 123 | 0.717524 | 4.781338 | false | false | false | false |
googlecodelabs/odml-pathways | object-detection/codelab2/android/starter/app/src/main/java/org/tensorflow/codelabs/objectdetection/MainActivity.kt | 2 | 10521 | /**
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.codelabs.objectdetection
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.*
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.max
import kotlin.math.min
class MainActivity : AppCompatActivity(), View.OnClickListener {
companion object {
const val TAG = "TFLite - ODT"
const val REQUEST_IMAGE_CAPTURE: Int = 1
private const val MAX_FONT_SIZE = 96F
}
private lateinit var captureImageFab: Button
private lateinit var inputImageView: ImageView
private lateinit var imgSampleOne: ImageView
private lateinit var imgSampleTwo: ImageView
private lateinit var imgSampleThree: ImageView
private lateinit var tvPlaceholder: TextView
private lateinit var currentPhotoPath: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
captureImageFab = findViewById(R.id.captureImageFab)
inputImageView = findViewById(R.id.imageView)
imgSampleOne = findViewById(R.id.imgSampleOne)
imgSampleTwo = findViewById(R.id.imgSampleTwo)
imgSampleThree = findViewById(R.id.imgSampleThree)
tvPlaceholder = findViewById(R.id.tvPlaceholder)
captureImageFab.setOnClickListener(this)
imgSampleOne.setOnClickListener(this)
imgSampleTwo.setOnClickListener(this)
imgSampleThree.setOnClickListener(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == Activity.RESULT_OK
) {
setViewAndDetect(getCapturedImage())
}
}
/**
* onClick(v: View?)
* Detect touches on the UI components
*/
override fun onClick(v: View?) {
when (v?.id) {
R.id.captureImageFab -> {
try {
dispatchTakePictureIntent()
} catch (e: ActivityNotFoundException) {
Log.e(TAG, e.message.toString())
}
}
R.id.imgSampleOne -> {
setViewAndDetect(getSampleImage(R.drawable.img_meal_one))
}
R.id.imgSampleTwo -> {
setViewAndDetect(getSampleImage(R.drawable.img_meal_two))
}
R.id.imgSampleThree -> {
setViewAndDetect(getSampleImage(R.drawable.img_meal_three))
}
}
}
/**
* runObjectDetection(bitmap: Bitmap)
* TFLite Object Detection function
*/
private fun runObjectDetection(bitmap: Bitmap) {
//TODO: Add object detection code here
}
/**
* setViewAndDetect(bitmap: Bitmap)
* Set image to view and call object detection
*/
private fun setViewAndDetect(bitmap: Bitmap) {
// Display capture image
inputImageView.setImageBitmap(bitmap)
tvPlaceholder.visibility = View.INVISIBLE
// Run ODT and display result
// Note that we run this in the background thread to avoid blocking the app UI because
// TFLite object detection is a synchronised process.
lifecycleScope.launch(Dispatchers.Default) { runObjectDetection(bitmap) }
}
/**
* getCapturedImage():
* Decodes and crops the captured image from camera.
*/
private fun getCapturedImage(): Bitmap {
// Get the dimensions of the View
val targetW: Int = inputImageView.width
val targetH: Int = inputImageView.height
val bmOptions = BitmapFactory.Options().apply {
// Get the dimensions of the bitmap
inJustDecodeBounds = true
BitmapFactory.decodeFile(currentPhotoPath, this)
val photoW: Int = outWidth
val photoH: Int = outHeight
// Determine how much to scale down the image
val scaleFactor: Int = max(1, min(photoW / targetW, photoH / targetH))
// Decode the image file into a Bitmap sized to fill the View
inJustDecodeBounds = false
inSampleSize = scaleFactor
inMutable = true
}
val exifInterface = ExifInterface(currentPhotoPath)
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
val bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> {
rotateImage(bitmap, 90f)
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
rotateImage(bitmap, 180f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
rotateImage(bitmap, 270f)
}
else -> {
bitmap
}
}
}
/**
* getSampleImage():
* Get image form drawable and convert to bitmap.
*/
private fun getSampleImage(drawable: Int): Bitmap {
return BitmapFactory.decodeResource(resources, drawable, BitmapFactory.Options().apply {
inMutable = true
})
}
/**
* rotateImage():
* Decodes and crops the captured image from camera.
*/
private fun rotateImage(source: Bitmap, angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height,
matrix, true
)
}
/**
* createImageFile():
* Generates a temporary image file for the Camera app to write to.
*/
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
/**
* dispatchTakePictureIntent():
* Start the Camera app to take a photo.
*/
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (e: IOException) {
Log.e(TAG, e.message.toString())
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"org.tensorflow.codelabs.objectdetection.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
}
/**
* drawDetectionResult(bitmap: Bitmap, detectionResults: List<DetectionResult>
* Draw a box around each objects and show the object's name.
*/
private fun drawDetectionResult(
bitmap: Bitmap,
detectionResults: List<DetectionResult>
): Bitmap {
val outputBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(outputBitmap)
val pen = Paint()
pen.textAlign = Paint.Align.LEFT
detectionResults.forEach {
// draw bounding box
pen.color = Color.RED
pen.strokeWidth = 8F
pen.style = Paint.Style.STROKE
val box = it.boundingBox
canvas.drawRect(box, pen)
val tagSize = Rect(0, 0, 0, 0)
// calculate the right font size
pen.style = Paint.Style.FILL_AND_STROKE
pen.color = Color.YELLOW
pen.strokeWidth = 2F
pen.textSize = MAX_FONT_SIZE
pen.getTextBounds(it.text, 0, it.text.length, tagSize)
val fontSize: Float = pen.textSize * box.width() / tagSize.width()
// adjust the font size so texts are inside the bounding box
if (fontSize < pen.textSize) pen.textSize = fontSize
var margin = (box.width() - tagSize.width()) / 2.0F
if (margin < 0F) margin = 0F
canvas.drawText(
it.text, box.left + margin,
box.top + tagSize.height().times(1F), pen
)
}
return outputBitmap
}
}
/**
* DetectionResult
* A class to store the visualization info of a detected object.
*/
data class DetectionResult(val boundingBox: RectF, val text: String)
| apache-2.0 | 135bf4afbc0a1440c4c282d6e5aaf23a | 33.495082 | 96 | 0.617812 | 4.893488 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/FailuresTest.kt | 1 | 2082 | package com.sksamuel.kotest
import com.sksamuel.kotest.throwablehandling.catchThrowable
import io.kotest.assertions.Failures
import io.kotest.assertions.shouldFail
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldStartWith
import io.kotest.matchers.types.shouldBeInstanceOf
class FailuresTest : FreeSpec() {
init {
"Failures.shouldFail" - {
"Should throw an exception when code succeeds" {
val thrown = catchThrowable { shouldFail { /* Code succeeds */ } }
thrown.shouldBeFailureWithNoAssertionErrorThrown()
}
"Should throw an exception when code throws something other than an assertion error" {
val thrown = catchThrowable { shouldFail { throw Exception() } }
thrown.shouldBeFailureWithWrongExceptionThrown()
}
"Should not thrown an exception when code fails with an assertion error" {
val thrown = catchThrowable { shouldFail { throw AssertionError() } }
thrown shouldBe null
}
}
"Failures.failure" - {
"filters stacktrace" {
val cause = RuntimeException()
val failure = Failures.failure("msg", cause)
failure.message shouldBe "msg"
failure.cause shouldBe cause
failure.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
"filters stacktrace when called by shouldBe" {
val t = shouldThrowAny { 1 shouldBe 2 }
t.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
}
}
private fun Throwable?.shouldBeFailureWithNoAssertionErrorThrown() {
shouldBeInstanceOf<AssertionError>()
this!!.message shouldBe "Expected exception java.lang.AssertionError but no exception was thrown."
}
private fun Throwable?.shouldBeFailureWithWrongExceptionThrown() {
shouldBeInstanceOf<AssertionError>()
this!!.message shouldBe "Expected exception java.lang.AssertionError but a Exception was thrown instead."
}
}
| apache-2.0 | d3202783ca9f97393129d4aa91e1932e | 34.896552 | 109 | 0.721902 | 4.945368 | false | true | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/ksp/generators/ObjectAdapterGenerator.kt | 1 | 998 | package se.ansman.kotshi.ksp.generators
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSClassDeclaration
import se.ansman.kotshi.model.GeneratableJsonAdapter
import se.ansman.kotshi.model.GlobalConfig
import se.ansman.kotshi.model.ObjectJsonAdapter
class ObjectAdapterGenerator(
environment: SymbolProcessorEnvironment,
element: KSClassDeclaration,
globalConfig: GlobalConfig,
resolver: Resolver
) : AdapterGenerator(environment, element, globalConfig, resolver) {
init {
require(element.classKind == ClassKind.OBJECT)
}
override fun getGeneratableJsonAdapter(): GeneratableJsonAdapter =
ObjectJsonAdapter(
targetPackageName = targetClassName.packageName,
targetSimpleNames = targetClassName.simpleNames,
polymorphicLabels = polymorphicLabels,
)
} | apache-2.0 | 0e2ce382ccf38b1ce9dfd31f640f647e | 36 | 70 | 0.778557 | 4.940594 | false | true | false | false |
GiuseppeGiacoppo/Android-Clean-Architecture-with-Kotlin | app/src/main/java/me/giacoppo/examples/kotlin/mvp/ui/home/MainActivity.kt | 1 | 3373 | package me.giacoppo.examples.kotlin.mvp.ui.home
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import me.giacoppo.examples.kotlin.mvp.R
import me.giacoppo.examples.kotlin.mvp.bean.Show
import me.giacoppo.examples.kotlin.mvp.data.executor.UIThread
import me.giacoppo.examples.kotlin.mvp.data.source.tmdb.TMDBRetrofitService
import me.giacoppo.examples.kotlin.mvp.data.source.tmdb.TMDBShowsRepository
import me.giacoppo.examples.kotlin.mvp.repository.interactor.GetPopularTVShows
import me.giacoppo.examples.kotlin.mvp.repository.interactor.executor.JobExecutor
import me.giacoppo.examples.kotlin.mvp.ui.PopularPresenter
import me.giacoppo.examples.kotlin.mvp.ui.contract.PopularContract
import me.giacoppo.examples.kotlin.mvp.ui.detail.DetailActivity
class MainActivity : AppCompatActivity(), PopularContract.View {
private lateinit var showsList: RecyclerView
private lateinit var message: TextView
private lateinit var progress: View
private lateinit var presenter: PopularContract.Presenter
private lateinit var adapter: ShowsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val getPopularUseCase = GetPopularTVShows(
TMDBShowsRepository(TMDBRetrofitService.instance.getService()),
JobExecutor.instance,
UIThread.instance)
//init presenter
presenter = PopularPresenter(this, getPopularUseCase)
//init views
showsList = findViewById(R.id.result)
message = findViewById(R.id.message)
progress = findViewById(R.id.progress)
adapter = ShowsAdapter({v,item -> startActivity(DetailActivity.getIntent(this, item))})
showsList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
showsList.adapter = adapter
//query
presenter.findPopularShows()
}
override fun showResults(results: List<Show>) {
adapter.addAll(results)
setState(1)
}
override fun showNoResults() {
adapter.clear()
message.text = "No shows found"
setState(2)
}
override fun showLoader() {
setState(0)
}
override fun showError() {
message.text = "Error finding shows"
setState(2)
}
/**
* 0: loading
* 1: show results
* 2: show a message
*/
private fun setState(state: Int) {
when (state) {
0 -> {
progress.visibility = View.VISIBLE
message.visibility = View.GONE
showsList.visibility = View.GONE
}
1 -> {
progress.visibility = View.GONE
message.visibility = View.GONE
showsList.visibility = View.VISIBLE
}
2 -> {
progress.visibility = View.GONE
message.visibility = View.VISIBLE
showsList.visibility = View.GONE
}
}
}
}
| apache-2.0 | d3517acea8aa518540c16bd1e60ec16d | 31.432692 | 96 | 0.673881 | 4.589116 | false | false | false | false |
kysersozelee/KotlinStudy | JsonParser/bin/JsonString.kt | 1 | 694 | class JsonString(string: String?) : JsonValue() {
val string: String? = string
override fun write(writer: JsonWriter): String {
writer.writeString(this.string)
return writer.string
}
override fun isString(): Boolean {
return true
}
override fun isNull(): Boolean {
if (null == string) return true else return false
}
override fun asString(): String {
if (null == this.string) throw Exception("invalid String") else return this.string
}
override fun equals(other: Any?): Boolean {
if (null == other || other !is JsonString) return false
val result = this.string?.equals(other)
if (null == result) return false else return result
}
} | bsd-2-clause | c608178493d3bd3c759b5fb743a15883 | 22 | 84 | 0.670029 | 3.671958 | false | false | false | false |
ze-pequeno/okhttp | mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt | 4 | 1708 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.mockwebserver
import okhttp3.Headers
class PushPromise(
@get:JvmName("method") val method: String,
@get:JvmName("path") val path: String,
@get:JvmName("headers") val headers: Headers,
@get:JvmName("response") val response: MockResponse
) {
@JvmName("-deprecated_method")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "method"),
level = DeprecationLevel.ERROR)
fun method(): String = method
@JvmName("-deprecated_path")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "path"),
level = DeprecationLevel.ERROR)
fun path(): String = path
@JvmName("-deprecated_headers")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "headers"),
level = DeprecationLevel.ERROR)
fun headers(): Headers = headers
@JvmName("-deprecated_response")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "response"),
level = DeprecationLevel.ERROR)
fun response(): MockResponse = response
}
| apache-2.0 | 1be466c317a7194b8701fecd9417e699 | 30.62963 | 75 | 0.694379 | 4.302267 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/handler/rpl/Rpl474Handler.kt | 1 | 1226 | package chat.willow.warren.handler.rpl
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl474Message
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl474MessageType
import chat.willow.warren.helper.loggerFor
import chat.willow.warren.state.CaseMappingState
import chat.willow.warren.state.JoiningChannelLifecycle
import chat.willow.warren.state.JoiningChannelsState
class Rpl474Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : KaleHandler<Rpl474MessageType>(Rpl474Message.Parser) {
private val LOGGER = loggerFor<Rpl474Handler>()
override fun handle(message: Rpl474MessageType, metadata: IMetadataStore) {
val channel = channelsState[message.channel]
if (channel == null) {
LOGGER.warn("got a banned from channel reply for a channel we don't think we're joining: $message")
LOGGER.trace("channels state: $channelsState")
return
}
LOGGER.warn("we are banned from channel, failed to join: $channel")
channel.status = JoiningChannelLifecycle.FAILED
LOGGER.trace("new channels state: $channelsState")
}
}
| isc | 9372a01b184bc0db8631f8a0d80004bf | 36.151515 | 157 | 0.75367 | 4.286713 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/extension/cap/handler/CapLsHandler.kt | 1 | 2020 | package chat.willow.warren.extension.cap.handler
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.extension.cap.CapMessage
import chat.willow.warren.IMessageSink
import chat.willow.warren.extension.cap.CapLifecycle
import chat.willow.warren.extension.cap.CapState
import chat.willow.warren.extension.cap.ICapManager
import chat.willow.warren.helper.loggerFor
class CapLsHandler(val capState: CapState, val sink: IMessageSink, val capManager: ICapManager) : KaleHandler<CapMessage.Ls.Message>(CapMessage.Ls.Message.Parser) {
private val LOGGER = loggerFor<CapLsHandler>()
override fun handle(message: CapMessage.Ls.Message, metadata: IMetadataStore) {
val caps = message.caps
val lifecycle = capState.lifecycle
capState.server += message.caps
LOGGER.trace("server supports following caps: $caps")
when (lifecycle) {
CapLifecycle.NEGOTIATING -> {
if (!message.isMultiline) {
val requestCaps = capState.server.keys.intersect(capState.negotiate)
val implicitlyRejectedCaps = capState.negotiate.subtract(requestCaps)
capState.rejected += implicitlyRejectedCaps
capManager.onRegistrationStateChanged()
if (!requestCaps.isEmpty()) {
LOGGER.trace("server gave us caps and ended with a non-multiline ls, requesting: $requestCaps, implicitly rejecting: $implicitlyRejectedCaps")
sink.write(CapMessage.Req.Command(caps = requestCaps.distinct()))
}
} else {
LOGGER.trace("server gave us a multiline cap ls, expecting more caps before ending")
}
message.caps.forEach { capManager.capValueSet(it.key, it.value) }
}
else -> LOGGER.trace("server told us about caps but we don't think we're negotiating")
}
}
}
| isc | e173fa8e4e621f2ea94bfaf487e27465 | 37.846154 | 166 | 0.661881 | 4.54955 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/smartspace/InterceptingViewPager.kt | 1 | 2243 | package app.lawnchair.smartspace
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.viewpager.widget.ViewPager
typealias EventProxy = (ev: MotionEvent) -> Boolean
class InterceptingViewPager @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
private var hasPerformedLongPress = false
private var hasPostedLongPress = false
private val longPressCallback = this::triggerLongPress
private val superOnIntercept: EventProxy = { super.onInterceptTouchEvent(it) }
private val superOnTouch: EventProxy = { super.onTouchEvent(it) }
private fun handleTouchOverride(ev: MotionEvent, proxy: EventProxy): Boolean {
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
hasPerformedLongPress = false
if (isLongClickable) {
cancelScheduledLongPress()
hasPostedLongPress = true
postDelayed(longPressCallback, ViewConfiguration.getLongPressTimeout().toLong())
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
cancelScheduledLongPress()
}
}
if (hasPerformedLongPress) {
cancelScheduledLongPress()
return true
}
if (proxy(ev)) {
cancelScheduledLongPress()
return true
}
return false
}
private fun triggerLongPress() {
hasPerformedLongPress = true
if (performLongClick()) {
parent.requestDisallowInterceptTouchEvent(true)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return handleTouchOverride(ev, superOnIntercept)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent): Boolean {
return handleTouchOverride(ev, superOnTouch)
}
private fun cancelScheduledLongPress() {
if (hasPostedLongPress) {
hasPostedLongPress = false
removeCallbacks(longPressCallback)
}
}
}
| gpl-3.0 | f7b1ab75b90141d1034e677db1478cd8 | 30.152778 | 100 | 0.653143 | 5.378897 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/psi/types/PyTypingNewType.kt | 1 | 2747 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.types
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.resolve.PyResolveUtil
data class PyTypingNewType(internal val classType: PyClassType, internal val isDefinition: Boolean, internal val myName: String?) : PyClassTypeImpl(
classType.pyClass, isDefinition) {
override fun getName() = myName
override fun getCallType(context: TypeEvalContext, callSite: PyCallSiteExpression): PyType? {
return PyTypingNewType(classType, false, name)
}
override fun toClass(): PyClassLikeType {
return if (isDefinition) this else PyTypingNewType(classType, true, name)
}
override fun toInstance(): PyClassType {
return if (isDefinition) PyTypingNewType(classType, false, name) else this
}
override fun isBuiltin() = false
override fun isCallable() = classType.isCallable || isDefinition
override fun toString() = "TypingNewType: " + myName
override fun getParameters(context: TypeEvalContext): List<PyCallableParameter>? {
return if (isCallable) {
listOf(PyCallableParameterImpl.nonPsi(null, classType.toInstance(), null))
}
else {
null
}
}
override fun getSuperClassTypes(context: TypeEvalContext): List<PyClassLikeType> = listOf(classType)
override fun getAncestorTypes(context: TypeEvalContext): List<PyClassLikeType> {
return listOf(classType) + classType.getAncestorTypes(context)
}
companion object {
private fun getImportedQualifiedName(referenceExpression: PyReferenceExpression): QualifiedName? {
val qualifier = referenceExpression.qualifier
if (qualifier is PyReferenceExpression) {
PyResolveUtil.resolveLocally(qualifier)
.filterIsInstance<PyImportElement>()
.firstOrNull { return it.importedQName?.append(referenceExpression.name) }
}
for (element in PyResolveUtil.resolveLocally(referenceExpression)) {
if (element is PyImportElement) {
val importStatement = element.containingImportStatement
if (importStatement is PyFromImportStatement) {
return importStatement.importSourceQName?.append(element.importedQName)
}
}
}
return null
}
fun isTypingNewType(callExpression: PyCallExpression): Boolean {
val calleeReference = callExpression.callee as? PyReferenceExpression ?: return false
return getImportedQualifiedName(calleeReference) == QualifiedName.fromDottedString(PyTypingTypeProvider.NEW_TYPE)
}
}
}
| apache-2.0 | 2223609b0e9986b3cc93a8a3b70d9771 | 37.690141 | 148 | 0.745905 | 4.914132 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/viewholder/EditTextTemplateViewHolder.kt | 1 | 1160 | package com.supercilex.robotscouter.feature.templates.viewholder
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.supercilex.robotscouter.core.data.model.update
import com.supercilex.robotscouter.core.model.Metric
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.shared.scouting.MetricViewHolderBase
import kotlinx.android.synthetic.main.scout_template_base_reorder.*
import kotlinx.android.synthetic.main.scout_template_notes.*
internal class EditTextTemplateViewHolder(
itemView: View
) : MetricViewHolderBase<Metric.Text, String?>(itemView),
MetricTemplateViewHolder<Metric.Text, String?> {
override val reorderView: ImageView by unsafeLazy { reorder }
override val nameEditor = name as EditText
init {
init()
text.onFocusChangeListener = this
}
override fun bind() {
super.bind()
text.setText(metric.value)
}
override fun onFocusChange(v: View, hasFocus: Boolean) {
super.onFocusChange(v, hasFocus)
if (!hasFocus && v === text) metric.update(text.text.toString())
}
}
| gpl-3.0 | 01b15b8e697edbf2c2845b35be258349 | 33.117647 | 72 | 0.74569 | 4.377358 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/browser/webview/WebViewFactoryUseCase.kt | 2 | 1172 | /*
* Copyright (c) 2020 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview
import android.content.Context
import android.webkit.WebView
import jp.toastkid.yobidashi.browser.webview.factory.WebChromeClientFactory
import jp.toastkid.yobidashi.browser.webview.factory.WebViewClientFactory
import jp.toastkid.yobidashi.browser.webview.factory.WebViewFactory
internal class WebViewFactoryUseCase(
private val webViewFactory: WebViewFactory = WebViewFactory(),
private val webViewClientFactory: WebViewClientFactory,
private val webChromeClientFactory: WebChromeClientFactory = WebChromeClientFactory()
) {
operator fun invoke(context: Context): WebView {
val webView = webViewFactory.make(context)
webView.webViewClient = webViewClientFactory.invoke()
webView.webChromeClient = webChromeClientFactory.invoke()
return webView
}
} | epl-1.0 | 7c5e3a2e0ada1f9257288bf37be86ca0 | 38.1 | 93 | 0.780717 | 4.842975 | false | false | false | false |
roylanceMichael/yaorm | yaorm/src/main/java/org/roylance/yaorm/services/sqlserver/SQLServerConnectionSourceFactory.kt | 1 | 3664 | package org.roylance.yaorm.services.sqlserver
import org.roylance.yaorm.services.IConnectionSourceFactory
import java.sql.*
class SQLServerConnectionSourceFactory(val host:String,
val schema:String,
val userName:String,
val password:String,
val port:Int = 1433,
createDatabaseIfNotExists: Boolean = true,
private val isAzure: Boolean = false): IConnectionSourceFactory {
private val SQLServerClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
private val SQLServerJDBCString: String
private val actualReadConnection: Connection
private val actualWriteConnection: Connection
private var isClosed: Boolean = false
init {
Class.forName(SQLServerClassName)
if (createDatabaseIfNotExists) {
this.createSchemaIfNotExists()
}
this.SQLServerJDBCString = buildConnectionString(host, port, schema, userName, password, isAzure, true)
this.actualReadConnection = DriverManager.getConnection(SQLServerJDBCString)
this.actualWriteConnection = DriverManager.getConnection(SQLServerJDBCString)
}
override val readConnection: Connection
get() {
if (this.isClosed) {
throw SQLException("already closed...")
}
return this.actualReadConnection
}
override val writeConnection: Connection
get() {
if (this.isClosed) {
throw SQLException("already closed...")
}
return this.actualWriteConnection
}
override fun generateReadStatement(): Statement {
val statement = this.readConnection.createStatement()
return statement
}
override fun generateUpdateStatement(): Statement {
return this.writeConnection.createStatement()
}
override fun close() {
if (!this.isClosed) {
this.readConnection.close()
this.writeConnection.close()
}
}
private fun createSchemaIfNotExists() {
val tempConnection = DriverManager.getConnection(buildConnectionString(host, port, schema, userName, password, isAzure, false))
val statement = tempConnection.createStatement()
try {
statement.executeUpdate("""if not exists(select * from sys.databases where name = '$schema')
create database $schema""")
}
finally {
statement?.close()
tempConnection?.close()
}
}
companion object {
fun buildConnectionString(host: String, port: Int, schema: String, userName: String, password: String, isAzure: Boolean, includeDatabase: Boolean): String {
if (isAzure && includeDatabase) {
return "jdbc:sqlserver://$host:$port;database=$schema;user=$userName;password=$password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
}
else if (isAzure) {
return "jdbc:sqlserver://$host:$port;user=$userName;password=$password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
}
else if (includeDatabase) {
return "jdbc:sqlserver://$host:$port;database=$schema;user=$userName;password=$password;loginTimeout=30;"
}
return "jdbc:sqlserver://$host:$port;user=$userName;password=$password;loginTimeout=30;"
}
}
} | mit | b975eb2ae726d8b4d1965f49a415eac0 | 40.179775 | 208 | 0.624727 | 5.256815 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/ui/controllers/UploadLogController.kt | 1 | 3669 | package cs.ut.ui.controllers
import cs.ut.configuration.ConfigurationReader
import cs.ut.providers.Dir
import cs.ut.providers.DirectoryConfiguration
import cs.ut.ui.controllers.modal.ParameterModalController.Companion.FILE
import cs.ut.util.NirdizatiInputStream
import cs.ut.util.NirdizatiReader
import org.apache.commons.io.FilenameUtils
import org.apache.logging.log4j.LogManager
import org.zkoss.util.media.Media
import org.zkoss.util.resource.Labels
import org.zkoss.zk.ui.Component
import org.zkoss.zk.ui.Executions
import org.zkoss.zk.ui.event.UploadEvent
import org.zkoss.zk.ui.select.SelectorComposer
import org.zkoss.zk.ui.select.annotation.Listen
import org.zkoss.zk.ui.select.annotation.Wire
import org.zkoss.zul.Button
import org.zkoss.zul.Label
import org.zkoss.zul.Vbox
import org.zkoss.zul.Window
import java.io.File
class UploadLogController : SelectorComposer<Component>(), Redirectable {
private val log = LogManager.getLogger(UploadLogController::class.java)
@Wire
private lateinit var fileName: Label
@Wire
private lateinit var upload: Button
@Wire
private lateinit var fileNameCont: Vbox
private lateinit var media: Media
private val allowedExtensions = ConfigurationReader.findNode("fileUpload/extensions").itemListValues()
/**
* Method that analyzes uploaded file. Checks that the file has required extension.
*
* @param event upload event where media should be retrieved from
*/
@Listen("onUpload = #chooseFile, #dropArea")
fun analyzeFile(event: UploadEvent) {
upload.isDisabled = true
log.debug("Upload event. Analyzing file")
val uploaded = event.media ?: return
if (FilenameUtils.getExtension(uploaded.name) in allowedExtensions) {
log.debug("Log is in allowed format")
fileNameCont.sclass = "file-upload"
fileName.value = uploaded.name
media = uploaded
upload.isDisabled = false
} else {
log.debug("Log is not in allowed format -> showing error")
fileNameCont.sclass = "file-upload-err"
fileName.value = Labels.getLabel(
"upload.wrong.format",
arrayOf(uploaded.name, FilenameUtils.getExtension(uploaded.name))
)
upload.isDisabled = true
}
}
/**
* Listener - user log has been accepted and now we need to generate data set parameters for it
*/
@Listen("onClick = #upload")
fun processLog() {
val runnable = Runnable {
val tmpDir = DirectoryConfiguration.dirPath(Dir.TMP_DIR)
val file = File(tmpDir + media.name.replace(File.separator, "_"))
log.debug("Creating file: ${file.absolutePath}")
file.createNewFile()
val uploadItem = if (media.isBinary) NirdizatiInputStream(media.streamData) else NirdizatiReader(media.readerData)
uploadItem.write(file)
val args = mapOf(FILE to file)
// Detach all of the old windows
self.getChildren<Component>()
.asSequence()
.filter { it is Window }
.forEach { it.detach() }
val window: Window = Executions.createComponents(
"/views/modals/params.zul",
self,
args
) as Window
if (self.getChildren<Component>().contains(window)) {
window.doModal()
upload.isDisabled = true
}
}
runnable.run()
log.debug("Started training file generation thread")
}
}
| lgpl-3.0 | fe710c04c7d7e650d037821c97baa651 | 33.942857 | 126 | 0.648678 | 4.441889 | false | false | false | false |
xiaopansky/Sketch | sample-video-thumbnail/src/main/java/me/panpf/sketch/sample/vt/ui/VideoListFragment.kt | 1 | 6507 | /*
* Copyright (C) 2019 Peng fei Pan <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.panpf.sketch.sample.vt.ui
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.view.setPadding
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.fragment_recycler.*
import me.panpf.adapter.paged.AssemblyPagedListAdapter
import me.panpf.androidxkt.arch.bindViewModel
import me.panpf.androidxkt.util.dp2px
import me.panpf.androidxkt.widget.showLongToast
import me.panpf.sketch.sample.vt.BaseFragment
import me.panpf.sketch.sample.vt.BindContentView
import me.panpf.sketch.sample.vt.R
import me.panpf.sketch.sample.vt.bean.BoundaryStatus
import me.panpf.sketch.sample.vt.bean.VideoInfo
import me.panpf.sketch.sample.vt.item.LoadMoreItemFactory
import me.panpf.sketch.sample.vt.item.VideoInfoItemFactory
import me.panpf.sketch.sample.vt.vm.VideoListViewModel
import java.io.File
@BindContentView(R.layout.fragment_recycler)
class VideoListFragment : BaseFragment() {
private val videoListViewModel: VideoListViewModel by bindViewModel(VideoListViewModel::class)
private val adapter = AssemblyPagedListAdapter<VideoInfo>(VideoInfo.DiffCallback()).apply {
addItemFactory(VideoInfoItemFactory().setOnItemClickListener { _, _, _, _, data ->
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(Uri.fromFile(File(data?.path)), data?.mimeType)
}
try {
startActivity(intent)
} catch (e: Throwable) {
e.printStackTrace()
showLongToast("Not found can play video app")
}
})
setMoreItem(LoadMoreItemFactory())
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerFragment_contentRecycler.apply {
setPadding(checkNotNull(context).dp2px(2))
clipToPadding = false
layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
[email protected] = [email protected]
}
recyclerFragment_refreshLayout.apply { setOnRefreshListener { videoListViewModel.refresh() } }
// recyclerFragment_refreshLayout.apply { setOnRefreshListener {
// videoListViewModel.getVideoListing(true).observe(this@VideoListFragment, Observer {
// adapter.submitList(it)
// })
// } }
videoListViewModel.getVideoListing().observe(this, Observer { adapter.submitList(it) })
videoListViewModel.initStatus.observe(this, Observer { initStatus ->
initStatus ?: return@Observer
if (recyclerFragment_refreshLayout.isRefreshing) {
when {
initStatus.isLoading() -> {
recyclerFragment_loadingText.visibility = View.GONE
}
initStatus.isError() -> {
recyclerFragment_refreshLayout.isRefreshing = false
recyclerFragment_loadingText.text = getString(R.string.hint_loadFailed, initStatus.message)
recyclerFragment_loadingText.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_error, 0, 0)
recyclerFragment_loadingText.visibility = View.VISIBLE
}
initStatus.isSuccess() -> {
recyclerFragment_refreshLayout.isRefreshing = false
if (videoListViewModel.boundaryStatus.value == BoundaryStatus.ZERO_ITEMS_LOADED) {
recyclerFragment_loadingText.text = getString(R.string.hint_empty_list, "Video")
recyclerFragment_loadingText.visibility = View.VISIBLE
} else {
recyclerFragment_loadingText.visibility = View.GONE
}
}
}
} else {
when {
initStatus.isLoading() -> {
recyclerFragment_loadingText.setText(R.string.hint_loading)
recyclerFragment_loadingText.setCompoundDrawables(null, null, null, null)
recyclerFragment_loadingText.visibility = View.VISIBLE
}
initStatus.isError() -> {
recyclerFragment_loadingText.text = getString(R.string.hint_loadFailed, initStatus.message)
recyclerFragment_loadingText.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_error, 0, 0)
recyclerFragment_loadingText.visibility = View.VISIBLE
}
initStatus.isSuccess() -> {
if (videoListViewModel.boundaryStatus.value == BoundaryStatus.ZERO_ITEMS_LOADED) {
recyclerFragment_loadingText.text = getString(R.string.hint_empty_list, "Video")
recyclerFragment_loadingText.visibility = View.VISIBLE
} else {
recyclerFragment_loadingText.visibility = View.GONE
}
}
}
}
})
videoListViewModel.pagingStatus.observe(this, Observer { pagingStatus ->
pagingStatus ?: return@Observer
when {
pagingStatus.isLoading() -> {
adapter.loadMoreFinished(false)
}
pagingStatus.isError() -> {
adapter.loadMoreFailed()
}
}
})
videoListViewModel.boundaryStatus.observe(this, Observer {
if (it == BoundaryStatus.ITEM_AT_END_LOADED) {
adapter.loadMoreFinished(true)
}
})
}
}
| apache-2.0 | 3c48008013569126c6eb09f4985e017c | 42.092715 | 122 | 0.617028 | 5.036378 | false | false | false | false |
ankidroid/Anki-Android | api/src/main/java/com/ichi2/anki/api/AddContentApi.kt | 1 | 33948 | /***************************************************************************************
* *
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* Copyright (c) 2016 Mark Carter <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.api
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Process
import android.text.TextUtils
import android.util.SparseArray
import com.ichi2.anki.FlashCardsContract
import com.ichi2.anki.FlashCardsContract.AnkiMedia
import com.ichi2.anki.FlashCardsContract.Card
import com.ichi2.anki.FlashCardsContract.CardTemplate
import com.ichi2.anki.FlashCardsContract.Deck
import com.ichi2.anki.FlashCardsContract.Model
import com.ichi2.anki.FlashCardsContract.Note
import java.io.File
import java.util.*
/**
* API which can be used to add and query notes,cards,decks, and models to AnkiDroid
*
* On Android M (and higher) the #READ_WRITE_PERMISSION is required for all read/write operations.
* On earlier SDK levels, the #READ_WRITE_PERMISSION is currently only required for update/delete operations but
* this may be extended to all operations at a later date.
*/
public class AddContentApi(context: Context) {
private val mContext: Context = context.applicationContext
private val mResolver: ContentResolver = mContext.contentResolver
/**
* Create a new note with specified fields, tags, and model and place it in the specified deck.
* No duplicate checking is performed - so the note should be checked beforehand using #findNotesByKeys
* @param modelId ID for the model used to add the notes
* @param deckId ID for the deck the cards should be stored in (use #DEFAULT_DECK_ID for default deck)
* @param fields fields to add to the note. Length should be the same as number of fields in model
* @param tags tags to include in the new note
* @return note id or null if the note could not be added
*/
public fun addNote(modelId: Long, deckId: Long, fields: Array<String>, tags: Set<String>?): Long? {
val noteUri = addNoteInternal(modelId, deckId, fields, tags) ?: return null
return noteUri.lastPathSegment!!.toLong()
}
private fun addNoteInternal(
modelId: Long,
deckId: Long,
fields: Array<String>,
tags: Set<String>?
): Uri? {
val values = ContentValues().apply {
put(Note.MID, modelId)
put(Note.FLDS, Utils.joinFields(fields))
if (tags != null) put(Note.TAGS, Utils.joinTags(tags))
}
return addNoteForContentValues(deckId, values)
}
private fun addNoteForContentValues(deckId: Long, values: ContentValues): Uri? {
val newNoteUri = mResolver.insert(Note.CONTENT_URI, values) ?: return null
// Move cards to specified deck
val cardsUri = Uri.withAppendedPath(newNoteUri, "cards")
val cardsQuery = mResolver.query(cardsUri, null, null, null, null) ?: return null
cardsQuery.use { cardsCursor ->
while (cardsCursor.moveToNext()) {
val ord = cardsCursor.getString(cardsCursor.getColumnIndex(Card.CARD_ORD))
val cardValues = ContentValues().apply { put(Card.DECK_ID, deckId) }
val cardUri = Uri.withAppendedPath(Uri.withAppendedPath(newNoteUri, "cards"), ord)
mResolver.update(cardUri, cardValues, null, null)
}
}
return newNoteUri
}
/**
* Create new notes with specified fields, tags and model and place them in the specified deck.
* No duplicate checking is performed - so all notes should be checked beforehand using #findNotesByKeys
* @param modelId id for the model used to add the notes
* @param deckId id for the deck the cards should be stored in (use #DEFAULT_DECK_ID for default deck)
* @param fieldsList List of fields arrays (one per note). Array lengths should be same as number of fields in model
* @param tagsList List of tags (one per note) (may be null)
* @return The number of notes added (<0 means there was a problem)
*/
public fun addNotes(
modelId: Long,
deckId: Long,
fieldsList: List<Array<String>>,
tagsList: List<Set<String>?>?
): Int {
require(!(tagsList != null && fieldsList.size != tagsList.size)) { "fieldsList and tagsList different length" }
val newNoteValuesList: MutableList<ContentValues> = ArrayList(fieldsList.size)
for (i in fieldsList.indices) {
val values = ContentValues().apply {
put(Note.MID, modelId)
put(Note.FLDS, Utils.joinFields(fieldsList[i]))
if (tagsList != null && tagsList[i] != null) {
put(Note.TAGS, Utils.joinTags(tagsList[i]))
}
}
newNoteValuesList.add(values)
}
// Add the notes to the content provider and put the new note ids into the result array
return if (newNoteValuesList.isEmpty()) {
0
} else compat.insertNotes(deckId, newNoteValuesList.toTypedArray())
}
/**
* Add a media file to AnkiDroid's media collection. You would likely supply this uri through a FileProvider, and
* then set FLAG_GRANT_READ_URI_PERMISSION using something like:
*
* ```
* getContext().grantUriPermission("com.ichi2.anki", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
* // Then when file is added, remove the permission
* // add File ...
* getContext().revokePermission(uri, Intent.FLAG_GRAN_READ_URI_PERMISSION)
* ```
*
* Example usage:
* ```
* Long modelId = getModelId(); // implementation can be seen in api sample app
* Long deckId = getDeckId(); // as above
* Set<String> tags = getTags(); // as above
* Uri fileUri = ... // this will be returned by a File Picker activity where we select an image file
* String addedImageFileName = mApi.addMediaFromUri(fileUri, "My_Image_File", "image");
*
* String[] fields = new String[] {"text on front of card", "text on back of card " + addedImageFileName};
* mApi.addNote(modelId, deckId, fields, tags)
* ```
*
* @param fileUri Uri for the file to be added, required.
* @param preferredName String to add to start of filename (do not use a file extension), required.
* @param mimeType String indicating the mimeType of the media. Accepts "audio" or "image", required.
* @return the correctly formatted String for the media file to be placed in the desired field of a Card, or null
* if unsuccessful.
*/
public fun addMediaFromUri(
fileUri: Uri,
preferredName: String,
mimeType: String
): String? {
val contentValues = ContentValues().apply {
put(AnkiMedia.FILE_URI, fileUri.toString())
put(AnkiMedia.PREFERRED_NAME, preferredName.replace(" ", "_"))
}
return try {
val returnUri = mResolver.insert(AnkiMedia.CONTENT_URI, contentValues)
// get the filename from Uri, return [sound:%s] % file.getName()
val fname = File(returnUri!!.path!!).toString()
formatMediaName(fname, mimeType)
} catch (e: Exception) {
null
}
}
private fun formatMediaName(fname: String, mimeType: String): String? = when (mimeType) {
"audio" -> "[sound:${fname.substring(1)}]" // first character in the path is "/"
"image" -> "<img src=\"${fname.substring(1)}\" />"
else -> null // something went wrong
}
/**
* Find all existing notes in the collection which have mid and a duplicate key
* @param mid model id
* @param key the first field of a note
* @return a list of duplicate notes
*/
public fun findDuplicateNotes(mid: Long, key: String): List<NoteInfo?> {
val notes = compat.findDuplicateNotes(mid, listOf(key))
return if (notes!!.size() == 0) {
emptyList<NoteInfo>()
} else notes.valueAt(0)
}
/**
* Find all notes in the collection which have mid and a first field that matches key
* Much faster than calling findDuplicateNotes(long, String) when the list of keys is large
* @param mid model id
* @param keys list of keys
* @return a SparseArray with a list of duplicate notes for each key
*/
public fun findDuplicateNotes(mid: Long, keys: List<String>): SparseArray<MutableList<NoteInfo?>>? {
return compat.findDuplicateNotes(mid, keys)
}
/**
* Get the number of notes that exist for the specified model ID
* @param mid id of the model to be used
* @return number of notes that exist with that model ID or -1 if there was a problem
*/
public fun getNoteCount(mid: Long): Int = compat.queryNotes(mid)?.use { cursor -> cursor.count } ?: 0
/**
* Set the tags for a given note
* @param noteId the ID of the note to update
* @param tags set of tags
* @return true if noteId was found, otherwise false
* @throws SecurityException if READ_WRITE_PERMISSION not granted (e.g. due to install order bug)
*/
public fun updateNoteTags(noteId: Long, tags: Set<String>): Boolean {
return updateNote(noteId, null, tags)
}
/**
* Set the fields for a given note
* @param noteId the ID of the note to update
* @param fields array of fields
* @return true if noteId was found, otherwise false
* @throws SecurityException if READ_WRITE_PERMISSION not granted (e.g. due to install order bug)
*/
public fun updateNoteFields(noteId: Long, fields: Array<String>): Boolean {
return updateNote(noteId, fields, null)
}
/**
* Get the contents of a note with known ID
* @param noteId the ID of the note to find
* @return object containing the contents of note with noteID or null if there was a problem
*/
public fun getNote(noteId: Long): NoteInfo? {
val noteUri = Uri.withAppendedPath(Note.CONTENT_URI, noteId.toString())
val query = mResolver.query(noteUri, PROJECTION, null, null, null) ?: return null
return query.use { cursor ->
if (!cursor.moveToNext()) {
null
} else NoteInfo.buildFromCursor(cursor)
}
}
private fun updateNote(noteId: Long, fields: Array<String>?, tags: Set<String?>?): Boolean {
val contentUri = Note.CONTENT_URI.buildUpon().appendPath(noteId.toString()).build()
val values = ContentValues().apply {
if (fields != null) put(Note.FLDS, Utils.joinFields(fields))
if (tags != null) put(Note.TAGS, Utils.joinTags(tags))
}
val numRowsUpdated = mResolver.update(contentUri, values, null, null)
// provider doesn't check whether fields actually changed, so just returns number of notes with id == noteId
return numRowsUpdated > 0
}
/**
* Get the html that would be generated for the specified note type and field list
* @param flds array of field values for the note. Length must be the same as num. fields in mid.
* @param mid id for the note type to be used
* @return list of front & back pairs for each card which contain the card HTML, or null if there was a problem
* @throws SecurityException if READ_WRITE_PERMISSION not granted (e.g. due to install order bug)
*/
public fun previewNewNote(mid: Long, flds: Array<String>): Map<String, Map<String, String>>? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && !hasReadWritePermission()) {
// avoid situation where addNote will pass, but deleteNote will fail
throw SecurityException("previewNewNote requires full read-write-permission")
}
val newNoteUri = addNoteInternal(mid, DEFAULT_DECK_ID, flds, setOf(TEST_TAG))
// Build map of HTML for each generated card
val cards: MutableMap<String, Map<String, String>> = HashMap()
val cardsUri = Uri.withAppendedPath(newNoteUri, "cards")
val cardsQuery = mResolver.query(cardsUri, null, null, null, null) ?: return null
cardsQuery.use { cardsCursor ->
while (cardsCursor.moveToNext()) {
// add question and answer for each card to map
val n = cardsCursor.getString(cardsCursor.getColumnIndex(Card.CARD_NAME))
val q = cardsCursor.getString(cardsCursor.getColumnIndex(Card.QUESTION))
val a = cardsCursor.getString(cardsCursor.getColumnIndex(Card.ANSWER))
cards[n] = hashMapOf(
"q" to q,
"a" to a,
)
}
}
// Delete the note
mResolver.delete(newNoteUri!!, null, null)
return cards
}
/**
* Insert a new basic front/back model with two fields and one card
* @param name name of the model
* @return the mid of the model which was created, or null if it could not be created
*/
public fun addNewBasicModel(name: String): Long? {
return addNewCustomModel(
name, BasicModel.FIELDS, BasicModel.CARD_NAMES, BasicModel.QFMT,
BasicModel.AFMT, null, null, null
)
}
/**
* Insert a new basic front/back model with two fields and TWO cards
* The first card goes from front->back, and the second goes from back->front
* @param name name of the model
* @return the mid of the model which was created, or null if it could not be created
*/
public fun addNewBasic2Model(name: String): Long? {
return addNewCustomModel(
name, Basic2Model.FIELDS, Basic2Model.CARD_NAMES, Basic2Model.QFMT,
Basic2Model.AFMT, null, null, null
)
}
/**
* Insert a new model into AnkiDroid.
* See the [Anki Desktop Manual](https://docs.ankiweb.net/templates/intro.html) for more help
* @param name name of model
* @param fields array of field names
* @param cards array of names for the card templates
* @param qfmt array of formatting strings for the question side of each template in cards
* @param afmt array of formatting strings for the answer side of each template in cards
* @param css css styling information to be shared across all of the templates. Use null for default CSS.
* @param did default deck to add cards to when using this model. Use null or #DEFAULT_DECK_ID for default deck.
* @param sortf index of field to be used for sorting. Use null for unspecified (unsupported in provider spec v1)
* @return the mid of the model which was created, or null if it could not be created
*/
@Suppress("MemberVisibilityCanBePrivate") // silence IDE
public fun addNewCustomModel(
name: String,
fields: Array<String>,
cards: Array<String>,
qfmt: Array<String>,
afmt: Array<String>,
css: String?,
did: Long?,
sortf: Int?
): Long? {
// Check that size of arrays are consistent
require(!(qfmt.size != cards.size || afmt.size != cards.size)) { "cards, qfmt, and afmt arrays must all be same length" }
// Create the model using dummy templates
var values = ContentValues().apply {
put(Model.NAME, name)
put(Model.FIELD_NAMES, Utils.joinFields(fields))
put(Model.NUM_CARDS, cards.size)
put(Model.CSS, css)
put(Model.DECK_ID, did)
put(Model.SORT_FIELD_INDEX, sortf)
}
val modelUri = mResolver.insert(Model.CONTENT_URI, values) ?: return null
// Set the remaining template parameters
val templatesUri = Uri.withAppendedPath(modelUri, "templates")
for (i in cards.indices) {
val uri = Uri.withAppendedPath(templatesUri, i.toString())
values = ContentValues().apply {
put(CardTemplate.NAME, cards[i])
put(CardTemplate.QUESTION_FORMAT, qfmt[i])
put(CardTemplate.ANSWER_FORMAT, afmt[i])
put(CardTemplate.ANSWER_FORMAT, afmt[i])
}
mResolver.update(uri, values, null, null)
}
return modelUri.lastPathSegment!!.toLong()
} // Get the current model
/**
* Get the ID for the note type / model which is currently in use
* @return id for current model, or <0 if there was a problem
*/
public val currentModelId: Long
get() {
// Get the current model
val uri = Uri.withAppendedPath(Model.CONTENT_URI, Model.CURRENT_MODEL_ID)
val singleModelQuery = mResolver.query(uri, null, null, null, null) ?: return -1L
return singleModelQuery.use { singleModelCursor ->
singleModelCursor.moveToFirst()
singleModelCursor.getLong(singleModelCursor.getColumnIndex(Model._ID))
}
}
/**
* Get the field names belonging to specified model
* @param modelId the ID of the model to use
* @return the names of all the fields, or null if the model doesn't exist or there was some other problem
*/
public fun getFieldList(modelId: Long): Array<String>? {
// Get the current model
val uri = Uri.withAppendedPath(Model.CONTENT_URI, modelId.toString())
val modelQuery = mResolver.query(uri, null, null, null, null) ?: return null
var splitFlds: Array<String>? = null
modelQuery.use { modelCursor ->
if (modelCursor.moveToNext()) {
splitFlds = Utils.splitFields(
modelCursor.getString(modelCursor.getColumnIndex(Model.FIELD_NAMES))
)
}
}
return splitFlds
}
/**
* Get a map of all model ids and names
* @return map of (id, name) pairs
*/
public val modelList: Map<Long, String>?
get() = getModelList(1)
/**
* Get a map of all model ids and names with number of fields larger than minNumFields
* @param minNumFields minimum number of fields to consider the model for inclusion
* @return map of (id, name) pairs or null if there was a problem
*/
public fun getModelList(minNumFields: Int): Map<Long, String>? {
// Get the current model
val allModelsQuery =
mResolver.query(Model.CONTENT_URI, null, null, null, null)
?: return null
val models: MutableMap<Long, String> = HashMap()
allModelsQuery.use { allModelsCursor ->
while (allModelsCursor.moveToNext()) {
val modelId = allModelsCursor.getLong(allModelsCursor.getColumnIndex(Model._ID))
val name = allModelsCursor.getString(allModelsCursor.getColumnIndex(Model.NAME))
val flds =
allModelsCursor.getString(allModelsCursor.getColumnIndex(Model.FIELD_NAMES))
val numFlds: Int = Utils.splitFields(flds).size
if (numFlds >= minNumFields) {
models[modelId] = name
}
}
}
return models
}
/**
* Get the name of the model which has given ID
* @param mid id of model
* @return the name of the model, or null if no model was found
*/
public fun getModelName(mid: Long): String? = modelList!![mid]
/**
* Create a new deck with specified name and save the reference to SharedPreferences for later
* @param deckName name of the deck to add
* @return id of the added deck, or null if the deck was not added
*/
public fun addNewDeck(deckName: String): Long? {
// Create a new note
val values = ContentValues().apply { put(Deck.DECK_NAME, deckName) }
val newDeckUri = mResolver.insert(Deck.CONTENT_ALL_URI, values)
return if (newDeckUri != null) {
newDeckUri.lastPathSegment!!.toLong()
} else {
null
}
}
/**
* Get the name of the selected deck
* @return deck name or null if there was a problem
*/
public val selectedDeckName: String?
get() {
val selectedDeckQuery = mResolver.query(
Deck.CONTENT_SELECTED_URI,
null,
null,
null,
null
) ?: return null
return selectedDeckQuery.use { selectedDeckCursor ->
if (selectedDeckCursor.moveToNext()) {
selectedDeckCursor.getString(selectedDeckCursor.getColumnIndex(Deck.DECK_NAME))
} else null
}
} // Get the current model
/**
* Get a list of all the deck id / name pairs
* @return Map of (id, name) pairs, or null if there was a problem
*/
public val deckList: Map<Long, String>?
get() {
// Get the current model
val allDecksQuery =
mResolver.query(Deck.CONTENT_ALL_URI, null, null, null, null) ?: return null
val decks: MutableMap<Long, String> = HashMap()
allDecksQuery.use { allDecksCursor ->
while (allDecksCursor.moveToNext()) {
val deckId = allDecksCursor.getLong(allDecksCursor.getColumnIndex(Deck.DECK_ID))
val name =
allDecksCursor.getString(allDecksCursor.getColumnIndex(Deck.DECK_NAME))
decks[deckId] = name
}
}
return decks
}
/**
* Get the name of the deck which has given ID
* @param did ID of deck
* @return the name of the deck, or null if no deck was found
*/
public fun getDeckName(did: Long): String? = deckList!![did]
/**
* The API spec version of the installed AnkiDroid app. This is not the same as the AnkiDroid app version code.
*
* SPEC VERSION 1: (AnkiDroid 2.5)
* #addNotes is very slow for large numbers of notes
* #findDuplicateNotes is very slow for large numbers of keys
* #addNewCustomModel is not persisted properly
* #addNewCustomModel does not support #sortf argument
*
* SPEC VERSION 2: (AnkiDroid 2.6)
*
* @return the spec version number or -1 if AnkiDroid is not installed.
*/
@Suppress("deprecation") // API33 symbol required until minSdkVersion >= 33
public val apiHostSpecVersion: Int
get() {
// PackageManager#resolveContentProvider docs suggest flags should be 0 (but that gives null metadata)
// GET_META_DATA seems to work anyway
val info =
if (Build.VERSION.SDK_INT >= 33)
mContext.packageManager.resolveContentProvider(
FlashCardsContract.AUTHORITY,
PackageManager.ComponentInfoFlags.of(
PackageManager.GET_META_DATA.toLong()
)
)
else
mContext.packageManager.resolveContentProvider(
FlashCardsContract.AUTHORITY,
PackageManager.GET_META_DATA
)
return if (info?.metaData != null && info.metaData.containsKey(
PROVIDER_SPEC_META_DATA_KEY
)
) {
info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY)
} else {
DEFAULT_PROVIDER_SPEC_VALUE
}
}
private fun hasReadWritePermission(): Boolean =
mContext.checkPermission(
READ_WRITE_PERMISSION,
Process.myPid(),
Process.myUid()
) == PackageManager.PERMISSION_GRANTED
/**
* Best not to store this in case the user updates AnkiDroid app while client app is staying alive
*/
private val compat: Compat
get() = if (apiHostSpecVersion < 2) CompatV1() else CompatV2()
private interface Compat {
/**
* Query all notes for a given model
* @param modelId the model ID to limit query to
* @return a cursor with all notes matching modelId
*/
fun queryNotes(modelId: Long): Cursor?
/**
* Add new notes to the AnkiDroid content provider in bulk.
* @param deckId the deck ID to put the cards in
* @param valuesArr the content values ready for bulk insertion into the content provider
* @return the number of successful entries
*/
fun insertNotes(deckId: Long, valuesArr: Array<ContentValues>): Int
/**
* For each key, look for an existing note that has matching first field
* @param modelId the model ID to limit the search to
* @param keys list of keys for each note
* @return array with a list of NoteInfo objects for each key if duplicates exist
*/
fun findDuplicateNotes(
modelId: Long,
keys: List<String?>
): SparseArray<MutableList<NoteInfo?>>?
}
private open inner class CompatV1 : Compat {
override fun queryNotes(modelId: Long): Cursor? {
val modelName = getModelName(modelId) ?: return null
val queryFormat = "note:\"$modelName\""
return mResolver.query(
Note.CONTENT_URI,
PROJECTION,
queryFormat,
null,
null
)
}
override fun insertNotes(deckId: Long, valuesArr: Array<ContentValues>): Int =
valuesArr.count { addNoteForContentValues(deckId, it) != null }
override fun findDuplicateNotes(
modelId: Long,
keys: List<String?>
): SparseArray<MutableList<NoteInfo?>>? {
// Content provider spec v1 does not support direct querying of the notes table, so use Anki browser syntax
val modelName = getModelName(modelId) ?: return null
val modelFieldList = getFieldList(modelId) ?: return null
val duplicates = SparseArray<MutableList<NoteInfo?>>()
// Loop through each item in fieldsArray looking for an existing note, and add it to the duplicates array
val queryFormat = "${modelFieldList[0]}:\"%%s\" note:\"$modelName\""
for (outputPos in keys.indices) {
val selection = String.format(queryFormat, keys[outputPos])
val query = mResolver.query(
Note.CONTENT_URI,
PROJECTION,
selection,
null,
null
) ?: continue
query.use { cursor ->
while (cursor.moveToNext()) {
addNoteToDuplicatesArray(
NoteInfo.buildFromCursor(cursor),
duplicates,
outputPos
)
}
}
}
return duplicates
}
/** Add a NoteInfo object to the given duplicates SparseArray at the specified position */
protected fun addNoteToDuplicatesArray(
note: NoteInfo?,
duplicates: SparseArray<MutableList<NoteInfo?>>,
position: Int
) {
val sparseArrayIndex = duplicates.indexOfKey(position)
if (sparseArrayIndex < 0) {
// No existing NoteInfo objects mapping to same key as the current note so add a new List
duplicates.put(position, mutableListOf(note))
} else { // Append note to existing list of duplicates for key
duplicates.valueAt(sparseArrayIndex).add(note)
}
}
}
private inner class CompatV2 : CompatV1() {
override fun queryNotes(modelId: Long): Cursor? {
return mResolver.query(
Note.CONTENT_URI_V2, PROJECTION,
String.format(Locale.US, "%s=%d", Note.MID, modelId),
null, null
)
}
override fun insertNotes(deckId: Long, valuesArr: Array<ContentValues>): Int {
val builder = Note.CONTENT_URI.buildUpon().appendQueryParameter(
Note.DECK_ID_QUERY_PARAM,
deckId.toString()
)
return mResolver.bulkInsert(builder.build(), valuesArr)
}
override fun findDuplicateNotes(
modelId: Long,
keys: List<String?>
): SparseArray<MutableList<NoteInfo?>>? {
// Build set of checksums and a HashMap from the key (first field) back to the original index in fieldsArray
val csums: MutableSet<Long?> = HashSet(keys.size)
val keyToIndexesMap: MutableMap<String?, MutableList<Int>> = HashMap(keys.size)
for (i in keys.indices) {
val key = keys[i]
csums.add(Utils.fieldChecksum(key!!))
if (!keyToIndexesMap.containsKey(key)) { // Use a list as some keys could potentially be duplicated
keyToIndexesMap[key] = ArrayList()
}
keyToIndexesMap[key]!!.add(i)
}
// Query for notes that have specified model and checksum of first field matches
val sel = String.format(
Locale.US,
"%s=%d and %s in (%s)",
Note.MID,
modelId,
Note.CSUM,
TextUtils.join(",", csums)
)
val notesTableQuery = mResolver.query(
Note.CONTENT_URI_V2,
PROJECTION,
sel,
null,
null
) ?: return null
// Loop through each note in the cursor, building the result array of duplicates
val duplicates = SparseArray<MutableList<NoteInfo?>>()
notesTableQuery.use { notesTableCursor ->
while (notesTableCursor.moveToNext()) {
val note = NoteInfo.buildFromCursor(notesTableCursor) ?: continue
if (keyToIndexesMap.containsKey(note.getKey())) { // skip notes that match csum but not key
// Add copy of note to EVERY position in duplicates array corresponding to the current key
val outputPos: List<Int> = keyToIndexesMap[note.getKey()]!!
for (i in outputPos.indices) {
addNoteToDuplicatesArray(
if (i > 0) NoteInfo(note) else note,
duplicates,
outputPos[i]
)
}
}
}
}
return duplicates
}
}
public companion object {
public const val READ_WRITE_PERMISSION: String = FlashCardsContract.READ_WRITE_PERMISSION
public const val DEFAULT_DECK_ID: Long = 1L
private const val TEST_TAG = "PREVIEW_NOTE"
private const val PROVIDER_SPEC_META_DATA_KEY = "com.ichi2.anki.provider.spec"
private const val DEFAULT_PROVIDER_SPEC_VALUE = 1 // for when meta-data key does not exist
private val PROJECTION = arrayOf(
Note._ID,
Note.FLDS,
Note.TAGS
)
/**
* Get the AnkiDroid package name that the API will communicate with.
* This can be used to check that a supported version of AnkiDroid is installed,
* or to get the application label and icon, etc.
* @param context a Context that can be used to get the PackageManager
* @return packageId of AnkiDroid if a supported version is not installed, otherwise null
*/
@Suppress("deprecation") // deprecated symbol until minSdkVersion >= 33
@JvmStatic // required for API
public fun getAnkiDroidPackageName(context: Context): String? {
val manager = context.packageManager
return if (Build.VERSION.SDK_INT >= 33)
manager.resolveContentProvider(
FlashCardsContract.AUTHORITY,
PackageManager.ComponentInfoFlags.of(0L)
)?.packageName
else
manager.resolveContentProvider(FlashCardsContract.AUTHORITY, 0)?.packageName
}
}
}
| gpl-3.0 | 84c4d7021d666bb984185ab9bb3d6ce5 | 43.668421 | 129 | 0.593791 | 4.661906 | false | false | false | false |
sleberknight/kotlin-koans | src/iii_conventions/_30_DestructuringDeclarations.kt | 1 | 682 | package iii_conventions.multiAssignemnt
import util.TODO
import util.doc30
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about destructuring declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
//operator fun MyDate.component1() = year
//operator fun MyDate.component2() = month
//operator fun MyDate.component3() = dayOfMonth
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
// 29 February of a leap year
return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | d2bcff91c9aad3515f9431aabb572771 | 26.32 | 125 | 0.687683 | 3.942197 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/SpannerExchangeStepsService.kt | 1 | 6281 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner
import io.grpc.Status
import java.time.Clock
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.singleOrNull
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.common.identity.IdGenerator
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.gcloud.common.toCloudDate
import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.internal.kingdom.ClaimReadyExchangeStepRequest
import org.wfanet.measurement.internal.kingdom.ClaimReadyExchangeStepResponse
import org.wfanet.measurement.internal.kingdom.ExchangeStep
import org.wfanet.measurement.internal.kingdom.ExchangeStepAttempt
import org.wfanet.measurement.internal.kingdom.ExchangeStepAttemptDetailsKt.debugLog
import org.wfanet.measurement.internal.kingdom.ExchangeStepsGrpcKt.ExchangeStepsCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.GetExchangeStepRequest
import org.wfanet.measurement.internal.kingdom.StreamExchangeStepsRequest
import org.wfanet.measurement.internal.kingdom.claimReadyExchangeStepResponse
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PROVIDER_PARAM
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.providerFilter
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries.StreamExchangeSteps
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ExchangeStepAttemptReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ExchangeStepReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.ClaimReadyExchangeStep
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.ClaimReadyExchangeStep.Result
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.CreateExchangesAndSteps
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.FinishExchangeStepAttempt
import org.wfanet.measurement.kingdom.service.internal.externalDataProviderId
import org.wfanet.measurement.kingdom.service.internal.externalModelProviderId
class SpannerExchangeStepsService(
private val clock: Clock,
private val idGenerator: IdGenerator,
private val client: AsyncDatabaseClient
) : ExchangeStepsCoroutineImplBase() {
override suspend fun getExchangeStep(request: GetExchangeStepRequest): ExchangeStep {
val exchangeStepResult =
ExchangeStepReader()
.fillStatementBuilder {
appendClause(
"""
WHERE RecurringExchanges.ExternalRecurringExchangeId = @external_recurring_exchange_id
AND ExchangeSteps.Date = @date
AND ExchangeSteps.StepIndex = @step_index
AND ${providerFilter(request.provider)}
"""
.trimIndent()
)
bind("external_recurring_exchange_id" to request.externalRecurringExchangeId)
bind("date" to request.date.toCloudDate())
bind("step_index" to request.stepIndex.toLong())
bind(PROVIDER_PARAM to request.provider.externalId)
appendClause("LIMIT 1")
}
.execute(client.singleUse())
.singleOrNull()
?: failGrpc(Status.NOT_FOUND) { "ExchangeStep not found" }
return exchangeStepResult.exchangeStep
}
override suspend fun claimReadyExchangeStep(
request: ClaimReadyExchangeStepRequest
): ClaimReadyExchangeStepResponse {
val externalModelProviderId = request.provider.externalModelProviderId
val externalDataProviderId = request.provider.externalDataProviderId
CreateExchangesAndSteps(provider = request.provider).execute(client, idGenerator)
// TODO(@efoxepstein): consider whether a more structured signal for auto-fail is needed
val debugLogEntry = debugLog {
message = "Automatically FAILED because of expiration"
time = clock.instant().toProtoTime()
}
ExchangeStepAttemptReader.forExpiredAttempts(
externalModelProviderId = externalModelProviderId,
externalDataProviderId = externalDataProviderId
)
.execute(client.singleUse())
.map { it.exchangeStepAttempt }
.collect { attempt: ExchangeStepAttempt ->
FinishExchangeStepAttempt(
provider = request.provider,
externalRecurringExchangeId = ExternalId(attempt.externalRecurringExchangeId),
exchangeDate = attempt.date,
stepIndex = attempt.stepIndex,
attemptNumber = attempt.attemptNumber,
terminalState = ExchangeStepAttempt.State.FAILED,
debugLogEntries = listOf(debugLogEntry),
clock = clock
)
.execute(client, idGenerator)
}
val result =
ClaimReadyExchangeStep(provider = request.provider, clock = clock)
.execute(client, idGenerator)
if (result.isPresent) {
return result.get().toClaimReadyExchangeStepResponse()
}
return claimReadyExchangeStepResponse {}
}
override fun streamExchangeSteps(request: StreamExchangeStepsRequest): Flow<ExchangeStep> {
return StreamExchangeSteps(request.filter, request.limit).execute(client.singleUse()).map {
it.exchangeStep
}
}
private fun Result.toClaimReadyExchangeStepResponse(): ClaimReadyExchangeStepResponse {
return claimReadyExchangeStepResponse {
this.exchangeStep = step
this.attemptNumber = attemptIndex
}
}
}
| apache-2.0 | 730da22370200d3839f0d38db103e380 | 43.546099 | 98 | 0.771056 | 4.945669 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RJson.kt | 1 | 6647 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import org.json.JSONArray
import org.json.JSONObject
import pyxis.uzuki.live.richutilskt.impl.F1
/**
* create JSONObject from String
* @return JSONObject object
*/
fun String.createJSONObject(): JSONObject? = this.convertAcceptNull({ JSONObject(this) }, null)
/**
* create JSONObject from Map
* @return JSONObject object
*/
fun Map<*, *>.createJSONObject(): JSONObject? = this.convertAcceptNull({ JSONObject(this) }, null)
/**
* create JSONArray from String
* @return JSONObject object
*/
fun String.createJSONArray(): JSONArray? = this.convertAcceptNull({ JSONArray(this) }, null)
/**
* create JSONArray from Map
* @return JSONArray object
*/
fun List<*>.createJSONArray(): JSONArray? = this.convertAcceptNull({ JSONArray(this) }, null)
/**
* get JSONObject from JSONObject
*
* @param[jsonObject] target JSONObject
* @param[name] name of key
* @return JSONObject object
*/
fun getJSONObject(jsonObject: JSONObject?, name: String): JSONObject? = jsonObject.convertAcceptNull({ it?.getJSONObject(name) }, null)
/**
* get JSONObject from JSONArray
*
* @param[jsonArray] target JSONArray
* @param[index] index of key
* @return JSONObject object
*/
fun getJSONObject(jsonArray: JSONArray?, index: Int): JSONObject? = jsonArray.convertAcceptNull({ it?.getJSONObject(index) }, null)
/**
* get JSONArray from JSONObject
*
* @param[jsonObject] target JSONObject
* @param[name] name of key
* @return JSONArray object
*/
fun getJSONArray(jsonObject: JSONObject?, name: String): JSONArray? = jsonObject.convertAcceptNull({ it?.getJSONArray(name) }, null)
/**
* get JSONArray from JSONArray
*
* @param[jsonArray] target JSONArray
* @param[index] index of key
* @return JSONArray object
*/
fun getJSONArray(jsonArray: JSONArray?, index: Int): JSONArray? = jsonArray.convertAcceptNull({ it?.getJSONArray(index) }, null)
/**
* get String from JSONObject
*
* @param[name] name of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return String object
*/
@JvmOverloads
fun JSONObject.getJSONString(name: String, def: String = ""): String = this.convert({ it.getString(name) }, def)
/**
* get String from JSONArray
*
* @param[index] index of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return String object
*/
@JvmOverloads
fun JSONArray.getJSONString(index: Int, def: String = ""): String = this.convert({ it.getString(index) }, def)
/**
* get Int from JSONObject
*
* @param[name] name of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Int object
*/
@JvmOverloads
fun JSONObject.getJSONInt(name: String, def: Int = 0): Int = this.convert({ it.getInt(name) }, def)
/**
* get Int from JSONArray
*
* @param[index] index of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Int object
*/
@JvmOverloads
fun JSONArray.getJSONInt(index: Int, def: Int = 0): Int = this.convert({ it.getInt(index) }, def)
/**
* get Boolean from JSONObject
*
* @param[name] name of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Boolean object
*/
@JvmOverloads
fun JSONObject.getJSONBoolean(name: String, def: Boolean = false): Boolean = this.convert({ it.getBoolean(name) }, def)
/**
* get Boolean from JSONArray
*
* @param[index] index of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Boolean object
*/
@JvmOverloads
fun JSONArray.getJSONBoolean(index: Int, def: Boolean = false): Boolean = this.convert({ it.getBoolean(index) }, def)
/**
* get Double from JSONObject
*
* @param[name] name of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Double object
*/
@JvmOverloads
fun JSONObject.getJSONDouble(name: String, def: Double = 0.toDouble()): Double = this.convert({ it.getDouble(name) }, def)
/**
* get Double from JSONArray
*
* @param[index] index of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Double object
*/
@JvmOverloads
fun JSONArray.getJSONDouble(index: Int, def: Double = 0.toDouble()): Double = this.convert({ it.getDouble(index) }, def)
/**
* get Long from JSONObject
*
* @param[name] name of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Long object
*/
@JvmOverloads
fun JSONObject.getJSONLong(name: String, def: Long = 0.toLong()): Long = this.convert({ it.getLong(name) }, def)
/**
* get Long from JSONArray
*
* @param[index] index of key
* @param[def] optional, if key is not presented or some unexpected problem happened, it will be return
* @return Long object
*/
@JvmOverloads
fun JSONArray.getJSONLong(index: Int, def: Long = 0.toLong()): Long = this.convert({ it.getLong(index) }, def)
/**
* put value to JSONObject
*
* @param[jsonObject] target JSONObject
* @param[name] name of key
* @param[value] actual value to input
*/
fun put(jsonObject: JSONObject?, name: String, value: Any) = jsonObject?.put(name, value)
/**
* put value to JSONArray
*
* @param[jsonArray] target JSONArray
* @param[index] index of key
* @param[value] actual value to input
*/
fun put(jsonArray: JSONArray?, index: Int, value: Any) = jsonArray?.put(index, value)
/**
* put value to JSONArray without ordering
*
* @param[jsonArray] target JSONArray
* @param[value] actual value to input
*/
fun put(jsonArray: JSONArray?, value: Any) = jsonArray?.put(value)
/**
* invoke [action] every JSONObject
*/
@JvmName("forObjectEach")
inline fun JSONArray.forEach(action: (JSONObject) -> Unit) {
for (i in 0 until this.length()) action(getJSONObject(i))
}
/**
* invoke [action] every JSONObject
*/
@JvmName("forObjectEach")
inline fun JSONArray.forEach(action: F1<JSONObject>) {
for (i in 0 until this.length()) action(getJSONObject(i))
}
/**
* convert JSONArray to List<JSONObject>
*/
@JvmName("toObjectList")
fun JSONArray.toList(): List<JSONObject> = List<JSONObject>(length()) { index -> getJSONObject(index) }
/**
* DSL-Style JSONObject builder
*/
class Json() : JSONObject() {
constructor(init: Json.() -> Unit) : this() {
this.init()
}
infix fun <T> String.to(value: T) {
put(this, value)
}
}
| apache-2.0 | 0100e7d1686b495a046275631b118ea9 | 27.774892 | 135 | 0.705882 | 3.72381 | false | false | false | false |
sabi0/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/GithubResponsePage.kt | 2 | 2183 | // 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.github.api.data
import org.jetbrains.plugins.github.exceptions.GithubConfusingException
class GithubResponsePage<T> constructor(val items: List<T>,
val firstLink: String? = null,
val prevLink: String? = null,
val nextLink: String? = null,
val lastLink: String? = null) {
companion object {
const val HEADER_NAME = "Link"
private val HEADER_SECTION_REGEX = Regex("""^<(.*)>; rel="(first|prev|next|last)"$""")
//<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=15>; rel="next", <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last", <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=1>; rel="first", <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=13>; rel="prev"
@JvmStatic
@Throws(GithubConfusingException::class)
fun <T> parseFromHeader(items: List<T>, linkHeaderValue: String?): GithubResponsePage<T> {
if (linkHeaderValue == null) return GithubResponsePage(items)
var firstLink: String? = null
var prevLink: String? = null
var nextLink: String? = null
var lastLink: String? = null
val split = linkHeaderValue.split(", ")
if (split.isEmpty()) throw GithubConfusingException("Can't determine total items count from header: $linkHeaderValue")
for (section in split) {
val matchResult = HEADER_SECTION_REGEX.matchEntire(section) ?: continue
val groupValues = matchResult.groupValues
if (groupValues.size == 3) {
when (groupValues[2]) {
"first" -> firstLink = groupValues[1]
"prev" -> prevLink = groupValues[1]
"next" -> nextLink = groupValues[1]
"last" -> lastLink = groupValues[1]
}
}
}
return GithubResponsePage(items, firstLink, prevLink, nextLink, lastLink)
}
}
}
| apache-2.0 | 3b09fea1422707e7c4ed28dd53b76b39 | 44.479167 | 340 | 0.622996 | 4.050093 | false | false | false | false |
FirebaseExtended/auth-without-play-services | app/src/main/java/com/google/firebase/nongmsauth/FirebaseTokenRefresher.kt | 1 | 4595 | /**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.nongmsauth
import android.os.Handler
import android.util.Log
import androidx.annotation.Keep
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.google.firebase.auth.internal.IdTokenListener
import com.google.firebase.internal.InternalTokenResult
import com.google.firebase.nongmsauth.utils.ExpirationUtils
class FirebaseTokenRefresher(val auth: FirebaseRestAuth) :
IdTokenListener, LifecycleObserver {
private var failureRetryTimeSecs: Long = MIN_RETRY_BACKOFF_SECS
private var lastToken: String? = null
private val handler: Handler = Handler()
private val refreshRunnable: Runnable = object : Runnable {
override fun run() {
val user = auth.currentUser
if (user == null) {
Log.d(TAG, "User signed out, nothing to refresh.")
return
}
val minSecsRemaining = TEN_MINUTES_SECS
val secsRemaining = ExpirationUtils.expiresInSeconds(user)
val diffSecs = secsRemaining - minSecsRemaining
// If the token has enough time left, run a refresh later.
if (diffSecs > 0) {
Log.d(TAG, "Token expires in $secsRemaining, scheduling refresh in $diffSecs seconds")
handler.postDelayed(this, diffSecs * 1000)
return
}
// Time to refresh the token now
Log.d(TAG, "Token expires in $secsRemaining, refreshing token now!")
auth.getAccessToken(true)
.addOnSuccessListener {
// On success just re-post, the logic above will handle the timing.
Log.d(TAG, "Token refreshed successfully.")
handler.post(this)
// Clear the failure backoff
failureRetryTimeSecs = MIN_RETRY_BACKOFF_SECS
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to refresh token", e)
Log.d(TAG, "Retrying in $failureRetryTimeSecs...")
// Retry and double the backoff time (up to the max)
handler.postDelayed(this, failureRetryTimeSecs * 1000)
failureRetryTimeSecs = Math.min(failureRetryTimeSecs * 2, MAX_RETRY_BACKOFF_SECS)
}
}
}
@Keep
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onLifecycleStarted() {
this.start()
}
@Keep
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onLifecycleStopped() {
this.stop()
}
fun bindTo(owner: LifecycleOwner) {
owner.lifecycle.addObserver(this)
}
private fun start() {
Log.d(TAG, "start()")
this.auth.addIdTokenListener(this)
this.handler.post(this.refreshRunnable)
}
private fun stop() {
Log.d(TAG, "stop()")
this.auth.removeIdTokenListener(this)
this.handler.removeCallbacksAndMessages(null)
this.lastToken = null
}
override fun onIdTokenChanged(res: InternalTokenResult) {
val token = res.token
if (token != null && lastToken == null) {
// We are now signed in, time to start refreshing
Log.d(TAG, "Token changed from null --> non-null, starting refreshing")
this.handler.post(this.refreshRunnable)
}
if (lastToken != null && token == null) {
// The user signed out, stop all refreshing
Log.d(TAG, "Signed out, canceling refreshes")
this.handler.removeCallbacksAndMessages(null)
}
this.lastToken = token
}
companion object {
private val TAG = FirebaseTokenRefresher::class.java.simpleName
const val TEN_MINUTES_SECS = 10 * 60
const val MIN_RETRY_BACKOFF_SECS = 30L
const val MAX_RETRY_BACKOFF_SECS = 5 * 60L
}
}
| apache-2.0 | ca48278f44ed18a67037a6983b0c51f7 | 33.810606 | 102 | 0.630468 | 4.522638 | false | false | false | false |
if710/if710.github.io | 2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/location/LocationMapsActivity.kt | 1 | 4906 | package br.ufpe.cin.android.systemservices.location
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import br.ufpe.cin.android.systemservices.R
import java.util.*
class LocationMapsActivity : Activity() {
private var isInPermission = false
private var state: Bundle? = null
protected val desiredPermissions: Array<String>
get() = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.state = savedInstanceState
if (state != null) {
isInPermission = state!!.getBoolean(KEY_IN_PERMISSION, false)
}
if (hasAllPermissions(desiredPermissions)) {
onReady()
} else if (!isInPermission) {
isInPermission = true
ActivityCompat.requestPermissions(this, netPermissions(desiredPermissions), ID_PERMISSION_REQUEST)
}
}
protected fun onReady() {
setContentView(R.layout.activity_location_maps)
val b1 = findViewById<View>(R.id.btn1) as Button
b1.setOnClickListener { startActivity(Intent(applicationContext, ProvidersActivity::class.java)) }
val b2 = findViewById<View>(R.id.btn2) as Button
b2.setOnClickListener { startActivity(Intent(applicationContext, LocationActivity::class.java)) }
val b3 = findViewById<View>(R.id.btn3) as Button
b3.setOnClickListener { startActivity(Intent(applicationContext, FusedLocationActivity::class.java)) }
val b4 = findViewById<View>(R.id.btn4) as Button
b4.setOnClickListener { startActivity(Intent(applicationContext, MapActivity::class.java)) }
val b5 = findViewById<View>(R.id.btn5) as Button
b5.setOnClickListener { startActivity(Intent(applicationContext, FusedLocationMapActivity::class.java)) }
}
protected fun onPermissionDenied() {
Toast.makeText(this, "Permissao negada!", Toast.LENGTH_LONG).show()
finish()
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
isInPermission = false
if (requestCode == ID_PERMISSION_REQUEST) {
if (hasAllPermissions(desiredPermissions)) {
onReady()
} else {
onPermissionDenied()
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_IN_PERMISSION, isInPermission)
}
private fun hasAllPermissions(perms: Array<String>): Boolean {
for (perm in perms) {
if (!hasPermission(perm)) {
return false
}
}
return true
}
protected fun hasPermission(perm: String): Boolean {
return ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED
}
private fun netPermissions(wanted: Array<String>): Array<String> {
val result = ArrayList<String>()
for (perm in wanted) {
if (!hasPermission(perm)) {
result.add(perm)
}
}
return result.toTypedArray()
}
companion object {
//Existem diversos dispositivos Android
//Diferentes maneiras de obter localização
//Objetos LocationProvider são usados para obter localização
// existem zero ou mais instâncias de LocationProvider,
// uma para cada serviço de localização disponível no device
// GPS_PROVIDER, NETWORK_PROVIDER
//Usamos o LocationManager para obter informações.
// eh papel do Manager escolher o LocationProvider adequado
//Permissao eh necessaria COARSE ou FINE
// GPS_PROVIDER so funciona com FINE_LOCATION
// permissoes sao dangerous, então precisamos pedir em novas APIs
//1. pegar o LocationManager
//2. escolher o LocationProvider
//2.1 oferecer escolha - pega lista de providers getProviders()
//2.2 escolher automaticamente (de acordo com objeto Criteria)
//setAltitude, setAccuracy...
//getBestProvider()
//3. getLastKnownLocation()
// retorna objeto Location
//4. registrar para receber updates
//Alguns location providers não respondem imediatamente.
// O GPS exige ativação do rádio e comunicação com satélites.
private val ID_PERMISSION_REQUEST = 2505
private val KEY_IN_PERMISSION = "temPermissao"
}
}
| mit | 77f50ac52377b463e4adae74ec7bf987 | 33.408451 | 113 | 0.656979 | 4.540892 | false | false | false | false |
asamm/locus-api | locus-api-core/src/main/java/locus/api/objects/geoData/Point.kt | 1 | 9186 | /*
* Copyright 2012, Asamm Software, s. r. o.
*
* This file is part of LocusAPI.
*
* LocusAPI is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* LocusAPI 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with LocusAPI. If not, see
* <http://www.gnu.org/licenses/lgpl.html/>.
*/
package locus.api.objects.geoData
import locus.api.objects.extra.GeoDataExtra
import locus.api.objects.extra.Location
import locus.api.objects.geocaching.GeocachingData
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import locus.api.utils.Logger
import java.io.IOException
class Point() : GeoData() {
/**
* Location of current point.
*/
var location: Location = Location()
// GEOCACHING DATA
/**
* Additional geoCaching data.
*/
var gcData: GeocachingData? = null
/**
* Deal with binary data of geocaching object.
*/
var gcDataBinary: ByteArray?
get() {
return try {
val dw = DataWriterBigEndian()
writeGeocachingData(dw)
dw.toByteArray()
} catch (e: IOException) {
Logger.logE(TAG, "gcDataBinary - get()", e)
null
}
}
set(data) = try {
gcData = readGeocachingData(DataReaderBigEndian(data))
} catch (e: Exception) {
Logger.logE(TAG, "gcDataBinary - set($data)", e)
gcData = null
}
/**
* Create point with known name and it's location.
*/
constructor(name: String, loc: Location) : this() {
this.name = name
this.location = loc
}
// EXTRA "CALLBACK"
val extraCallback: String?
get() = getParameter(GeoDataExtra.PAR_INTENT_EXTRA_CALLBACK)
/**
* Simply allow set callback value on point. This appear when you click on point
* and then under last button will be your button. Clicking on it, launch by you,
* defined intent
* <br></br><br></br>
* Do not forget to set this http://developer.android.com/guide/topics/manifest/activity-element.html#exported
* to your activity, if you'll set callback to other then launcher activity
*
* @param btnName Name displayed on button
* @param packageName this value is used for creating intent that
* will be called in callback (for example com.super.application)
* @param className the name of the class inside of com.super.application
* that implements the component (for example com.super.application.Main)
* @param returnDataName String under which data will be stored. Can be
* retrieved by String data = getIntent.getStringExtra("returnData");
* @param returnDataValue String under which data will be stored. Can be
* retrieved by String data = getIntent.getStringExtra("returnData");
*/
fun setExtraCallback(btnName: String, packageName: String, className: String,
returnDataName: String, returnDataValue: String) {
// prepare callback
val callBack = GeoDataExtra.generateCallbackString(btnName, packageName, className,
returnDataName, returnDataValue)
if (callBack.isEmpty()) {
return
}
// generate final text
val b = StringBuilder()
b.append(TAG_EXTRA_CALLBACK).append(";")
b.append(callBack)
// finally insert parameter
addParameter(GeoDataExtra.PAR_INTENT_EXTRA_CALLBACK, b.toString())
}
/**
* If you want to remove PAR_INTENT_EXTRA_CALLBACK parametr from Locus database,
* you need to send "clear" value in updated waypoint back to Locus. After that,
* Locus will remove this parameter from new stored point.
* <br></br><br></br>
* Second alternative, how to remove this callback, is to send new waypoints
* with forceOverwrite parameter set to `true`, that will overwrite
* completely all data
*/
fun removeExtraCallback() {
addParameter(GeoDataExtra.PAR_INTENT_EXTRA_CALLBACK, "clear")
}
// EXTRA "ON-DISPLAY"
val extraOnDisplay: String?
get() = getParameter(GeoDataExtra.PAR_INTENT_EXTRA_ON_DISPLAY)
/**
* Extra feature that allow to send to locus only partial point data. When you click on
* point (in time when small point dialog should appear), locus send intent to your app,
* you can then fill complete point and send it back to Locus. Clear and clever
* <br></br><br></br>
* Do not forget to set this http://developer.android.com/guide/topics/manifest/activity-element.html#exported
* to your activity, if you'll set callback to other then launcher activity
*
* @param packageName this value is used for creating intent that
* will be called in callback (for example com.super.application)
* @param className the name of the class inside of com.super.application
* that implements the component (for example com.super.application.Main)
* @param returnDataName String under which data will be stored. Can be
* retrieved by String data = getIntent.getStringExtra("returnData");
* @param returnDataValue value that will be received when you try to get
* data from received response
*/
fun setExtraOnDisplay(packageName: String, className: String,
returnDataName: String, returnDataValue: String) {
val sb = StringBuilder()
sb.append(TAG_EXTRA_ON_DISPLAY).append(";")
sb.append(packageName).append(";")
sb.append(className).append(";")
sb.append(returnDataName).append(";")
sb.append(returnDataValue).append(";")
addParameter(GeoDataExtra.PAR_INTENT_EXTRA_ON_DISPLAY, sb.toString())
}
/**
* If you want to remove PAR_INTENT_EXTRA_ON_DISPLAY parameter from Locus database,
* you need to send "clear" value in updated waypoint back to Locus. After that,
* Locus will remove this parameter from new stored point.
* <br></br><br></br>
* Second alternative, how to remove this callback, is to send new waypoints
* with forceOverwrite parameter set to `true`, that will overwrite
* completely all data
*/
fun removeExtraOnDisplay() {
addParameter(GeoDataExtra.PAR_INTENT_EXTRA_ON_DISPLAY, "clear")
}
//*************************************************
// STORABLE
//*************************************************
override fun getVersion(): Int {
return 4
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
id = dr.readLong()
name = dr.readString()
location = Location().apply { read(dr) }
// read extra data
readExtraData(dr)
readStyles(dr)
// read geocaching
gcData = readGeocachingData(dr)
// V1
if (version >= 1) {
timeCreated = dr.readLong()
}
// V2
if (version >= 2) {
protected = dr.readInt() == 0
}
// V3
if (version >= 3) {
timeUpdated = dr.readLong()
}
// V4
if (version >= 4) {
val privacyValue = dr.readString()
privacy = Privacy.values().find { it.name == privacyValue }
?: privacy
}
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
dw.writeLong(id)
dw.writeString(name)
location.write(dw)
// write extra data
writeExtraData(dw)
writeStyles(dw)
// write geocaching data
writeGeocachingData(dw)
// V1
dw.writeLong(timeCreated)
// V2
dw.writeInt(if (protected) 0 else 1)
// V3
dw.writeLong(timeUpdated)
// V4
dw.writeString(privacy.name)
}
@Throws(IOException::class)
private fun writeGeocachingData(dw: DataWriterBigEndian) {
gcData?.let {
dw.writeBoolean(true)
it.write(dw)
} ?: {
dw.writeBoolean(false)
}()
}
companion object {
// tag for logger
private const val TAG = "Point"
// callback parameter
const val TAG_EXTRA_CALLBACK = "TAG_EXTRA_CALLBACK"
// extra on-display parameter
const val TAG_EXTRA_ON_DISPLAY = "TAG_EXTRA_ON_DISPLAY"
@Throws(IOException::class)
fun readGeocachingData(dr: DataReaderBigEndian): GeocachingData? {
return if (dr.readBoolean()) {
GeocachingData().apply { read(dr) }
} else {
null
}
}
}
}
| mit | 41b58bcb30ea9c04a28aa6ca183b966e | 32.525547 | 114 | 0.618768 | 4.409986 | false | false | false | false |
JetBrains-Research/npy | src/main/kotlin/org/jetbrains/bio/npy/ChunkerMerger.kt | 1 | 8654 | package org.jetbrains.bio.npy
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.min
/** Default buffer size for [ArrayChunker] subclasses. */
private const val DEFAULT_BUFFER_SIZE = 65536
/**
* A chunked iterator for primitive array types.
*
* The maximum chunk size is currently a constant and is defined by
* [DEFAULT_BUFFER_SIZE].
*
* Why? Java does not provide an API for coercing a primitive buffer
* to a [ByteBuffer] without copying, because a primitive buffer might
* have a non-native byte ordering. This class implements
* constant-memory iteration over a primitive array without resorting
* to primitive buffers.
*
* Invariant: buffers produced by the iterator must be consumed
* **in order**, because their content is invalidated between
* [Iterator.next] calls.
*
* @since 0.3.1
*/
internal abstract class ArrayChunker<T>(
/** The array. */
protected val data: T,
/** Number of elements in the array. */
private val size: Int,
/** Byte order for the produced buffers. */
private val order: ByteOrder) : Sequence<ByteBuffer> {
/** Byte size of the element of [T]. */
abstract val bytes: Int
/**
* Populates this buffer using elements from [data].
*
* @see ByteBuffer.put
*/
abstract fun ByteBuffer.put(data: T, offset: Int, size: Int)
override fun iterator() = object : Iterator<ByteBuffer> {
private var offset = 0 // into the [data].
private var step = DEFAULT_BUFFER_SIZE / bytes
// Only allocated 'cache' if the [data] is bigger than [step].
private val cache by lazy {
// [DEFAULT_BUFFER_SIZE] is rounded down to be divisible by [bytes].
ByteBuffer.allocateDirect(step * bytes).order(order)
}
override fun hasNext() = offset < size
override fun next(): ByteBuffer {
val available = min(size - offset, step)
val result = if (available == step) {
cache.apply { rewind() }
} else {
ByteBuffer.allocateDirect(available * bytes).order(order)
}
with(result) {
put(data, offset, available)
rewind()
}
offset += available
return result
}
}
}
internal class BooleanArrayChunker(data: BooleanArray) :
ArrayChunker<BooleanArray>(data, data.size, ByteOrder.nativeOrder()) {
override val bytes: Int get() = 1
override fun ByteBuffer.put(data: BooleanArray, offset: Int, size: Int) {
for (i in offset until offset + size) {
put(if (data[i]) 1.toByte() else 0.toByte())
}
}
}
internal class ShortArrayChunker(data: ShortArray, order: ByteOrder) :
ArrayChunker<ShortArray>(data, data.size, order) {
override val bytes: Int get() = java.lang.Short.BYTES
override fun ByteBuffer.put(data: ShortArray, offset: Int, size: Int) {
asShortBuffer().put(data, offset, size)
}
}
internal class IntArrayChunker(data: IntArray, order: ByteOrder) :
ArrayChunker<IntArray>(data, data.size, order) {
override val bytes: Int get() = Integer.BYTES
override fun ByteBuffer.put(data: IntArray, offset: Int, size: Int) {
asIntBuffer().put(data, offset, size)
}
}
internal class LongArrayChunker(data: LongArray, order: ByteOrder) :
ArrayChunker<LongArray>(data, data.size, order) {
override val bytes: Int get() = java.lang.Long.BYTES
override fun ByteBuffer.put(data: LongArray, offset: Int, size: Int) {
asLongBuffer().put(data, offset, size)
}
}
internal class FloatArrayChunker(data: FloatArray, order: ByteOrder) :
ArrayChunker<FloatArray>(data, data.size, order) {
override val bytes: Int get() = java.lang.Float.BYTES
override fun ByteBuffer.put(data: FloatArray, offset: Int, size: Int) {
asFloatBuffer().put(data, offset, size)
}
}
internal class DoubleArrayChunker(data: DoubleArray, order: ByteOrder) :
ArrayChunker<DoubleArray>(data, data.size, order) {
override val bytes: Int get() = java.lang.Double.BYTES
override fun ByteBuffer.put(data: DoubleArray, offset: Int, size: Int) {
asDoubleBuffer().put(data, offset, size)
}
}
internal class StringArrayChunker(data: Array<String>) :
ArrayChunker<Array<String>>(data, data.size, ByteOrder.nativeOrder()) {
override val bytes: Int by lazy { data.asSequence().map { it.length }.maxOrNull() ?: 0 }
override fun ByteBuffer.put(data: Array<String>, offset: Int, size: Int) {
for (i in offset until offset + size) {
put(data[i].toByteArray(Charsets.US_ASCII).copyOf(bytes))
}
}
}
/**
* A chunked initializer for primitive array types.
*
* JVM does not allow mapping files larger that `Int.MAX_SIZE` bytes.
* As a result, one cannot simply read a primitive array from a memory
* mapped file via the usual [ByteBuffer] magic.
*
* This class allows to incrementally initialize an array from multiple
* buffers.
*
* @since 0.3.2
*/
internal abstract class ArrayMerger<out T>(protected val data: T) : (ByteBuffer) -> Unit {
protected var offset = 0
fun result() = data
}
internal class BooleanArrayMerger(size: Int) :
ArrayMerger<BooleanArray>(BooleanArray(size)) {
override fun invoke(chunk: ByteBuffer) {
while (chunk.hasRemaining()) {
data[offset++] = chunk.get() == 1.toByte()
}
}
}
internal class ByteArrayMerger(size: Int) : ArrayMerger<ByteArray>(ByteArray(size)) {
override fun invoke(chunk: ByteBuffer) = with(chunk) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
/** Adjusts this buffer position after executing [block]. */
private inline fun ByteBuffer.linked(bytes: Int, block: (ByteBuffer) -> Unit) {
val tick = position()
block(this)
val consumedCeiling = capacity() - tick
position(position() + (consumedCeiling - consumedCeiling % bytes))
}
internal class ShortArrayMerger(size: Int) : ArrayMerger<ShortArray>(ShortArray(size)) {
override fun invoke(chunk: ByteBuffer) = chunk.linked(java.lang.Short.BYTES) {
with(it.asShortBuffer()) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
}
internal class IntArrayMerger(size: Int) : ArrayMerger<IntArray>(IntArray(size)) {
override fun invoke(chunk: ByteBuffer) = chunk.linked(Integer.BYTES) {
with(it.asIntBuffer()) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
}
internal class LongArrayMerger(size: Int) : ArrayMerger<LongArray>(LongArray(size)) {
override fun invoke(chunk: ByteBuffer) = chunk.linked(java.lang.Long.BYTES) {
with(it.asLongBuffer()) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
}
internal class FloatArrayMerger(size: Int) : ArrayMerger<FloatArray>(FloatArray(size)) {
override fun invoke(chunk: ByteBuffer) = chunk.linked(java.lang.Float.BYTES) {
with(it.asFloatBuffer()) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
}
internal class DoubleArrayMerger(size: Int) : ArrayMerger<DoubleArray>(DoubleArray(size)) {
override fun invoke(chunk: ByteBuffer) = chunk.linked(java.lang.Double.BYTES) {
with(it.asDoubleBuffer()) {
while (hasRemaining()) {
val size = remaining()
get(data, offset, size)
offset += size
}
}
}
}
internal class StringArrayMerger(size: Int, private val bytes: Int) :
ArrayMerger<Array<String>>(Array(size) { "" }) {
override fun invoke(chunk: ByteBuffer) = with(chunk) {
// Iterate until there is not more data or the next value is
// split between chunks, e.g.
// chunk2
// .........
// "foo|bar\0\0\0"
// ...
// chunk1
while (remaining() >= bytes) {
val b = ByteArray(bytes)
get(b)
data[offset++] = String(b, Charsets.US_ASCII).trimEnd('\u0000')
}
}
} | mit | 5bebb1702113db878fd639f1edaf2ad1 | 31.660377 | 92 | 0.611394 | 4.117031 | false | false | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/barcodedetection/BarcodeResultFragment.kt | 1 | 3311 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.md.barcodedetection
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.mlkit.md.R
import com.google.mlkit.md.camera.WorkflowModel
import com.google.mlkit.md.camera.WorkflowModel.WorkflowState
/** Displays the bottom sheet to present barcode fields contained in the detected barcode. */
class BarcodeResultFragment : BottomSheetDialogFragment() {
override fun onCreateView(
layoutInflater: LayoutInflater,
viewGroup: ViewGroup?,
bundle: Bundle?
): View {
val view = layoutInflater.inflate(R.layout.barcode_bottom_sheet, viewGroup)
val arguments = arguments
val barcodeFieldList: ArrayList<BarcodeField> =
if (arguments?.containsKey(ARG_BARCODE_FIELD_LIST) == true) {
arguments.getParcelableArrayList(ARG_BARCODE_FIELD_LIST) ?: ArrayList()
} else {
Log.e(TAG, "No barcode field list passed in!")
ArrayList()
}
view.findViewById<RecyclerView>(R.id.barcode_field_recycler_view).apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity)
adapter = BarcodeFieldAdapter(barcodeFieldList)
}
return view
}
override fun onDismiss(dialogInterface: DialogInterface) {
activity?.let {
// Back to working state after the bottom sheet is dismissed.
ViewModelProviders.of(it).get(WorkflowModel::class.java).setWorkflowState(WorkflowState.DETECTING)
}
super.onDismiss(dialogInterface)
}
companion object {
private const val TAG = "BarcodeResultFragment"
private const val ARG_BARCODE_FIELD_LIST = "arg_barcode_field_list"
fun show(fragmentManager: FragmentManager, barcodeFieldArrayList: ArrayList<BarcodeField>) {
val barcodeResultFragment = BarcodeResultFragment()
barcodeResultFragment.arguments = Bundle().apply {
putParcelableArrayList(ARG_BARCODE_FIELD_LIST, barcodeFieldArrayList)
}
barcodeResultFragment.show(fragmentManager, TAG)
}
fun dismiss(fragmentManager: FragmentManager) {
(fragmentManager.findFragmentByTag(TAG) as BarcodeResultFragment?)?.dismiss()
}
}
}
| apache-2.0 | 8eb27d06131bd1dc2f329c75cf25d06a | 37.057471 | 110 | 0.709755 | 4.897929 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/WhenSettingEngineToRepeat.kt | 1 | 3754 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine
import com.lasthopesoftware.EmptyUrl
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListUtilities
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CyclicalFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.UrlKeyHolder
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WhenSettingEngineToRepeat {
companion object {
private val nowPlaying by lazy {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val library = Library()
library.setId(1)
library.setSavedTracksString(
FileStringListUtilities.promiseSerializedFileStringList(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
)
).toFuture().get()
)
library.setNowPlayingId(0)
val libraryProvider = object : ISpecificLibraryProvider {
override val library: Promise<Library?>
get() = library.toPromise()
}
val libraryStorage = PassThroughLibraryStorage()
val filePropertiesContainerRepository = mockk<IFilePropertiesContainerRepository>()
every {
filePropertiesContainerRepository.getFilePropertiesContainer(
UrlKeyHolder(
EmptyUrl.url,
ServiceFile(4)
)
)
} returns FilePropertiesContainer(1, mapOf(Pair(KnownFileProperties.DURATION, "100")))
val repository = NowPlayingRepository(libraryProvider, libraryStorage)
val playbackEngine = PlaybackEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 },
listOf(CompletingFileQueueProvider(), CyclicalFileQueueProvider()),
repository,
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f)))
playbackEngine.restoreFromSavedState()
playbackEngine.playRepeatedly().toFuture().get()
repository.nowPlaying.toFuture().get()
}
}
@Test
fun thenNowPlayingIsSetToRepeating() {
assertThat(nowPlaying?.isRepeating).isTrue
}
}
| lgpl-3.0 | 9e291027bff6d3e02cb4403411aa964d | 44.780488 | 128 | 0.829249 | 4.651797 | false | false | false | false |
NextFaze/dev-fun | devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/processing/AnnotationProcessor.kt | 1 | 3875 | package com.nextfaze.devfun.compiler.processing
import com.nextfaze.devfun.compiler.*
import com.squareup.kotlinpoet.*
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.*
import javax.lang.model.type.TypeMirror
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
internal interface Processor : WithElements {
val preprocessor: StringPreprocessor
val kElements: KElements
fun TypeMirror.toKClassBlock(
kotlinClass: Boolean = true,
isKtFile: Boolean = false,
castIfNotPublic: TypeName? = null
) = toKClassBlock(kotlinClass, isKtFile, castIfNotPublic, elements)
fun TypeElement.toClassElement() = kElements[this]
// during normal gradle builds string types will be java.lang
// during testing however they will be kotlin types
val TypeMirror.isString get() = toString().let { it == "java.lang.String" || it == "kotlin.String" }
fun String.toValue(element: Element?) = preprocessor.run(this, element)
}
internal interface AnnotationProcessor : Processor {
val options: Options
val willGenerateSource: Boolean
fun processAnnotatedElement(annotatedElement: AnnotatedElement, env: RoundEnvironment)
fun applyToFileSpec(fileSpec: FileSpec.Builder) = Unit
fun applyToTypeSpec(typeSpec: TypeSpec.Builder)
val VariableElement.classElement get() = kElements[enclosingElement as TypeElement]
val ExecutableElement.classElement get() = kElements[enclosingElement as TypeElement]
fun KCallable<*>.toPropertySpec(
propName: String = name,
returns: TypeName = returnType.asTypeName(),
init: Any? = null,
initBlock: CodeBlock? = null,
lazy: Any? = null,
kDoc: String? = null,
kDocEnabled: Boolean = options.isDebugCommentsEnabled
) =
PropertySpec.builder(
propName,
returns,
KModifier.OVERRIDE
).apply {
if (init != null) initializer("%L", init)
if (initBlock != null) initializer(initBlock)
if (lazy != null) delegate("lazy { %L }", lazy)
if (kDoc != null && kDocEnabled) addKdoc(kDoc)
}
fun Collection<*>.toListOfBlock(type: KClass<*>) =
CodeBlock.of("listOf<%T>(${",\n%L".repeat(size).drop(1)})", type, *toTypedArray())
fun Element.getSetAccessible(classIsPublic: Boolean) = if (!classIsPublic || !isPublic) ".apply { isAccessible = true }" else ""
fun ExecutableElement.toMethodRef(): CodeBlock {
val clazz = (enclosingElement as TypeElement).toClassElement()
// Can we call the function directly
val funIsPublic = isPublic
val classIsPublic = funIsPublic && clazz.isPublic
val funName = simpleName.escapeDollar()
val methodArgTypes = parameters.map { it.asType().toKClassBlock(kotlinClass = false) }.joiner(prefix = ", ")
val setAccessible = getSetAccessible(classIsPublic)
return if (options.useKotlinReflection) {
CodeBlock.of(
"""%L.declaredFunctions.filter { it.name == "${simpleName.stripInternal()}" && it.parameters.size == ${parameters.size + 1} }.single().javaMethod!!$setAccessible""",
clazz.type.toKClassBlock(kotlinClass = false, isKtFile = clazz.isKtFile)
)
} else {
CodeBlock.of(
"%L.getDeclaredMethod(\"$funName\"%L)$setAccessible",
clazz.type.toKClassBlock(kotlinClass = false, isKtFile = clazz.isKtFile),
methodArgTypes
)
}
}
}
internal data class AnnotatedElement(
val element: Element,
val annotationElement: KElements.ClassElement,
val asFunction: Boolean,
val asCategory: Boolean,
val asReference: Boolean
) {
val annotation: AnnotationMirror = element.getAnnotation(annotationElement)!!
}
| apache-2.0 | e6b76b496d442224deb8b22ce59e5414 | 37.366337 | 181 | 0.668903 | 4.564193 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/FilterTab.kt | 1 | 2626 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.project
import javafx.application.Platform
import javafx.scene.Node
import javafx.scene.layout.BorderPane
import uk.co.nickthecoder.paratask.ParaTaskApp
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.parameters.ChoiceParameter
import uk.co.nickthecoder.paratask.parameters.SimpleGroupParameter
import uk.co.nickthecoder.paratask.parameters.addParameters
import uk.co.nickthecoder.paratask.parameters.fields.ParametersForm
import uk.co.nickthecoder.paratask.table.filter.RowFilter
class FilterTab(val tool: Tool, filters: Map<String, RowFilter<*>>) : MinorTab("Filter") {
val whole = BorderPane()
var parametersPane: ParametersPane = ParametersPane_Impl(filters.values.first())
val choiceP = ChoiceParameter("filter", label = "Select a Filter", value = filters.values.first())
val choiceGroupP = SimpleGroupParameter("choiceGroup")
val choiceForm = ParametersForm(choiceGroupP, null)
init {
content = whole
whole.center = parametersPane as Node
if (filters.size > 1) {
filters.forEach { key, filter ->
choiceP.addChoice(key, filter, filter.label)
}
choiceGroupP.addParameters(choiceP)
choiceForm.buildContent()
whole.top = choiceForm
choiceP.listen {
parametersPane.detaching()
parametersPane = ParametersPane_Impl(choiceP.value!!)
parametersPane.attached(tool.toolPane!!)
whole.center = parametersPane as Node
}
}
}
override fun selected() {
focus()
}
override fun focus() {
if (tool.toolPane?.skipFocus != true) {
Platform.runLater {
ParaTaskApp.logFocus("FilterTab.focus. parametersPane.focus()")
parametersPane.focus()
}
}
}
override fun deselected() {
}
}
| gpl-3.0 | 85e4512d67abb0e420f6b800e1da47d9 | 33.103896 | 102 | 0.692308 | 4.443316 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/views/TypeView.kt | 1 | 5614 | /*
* Copyright (C) 2017 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.views
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.AdapterView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.Spinner
import com.jereksel.libresubstratum.R
import com.jereksel.libresubstratum.adapters.Type1SpinnerArrayAdapter
import com.jereksel.libresubstratum.data.Type1ExtensionToString
import com.jereksel.libresubstratum.extensions.getLogger
import org.jetbrains.anko.find
class TypeView : RelativeLayout, ITypeView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
val log = getLogger()
private val spinner: Spinner
override fun getSpinner() = spinner
private val seekbar: SeekBar
override fun getSeekBar() = seekbar
// private val colorview: ColorView
private var listener: ITypeView.TypeViewSelectionListener? = null
init {
val inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.view_typeview, this);
spinner = find(R.id.spinner)
seekbar = find(R.id.seekBar)
// colorview = find(R.id.colorview)
}
override fun onPositionChange(listener: ITypeView.TypeViewSelectionListener) {
this.listener = listener
}
override fun setSelection(position: Int) {
// if (spinner.selectedItemPosition != position) {
spinner.setSelection(position)
// }
/* seekbar.post {
seekbar.progress = position
}*/
}
override fun setType1(list: List<Type1ExtensionToString>) {
// spinner.selectListener { }
// if (spinner.adapter == null || (spinner.adapter as Type1SpinnerArrayAdapter).objects != list) {
spinner.adapter = Type1SpinnerArrayAdapter(context, list)
// }
// type1aSpinner.setSelection(position)
// val colors = list.map { it.type1.color }.map { if (it.isNotEmpty()) { it } else {"white"} }.map { Color.parseColor(it) }
//ColorView is hidden for now. It was bad idea, I'll prepare something like this:
//https://github.com/dmfs/color-picker
// colorview.visibility = View.GONE
seekbar.visibility = View.GONE
/*
if (colors.find { it != Color.parseColor("white") } == null || colors.size > 15) {
//There are only whites or too much colors
colorview.visibility = View.GONE
seekbar.visibility = View.GONE
} else {
colorview.visibility = View.VISIBLE
seekbar.visibility = View.VISIBLE
}
*/
/* colorview.colors = colors
colorview.invalidate()*/
val type1aSeekbar = seekbar
val type1aSpinner = spinner
/*
type1aSeekbar.post {
type1aSeekbar.setOnSeekBarChangeListener(null)
val width = type1aSeekbar.measuredWidth
val margin = ((width.toFloat()/colors.size)/2).toInt()
type1aSeekbar.setPadding(margin, 0, margin, 0)
type1aSeekbar.progressDrawable = ColorDrawable(Color.TRANSPARENT)
type1aSeekbar.max = colors.size - 1
type1aSeekbar.progress = 0
type1aSeekbar.invalidate()
type1aSeekbar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
type1aSpinner.background = ColorDrawable(colors[progress])
type1aSpinner.setSelection(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
}*/
spinner.selectListener { position ->
listener?.onPositionChange(position)
}
}
private fun Spinner.selectListener(fn: (Int) -> Unit) {
var user = false
this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (user) {
fn(position)
} else {
user = true
}
}
}
}
}
| mit | d6eb262d234f816d1c7edf6fa90622fb | 33.441718 | 144 | 0.659423 | 4.56052 | false | false | false | false |
ofalvai/BPInfo | app/src/main/java/com/ofalvai/bpinfo/ui/alertdetail/AlertDetailFragment.kt | 1 | 9617 | /*
* Copyright 2018 Olivér Falvai
*
* 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.ofalvai.bpinfo.ui.alertdetail
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.widget.ContentLoadingProgressBar
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.ofalvai.bpinfo.R
import com.ofalvai.bpinfo.model.Alert
import com.ofalvai.bpinfo.model.Resource
import com.ofalvai.bpinfo.model.Route
import com.ofalvai.bpinfo.ui.alertlist.AlertListType
import com.ofalvai.bpinfo.util.*
import com.wefika.flowlayout.FlowLayout
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.sufficientlysecure.htmltextview.HtmlTextView
import timber.log.Timber
class AlertDetailFragment : BottomSheetDialogFragment() {
companion object {
const val FRAGMENT_TAG = "alert_detail"
private const val ARG_ALERT_OBJECT = "alert_object"
private const val ARG_LIST_TYPE = "alert_list_type"
fun newInstance(alert: Alert, alertListType: AlertListType): AlertDetailFragment {
val fragment = AlertDetailFragment()
val args = bundleOf(
ARG_ALERT_OBJECT to alert,
ARG_LIST_TYPE to alertListType
)
fragment.arguments = args
return fragment
}
}
private val viewModel by viewModel<AlertDetailViewModel>()
private var alertWithDetails: Alert? = null
private lateinit var alertListType: AlertListType
private val analytics: Analytics by inject()
/**
* List of currently displayed route icons. This list is needed in order to find visually
* duplicate route data, and not to display them twice.
*/
private val displayedRoutes = mutableListOf<Route>()
private val titleTextView: TextView by bindView(R.id.alert_detail_title)
private val dateTextView: TextView by bindView(R.id.alert_detail_date)
private val routeIconsLayout: FlowLayout by bindView(R.id.alert_detail_route_icons_wrapper)
private val descriptionTextView: HtmlTextView by bindView(R.id.alert_detail_description)
private val urlTextView: TextView by bindView(R.id.alert_detail_url)
private val progressBar: ContentLoadingProgressBar by bindView(R.id.alert_detail_progress_bar)
private val errorLayout: LinearLayout by bindView(R.id.error_with_action)
private val errorMessage: TextView by bindView(R.id.error_message)
private val errorButton: Button by bindView(R.id.error_action_button)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
alertWithDetails = arguments?.getSerializable(ARG_ALERT_OBJECT) as Alert
alertListType = arguments?.getSerializable(ARG_LIST_TYPE) as AlertListType
}
if (savedInstanceState != null) {
alertWithDetails = savedInstanceState.getSerializable(ARG_ALERT_OBJECT) as Alert
}
analytics.logAlertContentView(alertWithDetails)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putSerializable(ARG_ALERT_OBJECT, alertWithDetails)
super.onSaveInstanceState(outState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_alert_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
displayAlert(alertWithDetails)
alertWithDetails?.let {
if (!it.isPartial) {
progressBar.hide()
}
}
errorButton.setOnClickListener {
alertWithDetails?.id?.let {
val alertLiveData = viewModel.reloadAlert(it, alertListType)
observe(alertLiveData) { resource ->
when (resource) {
is Resource.Success -> updateAlert(resource.value)
is Resource.Loading -> {
errorLayout.visibility = View.GONE
progressBar.show()
}
is Resource.Error -> onAlertUpdateFailed()
}
}
}
}
}
override fun onStart() {
super.onStart()
// Bottom sheets on tablets should have a smaller width than the screen width.
val width = requireContext().resources.getDimensionPixelSize(R.dimen.bottom_sheet_width)
val actualWidth = if (width > 0) width else ViewGroup.LayoutParams.MATCH_PARENT
dialog?.window?.setLayout(actualWidth, ViewGroup.LayoutParams.MATCH_PARENT)
}
fun updateAlert(alert: Alert) {
this.alertWithDetails = alert
displayedRoutes.clear()
routeIconsLayout.removeAllViews()
// Updating views
displayAlert(alert)
// View animations
// For some reason, ObjectAnimator doesn't work here (skips animation states, just shows the
// last frame), we need to use ValueAnimators.
val animatorSet = AnimatorSet()
animatorSet.duration = 300
animatorSet.interpolator = FastOutSlowInInterpolator()
// We can't measure the TextView's height before a layout happens because of the setText() call
// Note: even though displayAlert() was called earlier, the TextView's height is still 0.
val heightEstimate = descriptionTextView.lineHeight * descriptionTextView.lineCount + 10
val descriptionHeight = ValueAnimator.ofInt(descriptionTextView.height, heightEstimate)
descriptionHeight.addUpdateListener { animation ->
descriptionTextView.layoutParams.height = animation.animatedValue as Int
descriptionTextView.requestLayout()
}
descriptionHeight.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
descriptionTextView.alpha = 1.0f
descriptionTextView.visibility = View.VISIBLE
}
})
val descriptionAlpha = ValueAnimator.ofFloat(0.0f, 1.0f)
descriptionAlpha.addUpdateListener { animation ->
descriptionTextView.alpha = animation.animatedValue as Float
}
val progressHeight = ValueAnimator.ofInt(progressBar.height, 0)
progressHeight.addUpdateListener { animation ->
progressBar.layoutParams.height = animation.animatedValue as Int
progressBar.requestLayout()
}
progressHeight.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
progressBar.hide()
}
})
animatorSet.playTogether(progressHeight, descriptionHeight, descriptionAlpha)
animatorSet.start()
}
fun onAlertUpdateFailed() {
progressBar.hide()
errorMessage.setText(R.string.error_alert_detail_load)
errorButton.setText(R.string.label_retry)
errorLayout.visibility = View.VISIBLE
}
private fun displayAlert(alert: Alert?) {
if (alert == null) return
titleTextView.text = alert.header
val dateString = alert.formatDate(requireContext())
dateTextView.text = dateString
// There are alerts without affected routes, eg. announcements
for (route in alert.affectedRoutes) {
// Some affected routes are visually identical to others in the list, no need
// to display them again.
if (!isRouteVisuallyDuplicate(route, displayedRoutes)) {
displayedRoutes.add(route)
addRouteIcon(requireContext(), routeIconsLayout, route)
}
}
alert.description?.let {
try {
descriptionTextView.setHtml(it)
} catch (t: Throwable) {
analytics.logException(t)
Timber.e(t, "Failed to parse alert description HTML")
}
}
if (alert.url == null) {
urlTextView.visibility = View.GONE
} else {
urlTextView.paintFlags = urlTextView.paintFlags or Paint.UNDERLINE_TEXT_FLAG
urlTextView.setOnClickListener {
val url = Uri.parse(alert.url)
openCustomTab(requireActivity(), url)
analytics.logAlertUrlClick(alert)
}
}
}
}
| apache-2.0 | a1ad7f874bf56a76771aa3ab8f046afc | 36.271318 | 103 | 0.671901 | 4.995325 | false | false | false | false |
Kerr1Gan/ShareBox | common-componentes/src/main/java/com/common/componentes/activity/ImmersiveFragmentActivity.kt | 1 | 1850 | package com.common.componentes.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
/**
* Created by KerriGan on 2017/7/12.
*/
open class ImmersiveFragmentActivity : BaseFragmentActivity() {
companion object {
@JvmOverloads
@JvmStatic
fun newInstance(context: Context, fragment: Class<*>, bundle: Bundle? = null,
clazz: Class<out Activity> = getActivityClazz()): Intent {
return BaseFragmentActivity.newInstance(context, fragment, bundle, clazz)
}
fun getActivityClazz(): Class<out Activity> = ImmersiveFragmentActivity::class.java
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) //去除半透明状态栏
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) //一般配合fitsSystemWindows()使用, 或者在根部局加上属性android:fitsSystemWindows="true", 使根部局全屏显示
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(Color.TRANSPARENT)
}
if (Build.VERSION.SDK_INT >= 24/*Build.VERSION_CODES.N*/) {
try {
val decorViewClazz = Class.forName("com.android.internal.policy.DecorView")
val field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor")
field.isAccessible = true
field.setInt(window.decorView, Color.TRANSPARENT) //改为透明
} catch (e: Exception) {
}
}
}
} | apache-2.0 | eb96245d3700b8ce454ca461a3882e7c | 38.533333 | 177 | 0.68054 | 4.45614 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsListComponent.kt | 1 | 9036 | // 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.github.pullrequest.ui
import com.intellij.codeInsight.AutoPopupController
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.*
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.EventDispatcher
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.pullrequest.action.GithubPullRequestKeys
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsDetailsLoader
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsLoader
import org.jetbrains.plugins.github.pullrequest.data.SingleWorkerProcessExecutor
import org.jetbrains.plugins.github.pullrequest.search.GithubPullRequestSearchComponent
import org.jetbrains.plugins.github.pullrequest.search.GithubPullRequestSearchModel
import java.awt.Component
import java.util.*
import javax.swing.JComponent
import javax.swing.JScrollBar
import javax.swing.ScrollPaneConstants
import javax.swing.event.ListSelectionEvent
class GithubPullRequestsListComponent(project: Project,
actionManager: ActionManager,
autoPopupController: AutoPopupController,
popupFactory: JBPopupFactory,
private val externalDataProvider: DataProvider,
private val detailsLoader: GithubPullRequestsDetailsLoader,
private val loader: GithubPullRequestsLoader)
: BorderLayoutPanel(), Disposable,
GithubPullRequestsLoader.PullRequestsLoadingListener, SingleWorkerProcessExecutor.ProcessStateListener,
DataProvider {
private val tableModel = GithubPullRequestsTableModel()
private val table = GithubPullRequestsTable(tableModel)
private val scrollPane = ScrollPaneFactory.createScrollPane(table,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = JBUI.Borders.empty()
verticalScrollBar.model.addChangeListener { potentiallyLoadMore() }
}
private var loadOnScrollThreshold = true
private var isDisposed = false
private val errorPanel = HtmlErrorPanel()
private val progressStripe = ProgressStripe(scrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private val searchModel = GithubPullRequestSearchModel()
private val search = GithubPullRequestSearchComponent(project, autoPopupController, popupFactory, searchModel)
private val tableToolbarWrapper: Wrapper
private val selectionEventDispatcher = EventDispatcher.create(PullRequestSelectionListener::class.java)
init {
loader.addProcessListener(this, this)
loader.addLoadingListener(this, this)
searchModel.addListener(object : GithubPullRequestSearchModel.StateListener {
override fun queryChanged() {
loader.setSearchQuery(searchModel.query)
loader.reset()
}
}, this)
table.selectionModel.addListSelectionListener { e: ListSelectionEvent ->
if (!e.valueIsAdjusting) {
if (table.selectedRow < 0) selectionEventDispatcher.multicaster.selectionChanged(null)
else selectionEventDispatcher.multicaster.selectionChanged(tableModel.getValueAt(table.selectedRow, 0))
}
}
selectionEventDispatcher.addListener(detailsLoader, this)
val toolbar = actionManager.createActionToolbar("GithubPullRequestListToolbar",
actionManager.getAction("Github.PullRequest.ToolWindow.List.Toolbar") as ActionGroup,
true)
.apply {
setReservePlaceAutoPopupIcon(false)
setTargetComponent(this@GithubPullRequestsListComponent)
}
val popupHandler = object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
if (TableUtil.isPointOnSelection(table, x, y)) {
val popupMenu = actionManager
.createActionPopupMenu("GithubPullRequestListPopup",
actionManager.getAction("Github.PullRequest.ToolWindow.List.Popup") as ActionGroup)
popupMenu.setTargetComponent(this@GithubPullRequestsListComponent)
popupMenu.component.show(comp, x, y)
}
}
}
table.addMouseListener(popupHandler)
tableToolbarWrapper = Wrapper(toolbar.component)
val headerPanel = JBUI.Panels.simplePanel(0, 0).addToCenter(search).addToRight(tableToolbarWrapper)
val tableWithError = JBUI.Panels
.simplePanel(progressStripe)
.addToTop(errorPanel)
.withBorder(IdeBorderFactory.createBorder(SideBorder.TOP))
addToCenter(tableWithError)
addToTop(headerPanel)
resetSearch()
}
override fun getData(dataId: String): Any? {
return when {
GithubPullRequestKeys.PULL_REQUESTS_LOADER.`is`(dataId) -> loader
GithubPullRequestKeys.PULL_REQUESTS_DETAILS_LOADER.`is`(dataId) -> detailsLoader
else -> externalDataProvider.getData(dataId) ?: table.getData(dataId)
}
}
fun setToolbarHeightReferent(referent: JComponent) {
tableToolbarWrapper.setVerticalSizeReferent(referent)
}
fun addSelectionListener(listener: PullRequestSelectionListener, disposable: Disposable) =
selectionEventDispatcher.addListener(listener, disposable)
private fun potentiallyLoadMore() {
if (loadOnScrollThreshold && isScrollAtThreshold(scrollPane.verticalScrollBar)) {
loadMore()
}
}
private fun loadMore() {
if (isDisposed) return
loadOnScrollThreshold = false
loader.requestLoadMore()
}
private fun isScrollAtThreshold(verticalScrollBar: JScrollBar): Boolean {
val visibleAmount = verticalScrollBar.visibleAmount
val value = verticalScrollBar.value
val maximum = verticalScrollBar.maximum
if (maximum == 0) return false
val scrollFraction = (visibleAmount + value) / maximum.toFloat()
if (scrollFraction < 0.5) return false
return true
}
override fun processStarted() {
table.emptyText.text = "Loading pull requests..."
errorPanel.setError(null)
progressStripe.startLoading()
}
override fun processFinished() {
progressStripe.stopLoading()
}
override fun moreDataLoaded(data: List<GithubSearchedIssue>, hasNext: Boolean) {
if (searchModel.query.isEmpty()) {
table.emptyText.text = "No pull requests loaded."
}
else {
table.emptyText.text = "No pull requests matching filters."
table.emptyText.appendSecondaryText("Reset Filters", SimpleTextAttributes.LINK_ATTRIBUTES) {
resetSearch()
}
}
loadOnScrollThreshold = hasNext
tableModel.addItems(data)
//otherwise scrollbar will have old values (before data insert)
scrollPane.viewport.validate()
potentiallyLoadMore()
}
private fun resetSearch() {
search.searchText = "state:open"
}
override fun loaderReset() {
loadOnScrollThreshold = false
tableModel.clear()
loader.requestLoadMore()
}
override fun loadingErrorOccurred(error: Throwable) {
loadOnScrollThreshold = false
val prefix = if (table.isEmpty) "Cannot load pull requests." else "Cannot load full pull requests list."
table.emptyText.clear().appendText(prefix, SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(getLoadingErrorText(error), SimpleTextAttributes.ERROR_ATTRIBUTES, null)
.appendSecondaryText("Retry", SimpleTextAttributes.LINK_ATTRIBUTES) { loadMore() }
if (!table.isEmpty) {
//language=HTML
val errorText = "<html><body>$prefix ${getLoadingErrorText(error)}<a href=''>Retry</a></body></html>"
errorPanel.setError(errorText, linkActivationListener = { loadMore() })
}
}
private fun getLoadingErrorText(error: Throwable): String {
return error.message?.let { addDotIfNeeded(it) }?.let { addSpaceIfNeeded(it) }
?: "Unknown loading error. "
}
private fun addDotIfNeeded(line: String) = if (line.endsWith('.')) line else "$line."
private fun addSpaceIfNeeded(line: String) = if (line.endsWith(' ')) line else "$line "
override fun dispose() {
isDisposed = true
}
interface PullRequestSelectionListener : EventListener {
fun selectionChanged(selection: GithubSearchedIssue?)
}
} | apache-2.0 | ac6b15044f1c4b4b109743f631b70c53 | 40.454128 | 140 | 0.7251 | 5.102202 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/test/groovy/graphql/validation/SpecValidationSchemaPojos.kt | 1 | 828 | package graphql.validation
/**
* Sample schema pojos used in the spec for validation examples
* http://facebook.github.io/graphql/#sec-Validation
* @author dwinsor
*/
class SpecValidationSchemaPojos {
inner class Human {
var name: String? = null
}
inner class Alien {
var name: String? = null
}
inner class Dog {
var name: String? = null
var nickname: String? = null
var barkVolume: Int = 0
var doesKnowCommand: Boolean = false
var isHousetrained: Boolean = false
var owner: Human? = null
}
inner class Cat {
var name: String? = null
var nickname: String? = null
var meowVolume: Int = 0
var doesKnowCommand: Boolean = false
}
inner class QueryRoot {
var dog: Dog? = null
}
}
| mit | 4c4461f088de9e7bb56cea51abec362d | 22 | 63 | 0.599034 | 4.119403 | false | false | false | false |
adgvcxz/ViewModel | viewpagermodel/src/main/java/com/adgvcxz/viewpagermodel/ViewPagerViewModel.kt | 1 | 2499 | package com.adgvcxz.viewpagermodel
import com.adgvcxz.AFViewModel
import com.adgvcxz.IEvent
import com.adgvcxz.IModel
import com.adgvcxz.IMutation
import io.reactivex.rxjava3.core.Observable
/**
* zhaowei
* Created by zhaowei on 2017/8/4.
*/
class ViewPagerModel(values: List<ViewPagerItemViewModel<out IModel>>? = null): IModel {
var items: List<ViewPagerItemViewModel<out IModel>> = arrayListOf()
init {
values?.let { items = it }
items.forEach { it.disposable = it.model.subscribe() }
}
}
sealed class ViewPagerEventMutation : IEvent, IMutation
data class AppendData(val data: List<ViewPagerItemViewModel<out IModel>>) : ViewPagerEventMutation()
data class ReplaceData(val index: List<Int>, val data: List<ViewPagerItemViewModel<out IModel>>) : ViewPagerEventMutation()
data class RemoveData(val index: List<Int>) : ViewPagerEventMutation()
data class SetData(val data: List<ViewPagerItemViewModel<out IModel>>) : ViewPagerEventMutation()
abstract class ViewPagerViewModel: AFViewModel<ViewPagerModel>() {
override fun mutate(event: IEvent): Observable<IMutation> {
if (event is IMutation) {
return Observable.just(event)
}
return super.mutate(event)
}
override fun scan(model: ViewPagerModel, mutation: IMutation): ViewPagerModel {
when(mutation) {
is AppendData -> model.items += mutation.data.also { it.forEach { it.disposable = it.model.subscribe() } }
is ReplaceData -> {
model.items = model.items.mapIndexed { index, viewModel ->
if (mutation.index.contains(index)) {
viewModel.dispose()
mutation.data[mutation.index.indexOf(index)].also { it.disposable = it.model.subscribe() }
} else {
viewModel
}
}
}
is RemoveData -> {
model.items = model.items.filterIndexed { index, viewModel ->
val exist = mutation.index.contains(index)
if (exist) {
viewModel.dispose()
}
!exist
}
}
is SetData -> {
model.items.forEach { it.dispose() }
model.items = mutation.data.also { it.forEach { it.disposable = it.model.subscribe() } }
}
}
return super.scan(model, mutation)
}
} | apache-2.0 | 4b4e4b0af42592f2748c3cec5373386c | 35.764706 | 123 | 0.598639 | 4.610701 | false | false | false | false |
jitsi/jicofo | jicofo/src/test/kotlin/org/jitsi/jicofo/codec/JingleOfferFactoryTest.kt | 1 | 2550 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2015-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.jicofo.codec
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.jitsi.xmpp.extensions.jingle.ContentPacketExtension
import org.jitsi.xmpp.extensions.jingle.PayloadTypePacketExtension
import org.jitsi.xmpp.extensions.jingle.RtpDescriptionPacketExtension
import org.jitsi.jicofo.codec.JingleOfferFactory.INSTANCE as jingleOfferFactory
class JingleOfferFactoryTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.SingleInstance
init {
context("With default options") {
val offer = jingleOfferFactory.createOffer(OfferOptions())
offer.find { it.name == "audio" } shouldNotBe null
offer.find { it.name == "data" } shouldNotBe null
val videoContent = offer.find { it.name == "video" }
videoContent shouldNotBe null
videoContent!!.containsRtx() shouldBe true
}
context("Without audio and data") {
val offer = jingleOfferFactory.createOffer(OfferOptions(audio = false, sctp = false))
offer.find { it.name == "audio" } shouldBe null
offer.find { it.name == "video" } shouldNotBe null
offer.find { it.name == "data" } shouldBe null
}
context("Without RTX") {
val offer = jingleOfferFactory.createOffer(OfferOptions(rtx = false))
val videoContent = offer.find { it.name == "video" }
videoContent shouldNotBe null
videoContent!!.containsRtx() shouldBe false
}
}
private fun ContentPacketExtension.containsRtx() =
getChildExtensionsOfType(RtpDescriptionPacketExtension::class.java).any {
it.getChildExtensionsOfType(PayloadTypePacketExtension::class.java).any { it.name == "rtx" }
}
}
| apache-2.0 | e437bb33e6c864ab4f7aa8d585bd29cc | 40.129032 | 104 | 0.694902 | 4.373928 | false | true | false | false |
uchuhimo/kotlin-playground | konf/src/main/kotlin/com/uchuhimo/konf/source/hocon/HoconSource.kt | 1 | 1446 | package com.uchuhimo.konf.source.hocon
import com.typesafe.config.Config
import com.uchuhimo.konf.Path
import com.uchuhimo.konf.name
import com.uchuhimo.konf.source.Source
import com.uchuhimo.konf.unsupported
class HoconSource(
val config: Config,
context: Map<String, String> = mapOf()) : Source {
val _info = mutableMapOf("type" to "HOCON")
override val info: Map<String, String> get() = _info
override fun addInfo(name: String, value: String) {
_info.put(name, value)
}
val _context: MutableMap<String, String> = context.toMutableMap()
override val context: Map<String, String> get() = _context
override fun addContext(name: String, value: String) {
_context.put(name, value)
}
override fun contains(path: Path): Boolean = config.hasPath(path.name)
override fun getOrNull(path: Path): Source? {
val name = path.name
if (config.hasPath(name)) {
return HoconValueSource(config.getValue(name), context)
} else {
return null
}
}
override fun toInt(): Int = unsupported()
override fun toList(): List<Source> = unsupported()
override fun toMap(): Map<String, Source> = unsupported()
override fun toText(): String = unsupported()
override fun toBoolean(): Boolean = unsupported()
override fun toLong(): Long = unsupported()
override fun toDouble(): Double = unsupported()
}
| apache-2.0 | 48e92503b427e2b3247adfffb292317c | 26.807692 | 74 | 0.658368 | 4.143266 | false | true | false | false |
Dolvic/gw2-api | jackson/src/main/kotlin/dolvic/gw2/jackson/achievements/AchievementBitmaskMixin.kt | 1 | 729 | package dolvic.gw2.jackson.achievements
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import dolvic.gw2.api.achievements.ItemBitmask
import dolvic.gw2.api.achievements.MinipetBitmask
import dolvic.gw2.api.achievements.SkinBitmask
import dolvic.gw2.api.achievements.TextBitmask
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(name = "Text", value = TextBitmask::class),
JsonSubTypes.Type(name = "Item", value = ItemBitmask::class),
JsonSubTypes.Type(name = "Minipet", value = MinipetBitmask::class),
JsonSubTypes.Type(name = "Skin", value = SkinBitmask::class)
)
internal interface AchievementBitmaskMixin
| mit | 275882152457d7bbfab7dca1a7bcc985 | 41.882353 | 71 | 0.794239 | 3.857143 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/game/Game.kt | 1 | 12890 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.game
import de.sudoq.model.actionTree.*
import de.sudoq.model.sudoku.Cell
import de.sudoq.model.sudoku.Sudoku
import de.sudoq.model.sudoku.complexity.Complexity
import java.util.*
import kotlin.math.pow
/**
* This class represents a sudoku game.
* Functions as a Facade towards the controller.
*/
class Game {
/**
* Unique id for the game
*/
var id: Int
private set
/**
* The sudoku of the game.
*/
var sudoku: Sudoku? = null //todo make nonnullable
private set
/**
* manages the game state
*/
var stateHandler: GameStateHandler? = null //todo make non-nullable
private set
/**
* Passed time since start of the game in seconds
*/
var time = 0
private set
/**
* Total sum of used assistances in this game.
*/
var assistancesCost = 0
private set
/**
* game settings
*/
var gameSettings: GameSettings? = null //TODO make non-nullable
/**
* Indicates if game is finished
*/
private var finished = false
/* used by persistence (mapper) */
constructor(
id: Int,
time: Int,
assistancesCost: Int,
sudoku: Sudoku,
stateHandler: GameStateHandler,
gameSettings: GameSettings,
finished: Boolean
) {
this.id = id
this.time = time
this.assistancesCost = assistancesCost
this.sudoku = sudoku
this.stateHandler = stateHandler
this.gameSettings = gameSettings
this.finished = finished
}
/**
* Protected constructor to prevent instatiation outside this package.
* (apparently thats not possible in kotlin...)
* Available assistances are set from current profile. TODO really? make explicit instead
*
* @param id ID of the game
* @param sudoku Sudoku of the new game
*/
constructor(id: Int, sudoku: Sudoku) {//todo check visibility - make internal?
this.id = id
gameSettings = GameSettings()
this.sudoku = sudoku
this.time = 0
stateHandler = GameStateHandler()
}
/**
* creates a completely empty game
*/
// package scope!
internal constructor() {//TODO who uses this? can it be removed?
id = -1
}
/**
* Adds time to the game
*
* @param time Time to add in seconds
*/
fun addTime(time: Int) {
this.time += time
}
/**
* The score of the game
*/
val score: Int
get() {
var scoreFactor = 0
fun power(expo: Double): Int = sudoku!!.sudokuType?.numberOfSymbols?.let {
it.toDouble().pow(expo).toInt()
}!!
when (sudoku!!.complexity) {
Complexity.infernal -> scoreFactor = power(4.0)
Complexity.difficult -> scoreFactor = power(3.5)
Complexity.medium -> scoreFactor = power(3.0)
Complexity.easy -> scoreFactor = power(2.5)
}
return (scoreFactor * 10 / ((time + assistancesTimeCost) / 60.0f)).toInt()
}
val assistancesTimeCost: Int
get() = assistancesCost * 60
/**
* Checks the sudoku for correctness.
* This is an assistance so the total assistance cost is increased.
*
* @return true, if sudoku is correct so far, false otherwise
*/
fun checkSudoku(): Boolean {
assistancesCost += 1
return checkSudokuValidity()
}
/**
* Checks the sudoku for correctness
*
* @return true, if sudoku is correct so far, false otherwise
*/
private fun checkSudokuValidity(): Boolean {
val correct = !sudoku!!.hasErrors()
if (correct) {
currentState.markCorrect()
} else {
currentState.markWrong()
}
return correct
}
/**
* Executes the passed [Action] and saves it in the [ActionTree].
*
* @param action the [Action] to perform.
*/
fun addAndExecute(action: Action) {
if (finished) return
stateHandler!!.addAndExecute(action)
sudoku!!.getCell(action.cellId)?.let { updateNotes(it) }
if (isFinished()) finished = true
}
/**
* Updates the notes in den constraints of the cell by removing the cells current value from the notes.
* Is only executed if the respective assistance is available.
*
* @param cell the modified Cell
*/
private fun updateNotes(cell: Cell) {
if (!isAssistanceAvailable(Assistances.autoAdjustNotes)) return
val editedPos = sudoku!!.getPosition(cell.id)
val value = cell.currentValue
/*this.sudoku.getSudokuType().getConstraints().stream().filter(c -> c.includes(editedPos))
.flatMap(c -> c.getPositions().stream())
.filter(changePos -> this.sudoku.getField(changePos).isNoteSet(value))
.forEachOrdered(changePos -> this.addAndExecute(new NoteActionFactory().createAction(value, this.sudoku.getField(changePos))));
should work, but to tired to try*/
for (c in sudoku!!.sudokuType!!) {
if (c.includes(editedPos!!)) {
for (changePos in c) {
if (sudoku!!.getCell(changePos)?.isNoteSet(value)!!) {
addAndExecute(
NoteActionFactory().createAction(
value,
sudoku!!.getCell(changePos)!!
)
)
}
}
}
}
}
/**
* Returns the state of the game to the given node in the action tree.
* TODO what if the node is not in the action tree?
*
* @param ate The ActionTreeElement in which the state of the Sudoku is to be returned.
*
*/
fun goToState(ate: ActionTreeElement) {
stateHandler!!.goToState(ate)
}
/**
* Undoes the last action. Goes one step back in the action tree.
*/
fun undo() {
stateHandler!!.undo()
}
/**
* Redo the last [Action]. Goes one step forward in the action tree.
*/
fun redo() {
stateHandler!!.redo()
}
/**
* The action tree node of the current state.
*/
val currentState: ActionTreeElement
get() = stateHandler!!.currentState!! //todo find a way to ensure it can never be null (the implicit root)
/**
* Marks the current state to better find it later.
*/
fun markCurrentState() {
stateHandler!!.markCurrentState() //TODO what doe this mean is it a book mark?
}
/**
* Checks if the given [ActionTreeElement] is marked.
*
* @param ate the ActionTreeElement to check
* @return true iff it is marked
*/
fun isMarked(ate: ActionTreeElement?): Boolean {
return stateHandler!!.isMarked(ate)
}
/**
* Checks if the sudoku is solved completely and correct.
*
* @return true iff sudoku is finished (and correct)
*/
fun isFinished(): Boolean {
return finished || sudoku!!.isFinished
}
/**
* Tries to solve the specified [Cell] and returns if that attempt was successful.
* If the [Sudoku] is invalid or has mistakes false is returned.
*
* @param cell The cell to solve
* @return true, if cell could be solved, false otherwise
*/
fun solveCell(cell: Cell?): Boolean { //TODO don't accept null
if (sudoku!!.hasErrors() || cell == null) return false
assistancesCost += 3
val solution = cell.solution
return if (solution != Cell.EMPTYVAL) {
addAndExecute(SolveActionFactory().createAction(solution, cell))
true
} else {
false
}
}
/**
* Tries to solve a randomly selected [Cell] and returns whether that was successful.
*
* @return true, if a cell could be solved, false otherwise
*/
fun solveCell(): Boolean {
if (sudoku!!.hasErrors()) return false
assistancesCost += 3
for (f in sudoku!!) {
if (f.isNotSolved) {
addAndExecute(SolveActionFactory().createAction(f.solution, f))
break
}
}
return true
/*
* Solution solution = solver.getHint(); if (solution != null) {
* stateHandler.addAndExecute(solution.getAction()); return true; } else { return false; }
*/
}
/**
* Solves the entire sudoku.
*
* @return true, iff the sudoku could be solved, false otherwise
*/
fun solveAll(): Boolean {
if (sudoku!!.hasErrors()) return false
val unsolvedCells: MutableList<Cell> = ArrayList()
for (f in sudoku!!) {
if (f.isNotSolved) {
unsolvedCells.add(f)
}
}
val rnd = Random()
while (unsolvedCells.isNotEmpty()) {
val nr = rnd.nextInt(unsolvedCells.size)
val a = SolveActionFactory().createAction(unsolvedCells[nr].solution, unsolvedCells[nr])
addAndExecute(a)
unsolvedCells.removeAt(nr)
}
assistancesCost += Int.MAX_VALUE / 80
return true
/*
* if (solver.solveAll(false, false, false) != null) { for (Field f : unsolvedFields) { this.addAndExecute(new
* SolveActionFactory().createAction(f.getCurrentValue(), f)); } return true; } else { return false; }
*/
}
/**
* Goes back to the last correctly solved state in the action tree.
* If current state is correct, nothing happens.
* This is an assistance, so the AssistanceCost is increased.
*/
fun goToLastCorrectState() {
assistancesCost += 3
while (!checkSudokuValidity()) {
undo()
}
currentState.markCorrect()
}
/**
* Goes back to the last book mark in the [ActionTree].
* If the current state is already bookmarked, nothing happens.
* Goes back to the root if there is no bookmark. TODO maybe better if nothing happens in that case
*/
fun goToLastBookmark() {
while (stateHandler!!.currentState != stateHandler!!.actionTree.root
&& !stateHandler!!.currentState!!.isMarked
) {
undo()
}
}
/**
* Sets the available assistances.
*
* @param assistances Die Assistances die für dieses Game gesetzt werden soll
*/
fun setAssistances(assistances: GameSettings) {
gameSettings = assistances
/* calculate costs of passive assistances add them to the total assistance cost */
if (isAssistanceAvailable(Assistances.autoAdjustNotes)) assistancesCost += 4
if (isAssistanceAvailable(Assistances.markRowColumn)) assistancesCost += 2
if (isAssistanceAvailable(Assistances.markWrongSymbol)) assistancesCost += 6
if (isAssistanceAvailable(Assistances.restrictCandidates)) assistancesCost += 12
}
/**
* Checks whether the given assistance is available.
*
* @param assist The assistance to check for availability
*
* @return true, if the assistance is available
*/
fun isAssistanceAvailable(assist: Assistances): Boolean {//TODO don't accept null
return gameSettings!!.getAssistance(assist)
}
val isLefthandedModeActive: Boolean
get() = gameSettings!!.isLefthandModeSet
/**
* {@inheritDoc}
*/
override fun equals(other: Any?): Boolean {//todo refactor
if (other is Game) {
return (id == other.id
&& sudoku == other.sudoku
&& stateHandler!!.actionTree == other.stateHandler!!.actionTree
&& currentState == other.currentState)
}
return false
}
} | gpl-3.0 | 6a9a09a06a708915bcc69abf6b0f8579 | 30.98263 | 243 | 0.587368 | 4.662808 | false | false | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/tag/TagActivity.kt | 1 | 8974 | /*
* Copyright (C) 2015 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.tag
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat.getColor
import android.support.v4.graphics.ColorUtils
import android.support.v4.graphics.drawable.DrawableCompat
import android.util.Pair
import android.view.Menu
import com.jakewharton.rxbinding.support.v7.widget.itemClicks
import com.jakewharton.rxbinding.view.clicks
import com.jakewharton.rxbinding.widget.textChanges
import com.larswerkman.lobsterpicker.ColorAdapter
import com.larswerkman.lobsterpicker.OnColorListener
import com.mvcoding.expensius.R
import com.mvcoding.expensius.extension.pickForegroundColor
import com.mvcoding.expensius.extension.setTextIfChanged
import com.mvcoding.expensius.extension.snackbar
import com.mvcoding.expensius.feature.ActivityStarter
import com.mvcoding.expensius.feature.BaseActivity
import com.mvcoding.expensius.model.Color
import com.mvcoding.expensius.model.ModelState
import com.mvcoding.expensius.model.ModelState.NONE
import com.mvcoding.expensius.model.Tag
import com.mvcoding.expensius.model.Title
import kotlinx.android.synthetic.main.activity_tag.*
import kotlinx.android.synthetic.main.toolbar.*
import rx.Observable
import rx.Subscriber
import rx.lang.kotlin.observable
class TagActivity : BaseActivity(), TagPresenter.View {
companion object {
private const val EXTRA_TAG = "EXTRA_TAG"
fun start(context: Context, tag: Tag) = ActivityStarter(context, TagActivity::class)
.extra(EXTRA_TAG, tag)
.start()
}
private val presenter by lazy { provideTagPresenter(intent.getSerializableExtra(TagActivity.EXTRA_TAG) as Tag) }
private val darkTextColor by lazy { getColor(this, R.color.text_primary) }
private val lightTextColor by lazy { getColor(this, R.color.text_primary_inverse) }
private var colorAnimator: ValueAnimator? = null
private var isArchiveToggleVisible = true
private var archiveToggleTitle: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tag)
lobsterPicker.colorAdapter = MaterialColorAdapter(this)
lobsterPicker.addDecorator(lobsterShadeSlider)
}
override fun onStart() {
super.onStart()
presenter.attach(this)
}
override fun onStop() {
super.onStop()
presenter.detach(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.tag, menu)
val menuItem = menu.findItem(R.id.action_archive)
menuItem.isVisible = isArchiveToggleVisible
menuItem.title = archiveToggleTitle
return true
}
override fun titleChanges(): Observable<String> = titleEditText.textChanges().map { it.toString() }.distinctUntilChanged()
override fun colorChanges(): Observable<Int> = observable<Int> { withColorPickerListener(it) }.distinctUntilChanged()
override fun archiveToggles(): Observable<Unit> = toolbar.itemClicks().filter { it.itemId == R.id.action_archive }.map { Unit }
override fun saveRequests(): Observable<Unit> = saveButton.clicks()
override fun showTitle(title: Title): Unit = titleEditText.setTextIfChanged(title.text)
override fun displayResult(): Unit = finish()
override fun showColor(color: Color) {
if (colorAnimator == null) onTagColorUpdated(color.rgb, false)
lobsterPicker.history = color.rgb
if (colorAnimator == null) {
val colorAdapter = lobsterPicker.colorAdapter
colorAdapter.size().minus(1)
.downTo(0)
.flatMap {
colorPosition ->
colorAdapter.shades(colorPosition).minus(1).downTo(0).map { Pair(colorPosition, it) }
}
.find { colorAdapter.color(it.first, it.second) == color.rgb }
?.let {
lobsterPicker.colorPosition = it.first
lobsterShadeSlider.shadePosition = it.second
}
}
}
override fun showModelState(modelState: ModelState) {
archiveToggleTitle = resources.getString(if (modelState == NONE) R.string.archive else R.string.restore)
toolbar.menu.findItem(R.id.action_archive)?.title = archiveToggleTitle
}
override fun showTitleCannotBeEmptyError() {
snackbar(R.string.error_title_empty, Snackbar.LENGTH_LONG).show()
}
override fun showArchiveEnabled(archiveEnabled: Boolean) {
isArchiveToggleVisible = archiveEnabled
toolbar.menu.findItem(R.id.action_archive)?.isVisible = archiveEnabled
}
private fun onTagColorUpdated(rgb: Int, animate: Boolean) {
colorAnimator?.cancel()
if (!animate) {
setColorOnViews(rgb)
return
}
val startColor = (titleContainerView.background as ColorDrawable).color
val animator = ValueAnimator()
animator.setIntValues(startColor, rgb)
animator.setEvaluator(ArgbEvaluator())
animator.addUpdateListener { setColorOnViews(it.animatedValue as Int) }
animator.duration = 150
animator.start()
colorAnimator = animator
}
private fun setColorOnViews(color: Int) {
titleContainerView.setBackgroundColor(color)
toolbar.setBackgroundColor(color)
val textColor = pickForegroundColor(color, lightTextColor, darkTextColor)
titleEditText.setTextColor(textColor)
titleEditText.setHintTextColor(ColorUtils.setAlphaComponent(textColor, 0x88))
toolbar.setTitleTextColor(textColor)
val navigationIcon = DrawableCompat.wrap(toolbar.navigationIcon!!.mutate())
DrawableCompat.setTint(navigationIcon, textColor)
toolbar.navigationIcon = navigationIcon
window.statusBarColor = color
}
private fun withColorPickerListener(subscriber: Subscriber<in Int>) {
lobsterPicker.addOnColorListener(object : OnColorListener {
override fun onColorChanged(color: Int) {
subscriber.onNext(color)
onTagColorUpdated(color, true)
}
override fun onColorSelected(color: Int) {
subscriber.onNext(color)
}
})
}
private class MaterialColorAdapter(context: Context) : ColorAdapter {
val colors: Array<IntArray>
init {
val resources = context.resources
val red = resources.getIntArray(R.array.reds)
val deepPurple = resources.getIntArray(R.array.deep_purples)
val lightBlue = resources.getIntArray(R.array.light_blues)
val green = resources.getIntArray(R.array.greens)
val yellow = resources.getIntArray(R.array.yellows)
val deepOrange = resources.getIntArray(R.array.deep_oranges)
val blueGrey = resources.getIntArray(R.array.blue_greys)
val pink = resources.getIntArray(R.array.pinks)
val indigo = resources.getIntArray(R.array.indigos)
val cyan = resources.getIntArray(R.array.cyans)
val lightGreen = resources.getIntArray(R.array.light_greens)
val amber = resources.getIntArray(R.array.ambers)
val brown = resources.getIntArray(R.array.browns)
val purple = resources.getIntArray(R.array.purples)
val blue = resources.getIntArray(R.array.blues)
val teal = resources.getIntArray(R.array.teals)
val lime = resources.getIntArray(R.array.limes)
val orange = resources.getIntArray(R.array.oranges)
colors = arrayOf(red, deepPurple, lightBlue, green, yellow, deepOrange, blueGrey, pink, indigo, cyan, lightGreen, amber, brown,
purple, blue, teal, lime, orange)
}
override fun size(): Int {
return colors.size
}
override fun shades(position: Int): Int {
return colors[position].size
}
override fun color(position: Int, shade: Int): Int {
return colors[position][shade]
}
}
} | gpl-3.0 | 4845a6500e1e4c30f3ad938558466d84 | 40.169725 | 139 | 0.689102 | 4.520907 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/search/RsFindUsagesProvider.kt | 3 | 903 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.search
import com.intellij.lang.HelpID
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.ext.RsNamedElement
class RsFindUsagesProvider : FindUsagesProvider {
// XXX: must return new instance of WordScanner here, because it is not thread safe
override fun getWordsScanner() = RsWordScanner()
override fun canFindUsagesFor(element: PsiElement) =
element is RsNamedElement
override fun getHelpId(element: PsiElement) = HelpID.FIND_OTHER_USAGES
override fun getType(element: PsiElement) = ""
override fun getDescriptiveName(element: PsiElement) = (element as? RsNamedElement)?.name.orEmpty()
override fun getNodeText(element: PsiElement, useFullName: Boolean) = ""
}
| mit | 7db34e19346328a88e98cc80c24235db | 35.12 | 103 | 0.761905 | 4.426471 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/preprocessor/FortranMacroContext.kt | 1 | 2043 | package org.jetbrains.fortran.lang.preprocessor
import gnu.trove.THashMap
import java.util.*
interface FortranMacrosContext {
fun define(macro: FortranMacro)
fun undefine(name: String)
fun isDefined(name: String?): Boolean
fun enterIf(decision: Boolean)
fun exitIf()
fun enterElse()
fun enterElseIf(decision: Boolean)
fun inEvaluatedContext(): Boolean
}
class FortranMacrosContextImpl : FortranMacrosContext {
class Condition(
val decision: Boolean,
val isElseIf: Boolean = false
)
private val macros = THashMap<String, FortranMacro>()
private val nestedConditions = ArrayDeque<Condition>()
override fun define(macro: FortranMacro) {
if (inEvaluatedContext()) {
macros[macro.name] = macro
}
}
override fun undefine(name: String) {
if (inEvaluatedContext()) {
macros.remove(name)
}
}
override fun isDefined(name: String?) = name != null && macros.contains(name)
override fun enterIf(decision: Boolean) {
nestedConditions.push(Condition(decision))
}
override fun exitIf() {
if (nestedConditions.size != 0) {
var cnd = nestedConditions.pop()
while (nestedConditions.size != 0 && cnd.isElseIf) {
cnd = nestedConditions.pop()
}
}
}
override fun enterElse() {
if (nestedConditions.size != 0) {
val ifCond = nestedConditions.pop()
nestedConditions.push(Condition(!ifCond.decision, ifCond.isElseIf))
}
}
override fun enterElseIf(decision: Boolean) {
if (nestedConditions.size != 0) {
val ifCond = nestedConditions.pop()
nestedConditions.push(Condition(!ifCond.decision, ifCond.isElseIf))
nestedConditions.push(Condition(decision, isElseIf = true))
}
}
override fun inEvaluatedContext(): Boolean {
return nestedConditions.fold(true) { total, el -> total && el.decision }
}
} | apache-2.0 | 11cf62f6892bf05bbea5b42842fd3f54 | 27 | 81 | 0.624572 | 4.365385 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/macros/errors/MacroExpansionError.kt | 2 | 8419 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.errors
import com.intellij.util.io.IOUtil
import org.rust.lang.core.macros.MACRO_LOG
import org.rust.lang.core.macros.decl.FragmentKind
import org.rust.stdext.*
import java.io.DataInput
import java.io.DataOutput
import java.io.IOException
/**
* An error type for [org.rust.lang.core.macros.MacroExpander]
*/
sealed class MacroExpansionError
sealed class DeclMacroExpansionError : MacroExpansionError() {
data class Matching(val errors: List<MacroMatchingError>) : DeclMacroExpansionError()
object DefSyntax : DeclMacroExpansionError()
object TooLargeExpansion : DeclMacroExpansionError()
}
sealed class MacroMatchingError {
abstract val offsetInCallBody: Int
data class PatternSyntax(override val offsetInCallBody: Int) : MacroMatchingError()
data class ExtraInput(override val offsetInCallBody: Int) : MacroMatchingError()
data class EndOfInput(override val offsetInCallBody: Int) : MacroMatchingError()
data class UnmatchedToken(
override val offsetInCallBody: Int,
val expectedTokenType: String,
val expectedTokenText: String,
val actualTokenType: String,
val actualTokenText: String
) : MacroMatchingError() {
override fun toString(): String = "${super.toString()}(" +
"$expectedTokenType(`$expectedTokenText`) != $actualTokenType(`$actualTokenText`)" +
")"
}
data class FragmentIsNotParsed(
override val offsetInCallBody: Int,
val variableName: String,
val kind: FragmentKind
) : MacroMatchingError() {
override fun toString(): String = "${super.toString()}($variableName, $kind)"
}
data class EmptyGroup(override val offsetInCallBody: Int) : MacroMatchingError()
data class TooFewGroupElements(override val offsetInCallBody: Int) : MacroMatchingError()
data class Nesting(override val offsetInCallBody: Int, val variableName: String) : MacroMatchingError() {
override fun toString(): String = "${super.toString()}($variableName)"
}
override fun toString(): String = "${MacroMatchingError::class.simpleName}.${javaClass.simpleName}"
}
sealed class ProcMacroExpansionError : MacroExpansionError() {
/** An error occurred on the proc macro expander side. This usually means a panic from a proc-macro */
data class ServerSideError(val message: String) : ProcMacroExpansionError() {
override fun toString(): String = "${super.toString()}(message = \"$message\")"
}
/**
* The proc macro expander process exited before answering the request.
* This can indicate an issue with the procedural macro (a segfault or `std::process::exit()` call)
* or an issue with the proc macro expander process, for example it was killed by a user or OOM-killed.
*/
data class ProcessAborted(val exitCode: Int) : ProcMacroExpansionError()
/**
* An [IOException] thrown during communicating with the proc macro expander
* (this includes possible OS errors and JSON serialization/deserialization errors).
* The stacktrace is logged to [MACRO_LOG] logger.
*/
object IOExceptionThrown : ProcMacroExpansionError()
data class Timeout(val timeout: Long) : ProcMacroExpansionError()
object CantRunExpander : ProcMacroExpansionError()
object ExecutableNotFound : ProcMacroExpansionError()
object ProcMacroExpansionIsDisabled : ProcMacroExpansionError()
override fun toString(): String = "${ProcMacroExpansionError::class.simpleName}.${javaClass.simpleName}"
}
object BuiltinMacroExpansionError : MacroExpansionError()
@Throws(IOException::class)
fun DataOutput.writeMacroExpansionError(err: MacroExpansionError) {
val ordinal = when (err) {
is DeclMacroExpansionError.Matching -> 0
DeclMacroExpansionError.DefSyntax -> 1
is ProcMacroExpansionError.ServerSideError -> 2
is ProcMacroExpansionError.ProcessAborted -> 3
is ProcMacroExpansionError.IOExceptionThrown -> 4
is ProcMacroExpansionError.Timeout -> 5
ProcMacroExpansionError.CantRunExpander -> 6
ProcMacroExpansionError.ExecutableNotFound -> 7
ProcMacroExpansionError.ProcMacroExpansionIsDisabled -> 8
BuiltinMacroExpansionError -> 9
DeclMacroExpansionError.TooLargeExpansion -> 10
}
writeByte(ordinal)
when (err) {
is DeclMacroExpansionError.Matching -> {
writeVarInt(err.errors.size)
for (error in err.errors) {
saveMatchingError(error)
}
}
is ProcMacroExpansionError.ServerSideError -> IOUtil.writeUTF(this, err.message)
is ProcMacroExpansionError.ProcessAborted -> writeInt(err.exitCode)
is ProcMacroExpansionError.Timeout -> writeLong(err.timeout)
else -> Unit
}.exhaustive
}
@Throws(IOException::class)
fun DataInput.readMacroExpansionError(): MacroExpansionError = when (val ordinal = readUnsignedByte()) {
0 -> {
val size = readVarInt()
DeclMacroExpansionError.Matching((0 until size).map { readMatchingError() })
}
1 -> DeclMacroExpansionError.DefSyntax
2 -> ProcMacroExpansionError.ServerSideError(IOUtil.readUTF(this))
3 -> ProcMacroExpansionError.ProcessAborted(readInt())
4 -> ProcMacroExpansionError.IOExceptionThrown
5 -> ProcMacroExpansionError.Timeout(readLong())
6 -> ProcMacroExpansionError.CantRunExpander
7 -> ProcMacroExpansionError.ExecutableNotFound
8 -> ProcMacroExpansionError.ProcMacroExpansionIsDisabled
9 -> BuiltinMacroExpansionError
10 -> DeclMacroExpansionError.TooLargeExpansion
else -> throw IOException("Unknown expansion error code $ordinal")
}
@Throws(IOException::class)
private fun DataOutput.saveMatchingError(value: MacroMatchingError) {
val ordinal = when (value) {
is MacroMatchingError.PatternSyntax -> 0
is MacroMatchingError.ExtraInput -> 1
is MacroMatchingError.EndOfInput -> 2
is MacroMatchingError.UnmatchedToken -> 3
is MacroMatchingError.FragmentIsNotParsed -> 4
is MacroMatchingError.EmptyGroup -> 5
is MacroMatchingError.TooFewGroupElements -> 6
is MacroMatchingError.Nesting -> 7
}
writeByte(ordinal)
writeVarInt(value.offsetInCallBody)
when (value) {
is MacroMatchingError.UnmatchedToken -> {
IOUtil.writeUTF(this, value.expectedTokenType)
IOUtil.writeUTF(this, value.expectedTokenText)
IOUtil.writeUTF(this, value.actualTokenType)
IOUtil.writeUTF(this, value.actualTokenText)
}
is MacroMatchingError.FragmentIsNotParsed -> {
IOUtil.writeUTF(this, value.variableName)
writeEnum(value.kind)
}
is MacroMatchingError.Nesting -> {
IOUtil.writeUTF(this, value.variableName)
}
else -> Unit
}.exhaustive
}
@Throws(IOException::class)
private fun DataInput.readMatchingError(): MacroMatchingError {
val ordinal = readUnsignedByte()
val offsetInCallBody = readVarInt()
return when (ordinal) {
0 -> MacroMatchingError.PatternSyntax(offsetInCallBody)
1 -> MacroMatchingError.ExtraInput(offsetInCallBody)
2 -> MacroMatchingError.EndOfInput(offsetInCallBody)
3 -> MacroMatchingError.UnmatchedToken(
offsetInCallBody,
expectedTokenType = IOUtil.readUTF(this),
expectedTokenText = IOUtil.readUTF(this),
actualTokenType = IOUtil.readUTF(this),
actualTokenText = IOUtil.readUTF(this)
)
4 -> MacroMatchingError.FragmentIsNotParsed(offsetInCallBody, IOUtil.readUTF(this), readEnum())
5 -> MacroMatchingError.EmptyGroup(offsetInCallBody)
6 -> MacroMatchingError.TooFewGroupElements(offsetInCallBody)
7 -> MacroMatchingError.Nesting(offsetInCallBody, IOUtil.readUTF(this))
else -> throw IOException("Unknown matching error code $ordinal")
}
}
/**
* Some proc macro errors are not cached because they are pretty unstable
* (subsequent macro invocations may succeed)
*/
fun MacroExpansionError.canCacheError() = when (this) {
is DeclMacroExpansionError -> true
BuiltinMacroExpansionError -> true
is ProcMacroExpansionError -> false
}
| mit | 54ac473760a44152bf19d954128b4735 | 38.525822 | 109 | 0.709704 | 4.685031 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/rest/evomaster/src/test/kotlin/org/tsdes/advanced/rest/evomaster/EvoMasterDriver.kt | 1 | 3029 | package org.tsdes.advanced.rest.evomaster
import com.p6spy.engine.spy.P6SpyDriver
import org.evomaster.client.java.controller.EmbeddedSutController
import org.evomaster.client.java.controller.InstrumentedSutStarter
import org.evomaster.client.java.controller.api.dto.AuthenticationDto
import org.evomaster.client.java.controller.api.dto.SutInfoDto
import org.evomaster.client.java.controller.db.DbCleaner
import org.evomaster.client.java.controller.problem.ProblemInfo
import org.evomaster.client.java.controller.problem.RestProblem
import org.springframework.boot.SpringApplication
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.jdbc.core.JdbcTemplate
import org.tsdes.advanced.rest.guiv1.BookApplication
import java.sql.Connection
class EvoMasterDriver : EmbeddedSutController() {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val controller = EvoMasterDriver()
val starter = InstrumentedSutStarter(controller)
starter.start()
}
}
private var ctx: ConfigurableApplicationContext? = null
private var connection: Connection? = null
protected fun getSutPort(): Int {
return (ctx!!.environment
.propertySources.get("server.ports")!!
.source as Map<*, *>)["local.server.port"] as Int
}
override fun getPackagePrefixesToCover(): String {
return "org.tsdes.advanced"
}
override fun getConnection(): Connection? {
return connection
}
override fun getPreferredOutputFormat(): SutInfoDto.OutputFormat {
return SutInfoDto.OutputFormat.KOTLIN_JUNIT_5
}
override fun isSutRunning(): Boolean {
return ctx != null && ctx!!.isRunning
}
override fun resetStateOfSUT() {
DbCleaner.clearDatabase_H2(connection)
}
override fun startSut(): String {
ctx = SpringApplication.run(BookApplication::class.java,
"--server.port=0",
"--spring.datasource.url=jdbc:p6spy:h2:mem:testdb;DB_CLOSE_DELAY=-1;",
"--spring.datasource.driver-class-name=" + P6SpyDriver::class.java.name,
"--spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
"--spring.datasource.username=sa",
"--spring.datasource.password"
)!!
connection?.close()
val jdbc = ctx!!.getBean(JdbcTemplate::class.java)
connection = jdbc.dataSource!!.connection
return "http://localhost:" + getSutPort()
}
override fun stopSut() {
ctx?.stop()
}
override fun getInfoForAuthentication(): MutableList<AuthenticationDto>? {
return null
}
override fun getProblemInfo(): ProblemInfo {
return RestProblem(
"http://localhost:" + getSutPort() + "/v2/api-docs",
listOf("/error")
)
}
override fun getDatabaseDriverName(): String {
return "org.h2.Driver"
}
} | lgpl-3.0 | 8c5f98c150640b4ade1ae7009cd44c4f | 29.606061 | 88 | 0.667877 | 4.500743 | false | false | false | false |
androidx/androidx | text/text/src/main/java/androidx/compose/ui/text/android/TempListUtils.kt | 3 | 3265 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.android
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
// TODO: remove these when we can add new APIs to ui-util outside of beta cycle
/**
* Iterates through a [List] using the index and calls [action] for each item.
* This does not allocate an iterator like [Iterable.forEach].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@OptIn(ExperimentalContracts::class)
internal inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
contract { callsInPlace(action) }
for (index in indices) {
val item = get(index)
action(item)
}
}
/**
* Applies the given [transform] function to each element of the original collection
* and appends the results to the given [destination].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R, C : MutableCollection<in R>> List<T>.fastMapTo(
destination: C,
transform: (T) -> R
): C {
contract { callsInPlace(transform) }
fastForEach { item ->
destination.add(transform(item))
}
return destination
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each pair of two adjacent elements in this collection.
*
* The returned list is empty if this collection contains less than two elements.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R> List<T>.fastZipWithNext(transform: (T, T) -> R): List<R> {
contract { callsInPlace(transform) }
if (size == 0 || size == 1) return emptyList()
val result = mutableListOf<R>()
var current = get(0)
// `until` as we don't want to invoke this for the last element, since that won't have a `next`
for (i in 0 until lastIndex) {
val next = get(i + 1)
result.add(transform(current, next))
current = next
}
return result
}
| apache-2.0 | b5b8a7bb24614dd77b25a76169ef2359 | 37.869048 | 99 | 0.712404 | 4.148666 | false | false | false | false |
mauriciocoelho/upcomingmovies | domain/src/test/kotlin/com/mauscoelho/upcomingmovies/domain/GenreServiceTest.kt | 1 | 1613 | package com.mauscoelho.upcomingmovies.domain
import br.ufs.github.rxassertions.RxAssertions
import com.mauscoelho.upcomingmovies.domain.interactor.GenreServiceImpl
import com.mauscoelho.upcomingmovies.infrastructure.boundary.GenreRepository
import com.mauscoelho.upcomingmovies.model.Genre
import com.mauscoelho.upcomingmovies.model.Genres
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.mock
import rx.Observable
@RunWith(JUnitPlatform::class)
class GenreServiceTest : Spek({
val genreRepository = mock(GenreRepository::class.java)
val genreService = GenreServiceImpl(genreRepository)
val apiKey = "1f54bd990f1cdfb230adb312546d765d"
val language = "en-US"
describe("GenreServiceTest") {
context("Get genres") {
it("should return genres from service") {
val expected = Genres(listOf(Genre(1,"Horror"), Genre(2, "Terror")))
val result = Genres(listOf(Genre(1,"Horror"), Genre(2, "Terror")))
Mockito.`when`(genreRepository.loadGenres(apiKey, language)).thenReturn(Observable.just(result))
RxAssertions.assertThat(genreService.loadGenres(apiKey, language))
.completes()
.withoutErrors()
.emissionsCount(1)
.expectedSingleValue(expected)
}
}
}
}) | apache-2.0 | 363b223cd89da66af6a611bca9758ef3 | 38.365854 | 112 | 0.701798 | 4.312834 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/work/analogs/WorkAnalogsFragment.kt | 2 | 2815 | package ru.fantlab.android.ui.modules.work.analogs
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.WorkAnalog
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.adapter.AnalogsAdapter
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.work.WorkPagerActivity
import ru.fantlab.android.ui.modules.work.WorkPagerMvp
class WorkAnalogsFragment : BaseFragment<WorkAnalogsMvp.View, WorkAnalogsPresenter>(),
WorkAnalogsMvp.View {
private val adapter: AnalogsAdapter by lazy { AnalogsAdapter(arrayListOf()) }
private var pagerCallback: WorkPagerMvp.View? = null
override fun fragmentLayout() = R.layout.micro_grid_refresh_list
override fun providePresenter() = WorkAnalogsPresenter()
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
stateLayout.hideProgress()
}
stateLayout.setEmptyText(R.string.no_analogs)
stateLayout.setOnReloadListener(this)
refresh.setOnRefreshListener(this)
recycler.setEmptyView(stateLayout, refresh)
adapter.listener = presenter
recycler.adapter = adapter
fastScroller.attachRecyclerView(recycler)
presenter.onFragmentCreated(arguments)
}
override fun onInitViews(analogs: ArrayList<WorkAnalog>) {
hideProgress()
if (analogs.isEmpty()) {
stateLayout.showEmptyState()
return
}
adapter.addItems(analogs)
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
companion object {
val TAG: String = WorkAnalogsFragment::class.java.simpleName
fun newInstance(workId: Int): WorkAnalogsFragment {
val view = WorkAnalogsFragment()
view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end()
return view
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is WorkPagerMvp.View) {
pagerCallback = context
}
}
override fun onDetach() {
pagerCallback = null
super.onDetach()
}
override fun onSetTabCount(count: Int) {
pagerCallback?.onSetBadge(2, count)
}
override fun onRefresh() {
presenter.getAnalogs(true)
}
override fun onNotifyAdapter() {
hideProgress()
adapter.notifyDataSetChanged()
}
override fun onClick(p0: View?) {
onRefresh()
}
override fun onItemClicked(item: WorkAnalog) {
WorkPagerActivity.startActivity(context!!, item.id, item.name, 0)
}
} | gpl-3.0 | 2fa5803dcba9bd94ac12b3e5c9f13d16 | 26.339806 | 86 | 0.773002 | 3.768407 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-retrofit2/src/main/kotlin/org/ccci/gto/android/common/retrofit2/converter/JSONObjectConverterFactory.kt | 2 | 1890 | package org.ccci.gto.android.common.retrofit2.converter
import java.io.IOException
import java.lang.reflect.Type
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Converter
import retrofit2.Retrofit
object JSONObjectConverterFactory : Converter.Factory() {
override fun requestBodyConverter(
type: Type,
parameterAnnotations: Array<Annotation>,
methodAnnotations: Array<Annotation>,
retrofit: Retrofit
): Converter<*, RequestBody>? = when (type) {
JSONObject::class.java, JSONArray::class.java -> JSONObjectRequestBodyConverter
else -> null
}
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit) = when (type) {
JSONObject::class.java -> JSONObjectResponseBodyConverter
JSONArray::class.java -> JSONArrayResponseBodyConverter
else -> null
}
private object JSONObjectRequestBodyConverter : Converter<Any?, RequestBody> {
private val MEDIA_TYPE = MediaType.parse("text/json; charset=UTF-8")
override fun convert(value: Any?): RequestBody = RequestBody.create(MEDIA_TYPE, value?.toString().orEmpty())
}
private object JSONObjectResponseBodyConverter : Converter<ResponseBody, JSONObject> {
override fun convert(value: ResponseBody) = try {
JSONObject(value.string())
} catch (e: JSONException) {
throw IOException("Error parsing JSON", e)
}
}
private object JSONArrayResponseBodyConverter : Converter<ResponseBody, JSONArray> {
override fun convert(value: ResponseBody) = try {
JSONArray(value.string())
} catch (e: JSONException) {
throw IOException("Error parsing JSON", e)
}
}
}
| mit | 56a229938f8489d1a44cc3efdcce0d62 | 35.346154 | 118 | 0.700529 | 4.921875 | false | false | false | false |
remdevlab/android-rem-com | commander/src/main/java/org/remdev/android/commander/models/InteractionResult.kt | 1 | 3385 | package org.remdev.android.commander.models;
import org.remdev.android.commander.ResultCodes
import org.remdev.android.commander.annotations.POJO
import org.remdev.android.commander.utils.fromJson
import org.remdev.android.commander.utils.getClass
import org.remdev.android.commander.utils.toJson
import org.remdev.timlog.Log
import org.remdev.timlog.LogFactory
open class InteractionResult<T: Any?> : JsonSerializable<InteractionResult<T>> {
var code = 0
var errorCode = 0
@POJO
var payload : T? = null
override fun toJson(): String {
val map : MutableMap<String, String> = mutableMapOf(
FIELD_CODE to code.toString(),
FIELD_ERROR_CODE to errorCode.toString()
)
payload?.let {
map.put(FIELD_PAYLOAD_CLASS, getClass(it!!).name)
map.put(FIELD_PAYLOAD, toJson(it))
}
return toJson(map)
}
companion object {
val log : Log = LogFactory.create(InteractionResult::class.java)
const val FIELD_CODE = "code"
const val FIELD_ERROR_CODE = "errorCode"
const val FIELD_PAYLOAD_CLASS = "payloadClass"
const val FIELD_PAYLOAD = "payload"
fun success() : InteractionResult<Any?> = success(null)
fun <R> success(payload: R) : InteractionResult<R> {
val res = InteractionResult<R>()
res.code = ResultCodes.CODE_OK
res.errorCode = 0
res.payload = payload
return res
}
fun <R> error() : InteractionResult<R?> = error(0)
fun <R> error(errorCode: Int): InteractionResult<R?> = error(errorCode, null)
fun <R> error(@POJO payload: R?): InteractionResult<R?> = error(0, payload)
fun <R> error(errorCode: Int, @POJO payload: R?): InteractionResult<R> {
val result = InteractionResult<R>()
result.code = ResultCodes.CODE_ERROR
result.errorCode = errorCode
result.payload = payload
return result
}
fun <T> parseFromJson(json: String?) : InteractionResult<T>? {
if (json == null) {
return null
}
val map = fromJson(json, Map::class.java)
if (map == null) {
return null;
}
val code = (map[FIELD_CODE] as String?)?.toInt()
val errorCode = (map[FIELD_ERROR_CODE] as String?)?.toInt()
val className = map[FIELD_PAYLOAD_CLASS] as String?
val payloadJson = map[FIELD_PAYLOAD] as String?
if (code == null || errorCode == null) {
throw IllegalArgumentException("Invalid json: " + json);
}
var payload : T? = null
if (className != null) {
try {
@Suppress("UNCHECKED_CAST")
val clazz = Class.forName(className) as Class<T>
payload = fromJson(payloadJson, clazz)
} catch (e: ClassNotFoundException) {
log.e("Could not found class %s", className)
throw IllegalArgumentException("Invalid json: "+ json)
}
}
val res = InteractionResult<T>();
res.code = code
res.errorCode = errorCode
res.payload = payload
return res;
}
}
} | apache-2.0 | f3816a1751fd26a38edaa53b2cd99289 | 35.021277 | 85 | 0.565731 | 4.465699 | false | false | false | false |
JetBrains-Research/big | src/main/kotlin/org/jetbrains/bio/tdf/TdfTile.kt | 2 | 4724 | package org.jetbrains.bio.tdf
import org.jetbrains.bio.RomBuffer
import org.jetbrains.bio.ScoredInterval
import org.slf4j.LoggerFactory
/**
* Data container in [TdfFile].
*
* @since 0.2.2
*/
interface TdfTile {
fun view(trackNumber: Int) = TdfTileView(this, trackNumber)
fun getValue(trackNumber: Int, idx: Int): Float
fun getStartOffset(idx: Int): Int
fun getEndOffset(idx: Int): Int
/** Number of data points in a tile. */
val size: Int
companion object {
private val LOG = LoggerFactory.getLogger(TdfTile::class.java)
internal fun read(input: RomBuffer, expectedTracks: Int) = with(input) {
val type = readCString()
when (type) {
"fixedStep" -> TdfFixedTile.fill(this, expectedTracks)
"variableStep" -> TdfVaryTile.fill(this, expectedTracks)
"bed", "bedWithName" -> {
if (type === "bedWithName") {
LOG.warn("bedWithName is not supported, assuming bed")
}
TdfBedTile.fill(this, expectedTracks)
}
else -> error("unexpected type: $type")
}
}
}
}
/** A view of a single track in a [TdfTile]. */
class TdfTileView(private val tile: TdfTile,
private val trackNumber: Int) : Iterable<ScoredInterval?> {
override fun iterator(): Iterator<ScoredInterval?> {
return (0 until tile.size).asSequence().map {
val value = tile.getValue(trackNumber, it)
if (value.isNaN()) {
null
} else {
val start = tile.getStartOffset(it)
val end = tile.getEndOffset(it)
ScoredInterval(start, end, value)
}
}.iterator()
}
}
data class TdfBedTile(val starts: IntArray, val ends: IntArray,
val data: Array<FloatArray>) : TdfTile {
override val size: Int get() = starts.size
override fun getStartOffset(idx: Int) = starts[idx]
override fun getEndOffset(idx: Int) = ends[idx]
override fun getValue(trackNumber: Int, idx: Int) = data[trackNumber][idx]
companion object {
fun fill(input: RomBuffer, expectedTracks: Int) = with(input) {
val size = readInt()
val start = readInts(size)
val end = readInts(size)
val trackCount = readInt()
check(trackCount == expectedTracks) {
"expected $expectedTracks tracks, got: $trackCount"
}
val data = Array(trackCount) {
readFloats(size)
}
TdfBedTile(start, end, data)
}
}
}
data class TdfFixedTile(val start: Int, val span: Double,
val data: Array<FloatArray>) : TdfTile {
override val size: Int get() = data.first().size
override fun getStartOffset(idx: Int): Int {
return start + (idx * span).toInt()
}
override fun getEndOffset(idx: Int): Int {
return start + ((idx + 1) * span).toInt()
}
override fun getValue(trackNumber: Int, idx: Int) = data[trackNumber][idx]
companion object {
fun fill(input: RomBuffer, expectedTracks: Int) = with(input) {
val size = readInt()
val start = readInt()
val span = readInt().toDouble()
// vvv not part of the implementation, see igvteam/igv/#180.
// val trackCount = readInt()
val data = Array(expectedTracks) {
readFloats(size)
}
TdfFixedTile(start, span, data)
}
}
}
data class TdfVaryTile(val starts: IntArray,
val span: Int,
val data: Array<FloatArray>) : TdfTile {
override val size: Int get() = starts.size
override fun getStartOffset(idx: Int) = starts[idx]
override fun getEndOffset(idx: Int) = (starts[idx] + span).toInt()
override fun getValue(trackNumber: Int, idx: Int) = data[trackNumber][idx]
companion object {
fun fill(input: RomBuffer, expectedTracks: Int) = with(input) {
// This is called 'tiledStart' in IGV sources and is unused.
readInt() // start
val span = readFloat().toInt() // Really?
val size = readInt()
val step = readInts(size)
val trackCount = readInt()
check(trackCount == expectedTracks) {
"expected $expectedTracks tracks, got: $trackCount"
}
val data = Array(trackCount) {
readFloats(size)
}
TdfVaryTile(step, span, data)
}
}
} | mit | c2b27580ec2c7eb09e432abfc4791b7b | 28.905063 | 80 | 0.556943 | 4.271248 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/lang/highlighter/SchemaTypeAnnotator.kt | 1 | 6442 | /*
* Copyright (C) 2020-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.highlighter
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.XmlHighlighterColors
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.schema.ISchemaListType
import uk.co.reecedunn.intellij.plugin.xdm.schema.ISchemaType
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathNCName
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathQName
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathSequenceType
import uk.co.reecedunn.intellij.plugin.xslt.ast.schema.XsltHashedKeyword
import uk.co.reecedunn.intellij.plugin.xslt.resources.XsltBundle
import uk.co.reecedunn.intellij.plugin.xslt.schema.XsltSchemaTypes
class SchemaTypeAnnotator(val schemaType: ISchemaType? = null) : Annotator {
companion object {
@Suppress("RegExpAnonymousGroup")
val REMOVE_START: Regex = "^(Plugin|Scripting|UpdateFacility|XPath|XQuery|Xslt)".toRegex()
@Suppress("RegExpAnonymousGroup")
val REMOVE_END: Regex = "(PsiImpl|Impl)$".toRegex()
}
private fun getSymbolName(element: PsiElement): String {
return element.javaClass.name.split('.').last().replace(REMOVE_START, "").replace(REMOVE_END, "")
}
fun accept(schemaType: ISchemaType, element: PsiElement): Boolean = when (schemaType) {
XsltSchemaTypes.XslAccumulatorNames -> when (element) {
is XsltHashedKeyword -> element.keyword === XsltSchemaTypes.KAll
else -> true
}
XsltSchemaTypes.XslDefaultModeType -> when (element) {
is XsltHashedKeyword -> element.keyword === XsltSchemaTypes.KUnnamed
else -> true
}
XsltSchemaTypes.XslEQName,
XsltSchemaTypes.XslEQNameInNamespace,
XsltSchemaTypes.XslEQNames,
XsltSchemaTypes.XslStreamabilityType ->
element !is XsltHashedKeyword
XsltSchemaTypes.XslItemType -> element !is XPathSequenceType
XsltSchemaTypes.XslMode -> when (element) {
is XsltHashedKeyword -> when (element.keyword) {
XsltSchemaTypes.KCurrent -> true
XsltSchemaTypes.KDefault -> true
XsltSchemaTypes.KUnnamed -> true
else -> false
}
else -> true
}
XsltSchemaTypes.XslModes -> when (element) {
is XsltHashedKeyword -> when (element.keyword) {
XsltSchemaTypes.KAll -> true
XsltSchemaTypes.KDefault -> true
XsltSchemaTypes.KUnnamed -> true
else -> false
}
else -> true
}
XsltSchemaTypes.XslPrefixes, XsltSchemaTypes.XslTokens -> when (element) {
is XPathNCName -> true
is PsiWhiteSpace -> true
is PsiErrorElement -> true
else -> false
}
XsltSchemaTypes.XslPrefix, XsltSchemaTypes.XslPrefixList, XsltSchemaTypes.XslPrefixOrDefault -> when (element) {
is XsltHashedKeyword -> element.keyword === XsltSchemaTypes.KDefault
is XPathNCName -> true
is PsiWhiteSpace -> true
is PsiErrorElement -> true
else -> false
}
XsltSchemaTypes.XslPrefixListOrAll -> when (element) {
is XsltHashedKeyword -> when (element.keyword) {
XsltSchemaTypes.KAll -> true
XsltSchemaTypes.KDefault -> true
else -> false
}
is XPathNCName -> true
is PsiWhiteSpace -> true
is PsiErrorElement -> true
else -> false
}
XsltSchemaTypes.XslMethod, XsltSchemaTypes.XslQName, XsltSchemaTypes.XslQNames -> when (element) {
is XPathNCName -> true
is XPathQName -> true
is PsiWhiteSpace -> true
is PsiErrorElement -> true
else -> false
}
XsltSchemaTypes.XslSequenceType -> true
else -> true
}
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element !is PsiFile) return
val schemaType = schemaType ?: XsltSchemaTypes.create(element) ?: return
var itemCount = 0
element.children().forEach { child ->
if (child is XsltHashedKeyword) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(child)
.textAttributes(XmlHighlighterColors.XML_ATTRIBUTE_VALUE)
.create()
}
if (accept(schemaType, child)) {
if (child !is PsiWhiteSpace && child !is PsiErrorElement) {
itemCount += 1
if (itemCount > 1 && schemaType !is ISchemaListType) {
val message = XsltBundle.message("schema.validation.multiple-items", schemaType.type)
holder.newAnnotation(HighlightSeverity.ERROR, message).range(child).create()
}
}
} else {
val symbol = getSymbolName(child)
val message =
if (child is XsltHashedKeyword)
XsltBundle.message("schema.validation.unsupported-keyword", child.text, schemaType.type)
else
XsltBundle.message("schema.validation.unsupported", symbol, schemaType.type)
holder.newAnnotation(HighlightSeverity.ERROR, message).range(child).create()
}
}
}
}
| apache-2.0 | 026604b11eccb4e1c3a754cda5e5399d | 42.234899 | 120 | 0.635206 | 4.668116 | false | false | false | false |
WillowChat/Hopper | src/main/kotlin/chat/willow/hopper/routes/connection/ConnectionGetRouteHandler.kt | 1 | 1817 | package chat.willow.hopper.routes.connection
import chat.willow.hopper.connections.HopperConnection
import chat.willow.hopper.connections.IHopperConnections
import chat.willow.hopper.logging.loggerFor
import chat.willow.hopper.routes.*
import chat.willow.hopper.routes.shared.EmptyBody
import chat.willow.hopper.routes.shared.ErrorResponseBody
import com.squareup.moshi.Moshi
import spark.Request
// todo: compose contexts
data class ConnectionGetContext(val authenticatedContext: AuthenticatedContext, val id: String) {
companion object Builder: IContextBuilder<ConnectionGetContext> {
override fun build(request: Request): ConnectionGetContext? {
val authContext = AuthenticatedContext.Builder.build(request) ?: return null
val id = request.params("connection_id") ?: return null
return ConnectionGetContext(authContext, id)
}
}
}
data class ConnectionGetResponseBody(val connection: HopperConnection)
class ConnectionGetRouteHandler(moshi: Moshi, private val connections: IHopperConnections) :
JsonRouteHandler<EmptyBody, ConnectionGetResponseBody, ConnectionGetContext>(
EmptyBody,
moshi.stringSerialiser(),
moshi.stringSerialiser(),
ConnectionGetContext.Builder
) {
private val LOGGER = loggerFor<ConnectionGetRouteHandler>()
override fun handle(request: EmptyBody, context: ConnectionGetContext): RouteResult<ConnectionGetResponseBody, ErrorResponseBody> {
LOGGER.info("handling GET /connection for id ${context.id}: $request")
val server = connections[context.id] ?: return jsonFailure(404, message = "couldn't find a server with id ${context.id}")
return RouteResult.success(value = ConnectionGetResponseBody(server))
}
} | isc | 8fbb8ce005f07f8f6e2f3caa133a0e51 | 38.521739 | 135 | 0.742433 | 4.69509 | false | false | false | false |
andrewvora/historian | app/src/main/java/com/andrewvora/apps/historian/history/HistoryAdapter.kt | 1 | 3328 | package com.andrewvora.apps.historian.history
import android.support.v7.widget.RecyclerView
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.ButterKnife
import com.andrewvora.apps.historian.R
import com.andrewvora.apps.historian.common.SelectableAdapter
import com.andrewvora.apps.historian.data.models.Snapshot
import com.andrewvora.apps.historian.util.TimeFormatter
/**
* Created on 6/11/2017.
* @author Andrew Vorakrajangthiti
*/
class HistoryAdapter(var snapshots: List<Snapshot>, val listener: ActionListener) :
RecyclerView.Adapter<HistoryAdapter.SnapshotViewHolder>(),
SelectableAdapter
{
interface ActionListener {
fun snapshotClicked(snapshot: Snapshot, position: Int)
fun snapshotLongPressed(snapshot: Snapshot, position: Int)
}
constructor(snaps: List<Snapshot>, listen: ActionListener, selected: SparseBooleanArray) : this(snaps, listen) {
this.selected = selected
}
private var selected = SparseBooleanArray()
override fun onBindViewHolder(holder: SnapshotViewHolder?, position: Int) {
val snapshot = snapshots[position]
holder?.nameTextView?.text = snapshot.name()
holder?.timeTextView?.text = TimeFormatter.formatTimestamp(
holder?.itemView?.context,
snapshot.capturedAt())
holder?.itemView?.isSelected = selected[position]
holder?.itemView?.setOnClickListener {
val clickedSnap = snapshots[holder.adapterPosition]
listener.snapshotClicked(clickedSnap, holder.adapterPosition)
}
holder?.itemView?.setOnLongClickListener {
val pressedSnap = snapshots[holder.adapterPosition]
listener.snapshotLongPressed(pressedSnap, holder.adapterPosition)
true
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): SnapshotViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.row_item_snapshot, parent, false)
return SnapshotViewHolder(view)
}
override fun getItemCount() = snapshots.size
override fun setSelectedAt(position: Int) {
selected.put(position, !selected.get(position))
}
override fun setSelectedArray(selectedArray: SparseBooleanArray) {
selected = selectedArray
}
override fun getSelectedArray(): SparseBooleanArray {
return selected
}
override fun getSelectedCount(): Int {
val count = (0 until snapshots.size).count {
selected[it]
}
return count
}
override fun notifyChanged() {
notifyDataSetChanged()
}
override fun notifyChanged(position: Int) {
notifyItemChanged(position)
}
override fun getTotalCount(): Int {
return itemCount
}
fun setData(snapshots: List<Snapshot>) {
this.snapshots = snapshots
}
class SnapshotViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val nameTextView : TextView = view.findViewById(R.id.snapshot_name)
val timeTextView : TextView = view.findViewById(R.id.snapshot_timestamp)
init {
ButterKnife.bind(this, view)
}
}
}
| mit | 1ae420ca22e19d20bb128f5c002fcc5d | 30.396226 | 116 | 0.69381 | 4.915805 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt | 1 | 3667 | package eu.kanade.tachiyomi.ui.library
import eu.kanade.domain.library.model.LibraryManga
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.getNameForMangaInfo
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class LibraryItem(
val libraryManga: LibraryManga,
private val sourceManager: SourceManager = Injekt.get(),
) {
var displayMode: Long = -1
var downloadCount: Long = -1
var unreadCount: Long = -1
var isLocal = false
var sourceLanguage = ""
/**
* Filters a manga depending on a query.
*
* @param constraint the query to apply.
* @return true if the manga should be included, false otherwise.
*/
fun filter(constraint: String): Boolean {
val sourceName by lazy { sourceManager.getOrStub(libraryManga.manga.source).getNameForMangaInfo() }
val genres by lazy { libraryManga.manga.genre }
return libraryManga.manga.title.contains(constraint, true) ||
(libraryManga.manga.author?.contains(constraint, true) ?: false) ||
(libraryManga.manga.artist?.contains(constraint, true) ?: false) ||
(libraryManga.manga.description?.contains(constraint, true) ?: false) ||
if (constraint.contains(",")) {
constraint.split(",").all { containsSourceOrGenre(it.trim(), sourceName, genres) }
} else {
containsSourceOrGenre(constraint, sourceName, genres)
}
}
/**
* Filters a manga by checking whether the query is the manga's source OR part of
* the genres of the manga
* Checking for genre is done only if the query isn't part of the source name.
*
* @param query the query to check
* @param sourceName name of the manga's source
* @param genres list containing manga's genres
*/
private fun containsSourceOrGenre(query: String, sourceName: String, genres: List<String>?): Boolean {
val minus = query.startsWith("-")
val tag = if (minus) { query.substringAfter("-") } else query
return when (sourceName.contains(tag, true)) {
false -> containsGenre(query, genres)
else -> !minus
}
}
private fun containsGenre(tag: String, genres: List<String>?): Boolean {
return if (tag.startsWith("-")) {
genres?.find {
it.trim().equals(tag.substringAfter("-"), ignoreCase = true)
} == null
} else {
genres?.find {
it.trim().equals(tag, ignoreCase = true)
} != null
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LibraryItem
if (libraryManga != other.libraryManga) return false
if (sourceManager != other.sourceManager) return false
if (displayMode != other.displayMode) return false
if (downloadCount != other.downloadCount) return false
if (unreadCount != other.unreadCount) return false
if (isLocal != other.isLocal) return false
if (sourceLanguage != other.sourceLanguage) return false
return true
}
override fun hashCode(): Int {
var result = libraryManga.hashCode()
result = 31 * result + sourceManager.hashCode()
result = 31 * result + displayMode.hashCode()
result = 31 * result + downloadCount.toInt()
result = 31 * result + unreadCount.toInt()
result = 31 * result + isLocal.hashCode()
result = 31 * result + sourceLanguage.hashCode()
return result
}
}
| apache-2.0 | 811c476cd29c4eb37e1040ea649f4bc2 | 36.804124 | 107 | 0.627488 | 4.653553 | false | false | false | false |
Mindera/skeletoid | apprating/src/main/java/com/mindera/skeletoid/apprating/dialogs/AppRatingDialog.kt | 1 | 4269 | package com.mindera.skeletoid.apprating.dialogs
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import com.mindera.skeletoid.apprating.AppRatingInitializer
import com.mindera.skeletoid.apprating.R
import com.mindera.skeletoid.apprating.callbacks.AppRatingDialogResponse
import com.mindera.skeletoid.apprating.callbacks.AppRatingDialogResponseCallback
import com.mindera.skeletoid.logs.LOG
class AppRatingDialog: DialogFragment() {
companion object {
const val TAG = "AppRatingDialog"
private const val ARGUMENT_TITLE = "ARGUMENT_TITLE"
private const val ARGUMENT_MESSAGE = "ARGUMENT_MESSAGE"
private const val ARGUMENT_POSITIVE_TEXT = "ARGUMENT_POSITIVE_TEXT"
private const val ARGUMENT_NEUTRAL_TEXT = "ARGUMENT_NEUTRAL_TEXT"
private const val ARGUMENT_NEGATIVE_TEXT = "ARGUMENT_NEGATIVE_TEXT"
fun newInstance(
title: Int = R.string.dialog_title,
message: Int = R.string.dialog_message,
positiveButtonText: Int = R.string.dialog_positive_button_text,
neutralButtonText: Int = R.string.dialog_neutral_button_text,
negativeButtonText: Int = R.string.dialog_negative_button_text
): AppRatingDialog {
return AppRatingDialog().apply {
arguments = Bundle().apply {
putInt(ARGUMENT_TITLE, title)
putInt(ARGUMENT_MESSAGE, message)
putInt(ARGUMENT_POSITIVE_TEXT, positiveButtonText)
putInt(ARGUMENT_NEUTRAL_TEXT, neutralButtonText)
putInt(ARGUMENT_NEGATIVE_TEXT, negativeButtonText)
}
}
}
}
private var title: Int = 0
private var message: Int = 0
private var positiveButtonText: Int = 0
private var neutralButtonText: Int = 0
private var negativeButtonText: Int = 0
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
readArguments()
return AlertDialog.Builder(activity)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonText) { _, _ ->
activity?.let {
if (it is AppRatingDialogResponseCallback) {
(it as AppRatingDialogResponseCallback).onRateNowClick()
AppRatingInitializer.handleDialogResponse(it.applicationContext, AppRatingDialogResponse.RATE_NOW)
} else {
LOG.e(TAG, "The activity that calls the prompt should implement AppRatingDialogResponseCallback")
}
}
}
.setNeutralButton(neutralButtonText) { _, _ ->
activity?.let {
if (it is AppRatingDialogResponseCallback) {
(it as AppRatingDialogResponseCallback).onRateLaterClick()
AppRatingInitializer.handleDialogResponse(it.applicationContext, AppRatingDialogResponse.RATE_LATER)
} else {
LOG.e(TAG, "The activity that calls the prompt should implement AppRatingDialogResponseCallback")
}
}
}
.setNegativeButton(negativeButtonText) { _, _ ->
activity?.let {
if (it is AppRatingDialogResponseCallback) {
(it as AppRatingDialogResponseCallback).onNeverRateClick()
AppRatingInitializer.handleDialogResponse(it.applicationContext, AppRatingDialogResponse.NEVER_RATE)
} else {
LOG.e(TAG, "The activity that calls the prompt should implement AppRatingDialogResponseCallback")
}
}
}
.create()
}
private fun readArguments() {
arguments?.let {
title = it.getInt(ARGUMENT_TITLE)
message = it.getInt(ARGUMENT_MESSAGE)
positiveButtonText = it.getInt(ARGUMENT_POSITIVE_TEXT)
neutralButtonText = it.getInt(ARGUMENT_NEUTRAL_TEXT)
negativeButtonText = it.getInt(ARGUMENT_NEGATIVE_TEXT)
}
}
}
| mit | f8026dcbe4293715ad9c449ca60adf92 | 43.010309 | 124 | 0.616304 | 5.376574 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt | 1 | 1913 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType
import java.nio.ByteBuffer
class GetStatusCommand private constructor(
uniqueId: Int,
sequenceNumber: Short,
multiCommandFlag: Boolean,
private val statusResponseType: ResponseType.StatusResponseType
) : HeaderEnabledCommand(CommandType.GET_STATUS, uniqueId, sequenceNumber, multiCommandFlag) {
override val encoded: ByteArray
get() = appendCrc(
ByteBuffer.allocate(LENGTH + HEADER_LENGTH)
.put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag))
.put(commandType.value)
.put(BODY_LENGTH)
.put(statusResponseType.value)
.array()
)
class Builder : HeaderEnabledCommandBuilder<Builder, GetStatusCommand>() {
private var statusResponseType: ResponseType.StatusResponseType? = null
fun setStatusResponseType(statusResponseType: ResponseType.StatusResponseType): Builder {
this.statusResponseType = statusResponseType
return this
}
override fun buildCommand(): GetStatusCommand {
requireNotNull(statusResponseType) { "immediateBeepType can not be null" }
return GetStatusCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, statusResponseType!!)
}
}
companion object {
private const val LENGTH: Short = 3
private const val BODY_LENGTH: Byte = 1
}
}
| agpl-3.0 | a91997a7f1ee5da810d4e0d77098705d | 39.702128 | 119 | 0.722426 | 4.830808 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt | 1 | 3313 | package com.auth0.android.request.internal
import android.util.Base64
import android.util.Log
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
import java.math.BigInteger
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.PublicKey
import java.security.spec.InvalidKeySpecException
import java.security.spec.RSAPublicKeySpec
internal class JwksDeserializer : JsonDeserializer<Map<String, PublicKey>> {
@Throws(JsonParseException::class)
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): Map<String, PublicKey> {
if (!json.isJsonObject || json.isJsonNull || json.asJsonObject.entrySet().isEmpty()) {
throw JsonParseException("jwks json must be a valid and non-empty json object")
}
val jwks = mutableMapOf<String, PublicKey>()
val keys = json.asJsonObject.getAsJsonArray("keys")
for (k in keys) {
val currentKey = k.asJsonObject
val keyAlg = context.deserialize<String>(currentKey["alg"], String::class.java)
val keyUse = context.deserialize<String>(currentKey["use"], String::class.java)
if (RSA_ALGORITHM != keyAlg || USE_SIGNING != keyUse) {
//Key not supported at this time
continue
}
val keyType = context.deserialize<String>(currentKey["kty"], String::class.java)
val keyId = context.deserialize<String>(currentKey["kid"], String::class.java)
val keyModulus = context.deserialize<String>(currentKey["n"], String::class.java)
val keyPublicExponent = context.deserialize<String>(currentKey["e"], String::class.java)
try {
val kf = KeyFactory.getInstance(keyType)
val modulus = BigInteger(
1,
Base64.decode(
keyModulus,
Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP
)
)
val exponent = BigInteger(
1,
Base64.decode(
keyPublicExponent,
Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP
)
)
val pub = kf.generatePublic(RSAPublicKeySpec(modulus, exponent))
jwks[keyId] = pub
} catch (e: NoSuchAlgorithmException) {
Log.e(
JwksDeserializer::class.java.simpleName,
"Could not parse the JWK with ID $keyId",
e
)
//Would result in an empty key set
} catch (e: InvalidKeySpecException) {
Log.e(
JwksDeserializer::class.java.simpleName,
"Could not parse the JWK with ID $keyId",
e
)
}
}
return jwks.toMap()
}
companion object {
private const val RSA_ALGORITHM = "RS256"
private const val USE_SIGNING = "sig"
}
} | mit | 826ff5dd5e91bccad44f429c4c4d4506 | 39.91358 | 100 | 0.582252 | 4.836496 | false | false | false | false |
onoderis/failchat | src/main/kotlin/failchat/twitch/TwitchBadgeHandler.kt | 2 | 1521 | package failchat.twitch
import failchat.chat.MessageHandler
import failchat.chat.badge.Badge
import failchat.chat.badge.BadgeFinder
import failchat.chat.badge.BadgeOrigin.TWITCH_CHANNEL
import failchat.chat.badge.BadgeOrigin.TWITCH_GLOBAL
import failchat.util.notEmptyOrNull
import mu.KLogging
class TwitchBadgeHandler(
private val badgeFinder: BadgeFinder
) : MessageHandler<TwitchMessage> {
private companion object : KLogging()
override fun handleMessage(message: TwitchMessage) {
val badgesTag = message.tags.get(TwitchIrcTags.badges).notEmptyOrNull() ?: return
val messageBadgeIds = parseBadgesTag(badgesTag)
messageBadgeIds.forEach { messageBadgeId ->
val badge: Badge? = badgeFinder.findBadge(TWITCH_CHANNEL, messageBadgeId)
?: badgeFinder.findBadge(TWITCH_GLOBAL, messageBadgeId)
if (badge == null) {
logger.debug("Badge not found. Origin: {}, {}; badge id: {}", TWITCH_CHANNEL, TWITCH_GLOBAL, messageBadgeId)
return@forEach
}
message.addBadge(badge)
}
}
private fun parseBadgesTag(badgesTag: String): List<TwitchBadgeId> {
return badgesTag
.split(',')
.asSequence()
.map { it.split('/', limit = 2) }
.map {
val version = if (it.size < 2) "" else it[1]
TwitchBadgeId(it[0], version)
}
.toList()
}
}
| gpl-3.0 | 10a899b6d2fa56c73645cadfe36c67c8 | 31.361702 | 124 | 0.618014 | 4.460411 | false | false | false | false |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-ext/src/main/java/com/safframework/ext/Boolean+Extension.kt | 1 | 631 | package com.safframework.ext
/**
*
* @FileName:
* com.safframework.ext.Booleans.java
* @author: Tony Shen
* @date: 2018-04-19 00:35
* @version V1.0 <描述当前版本功能>
*/
infix fun <T> Boolean.then(value: T?) = if (this) value else null
fun <T> Boolean.then(value: T?, default: T) = if (this) value else default
inline fun <T> Boolean.then(function: () -> T, default: T) = if (this) function() else default
inline fun <T> Boolean.then(function: () -> T, default: () -> T) = if (this) function() else default()
infix inline fun <reified T> Boolean.then(function: () -> T) = if (this) function() else null | apache-2.0 | d2d9abc554381e16f3dca8f9e5109bd2 | 31.421053 | 102 | 0.645528 | 3.014706 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/editor/media/OptimizeMediaUseCase.kt | 1 | 2773 | package org.wordpress.android.ui.posts.editor.media
import android.net.Uri
import dagger.Reusable
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.posts.editor.EditorTracker
import org.wordpress.android.util.MediaUtilsWrapper
import javax.inject.Inject
import javax.inject.Named
/**
* Optimizes images and fixes their rotation.
*
* Warning: This use case optimizes images only if the user enabled image optimization (AppPrefs.isImageOptimize()).
*/
@Reusable
class OptimizeMediaUseCase @Inject constructor(
private val editorTracker: EditorTracker,
private val mediaUtilsWrapper: MediaUtilsWrapper,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher
) {
suspend fun optimizeMediaIfSupportedAsync(
site: SiteModel,
freshlyTaken: Boolean,
uriList: List<Uri>,
trackEvent: Boolean = true
): OptimizeMediaResult {
return withContext(bgDispatcher) {
uriList
.map { async { optimizeMedia(it, freshlyTaken, site, trackEvent) } }
.map { it.await() }
.let {
OptimizeMediaResult(
optimizedMediaUris = it.filterNotNull(),
loadingSomeMediaFailed = it.contains(null)
)
}
}
}
private fun optimizeMedia(mediaUri: Uri, freshlyTaken: Boolean, site: SiteModel, trackEvent: Boolean): Uri? {
val path = mediaUtilsWrapper.getRealPathFromURI(mediaUri) ?: return null
val isVideo = mediaUtilsWrapper.isVideo(mediaUri.toString())
/**
* If the user enabled the optimize images feature, the image gets rotated in mediaUtils.getOptimizedMedia.
* If the user haven't enabled it, WPCom server takes care of rotating the image, however we need to rotate it
* manually on self-hosted sites. (https://github.com/wordpress-mobile/WordPress-Android/issues/5737)
*/
val updatedMediaUri: Uri = mediaUtilsWrapper.getOptimizedMedia(path, isVideo)
?: if (!site.isWPCom) {
mediaUtilsWrapper.fixOrientationIssue(path, isVideo) ?: mediaUri
} else {
mediaUri
}
if (trackEvent) {
editorTracker.trackAddMediaFromDevice(site, freshlyTaken, isVideo, updatedMediaUri)
}
return updatedMediaUri
}
data class OptimizeMediaResult(
val optimizedMediaUris: List<Uri>,
val loadingSomeMediaFailed: Boolean
)
}
| gpl-2.0 | d9063cab9b7d9b7aa04b08a9d4f0ebcd | 38.056338 | 118 | 0.658853 | 4.951786 | false | false | false | false |
mdaniel/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/SingleConnectionNetService.kt | 13 | 2987 | // 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.builtInWebServer
import com.intellij.execution.process.OSProcessHandler
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.util.io.ConnectToChannelResult
import com.intellij.util.io.addChannelListener
import com.intellij.util.io.closeAndShutdownEventLoop
import com.intellij.util.io.connectRetrying
import com.intellij.util.net.loopbackSocketAddress
import io.netty.bootstrap.Bootstrap
import io.netty.channel.Channel
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.catchError
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.ide.BuiltInServerManager
import java.util.concurrent.atomic.AtomicReference
abstract class SingleConnectionNetService(project: Project) : NetService(project) {
protected val processChannel = AtomicReference<Channel>()
@Volatile
private var port = -1
@Volatile
private var bootstrap: Bootstrap? = null
protected abstract fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>)
final override fun connectToProcess(promise: AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) {
val bootstrap = BuiltInServerManager.getInstance().createClientBootstrap()
configureBootstrap(bootstrap, errorOutputConsumer)
this.bootstrap = bootstrap
this.port = port
val connectResult = bootstrap.connectRetrying(loopbackSocketAddress(port))
connectResult.channel?.let {
promise.catchError {
processChannel.set(it)
addCloseListener(it)
promise.setResult(processHandler)
}
}
handleErrors(connectResult, promise)
}
protected fun connectAgain(): Promise<Channel> {
val channel = processChannel.get()
if (channel != null) {
return resolvedPromise(channel)
}
val promise = AsyncPromise<Channel>()
val connectResult = bootstrap!!.connectRetrying(loopbackSocketAddress(port))
connectResult.channel?.let {
promise.catchError {
processChannel.set(it)
addCloseListener(it)
promise.setResult(it)
}
}
handleErrors(connectResult, promise)
return promise
}
private fun handleErrors(connectResult: ConnectToChannelResult, promise: AsyncPromise<*>) {
connectResult
.handleError(java.util.function.Consumer {
promise.setError(it)
})
.handleThrowable(java.util.function.Consumer {
promise.setError(it)
})
}
protected open fun addCloseListener(it: Channel) {
it.closeFuture().addChannelListener {
processChannel.compareAndSet(it.channel(), null)
}
}
override fun closeProcessConnections() {
processChannel.getAndSet(null)?.closeAndShutdownEventLoop()
}
} | apache-2.0 | 0f36907aac026ee5eba0b1c7590cbfb9 | 32.954545 | 164 | 0.75996 | 4.809984 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/project/ProbablyNothingCallableNamesImpl.kt | 4 | 1512 | // 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.project
import com.intellij.openapi.project.Project
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.stubindex.KotlinProbablyNothingFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinProbablyNothingPropertyShortNameIndex
import org.jetbrains.kotlin.resolve.lazy.ProbablyNothingCallableNames
class ProbablyNothingCallableNamesImpl(project: Project) : ProbablyNothingCallableNames {
private val functionNames = createCachedValue(project) { KotlinProbablyNothingFunctionShortNameIndex.getAllKeys(project) }
private val propertyNames = createCachedValue(project) { KotlinProbablyNothingPropertyShortNameIndex.getAllKeys(project) }
override fun functionNames(): Collection<String> = functionNames.value
override fun propertyNames(): Collection<String> = propertyNames.value
}
private inline fun createCachedValue(project: Project, crossinline names: () -> Collection<String>) =
CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result.create(names(), KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker)
}, false
)
| apache-2.0 | 5b1a79271f46f513673a0a11cbb90a71 | 57.153846 | 158 | 0.823413 | 5.231834 | false | false | false | false |
android/nowinandroid | core/datastore/src/main/java/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSource.kt | 1 | 8175 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.datastore
import android.util.Log
import androidx.datastore.core.DataStore
import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig
import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand
import com.google.samples.apps.nowinandroid.core.model.data.UserData
import java.io.IOException
import javax.inject.Inject
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
class NiaPreferencesDataSource @Inject constructor(
private val userPreferences: DataStore<UserPreferences>
) {
val userDataStream = userPreferences.data
.map {
UserData(
bookmarkedNewsResources = it.bookmarkedNewsResourceIdsMap.keys,
followedTopics = it.followedTopicIdsMap.keys,
followedAuthors = it.followedAuthorIdsMap.keys,
themeBrand = when (it.themeBrand) {
null,
ThemeBrandProto.THEME_BRAND_UNSPECIFIED,
ThemeBrandProto.UNRECOGNIZED,
ThemeBrandProto.THEME_BRAND_DEFAULT -> ThemeBrand.DEFAULT
ThemeBrandProto.THEME_BRAND_ANDROID -> ThemeBrand.ANDROID
},
darkThemeConfig = when (it.darkThemeConfig) {
null,
DarkThemeConfigProto.DARK_THEME_CONFIG_UNSPECIFIED,
DarkThemeConfigProto.UNRECOGNIZED,
DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM ->
DarkThemeConfig.FOLLOW_SYSTEM
DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT ->
DarkThemeConfig.LIGHT
DarkThemeConfigProto.DARK_THEME_CONFIG_DARK -> DarkThemeConfig.DARK
},
shouldHideOnboarding = it.shouldHideOnboarding
)
}
suspend fun setFollowedTopicIds(topicIds: Set<String>) {
try {
userPreferences.updateData {
it.copy {
followedTopicIds.clear()
followedTopicIds.putAll(topicIds.associateWith { true })
updateShouldHideOnboardingIfNecessary()
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun toggleFollowedTopicId(topicId: String, followed: Boolean) {
try {
userPreferences.updateData {
it.copy {
if (followed) {
followedTopicIds.put(topicId, true)
} else {
followedTopicIds.remove(topicId)
}
updateShouldHideOnboardingIfNecessary()
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun setFollowedAuthorIds(authorIds: Set<String>) {
try {
userPreferences.updateData {
it.copy {
followedAuthorIds.clear()
followedAuthorIds.putAll(authorIds.associateWith { true })
updateShouldHideOnboardingIfNecessary()
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun toggleFollowedAuthorId(authorId: String, followed: Boolean) {
try {
userPreferences.updateData {
it.copy {
if (followed) {
followedAuthorIds.put(authorId, true)
} else {
followedAuthorIds.remove(authorId)
}
updateShouldHideOnboardingIfNecessary()
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun setThemeBrand(themeBrand: ThemeBrand) {
userPreferences.updateData {
it.copy {
this.themeBrand = when (themeBrand) {
ThemeBrand.DEFAULT -> ThemeBrandProto.THEME_BRAND_DEFAULT
ThemeBrand.ANDROID -> ThemeBrandProto.THEME_BRAND_ANDROID
}
}
}
}
suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
userPreferences.updateData {
it.copy {
this.darkThemeConfig = when (darkThemeConfig) {
DarkThemeConfig.FOLLOW_SYSTEM ->
DarkThemeConfigProto.DARK_THEME_CONFIG_FOLLOW_SYSTEM
DarkThemeConfig.LIGHT -> DarkThemeConfigProto.DARK_THEME_CONFIG_LIGHT
DarkThemeConfig.DARK -> DarkThemeConfigProto.DARK_THEME_CONFIG_DARK
}
}
}
}
suspend fun toggleNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) {
try {
userPreferences.updateData {
it.copy {
if (bookmarked) {
bookmarkedNewsResourceIds.put(newsResourceId, true)
} else {
bookmarkedNewsResourceIds.remove(newsResourceId)
}
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun getChangeListVersions() = userPreferences.data
.map {
ChangeListVersions(
topicVersion = it.topicChangeListVersion,
authorVersion = it.authorChangeListVersion,
newsResourceVersion = it.newsResourceChangeListVersion,
)
}
.firstOrNull() ?: ChangeListVersions()
/**
* Update the [ChangeListVersions] using [update].
*/
suspend fun updateChangeListVersion(update: ChangeListVersions.() -> ChangeListVersions) {
try {
userPreferences.updateData { currentPreferences ->
val updatedChangeListVersions = update(
ChangeListVersions(
topicVersion = currentPreferences.topicChangeListVersion,
authorVersion = currentPreferences.authorChangeListVersion,
newsResourceVersion = currentPreferences.newsResourceChangeListVersion
)
)
currentPreferences.copy {
topicChangeListVersion = updatedChangeListVersions.topicVersion
authorChangeListVersion = updatedChangeListVersions.authorVersion
newsResourceChangeListVersion = updatedChangeListVersions.newsResourceVersion
}
}
} catch (ioException: IOException) {
Log.e("NiaPreferences", "Failed to update user preferences", ioException)
}
}
suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) {
userPreferences.updateData {
it.copy {
this.shouldHideOnboarding = shouldHideOnboarding
}
}
}
}
private fun UserPreferencesKt.Dsl.updateShouldHideOnboardingIfNecessary() {
if (followedTopicIds.isEmpty() && followedAuthorIds.isEmpty()) {
shouldHideOnboarding = false
}
}
| apache-2.0 | 358bbaf110a2acbd75bc64e95a99aa8c | 37.744076 | 97 | 0.588991 | 5.486577 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/yargor/YarGorTransitFactory.kt | 1 | 2337 | /*
* YarGorTransitFactory.kt
*
* Copyright 2019 Google
*
* 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.yargor
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.CardInfo
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.TransitRegion
import au.id.micolous.metrodroid.util.HashUtils
object YarGorTransitFactory : ClassicCardTransitFactory {
val CARD_INFO = CardInfo(
name = R.string.card_name_yargor,
locationId = R.string.location_yaroslavl,
imageId = R.drawable.yargor,
imageAlphaId = R.drawable.iso7810_id1_alpha,
cardType = CardType.MifareClassic,
keysRequired = true, keyBundle = "yargor",
region = TransitRegion.RUSSIA,
preview = true)
override val earlySectors: Int
get() = 11
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun earlyCheck(sectors: List<ClassicSector>): Boolean = HashUtils.checkKeyHash(sectors[10],
"yaroslavl", "0deaf06098f0f7ab47a7ea22945ee81a", "6775e7c1a73e0e9c98167a7665ef4bc1") >= 0
override fun parseTransitIdentity(card: ClassicCard): TransitIdentity =
TransitIdentity(R.string.card_name_yargor, YarGorTransitData.formatSerial(YarGorTransitData.getSerial(card)))
override fun parseTransitData(card: ClassicCard) = YarGorTransitData.parse(card)
}
| gpl-3.0 | 42adb22096b4d669acc28b8b3db06693 | 40.732143 | 121 | 0.741549 | 3.947635 | false | false | false | false |
ianhanniballake/ContractionTimer | mobile/src/main/java/com/ianhanniballake/contractiontimer/ui/ViewFragment.kt | 1 | 9112 | package com.ianhanniballake.contractiontimer.ui
import android.content.ComponentName
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.provider.BaseColumns
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.cursoradapter.widget.CursorAdapter
import androidx.fragment.app.Fragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import com.google.firebase.analytics.FirebaseAnalytics
import com.ianhanniballake.contractiontimer.BuildConfig
import com.ianhanniballake.contractiontimer.R
import com.ianhanniballake.contractiontimer.appwidget.AppWidgetUpdateHandler
import com.ianhanniballake.contractiontimer.notification.NotificationUpdateReceiver
import com.ianhanniballake.contractiontimer.provider.ContractionContract
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Date
/**
* Fragment showing the details of an individual contraction
*/
class ViewFragment : Fragment(), LoaderManager.LoaderCallbacks<Cursor> {
companion object {
private const val TAG = "ViewFragment"
/**
* Creates a new Fragment to display the given contraction
*
* @param contractionId Id of the Contraction to display
* @return ViewFragment associated with the given id
*/
fun createInstance(contractionId: Long): ViewFragment {
val viewFragment = ViewFragment()
val args = Bundle()
args.putLong(BaseColumns._ID, contractionId)
viewFragment.arguments = args
return viewFragment
}
}
/**
* Whether the current contraction is ongoing (i.e., not yet ended).
* Null indicates that we haven't checked yet,
* while true or false indicates whether the contraction is ongoing
*/
internal var isContractionOngoing: Boolean? = null
/**
* Adapter to display the detailed data
*/
private lateinit var adapter: CursorAdapter
/**
* Id of the current contraction to show
*/
private var contractionId: Long = -1
/**
* We need to find the exact view_fragment view as there is a NoSaveStateFrameLayout view inserted in between the
* parent and the view we created in onCreateView
*
* @return View created in onCreateView
*/
private val fragmentView: View?
get() {
val rootView = view
return rootView?.findViewById(R.id.view_fragment)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
adapter = object : CursorAdapter(activity, null, 0) {
override fun bindView(view: View, context: Context, cursor: Cursor) {
val startTimeView = view.findViewById<TextView>(R.id.start_time)
val timeFormat = if (DateFormat.is24HourFormat(context))
"kk:mm:ss"
else
"hh:mm:ssa"
val startTimeColumnIndex = cursor.getColumnIndex(
ContractionContract.Contractions.COLUMN_NAME_START_TIME)
val startTime = cursor.getLong(startTimeColumnIndex)
startTimeView.text = DateFormat.format(timeFormat, startTime)
val startDateView = view.findViewById<TextView>(R.id.start_date)
val startDate = Date(startTime)
startDateView.text = DateFormat.getDateFormat(activity).format(startDate)
val endTimeView = view.findViewById<TextView>(R.id.end_time)
val endDateView = view.findViewById<TextView>(R.id.end_date)
val durationView = view.findViewById<TextView>(R.id.duration)
val endTimeColumnIndex = cursor.getColumnIndex(
ContractionContract.Contractions.COLUMN_NAME_END_TIME)
isContractionOngoing = cursor.isNull(endTimeColumnIndex)
if (isContractionOngoing == true) {
endTimeView.text = " "
endDateView.text = " "
durationView.text = getString(R.string.duration_ongoing)
} else {
val endTime = cursor.getLong(endTimeColumnIndex)
endTimeView.text = DateFormat.format(timeFormat, endTime)
val endDate = Date(endTime)
endDateView.text = DateFormat.getDateFormat(activity).format(endDate)
val durationInSeconds = (endTime - startTime) / 1000
durationView.text = DateUtils.formatElapsedTime(durationInSeconds)
}
requireActivity().invalidateOptionsMenu()
val noteView = view.findViewById<TextView>(R.id.note)
val noteColumnIndex = cursor.getColumnIndex(
ContractionContract.Contractions.COLUMN_NAME_NOTE)
val note = cursor.getString(noteColumnIndex)
noteView.text = note
}
override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View? {
// View is already inflated in onCreateView
return null
}
}
if (arguments != null) {
contractionId = requireArguments().getLong(BaseColumns._ID, 0)
if (contractionId != -1L)
loaderManager.initLoader(0, null, this)
}
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
val contractionUri = ContentUris.withAppendedId(
ContractionContract.Contractions.CONTENT_ID_URI_PATTERN,
contractionId
)
return CursorLoader(
requireContext(), contractionUri, null,
null, null, null
)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
// Only allow editing contractions that have already finished
val showEdit = isContractionOngoing != true
val editItem = menu.findItem(R.id.menu_edit)
editItem.isVisible = showEdit
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_view, container, false)
override fun onLoaderReset(data: Loader<Cursor>) {
adapter.swapCursor(null)
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
adapter.swapCursor(data)
if (data.moveToFirst())
adapter.bindView(fragmentView, activity, data)
requireActivity().invalidateOptionsMenu()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val uri = ContentUris.withAppendedId(
ContractionContract.Contractions.CONTENT_ID_URI_BASE, contractionId
)
val analytics = FirebaseAnalytics.getInstance(requireContext())
when (item.itemId) {
R.id.menu_edit -> {
// isContractionOngoing should be non-null at this point, but
// just in case
if (isContractionOngoing == null)
return true
if (BuildConfig.DEBUG)
Log.d(TAG, "View selected edit")
if (isContractionOngoing == true)
Toast.makeText(activity, R.string.edit_ongoing_error, Toast.LENGTH_SHORT).show()
else {
analytics.logEvent("edit_open_view", null)
startActivity(
Intent(Intent.ACTION_EDIT, uri)
.setComponent(ComponentName(requireContext(), EditActivity::class.java))
)
}
return true
}
R.id.menu_delete -> {
if (BuildConfig.DEBUG)
Log.d(TAG, "View selected delete")
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.VALUE, 1.toString())
analytics.logEvent("delete_view", bundle)
val activity = requireActivity()
GlobalScope.launch {
activity.contentResolver.delete(uri, null, null)
AppWidgetUpdateHandler.createInstance().updateAllWidgets(activity)
NotificationUpdateReceiver.updateNotification(activity)
activity.finish()
}
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
| bsd-3-clause | 9670ce19723d5bf5ba03dedb9b600833 | 40.798165 | 117 | 0.630048 | 5.136415 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/FormattingChanges.kt | 4 | 4889 | // 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.codeInspection.incorrectFormatting
import com.intellij.application.options.CodeStyle
import com.intellij.formatting.service.CoreFormattingService
import com.intellij.formatting.service.FormattingServiceUtil
import com.intellij.lang.LanguageFormatting
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategy
import com.intellij.psi.formatter.WhiteSpaceFormattingStrategyFactory
import com.intellij.util.LocalTimeCounter
data class FormattingChanges(val preFormatText: CharSequence, val postFormatText: CharSequence, val mismatches: List<WhitespaceMismatch>) {
data class WhitespaceMismatch(val preFormatRange: TextRange, val postFormatRange: TextRange)
}
/**
* Detects whitespace which is not in agreement with formatting rules for given [file]. Ranges of the returned
* [FormattingChanges.mismatches] always encompass the entirety of the whitespace between tokens for each detected change in both the
* original and formatted text.
*
* Uses code style settings associated with [file]. To detect changes using different [CodeStyleSettings], use
* [CodeStyle.doWithTemporarySettings].
*
* @param file
* @return [FormattingChanges] object describing the changes. `null` if detection could not be performed. Empty list if no changes were
* detected.
*/
fun detectFormattingChanges(file: PsiFile): FormattingChanges? {
if (!LanguageFormatting.INSTANCE.isAutoFormatAllowed(file)) {
return null
}
val fileDoc = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null
val baseLanguage = file.viewProvider.baseLanguage
val psiCopy = PsiFileFactory.getInstance(file.project).createFileFromText(
file.name,
file.fileType,
fileDoc.text,
LocalTimeCounter.currentTime(),
false,
true
)
// Necessary if we want to apply the same .editorconfig files
psiCopy.putUserData(PsiFileFactory.ORIGINAL_FILE, file)
val copyDoc = psiCopy.viewProvider.document!!
val formattingService = FormattingServiceUtil.findService(file, true, true)
if (formattingService !is CoreFormattingService) {
return null
}
val copyService = FormattingServiceUtil.findService(psiCopy, true, true)
if (formattingService != copyService) {
logger<FormattingChanges>().warn("${formattingService::class} cannot format an in-memory copy.")
return null
}
//if (formattingService is AbstractDocumentFormattingService) {
// AbstractDocumentFormattingService.setDocument(psiCopy, psiCopy.viewProvider.document)
// psiCopy.viewProvider.document.putUserData(AsyncDocumentFormattingService.FORMAT_DOCUMENT_SYNCHRONOUSLY, true)
//}
CodeStyleManager.getInstance(psiCopy.project).reformat(psiCopy, true)
val preFormat = fileDoc.text
val postFormat = copyDoc.text
val changes = diffWhitespace(preFormat,
postFormat,
WhiteSpaceFormattingStrategyFactory.getStrategy(baseLanguage))
return FormattingChanges(preFormat, postFormat, changes)
}
/**
* Assumes the following:
* 1. `\n` is the line separator for both [pre] and [post]. (Note that [WhiteSpaceFormattingStrategy] implementations also assume this.)
* 2. [pre] and [post] are identical up to whitespace, as identified by [whiteSpaceFormattingStrategy] */
private fun diffWhitespace(pre: CharSequence,
post: CharSequence,
whiteSpaceFormattingStrategy: WhiteSpaceFormattingStrategy): List<FormattingChanges.WhitespaceMismatch> {
val mismatches = mutableListOf<FormattingChanges.WhitespaceMismatch>()
var i = 0
var j = 0
while (i < pre.length && j < post.length) {
val iWsEnd = whiteSpaceFormattingStrategy.check(pre, i, pre.length)
val jWsEnd = whiteSpaceFormattingStrategy.check(post, j, post.length)
if (iWsEnd > i || jWsEnd > j) {
val iWsStart = i
val jWsStart = j
val iWsLen = iWsEnd - iWsStart
val jWsLen = jWsEnd - jWsStart
var changeDetected = false
if (iWsLen == jWsLen) {
while (i < iWsEnd) {
if (pre[i] != post[j]) changeDetected = true
++i
++j
}
}
if (changeDetected || iWsLen != jWsLen) {
mismatches += FormattingChanges.WhitespaceMismatch(TextRange(iWsStart, iWsEnd), TextRange(jWsStart, jWsEnd))
}
i = iWsEnd
j = jWsEnd
}
else if (pre[i] != post[j]) {
throw IllegalArgumentException("Non-whitespace change")
}
else {
++i
++j
}
}
return mismatches
} | apache-2.0 | 268683caaaea5b032aaad7220b23807c | 39.081967 | 139 | 0.736347 | 4.36908 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/utils/DefaultBackgroundExecutor.kt | 2 | 8415 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.configuration.utils
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import com.intellij.util.containers.HashSetQueue
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_DELAY
import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_MIN_QUEUE
import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog
import java.util.*
import javax.swing.SwingUtilities
/**
* Sequentially loads script configuration in background.
* Loading tasks scheduled by calling [ensureScheduled].
*
* Progress indicator will be shown after [PROGRESS_INDICATOR_DELAY] ms or if
* more then [PROGRESS_INDICATOR_MIN_QUEUE] tasks scheduled.
*
* States:
* silentWorker underProgressWorker
* - sleep
* - silent x
* - silent and under progress x x
* - under progress x
*/
internal class DefaultBackgroundExecutor(
val project: Project,
val manager: CompositeScriptConfigurationManager
) : BackgroundExecutor {
companion object {
const val PROGRESS_INDICATOR_DELAY = 1000
const val PROGRESS_INDICATOR_MIN_QUEUE = 3
}
private val rootsManager get() = manager.updater
private val work = Any()
private val queue: Queue<LoadTask> = HashSetQueue()
/**
* Let's fix queue size when progress bar displayed.
* Progress for rest items will be counted from zero
*/
private var currentProgressSize: Int = 0
private var currentProgressDone: Int = 0
private var silentWorker: SilentWorker? = null
private var underProgressWorker: UnderProgressWorker? = null
private val longRunningAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, KotlinPluginDisposable.getInstance(project))
private var longRunningAlarmRequested = false
private var inTransaction: Boolean = false
private var currentFile: VirtualFile? = null
class LoadTask(val key: VirtualFile, val actions: () -> Unit) {
override fun equals(other: Any?) =
this === other || (other is LoadTask && key == other.key)
override fun hashCode() = key.hashCode()
}
@Synchronized
override fun ensureScheduled(key: VirtualFile, actions: () -> Unit) {
val task = LoadTask(key, actions)
if (queue.add(task)) {
scriptingDebugLog(task.key) { "added to update queue" }
// If the queue is longer than PROGRESS_INDICATOR_MIN_QUEUE, show progress and cancel button
if (queue.size > PROGRESS_INDICATOR_MIN_QUEUE) {
requireUnderProgressWorker()
} else {
requireSilentWorker()
if (!longRunningAlarmRequested) {
longRunningAlarmRequested = true
longRunningAlarm.addRequest(
{
longRunningAlarmRequested = false
requireUnderProgressWorker()
},
PROGRESS_INDICATOR_DELAY
)
}
}
}
}
@Synchronized
private fun requireSilentWorker() {
if (silentWorker == null && underProgressWorker == null) {
silentWorker = SilentWorker().also { it.start() }
}
}
@Synchronized
private fun requireUnderProgressWorker() {
if (queue.isEmpty() && silentWorker == null) return
silentWorker?.stopGracefully()
if (underProgressWorker == null) {
underProgressWorker = UnderProgressWorker().also { it.start() }
restartProgressBar()
updateProgress()
}
}
@Synchronized
private fun restartProgressBar() {
currentProgressSize = queue.size
currentProgressDone = 0
}
@Synchronized
fun updateProgress() {
underProgressWorker?.progressIndicator?.let {
it.text2 = currentFile?.path ?: ""
if (queue.size == 0) {
// last file
it.isIndeterminate = true
} else {
it.isIndeterminate = false
if (currentProgressDone > currentProgressSize) {
restartProgressBar()
}
it.fraction = currentProgressDone.toDouble() / currentProgressSize.toDouble()
}
}
}
@Synchronized
private fun ensureInTransaction() {
if (inTransaction) return
inTransaction = true
rootsManager.beginUpdating()
}
@Synchronized
private fun endBatch() {
check(inTransaction)
rootsManager.commit()
inTransaction = false
}
private abstract inner class Worker {
private var shouldStop = false
open fun start() {
ensureInTransaction()
}
fun stopGracefully() {
shouldStop = true
}
protected open fun checkCancelled() = false
protected abstract fun close()
protected fun run() {
try {
while (true) {
// prevent parallel work in both silent and under progress
synchronized(work) {
val next = synchronized(this@DefaultBackgroundExecutor) {
if (shouldStop) return
if (checkCancelled()) {
queue.clear()
endBatch()
return
} else if (queue.isEmpty()) {
endBatch()
return
}
queue.poll()?.also {
currentFile = it.key
currentProgressDone++
updateProgress()
}
}
next?.actions?.invoke()
synchronized(work) {
currentFile = null
}
}
}
} finally {
close()
}
}
}
private inner class UnderProgressWorker : Worker() {
var progressIndicator: ProgressIndicator? = null
override fun start() {
super.start()
object : Task.Backgroundable(project, KotlinBaseScriptingBundle.message("text.kotlin.loading.script.configuration"), true) {
override fun run(indicator: ProgressIndicator) {
progressIndicator = indicator
updateProgress()
run()
}
}.queue()
}
override fun checkCancelled(): Boolean = progressIndicator?.isCanceled == true
override fun close() {
synchronized(this@DefaultBackgroundExecutor) {
underProgressWorker = null
progressIndicator = null
}
}
}
private inner class SilentWorker : Worker() {
override fun start() {
super.start()
// executeOnPooledThread requires read lock, and we may fail to acquire it
SwingUtilities.invokeLater {
BackgroundTaskUtil.executeOnPooledThread(KotlinPluginDisposable.getInstance(project)) {
run()
}
}
}
override fun close() {
synchronized(this@DefaultBackgroundExecutor) {
silentWorker = null
}
}
}
}
| apache-2.0 | 071d6a99454f67a1ec2cd628a23b2d8e | 32.931452 | 158 | 0.571123 | 5.771605 | false | false | false | false |
linkedin/LiTr | litr/src/main/java/com/linkedin/android/litr/codec/PassthroughDecoder.kt | 1 | 3162 | /*
* Copyright 2021 LinkedIn Corporation
* All Rights Reserved.
*
* Licensed under the BSD 2-Clause License (the "License"). See License in the project root for
* license information.
*/
package com.linkedin.android.litr.codec
import android.media.MediaCodec
import android.media.MediaFormat
import android.view.Surface
import java.nio.ByteBuffer
private const val DEFAULT_BUFFER_POOL_SIZE = 2
/**
* Implementation of [Decoder] that produces frames identical to ones it consumes, preserving the order.
* If running in hardware accelerated mode, with non-null [Surface], triggers a GL draw call.
*/
class PassthroughDecoder(
inputBufferCapacity: Int
) : Decoder {
// pool of unused frames
private val availableFrames = mutableSetOf<Frame>()
// pool of frames a client dequeued to populate with encoded input data
private val dequeuedInputFrames = mutableMapOf<Int, Frame>()
// queue of frames being decoded
private val decodeQueue = mutableListOf<Int>()
// pool of decoded frames
private val decodedFrames = mutableMapOf<Int, Frame>()
private lateinit var mediaFormat: MediaFormat
private var surface: Surface? = null
private var isRunning = false
init {
for (tag in 0 until DEFAULT_BUFFER_POOL_SIZE) {
availableFrames.add(Frame(tag, ByteBuffer.allocate(inputBufferCapacity), MediaCodec.BufferInfo()))
}
}
override fun init(mediaFormat: MediaFormat, surface: Surface?) {
this.mediaFormat = mediaFormat
this.surface = surface
}
override fun start() {
isRunning = true
}
override fun isRunning(): Boolean {
return isRunning
}
override fun dequeueInputFrame(timeout: Long): Int {
return availableFrames.firstOrNull()?.let { availableFrame ->
availableFrames.remove(availableFrame)
dequeuedInputFrames[availableFrame.tag] = availableFrame
availableFrame.tag
} ?: MediaCodec.INFO_TRY_AGAIN_LATER
}
override fun getInputFrame(tag: Int): Frame? {
return dequeuedInputFrames[tag]
}
override fun queueInputFrame(frame: Frame) {
dequeuedInputFrames.remove(frame.tag)
decodeQueue.add(frame.tag)
decodedFrames[frame.tag] = frame
}
override fun dequeueOutputFrame(timeout: Long): Int {
return if (decodeQueue.isNotEmpty()) decodeQueue.removeAt(0) else MediaCodec.INFO_TRY_AGAIN_LATER
}
override fun getOutputFrame(tag: Int): Frame? {
return decodedFrames[tag]
}
override fun releaseOutputFrame(tag: Int, render: Boolean) {
surface?.let { surface ->
if (render) {
val canvas = surface.lockCanvas(null)
surface.unlockCanvasAndPost(canvas)
}
}
decodedFrames.remove(tag)?.let {
availableFrames.add(it)
}
}
override fun getOutputFormat(): MediaFormat {
return mediaFormat
}
override fun stop() {
isRunning = false
}
override fun release() {
}
override fun getName(): String {
return "PassthroughDecoder"
}
} | bsd-2-clause | 088ce3a7d61a696f020d3d33a7ceb51c | 27.754545 | 110 | 0.664453 | 4.562771 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/util/system/WebViewUtil.kt | 2 | 2038 | package eu.kanade.tachiyomi.util.system
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import logcat.LogPriority
object WebViewUtil {
const val REQUESTED_WITH = "com.android.browser"
const val MINIMUM_WEBVIEW_VERSION = 88
fun supportsWebView(context: Context): Boolean {
try {
// May throw android.webkit.WebViewFactory$MissingWebViewPackageException if WebView
// is not installed
CookieManager.getInstance()
} catch (e: Throwable) {
logcat(LogPriority.ERROR, e)
return false
}
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)
}
}
fun WebView.isOutdated(): Boolean {
return getWebViewMajorVersion() < WebViewUtil.MINIMUM_WEBVIEW_VERSION
}
@SuppressLint("SetJavaScriptEnabled")
fun WebView.setDefaultSettings() {
with(settings) {
javaScriptEnabled = true
domStorageEnabled = true
databaseEnabled = true
setAppCacheEnabled(true)
useWideViewPort = true
loadWithOverviewMode = true
cacheMode = WebSettings.LOAD_DEFAULT
}
}
private fun WebView.getWebViewMajorVersion(): Int {
val uaRegexMatch = """.*Chrome/(\d+)\..*""".toRegex().matchEntire(getDefaultUserAgentString())
return if (uaRegexMatch != null && uaRegexMatch.groupValues.size > 1) {
uaRegexMatch.groupValues[1].toInt()
} else {
0
}
}
// Based on https://stackoverflow.com/a/29218966
private fun WebView.getDefaultUserAgentString(): String {
val originalUA: String = settings.userAgentString
// Next call to getUserAgentString() will get us the default
settings.userAgentString = null
val defaultUserAgentString = settings.userAgentString
// Revert to original UA string
settings.userAgentString = originalUA
return defaultUserAgentString
}
| apache-2.0 | e94054976cb00598904423ccb784d10c | 28.970588 | 98 | 0.709519 | 4.706697 | false | false | false | false |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/view/settings/SettingsActivity.kt | 1 | 8252 | package com.example.demoaerisproject.view.settings
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Observer
import com.example.demoaerisproject.view.BaseActivity
import com.example.demoaerisproject.R
import com.example.demoaerisproject.view.map.MyMapActivity
import com.example.demoaerisproject.view.weather.MainActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SettingsActivity : BaseActivity() {
private val viewModel: PrefViewModel by viewModels()
private val isEnabledNotification = mutableStateOf(false)
private val isMetric = mutableStateOf(false)
override fun onCreate(savedInstanceState: Bundle?) {
actionBarTitle = resources.getString(R.string.action_settings)
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
viewModel.isNotificationEnabled.observe(this, Observer(::onNotificationEvent))
viewModel.isMetric.observe(this, Observer(::onMetricEvent))
render()
}
override fun onBackPressed() {
val name = when (intent.getStringExtra("TAG")) {
MyMapActivity.TAG.toString() -> MyMapActivity::class.java
else -> MainActivity::class.java
}
val targetIntent = Intent(this, name)
intent.getStringExtra("route")?.let {
targetIntent.putExtra("route", it)
}
startActivity(targetIntent)
}
private fun onNotificationEvent(isEnabled: Boolean?) {
when (isEnabled) {
null -> {}
else -> {
isEnabledNotification.value = isEnabled
}
}
}
private fun onMetricEvent(isEnabled: Boolean?) {
when (isEnabled) {
null -> {}
else -> {
isMetric.value = isEnabled
}
}
}
private fun render() {
setContent {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
)
Card(
Modifier
.padding(vertical = 5.dp)
.fillMaxWidth()
.background(Color.Black),
shape = RoundedCornerShape(corner = CornerSize(6.dp))
) {
Column(
modifier = Modifier.fillMaxWidth()
) {
ComposePrefNotification(isEnabledNotification.value)
ComposeMetricImperial(isMetric.value)
Divider(color = Color(0xFF808080), thickness = 1.dp)
}
}
}
}
@Composable
private fun ComposeMetricImperial(isMetrics: Boolean) {
Divider(color = Color(0xFF808080), thickness = 1.dp)
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
Text(
color = Color.White,
text = resources.getString(R.string.unit_measure_title),
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
modifier = Modifier
.padding(10.dp, 10.dp, 10.dp, 10.dp)
.fillMaxWidth(),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
val radioOptions = listOf(
resources.getString(R.string.radio_title_imperial),
resources.getString(R.string.radio_title_metric)
)
val (selectedOption, onSelected) = remember {
mutableStateOf(radioOptions[0])
}
val i = if (isMetrics) {
1
} else {
0
}
onSelected(radioOptions.get(i))
Column() {
radioOptions.forEach { text ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.selectable(selected = text == selectedOption,
onClick = {
onSelected(text)
val isMetricsEnabled = text == radioOptions[1]
viewModel.setMetric(isMetricsEnabled)
})
) {
RadioButton(
selected = (text == selectedOption),
onClick = {
onSelected(text)
val isMetricsEnabled = text == radioOptions[1]
viewModel.setMetric(isMetricsEnabled)
},
colors = RadioButtonDefaults.colors(unselectedColor = Color.White)
)
Text(
text = text,
modifier = Modifier.padding(10.dp, 12.dp, 0.dp, 0.dp),
color = Color.White
)
}
}
}
}
}
@Composable
private fun ComposePrefNotification(isEnabled: Boolean) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
Text(
color = Color.White,
text = resources.getString(R.string.pref_cat_ntf_title),
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
modifier = Modifier
.padding(10.dp, 10.dp, 10.dp, 10.dp)
.fillMaxWidth(),
)
}
Divider(color = Color(0xFF808080), thickness = 1.dp)
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
Text(
color = Color.White,
text = resources.getString(R.string.pref_ntf_enabled_title),
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
modifier = Modifier
.padding(10.dp, 10.dp, 10.dp, 10.dp)
.fillMaxWidth(),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
) {
Column(
modifier = Modifier
.weight(4f)
) {
Text(
color = Color.White,
text = resources.getString(R.string.pref_ntf_enabled_sum),
fontSize = 18.sp,
modifier = Modifier
.padding(10.dp, 10.dp, 10.dp, 10.dp)
.fillMaxWidth(),
)
}
Column(
modifier = Modifier
.weight(1f),
horizontalAlignment = Alignment.Start
) {
Checkbox(
checked = isEnabled,
colors = CheckboxDefaults.colors(uncheckedColor = Color.White),
onCheckedChange = {
viewModel.setNotificationEnabled(it)
}, enabled = true
)
}
}
}
} | mit | dcf25922d577ecfddd466903585870fc | 32.82377 | 94 | 0.500727 | 5.47578 | false | false | false | false |
alekratz/markov-bot | src/main/kotlin/edu/appstate/cs/markovbot/VersionInfo.kt | 1 | 277 | package edu.appstate.cs.markovbot
/**
* @author Alek Ratzloff <[email protected]>
*/
object VersionInfo {
const val MAJOR = 0
const val MINOR = 2
const val REV = 0
const val SUFFIX = "-dev"
const val STR = "$MAJOR.$MINOR.$REV$SUFFIX"
} | bsd-2-clause | 8779a27449f0876cbf3f72b6a8a70231 | 20.384615 | 47 | 0.602888 | 3.22093 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/currentWeather/CurrentWeatherRepository.kt | 1 | 1725 | package soutvoid.com.DsrWeatherApp.interactor.currentWeather
import com.agna.ferro.mvp.component.scope.PerApplication
import rx.Observable
import soutvoid.com.DsrWeatherApp.domain.CurrentWeather
import soutvoid.com.DsrWeatherApp.interactor.currentWeather.network.CurrentWeatherApi
import soutvoid.com.DsrWeatherApp.interactor.util.Accuracy
import soutvoid.com.DsrWeatherApp.interactor.util.Units
import java.util.*
import javax.inject.Inject
@PerApplication
class CurrentWeatherRepository @Inject constructor(val api: CurrentWeatherApi) {
fun getByCityName(query: String,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<CurrentWeather> {
return api.getByCityName(query, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getByCityId(cityId: Int,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<CurrentWeather> {
return api.getByCityId(cityId, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getByCoordinates(latitude: Double,
longitude: Double,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<CurrentWeather> {
return api.getByCoordinates(latitude, longitude, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
} | apache-2.0 | 4a5a2f4caf5cc31fa06658056382c1af | 41.097561 | 121 | 0.666667 | 4.845506 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/GeneratorInventory.kt | 1 | 2420 | package com.ore.infinium
import com.artemis.World
import com.ore.infinium.util.INVALID_ENTITY_ID
/**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
class GeneratorInventory(slotCount: Int, artemisWorld: World) : Inventory(slotCount, artemisWorld) {
//when a fuel source is initially burned, it is set to 100
//over time it will decrease until 0, at which point the fuel
//source is consumed
var fuelSourceHealth = 0
/**
* the generator that this generator applies to.
* while this instance will always exist, this
* field will be set/cleared when the window is shown/closed
*/
var owningGeneratorEntityId: Int? = null
init {
inventoryType = Network.Shared.InventoryType.Generator
//hack clearing them because base class already populates
//but we need fuel sources in here too
slots.clear()
//add first as fuel source
slots.add(InventorySlot(INVALID_ENTITY_ID, InventorySlotType.FuelSource))
//start at 1 because fuel source already added(and is counted), and subtract from slotCount
for (i in 1..slotCount - 1) {
slots.add(InventorySlot(INVALID_ENTITY_ID, InventorySlotType.Slot))
}
}
val changedListeners = listOf<Unit>()
companion object {
val MAX_SLOTS = 32
val FUEL_SOURCE_HEALTH_MAX = 100
}
}
| mit | 6db714fc031ea4539256048df9fca20c | 35.666667 | 100 | 0.731818 | 4.448529 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/api/TootApiResult.kt | 1 | 5761 | package jp.juggler.subwaytooter.api
import jp.juggler.subwaytooter.util.DecodeOptions
import jp.juggler.util.*
import okhttp3.Response
import okhttp3.WebSocket
open class TootApiResult(
@Suppress("unused") val dummy: Int = 0,
var error: String? = null,
var response: Response? = null,
var caption: String = "?",
var bodyString: String? = null,
) {
companion object {
private val log = LogCategory("TootApiResult")
private val reWhiteSpace = """\s+""".asciiPattern()
private val reLinkURL = """<([^>]+)>;\s*rel="([^"]+)"""".asciiPattern()
fun makeWithCaption(caption: String?): TootApiResult {
val result = TootApiResult()
if (caption?.isEmpty() != false) {
log.e("makeWithCaption: missing caption!")
result.error = "missing instance name"
} else {
result.caption = caption
}
return result
}
}
var requestInfo = ""
var tokenInfo: JsonObject? = null
var data: Any? = null
set(value) {
if (value is JsonArray) {
parseLinkHeader(response, value)
}
field = value
}
val jsonObject: JsonObject?
get() = data as? JsonObject
val jsonArray: JsonArray?
get() = data as? JsonArray
val string: String?
get() = data as? String
var linkOlder: String? = null // より古いデータへのリンク
var linkNewer: String? = null // より新しいデータへの
constructor() : this(0)
constructor(error: String) : this(0, error = error)
constructor(socket: WebSocket) : this(0) {
this.data = socket
}
constructor(response: Response, error: String)
: this(0, error, response)
constructor(response: Response, bodyString: String, data: Any?) : this(
0,
response = response,
bodyString = bodyString
) {
this.data = data
}
// return result.setError(...) と書きたい
fun setError(error: String): TootApiResult {
this.error = error
return this
}
private fun parseLinkHeader(response: Response?, array: JsonArray) {
response ?: return
log.d("array size=${array.size}")
val sv = response.header("Link")
if (sv == null) {
log.d("missing Link header")
} else {
// Link: <https://mastodon.juggler.jp/api/v1/timelines/home?limit=XX&max_id=405228>; rel="next",
// <https://mastodon.juggler.jp/api/v1/timelines/home?limit=XX&since_id=436946>; rel="prev"
val m = reLinkURL.matcher(sv)
while (m.find()) {
val url = m.groupEx(1)
val rel = m.groupEx(2)
// warning.d("Link %s,%s",rel,url);
if ("next" == rel) linkOlder = url
if ("prev" == rel) linkNewer = url
}
}
}
// アカウント作成APIのdetailsを読むため、エラー応答のjsonオブジェクトを保持する
private var errorJson: JsonObject? = null
internal fun simplifyErrorHtml(
sv: String,
jsonErrorParser: (json: JsonObject) -> String? = TootApiClient.DEFAULT_JSON_ERROR_PARSER,
): String {
val response = this.response!!
// JsonObjectとして解釈できるならエラーメッセージを検出する
try {
val json = sv.decodeJsonObject()
this.errorJson = json
jsonErrorParser(json)?.notEmpty()?.let { return it }
} catch (_: Throwable) {
}
// HTMLならタグの除去を試みる
val ct = response.body?.contentType()
if (ct?.subtype == "html") {
val decoded = DecodeOptions().decodeHTML(sv).toString()
return reWhiteSpace.matcher(decoded).replaceAll(" ").trim()
}
// XXX: Amazon S3 が403を返した場合にcontent-typeが?/xmlでserverがAmazonならXMLをパースしてエラーを整形することもできるが、多分必要ない
return reWhiteSpace.matcher(sv).replaceAll(" ").trim()
}
fun parseErrorResponse(
bodyString: String? = null,
jsonErrorParser: (json: JsonObject) -> String? = TootApiClient.DEFAULT_JSON_ERROR_PARSER,
) {
val response = this.response!!
val sb = StringBuilder()
try {
// body は既に読み終わっているか、そうでなければこれから読む
if (bodyString != null) {
sb.append(simplifyErrorHtml(bodyString, jsonErrorParser))
} else {
try {
val string = response.body?.string()
if (string != null) {
sb.append(simplifyErrorHtml(string, jsonErrorParser))
}
} catch (ex: Throwable) {
log.e(ex, "missing response body.")
sb.append("(missing response body)")
}
}
if (sb.isNotEmpty()) sb.append(' ')
sb.append("(HTTP ").append(response.code.toString())
val message = response.message
if (message.isNotEmpty()) sb.append(' ').append(message)
sb.append(")")
if (caption.isNotEmpty()) {
sb.append(' ').append(caption)
}
} catch (ex: Throwable) {
log.trace(ex)
}
this.error = sb.toString().replace("\n+".toRegex(), "\n")
}
}
| apache-2.0 | 21088da9099a5b34825985db3165df0a | 29.102857 | 110 | 0.527834 | 4.183705 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/GroovyKeywordAnnotator.kt | 2 | 2566 | // 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.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 {
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 | 6ad028f831e3002d8b649efb2a83e320 | 44.821429 | 140 | 0.774357 | 4.363946 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/managecars/RecyclerTouchListener.kt | 1 | 1615 | package se.barsk.park.managecars
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import android.content.Context
import android.view.GestureDetector
import android.view.View
/**
* Touch listener for recycler views
*/
class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, private val clickListener: ClickListener?) : RecyclerView.OnItemTouchListener {
private val gestureDetector: GestureDetector
interface ClickListener {
fun onClick(view: View, position: Int)
fun onLongClick(view: View, position: Int)
}
init {
gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean = true
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child))
}
}
})
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
val child = rv.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child))
}
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) = Unit
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) = Unit
} | mit | 1c32a03aaeee6012a7f21ae1a07ee0e8 | 35.727273 | 153 | 0.691022 | 5.192926 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationUtil.kt | 6 | 2256 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.transformations
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
class TransformationResult(
val methods: Array<PsiMethod>,
val fields: Array<GrField>,
val innerClasses: Array<PsiClass>,
val implementsTypes: Array<PsiClassType>,
val extendsTypes: Array<PsiClassType>
)
private val ourTransformationContext = object : ThreadLocal<MutableSet<GrTypeDefinition>>() {
override fun initialValue(): MutableSet<GrTypeDefinition> = HashSet()
}
private inline val transformationContext get() = ourTransformationContext.get()
fun transformDefinition(definition: GrTypeDefinition): TransformationResult {
assert(transformationContext.add(definition))
try {
val transformationContext = TransformationContextImpl(definition)
for (transformation in AstTransformationSupport.EP_NAME.extensions) {
ProgressManager.checkCanceled()
transformation.applyTransformation(transformationContext)
}
return transformationContext.transformationResult
}
finally {
transformationContext.remove(definition)
}
}
fun isUnderTransformation(clazz: PsiClass?): Boolean {
return clazz is GrTypeDefinition && clazz in transformationContext
}
infix operator fun TransformationContext.plusAssign(method: PsiMethod): Unit = addMethod(method)
infix operator fun TransformationContext.plusAssign(field: GrField): Unit = addField(field)
| apache-2.0 | 242a907890f7829054d5967892f530ef | 36.6 | 96 | 0.791223 | 4.641975 | false | false | false | false |
paplorinc/intellij-community | plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.kt | 6 | 3036 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.cherrypick
import com.intellij.vcs.log.impl.HashImpl
import git4idea.test.*
abstract class GitCherryPickTest : GitSingleRepoTest() {
protected fun `check dirty tree conflicting with commit`() {
val file = file("c.txt")
file.create("initial\n").addCommit("initial")
branch("feature")
val commit = file.append("master\n").addCommit("fix #1").hash()
checkout("feature")
file.append("local\n")
cherryPick(commit)
assertErrorNotification("Cherry-pick Failed", """
${shortHash(commit)} fix #1
Your local changes would be overwritten by cherry-pick.
Commit your changes or stash them to proceed.""")
}
protected fun `check untracked file conflicting with commit`() {
branch("feature")
val file = file("untracked.txt")
val commit = file.create("master\n").addCommit("fix #1").hash()
checkout("feature")
file.create("untracked\n")
cherryPick(commit)
assertErrorNotification("Untracked Files Prevent Cherry-pick", """
Move or commit them before cherry-pick""")
}
protected fun `check conflict with cherry-picked commit should show merge dialog`() {
val initial = tac("c.txt", "base\n")
val commit = repo.appendAndCommit("c.txt", "master")
repo.checkoutNew("feature", initial)
repo.appendAndCommit("c.txt", "feature")
`do nothing on merge`()
cherryPick(commit)
`assert merge dialog was shown`()
}
protected fun `check resolve conflicts and commit`() {
val commit = repo.prepareConflict()
`mark as resolved on merge`()
vcsHelper.onCommit { msg ->
git("commit -am '$msg'")
true
}
cherryPick(commit)
`assert commit dialog was shown`()
assertLastMessage("on_master")
repo.assertCommitted {
modified("c.txt")
}
assertSuccessfulNotification("Cherry-pick successful",
"${shortHash(commit)} on_master")
changeListManager.assertNoChanges()
changeListManager.waitScheduledChangelistDeletions()
changeListManager.assertOnlyDefaultChangelist()
}
protected fun cherryPick(hashes: List<String>) {
updateChangeListManager()
val details = readDetails(hashes)
GitCherryPicker(project, git).cherryPick(details)
}
protected fun cherryPick(vararg hashes: String) {
cherryPick(hashes.asList())
}
protected fun shortHash(hash: String) = HashImpl.build(hash).toShortString()
}
| apache-2.0 | 47fd639372e3bc2a0f9fea43e892722a | 29.979592 | 87 | 0.690711 | 4.34957 | false | false | false | false |
paplorinc/intellij-community | platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt | 1 | 11456 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.concurrency.JobScheduler
import com.intellij.ide.FrameStateListener
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.ManagingFS
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.util.SingleAlarm
import com.intellij.util.pooledThreadSingleAlarm
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.CalledInAwt
import java.beans.PropertyChangeListener
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
private const val LISTEN_DELAY = 15
internal class SaveAndSyncHandlerImpl : BaseSaveAndSyncHandler(), Disposable {
private val refreshDelayAlarm = SingleAlarm(Runnable { this.doScheduledRefresh() }, delay = 300, parentDisposable = this)
private val blockSaveOnFrameDeactivationCount = AtomicInteger()
private val blockSyncOnFrameActivationCount = AtomicInteger()
@Volatile
private var refreshSessionId = -1L
private val saveQueue = ArrayDeque<SaveAndSyncHandler.SaveTask>()
private val saveAlarm = pooledThreadSingleAlarm(delay = 300, parentDisposable = this) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && !app.isDisposeInProgress && blockSaveOnFrameDeactivationCount.get() == 0) {
runBlocking {
processTasks()
}
}
}
init {
// add listeners after some delay - doesn't make sense to listen earlier
JobScheduler.getScheduler().schedule(Runnable {
ApplicationManager.getApplication().invokeLater { addListeners() }
}, LISTEN_DELAY.toLong(), TimeUnit.SECONDS)
}
private suspend fun processTasks() {
while (true) {
val task = synchronized(saveQueue) {
saveQueue.pollFirst() ?: return
}
if (task.onlyProject?.isDisposed == true) {
continue
}
LOG.runAndLogException {
coroutineScope {
if (task.saveDocuments) {
launch(storeEdtCoroutineContext) {
// forceSavingAllSettings is set to true currently only if save triggered explicitly (or on close app/project), so, pass equal isDocumentsSavingExplicit
// in any case flag isDocumentsSavingExplicit is not really important
(FileDocumentManagerImpl.getInstance() as FileDocumentManagerImpl).saveAllDocuments(task.forceSavingAllSettings)
}
}
launch {
saveProjectsAndApp(forceSavingAllSettings = task.forceSavingAllSettings, onlyProject = task.onlyProject)
}
}
}
}
}
@CalledInAwt
private fun addListeners() {
val settings = GeneralSettings.getInstance()
val idleListener = Runnable {
if (settings.isAutoSaveIfInactive && canSyncOrSave()) {
submitTransaction {
(FileDocumentManagerImpl.getInstance() as FileDocumentManagerImpl).saveAllDocuments(false)
}
}
}
var disposable: Disposable? = null
fun addIdleListener() {
IdeEventQueue.getInstance().addIdleListener(idleListener, settings.inactiveTimeout * 1000)
disposable = Disposable { IdeEventQueue.getInstance().removeIdleListener(idleListener) }
Disposer.register(this, disposable!!)
}
settings.addPropertyChangeListener(GeneralSettings.PROP_INACTIVE_TIMEOUT, this, PropertyChangeListener {
disposable?.let { Disposer.dispose(it) }
addIdleListener()
})
addIdleListener()
if (LISTEN_DELAY >= (settings.inactiveTimeout * 1000)) {
idleListener.run()
}
val busConnection = ApplicationManager.getApplication().messageBus.connect(this)
busConnection.subscribe(FrameStateListener.TOPIC, object : FrameStateListener {
override fun onFrameDeactivated() {
if (!settings.isSaveOnFrameDeactivation || !canSyncOrSave()) {
return
}
// for web development it is crucially important to save documents on frame deactivation as early as possible
FileDocumentManager.getInstance().saveAllDocuments()
if (addToSaveQueue(saveAppAndProjectsSettingsTask)) {
// do not cancel if there is already request - opposite to scheduleSave,
// on frame deactivation better to save as soon as possible
saveAlarm.request()
}
}
override fun onFrameActivated() {
if (!ApplicationManager.getApplication().isDisposed && settings.isSyncOnFrameActivation) {
scheduleRefresh()
}
}
})
}
override fun scheduleSave(task: SaveAndSyncHandler.SaveTask, forceExecuteImmediately: Boolean) {
if (addToSaveQueue(task) || forceExecuteImmediately) {
saveAlarm.cancelAndRequest(forceRun = forceExecuteImmediately)
}
}
private fun addToSaveQueue(task: SaveAndSyncHandler.SaveTask): Boolean {
synchronized(saveQueue) {
if (task.onlyProject == null) {
saveQueue.removeAll(task::isMoreGenericThan)
}
else if (saveQueue.any { it.isMoreGenericThan(task) }) {
return false
}
return when {
saveQueue.contains(task) -> false
else -> saveQueue.add(task)
}
}
}
override fun cancelScheduledSave() {
saveAlarm.cancel()
}
private fun waitForScheduledSave() {
if (saveAlarm.isEmpty) {
return
}
while (true) {
ApplicationManager.getApplication().invokeAndWait(Runnable {
edtPoolDispatcherManager.processTasks()
}, ModalityState.any())
if (saveAlarm.isEmpty) {
return
}
Thread.sleep(5)
}
}
/**
* On app or project closing save is performed. In EDT. It means that if there is already running save in a pooled thread,
* deadlock may be occurred because some save activities requires EDT with modality state "not modal" (by intention).
* So, save on app or project closing uses this method to process scheduled for EDT activities - instead of using regular EDT queue special one is used.
*/
@CalledInAwt
override fun saveSettingsUnderModalProgress(componentManager: ComponentManager, isSaveAppAlso: Boolean): Boolean {
if (!ApplicationManager.getApplication().isDispatchThread) {
throw IllegalStateException(
"saveSettingsUnderModalProgress is intended to be called only in EDT because otherwise wrapping into modal progress task is not required" +
" and `saveSettings` should be called directly")
}
var isSavedSuccessfully = true
runInSaveOnFrameDeactivationDisabledMode {
edtPoolDispatcherManager.processTasks()
ProgressManager.getInstance().run(object : Task.Modal(componentManager as? Project, "Saving " + (if (componentManager is Application) "Application" else "Project"), /* canBeCancelled = */ false) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
if (project != null) {
synchronized(saveQueue) {
saveQueue.removeAll { it.onlyProject === project }
}
}
waitForScheduledSave()
runBlocking {
isSavedSuccessfully = saveSettings(componentManager, forceSavingAllSettings = true)
if (isSaveAppAlso && componentManager !is Application) {
saveSettings(ApplicationManager.getApplication(), forceSavingAllSettings = true)
}
}
}
})
}
return isSavedSuccessfully
}
override fun dispose() {
if (refreshSessionId != -1L) {
RefreshQueue.getInstance().cancelSession(refreshSessionId)
}
}
private fun canSyncOrSave(): Boolean {
return !LaterInvocator.isInModalContext() && !ProgressManager.getInstance().hasModalProgressIndicator()
}
override fun scheduleRefresh() {
refreshDelayAlarm.cancelAndRequest()
}
private fun doScheduledRefresh() {
submitTransaction {
if (canSyncOrSave()) {
refreshOpenFiles()
}
maybeRefresh(ModalityState.NON_MODAL)
}
}
override fun maybeRefresh(modalityState: ModalityState) {
if (blockSyncOnFrameActivationCount.get() == 0 && GeneralSettings.getInstance().isSyncOnFrameActivation) {
val queue = RefreshQueue.getInstance()
queue.cancelSession(refreshSessionId)
val session = queue.createSession(true, true, null, modalityState)
session.addAllFiles(*ManagingFS.getInstance().localRoots)
refreshSessionId = session.id
session.launch()
LOG.debug("vfs refreshed")
}
else {
LOG.debug { "vfs refresh rejected, blocked: ${blockSyncOnFrameActivationCount.get() != 0}, isSyncOnFrameActivation: ${GeneralSettings.getInstance().isSyncOnFrameActivation}" }
}
}
override fun refreshOpenFiles() {
val files = ArrayList<VirtualFile>()
for (project in ProjectManager.getInstance().openProjects) {
FileEditorManager.getInstance(project).selectedFiles.filterTo(files) { it is NewVirtualFile }
}
if (!files.isEmpty()) {
// refresh open files synchronously so it doesn't wait for potentially longish refresh request in the queue to finish
RefreshQueue.getInstance().refresh(false, false, null, files)
}
}
override fun blockSaveOnFrameDeactivation() {
LOG.debug("save blocked")
blockSaveOnFrameDeactivationCount.incrementAndGet()
}
override fun unblockSaveOnFrameDeactivation() {
blockSaveOnFrameDeactivationCount.decrementAndGet()
LOG.debug("save unblocked")
}
override fun blockSyncOnFrameActivation() {
LOG.debug("sync blocked")
blockSyncOnFrameActivationCount.incrementAndGet()
}
override fun unblockSyncOnFrameActivation() {
blockSyncOnFrameActivationCount.decrementAndGet()
LOG.debug("sync unblocked")
}
private inline fun submitTransaction(crossinline handler: () -> Unit) {
TransactionGuard.submitTransaction(this, Runnable { handler() })
}
}
private val saveAppAndProjectsSettingsTask = SaveAndSyncHandler.SaveTask(saveDocuments = false)
internal abstract class BaseSaveAndSyncHandler : SaveAndSyncHandler() {
internal val edtPoolDispatcherManager = EdtPoolDispatcherManager()
} | apache-2.0 | be20e0191cc1e328419c45161c9c544e | 35.371429 | 202 | 0.724162 | 5.114286 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/FontSizeInfoUsageCollector.kt | 6 | 5354 | // 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.collectors.fus.ui
import com.intellij.ide.ui.UISettings
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
/**
* @author Konstantin Bulenkov
*/
class FontSizeInfoUsageCollector : ApplicationUsagesCollector() {
companion object {
private val GROUP = EventLogGroup("ui.fonts", 5)
val FONT_NAME = EventFields.String(
"font_name", arrayListOf(
"Monospaced", "Menlo", "DejaVu_Sans_Mono", ".SFNSText-Regular", "Fira_Code", "Lucida_Grande", "Source_Code_Pro", "Segoe_UI", "Ubuntu",
".SF_NS_Text", "Consolas", "Noto_Sans_Regular", "Microsoft_YaHei", "Fira_Code_Retina", "Cantarell_Regular", "Microsoft_YaHei_UI",
"Monaco", "Noto_Sans", "Dialog.plain", "Fira_Code_Medium", "Courier_New", "Tahoma", "Hack", "DejaVu_Sans", "Ubuntu_Mono",
"Droid_Sans_Mono", "Dialog", "Inconsolata", "Malgun_Gothic", "Cantarell", "DialogInput", "Yu_Gothic_UI_Regular", "Roboto",
"Liberation_Mono", "Lucida_Console", "D2Coding", "Lucida_Sans_Typewriter", "Fira_Code_Light", "Droid_Sans", "Verdana", "Arial",
"Roboto_Mono", "Segoe_UI_Semibold", "SF_Mono", "Droid_Sans_Mono_Slashed", "LucidaGrande", "Operator_Mono", "Ayuthaya", "Hasklig",
"Iosevka", "Andale_Mono", "Anonymous_Pro", "Anonymous_Pro_for_Powerline", "D2Coding_ligature", "Dank_Mono",
"DejaVu_Sans_Mono_for_Powerline", "Fantasque_Sans_Mono", "Fira_Mono_for_Powerline", "Hack_Nerd_Font", "IBM_Plex_Mono",
"Meslo_LG_L_DZ_for_Powerline", "Meslo_LG_M_for_Powerline", "Meslo_LG_S_for_Powerline", "Microsoft_YaHei_Mono",
"Noto_Mono_for_Powerline", "Noto_Sans_Mono", "PT_Mono", "PragmataPro", "SourceCodePro+Powerline+Awesome_Regular",
"Source_Code_Pro_Semibold", "Source_Code_Pro_for_Powerline", "Ubuntu_Mono_derivative_Powerline", "YaHei_Consolas_Hybrid",
"mononoki", "Bitstream_Vera_Sans_Mono", "Comic_Sans_MS", "Courier_10_Pitch", "Cousine", "2Coding_ligature", "Droid_Sans_Mono_Dotted",
"Inconsolata-dz", "Input", "Input_Mono", "Meslo_LG_M_DZ_for_Powerline", "Migu_2M", "Monoid", "Operator_Mono_Book",
"Operator_Mono_Lig", "Operator_Mono_Medium", "Abadi_MT_Condensed_Extra_Bold", "Al_Bayan", "Meiryo", "Microsoft_JhengHei",
"Microsoft_Yahei_UI", "SansSerif", "Ubuntu_Light", "JetBrains_Mono", ".AppleSystemUIFont", ".SFNS-Regular"
))
val FONT_SIZE = EventFields.Int("font_size")
val FONT_SIZE_2D = EventFields.Float("font_size_2d")
val LINE_SPACING = EventFields.Float("line_spacing")
val FONT_SIZE_STRING = EventFields.String(
"font_size", arrayListOf("X_SMALL", "X_LARGE", "XX_SMALL", "XX_LARGE", "SMALL", "MEDIUM", "LARGE")
)
val UI_FONT = GROUP.registerEvent("UI", FONT_NAME, FONT_SIZE, FONT_SIZE_2D)
val PRESENTATION_MODE_FONT = GROUP.registerEvent("Presentation.mode", FONT_SIZE)
val EDITOR_FONT = GROUP.registerVarargEvent("Editor", FONT_NAME, FONT_SIZE, FONT_SIZE_2D, LINE_SPACING)
val IDE_EDITOR_FONT = GROUP.registerVarargEvent("IDE.editor", FONT_NAME, FONT_SIZE, FONT_SIZE_2D, LINE_SPACING)
val CONSOLE_FONT = GROUP.registerVarargEvent("Console", FONT_NAME, FONT_SIZE, FONT_SIZE_2D, LINE_SPACING)
val QUICK_DOC_FONT = GROUP.registerEvent("QuickDoc", FONT_SIZE_STRING)
}
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): Set<MetricEvent> {
val scheme = EditorColorsManager.getInstance().globalScheme
val ui = UISettings.shadowInstance
val usages = mutableSetOf(
UI_FONT.metric(ui.fontFace, ui.fontSize, ui.fontSize2D),
PRESENTATION_MODE_FONT.metric(ui.presentationModeFontSize)
)
if (!scheme.isUseAppFontPreferencesInEditor) {
usages += EDITOR_FONT.metric(
FONT_NAME.with(scheme.editorFontName),
FONT_SIZE.with(scheme.editorFontSize),
FONT_SIZE_2D.with(scheme.editorFontSize2D),
LINE_SPACING.with(scheme.lineSpacing))
}
else {
val appPrefs = AppEditorFontOptions.getInstance().fontPreferences
usages += IDE_EDITOR_FONT.metric(
FONT_NAME.with(appPrefs.fontFamily),
FONT_SIZE.with(appPrefs.getSize(appPrefs.fontFamily)),
FONT_SIZE_2D.with(appPrefs.getSize2D(appPrefs.fontFamily)),
LINE_SPACING.with(appPrefs.lineSpacing))
}
if (!scheme.isUseEditorFontPreferencesInConsole) {
usages += CONSOLE_FONT.metric(
FONT_NAME.with(scheme.consoleFontName),
FONT_SIZE.with(scheme.consoleFontSize),
FONT_SIZE_2D.with(scheme.consoleFontSize2D),
LINE_SPACING.with(scheme.consoleLineSpacing))
}
val quickDocFontSize = PropertiesComponent.getInstance().getValue("quick.doc.font.size.v3")
if (quickDocFontSize != null) {
usages += QUICK_DOC_FONT.metric(quickDocFontSize)
}
return usages
}
}
| apache-2.0 | e9dc7c0af6eb9085509ea9c171030d1e | 57.195652 | 140 | 0.710684 | 3.371537 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/SO_MENU.kt | 2 | 4311 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object SO_MENU: Response() {
override val url = "http://localhost:8080/restful/services/simple.SimpleObjectMenu"
override val str = """{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Simple Objects"
},
{
"rel": "describedby",
"href": "http://localhost:8080/restful/domain-types/simple.SimpleObjectMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/domain-type\""
},
{
"rel": "urn:org.apache.causeway.restfulobjects:rels/layout",
"href": "http://localhost:8080/restful/domain-types/simple.SimpleObjectMenu/layout",
"method": "GET",
"type": "application/xmlprofile=\"urn:org.restfulobjects:repr-types/layout-bs3\""
},
{
"rel": "up",
"href": "http://localhost:8080/restful/services",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/list\""
}
],
"extensions": {
"oid": "simple.SimpleObjectMenu:1",
"isService": true,
"isPersistent": true,
"menuBar": "PRIMARY"
},
"title": "Simple Objects",
"serviceId": "simple.SimpleObjectMenu",
"members": {
"listAll": {
"id": "listAll",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"listAll\"",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/listAll",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
},
"findByName": {
"id": "findByName",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"findByName\"",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/findByName",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
},
"create": {
"id": "create",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"create\"",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/create",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
}
}
}"""
}
| apache-2.0 | c9d645b313aaff460425adf23d87f4ab | 42.11 | 116 | 0.52424 | 4.71663 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.