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/idea/tests/test/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInLibrarySourcesTest.kt | 2 | 2745 | // 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.resolve
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.util.ThrowableRunnable
import junit.framework.AssertionFailedError
import org.jetbrains.kotlin.idea.navigation.NavigationTestUtils
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.junit.Assert
abstract class AbstractReferenceResolveInLibrarySourcesTest : KotlinLightCodeInsightFixtureTestCase() {
companion object {
private const val REF_CARET_MARKER = "<ref-caret>"
}
private val mockLibraryFacility = MockLibraryFacility(
source = IDEA_TEST_DATA_DIR.resolve("resolve/referenceInLib/inLibrarySource"),
)
override fun setUp() {
super.setUp()
mockLibraryFacility.setUp(module)
}
override fun tearDown() {
runAll(
ThrowableRunnable { mockLibraryFacility.tearDown(module) },
ThrowableRunnable { super.tearDown() }
)
}
fun doTest(unused: String) {
val fixture = myFixture!!
fixture.configureByFile(fileName())
val expectedResolveData = AbstractReferenceResolveTest.readResolveData(fixture.file!!.text, 0)
val gotoData = NavigationTestUtils.invokeGotoImplementations(fixture.editor, fixture.file)!!
Assert.assertEquals("Single target expected for original file", 1, gotoData.targets.size)
val testedPsiElement = gotoData.targets[0].navigationElement
val testedElementFile = testedPsiElement.containingFile!!
val lineContext = InTextDirectivesUtils.findStringWithPrefixes(fixture.file!!.text, "CONTEXT:")
?: throw AssertionFailedError("'CONTEXT: ' directive is expected to set up position in library file: ${testedElementFile.name}")
val inContextOffset = lineContext.indexOf(REF_CARET_MARKER)
check(inContextOffset != -1) { "No '$REF_CARET_MARKER' marker found in 'CONTEXT: $lineContext'" }
val contextStr = lineContext.replace(REF_CARET_MARKER, "")
val offsetInFile = testedElementFile.text!!.indexOf(contextStr)
check(offsetInFile != -1) { "Context '$contextStr' wasn't found in file ${testedElementFile.name}" }
val offset = offsetInFile + inContextOffset
val reference = testedElementFile.findReferenceAt(offset)!!
AbstractReferenceResolveTest.checkReferenceResolve(expectedResolveData, offset, reference)
}
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance()
}
| apache-2.0 | f6769969883f9d2d1bb1be60cf1ae85f | 41.230769 | 158 | 0.735883 | 5.027473 | false | true | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/ui/detail/playback/ExoPlayerAdapter.kt | 1 | 5393 | package de.stefanmedack.ccctv.ui.detail.playback
import android.app.Instrumentation
import android.content.Context
import android.net.Uri
import android.view.KeyEvent
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.video.VideoListener
import de.stefanmedack.ccctv.ui.detail.uiModels.VideoPlaybackUiModel
import de.stefanmedack.ccctv.util.bestRecording
import de.stefanmedack.ccctv.util.switchAspectRatio
import info.metadude.kotlin.library.c3media.models.Event
import info.metadude.kotlin.library.c3media.models.Language
import info.metadude.kotlin.library.c3media.models.Recording
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.subscribeBy
import timber.log.Timber
import java.util.*
class ExoPlayerAdapter(context: Context) : BaseExoPlayerAdapter(context) {
private var event: Event? = null
private var shouldUseHighQuality = true
private var bestRecording: Recording? = null
private var currentRecordingWidth: Int? = null
private var currentRecordingHeight: Int? = null
private val disposables = CompositeDisposable()
override fun onDetachedFromHost() {
disposables.clear()
super.onDetachedFromHost()
}
fun bindRecordings(recordings: Single<VideoPlaybackUiModel>) {
disposables.add(recordings.subscribeBy(
onSuccess = {
event = it.event
extractBestRecording(it.event)
prepareMediaForPlaying()
if (it.retainedPlaybackSeconds > 0) {
player.seekTo(it.retainedPlaybackSeconds * 1000L)
}
}
))
}
fun changeQuality(isHigh: Boolean) {
event?.let { event ->
shouldUseHighQuality = isHigh
extractBestRecording(event)
mediaSourceUri?.let {
val currPos = player.currentPosition
player.prepare(onCreateMediaSource(it))
player.seekTo(currPos)
}
}
}
fun toggleAspectRatio() {
if (currentRecordingWidth != null && currentRecordingHeight != null) {
currentRecordingWidth = switchAspectRatio(currentRecordingWidth!!, currentRecordingHeight!!)
callback.onVideoSizeChanged(this@ExoPlayerAdapter,
currentRecordingWidth!!,
currentRecordingHeight!!)
}
}
private fun prepareMediaForPlaying() {
reset()
mediaSourceUri?.let {
player.prepare(onCreateMediaSource(it))
}
player.addVideoListener(object : VideoListener {
override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
currentRecordingWidth = (width * pixelWidthHeightRatio).toInt()
currentRecordingHeight = height
callback.onVideoSizeChanged(
this@ExoPlayerAdapter,
currentRecordingWidth!!,
currentRecordingHeight!!
)
}
override fun onRenderedFirstFrame() {}
})
notifyBufferingStartEnd()
callback.onPlayStateChanged(this@ExoPlayerAdapter)
}
private fun extractBestRecording(ev: Event) {
bestRecording = ev.bestRecording(
if (ev.originalLanguage.isEmpty())
Language.toLanguage(Locale.getDefault().isO3Country)
else
ev.originalLanguage.first(),
shouldUseHighQuality
)
currentRecordingHeight = bestRecording?.height
currentRecordingWidth = bestRecording?.width
mediaSourceUri = Uri.parse(bestRecording?.recordingUrl)
}
// This is a workaround to simulate a Dpad enter key after seeking. As long as the SeekProvider with video thumbnails is not implemented
// (see https://developer.android.com/reference/android/support/v17/leanback/media/PlaybackTransportControlGlue.html#setSeekProvider ),
// the default behaviour for seeking implemented by PlaybackTransportControlGlue is quite confusing to the user.
//
// Any better solutions than this one are gladly accepted
private var shouldTriggerDpadCenterKeyEvent = false
fun simpleSeekTo(newPosition: Long) {
seekTo(newPosition)
shouldTriggerDpadCenterKeyEvent = false
}
override fun seekTo(newPosition: Long) {
super.seekTo(newPosition)
if (initialized) {
shouldTriggerDpadCenterKeyEvent = true
}
}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
super.onPlayerStateChanged(playWhenReady, playbackState)
if (shouldTriggerDpadCenterKeyEvent && playbackState == Player.STATE_READY) {
shouldTriggerDpadCenterKeyEvent = false
triggerDpadCenterKeyEvent()
}
}
private fun triggerDpadCenterKeyEvent() {
Thread({
try {
val inst = Instrumentation()
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER)
} catch (e: InterruptedException) {
Timber.w(e, "Could not simulate KEYCODE_ENTER")
}
}).start()
}
// end workaround for seeking
} | apache-2.0 | 7a6309bc0474ac02592c3c6c754635d3 | 34.96 | 140 | 0.654181 | 5.200579 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/concurrent/Lock.kt | 2 | 1473 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
import kotlin.native.internal.Frozen
@ThreadLocal
private object CurrentThread {
val id = Any().freeze()
}
@Frozen
internal class Lock {
private val locker_ = AtomicInt(0)
private val reenterCount_ = AtomicInt(0)
// TODO: make it properly reschedule instead of spinning.
fun lock() {
val lockData = CurrentThread.id.hashCode()
loop@ do {
val old = locker_.compareAndSwap(0, lockData)
when (old) {
lockData -> {
// Was locked by us already.
reenterCount_.increment()
break@loop
}
0 -> {
// We just got the lock.
assert(reenterCount_.value == 0)
break@loop
}
}
} while (true)
}
fun unlock() {
if (reenterCount_.value > 0) {
reenterCount_.decrement()
} else {
val lockData = CurrentThread.id.hashCode()
val old = locker_.compareAndSwap(lockData, 0)
assert(old == lockData)
}
}
}
internal inline fun <R> locked(lock: Lock, block: () -> R): R {
lock.lock()
try {
return block()
} finally {
lock.unlock()
}
} | apache-2.0 | bd1b11d184bd39cdc6ff2417cfc3861f | 24.413793 | 101 | 0.522743 | 4.232759 | false | false | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/target/PyInterpreterVersionUtil.kt | 1 | 3959 | // 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.
@file:JvmName("PyInterpreterVersionUtil")
package com.jetbrains.python.target
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.target.TargetProgressIndicatorAdapter
import com.intellij.execution.target.TargetedCommandLineBuilder
import com.intellij.execution.target.getTargetEnvironmentRequest
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.util.Ref
import com.intellij.remote.RemoteSdkException
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.PyBundle
@Throws(RemoteSdkException::class)
fun PyTargetAwareAdditionalData.getInterpreterVersion(project: Project?, nullForUnparsableVersion: Boolean = true): String? {
return getInterpreterVersion(project, interpreterPath, nullForUnparsableVersion)
}
@Throws(RemoteSdkException::class)
fun PyTargetAwareAdditionalData.getInterpreterVersion(project: Project?,
interpreterPath: String,
nullForUnparsableVersion: Boolean = true): String? {
val targetEnvironmentRequest = getTargetEnvironmentRequest(project)
?: throw IllegalStateException("Unable to get target configuration from Python SDK data")
val result = Ref.create<String>()
val exception = Ref.create<RemoteSdkException>()
val task: Task.Modal = object : Task.Modal(project, PyBundle.message("python.sdk.getting.remote.interpreter.version"), true) {
override fun run(indicator: ProgressIndicator) {
val flavor = flavor
if (flavor != null) {
try {
try {
val targetedCommandLineBuilder = TargetedCommandLineBuilder(targetEnvironmentRequest)
targetedCommandLineBuilder.setExePath(interpreterPath)
targetedCommandLineBuilder.addParameter(flavor.versionOption)
val targetEnvironment = targetEnvironmentRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
val targetedCommandLine = targetedCommandLineBuilder.build()
val process = targetEnvironment.createProcess(targetedCommandLine, indicator)
val commandLineString = targetedCommandLine.collectCommandsSynchronously().joinToString(separator = " ")
val capturingProcessHandler = CapturingProcessHandler(process, Charsets.UTF_8, commandLineString)
val processOutput = capturingProcessHandler.runProcess()
if (processOutput.exitCode == 0) {
val version = flavor.getVersionStringFromOutput(processOutput)
if (version != null || nullForUnparsableVersion) {
result.set(version)
return
}
else {
throw RemoteSdkException(PyBundle.message("python.sdk.empty.version.string"), processOutput.stdout, processOutput.stderr)
}
}
else {
throw RemoteSdkException(
PyBundle.message("python.sdk.non.zero.exit.code", processOutput.exitCode), processOutput.stdout, processOutput.stderr)
}
}
catch (e: Exception) {
throw RemoteSdkException.cantObtainRemoteCredentials(e)
}
}
catch (e: RemoteSdkException) {
exception.set(e)
}
}
}
}
if (!ProgressManager.getInstance().hasProgressIndicator()) {
UIUtil.invokeAndWaitIfNeeded(Runnable { ProgressManager.getInstance().run(task) })
}
else {
task.run(ProgressManager.getInstance().progressIndicator)
}
if (!exception.isNull) {
throw exception.get()
}
return result.get()
} | apache-2.0 | 31c7744f4530090b1e36a2ae6abeb968 | 45.588235 | 158 | 0.70245 | 5.13489 | false | false | false | false |
Zeroami/CommonLib-Kotlin | commonlib/src/main/java/com/zeroami/commonlib/http/LProgressRequestBody.kt | 1 | 2149 | package com.zeroami.commonlib.http
import java.io.IOException
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSink
import okio.Okio
import okio.Sink
/**
* 带进度信息的RequestBody
*
* @author Zeroami
*/
class LProgressRequestBody(
private val requestBody: RequestBody,
private val progressListener: (current: Long, total: Long) -> Unit) : RequestBody() {
//包装完成的BufferedSink
private var bufferedSink: BufferedSink? = null
/**
* 重写调用实际的响应体的contentType
*/
override fun contentType(): MediaType {
return requestBody.contentType()
}
/**
* 重写调用实际的响应体的contentLength
*/
@Throws(IOException::class)
override fun contentLength(): Long {
return requestBody.contentLength()
}
/**
* 重写进行写入
*/
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink))
}
requestBody.writeTo(bufferedSink)
//必须调用flush,否则最后一部分数据可能不会被写入
bufferedSink?.flush()
}
/**
* 写入,回调进度接口
*/
private fun sink(sink: Sink): Sink {
return object : ForwardingSink(sink) {
//当前写入字节数
internal var writtenBytesCount = 0L
//总字节长度,避免多次调用contentLength()方法
internal var totalBytesCount = 0L
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
super.write(source, byteCount)
//增加当前写入的字节数
writtenBytesCount += byteCount
//获得contentLength的值,后续不再调用
if (totalBytesCount.toInt() == 0) {
totalBytesCount = contentLength()
}
progressListener(writtenBytesCount, totalBytesCount)
}
}
}
} | apache-2.0 | 66535a245ad532447822631c4b4c9b46 | 24.368421 | 93 | 0.601972 | 4.399543 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinStringUSimpleReferenceExpression.kt | 4 | 1330 | // 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.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.ResolveResult
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UMultiResolvable
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.kotlin.internal.multiResolveResults
@ApiStatus.Internal
class KotlinStringUSimpleReferenceExpression(
override val identifier: String,
givenParent: UElement?,
override val sourcePsi: PsiElement? = null,
private val referenceAnchor: KtElement? = null
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable {
override val psi: PsiElement?
get() = null
private val resolved by lz { referenceAnchor?.references?.singleOrNull()?.resolve() }
override fun resolve() = resolved
override val resolvedName: String
get() = (resolved as? PsiNamedElement)?.name ?: identifier
override fun multiResolve(): Iterable<ResolveResult> = referenceAnchor?.multiResolveResults().orEmpty().asIterable()
}
| apache-2.0 | 9b4e7874aaa75d6cafd5aea480007af0 | 40.5625 | 158 | 0.78797 | 4.907749 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/caches/trackers/KotlinModuleOutOfCodeBlockModificationTracker.kt | 1 | 5039 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.trackers
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.Processors
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.caches.project.cacheByClassInvalidatingOnRootModifications
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import org.jetbrains.kotlin.psi.KtFile
class KotlinModuleOutOfCodeBlockModificationTracker(private val module: Module) : ModificationTracker {
private val kotlinOutOfCodeBlockTracker = KotlinCodeBlockModificationListener.getInstance(module.project).kotlinOutOfCodeBlockTracker
private val updater
get() = getUpdaterInstance(module.project)
private val dependencies by lazy {
// Avoid implicit capturing for this to make CachedValueStabilityChecker happy
val module = module
module.cacheByClassInvalidatingOnRootModifications(KeyForCachedDependencies::class.java) {
val modules = HashSet<Module>()
val processor = Processors.cancelableCollectProcessor(modules)
ModuleRootManager.getInstance(module).orderEntries().recursively().forEachModule(processor)
ModuleDependencyProviderExtension.getInstance(module.project).processAdditionalDependencyModules(module, processor)
modules
}
}
object KeyForCachedDependencies
override fun getModificationCount(): Long {
val currentGlobalCount = kotlinOutOfCodeBlockTracker.modificationCount
if (updater.hasPerModuleModificationCounts()) {
val selfCount = updater.getModificationCount(module)
if (selfCount == currentGlobalCount) return selfCount
var maxCount = selfCount
for (dependency in dependencies) {
val depCount = updater.getModificationCount(dependency)
if (depCount == currentGlobalCount) return currentGlobalCount
if (depCount > maxCount) maxCount = depCount
}
return maxCount
}
return currentGlobalCount
}
companion object {
internal fun getUpdaterInstance(project: Project): Updater =
project.getServiceSafe()
@TestOnly
fun getModificationCount(module: Module): Long = getUpdaterInstance(module.project).getModificationCount(module)
}
@Service
class Updater(private val project: Project): Disposable {
private val kotlinOfOfCodeBlockTracker
get() =
KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker
private val perModuleModCount = mutableMapOf<Module, Long>()
private var lastAffectedModule: Module? = null
private var lastAffectedModuleModCount = -1L
// All modifications since that count are known to be single-module modifications reflected in
// perModuleModCount map
private var perModuleChangesHighWatermark: Long? = null
internal fun getModificationCount(module: Module): Long {
return perModuleModCount[module] ?: perModuleChangesHighWatermark ?: kotlinOfOfCodeBlockTracker.modificationCount
}
internal fun hasPerModuleModificationCounts() = perModuleChangesHighWatermark != null
internal fun onKotlinPhysicalFileOutOfBlockChange(ktFile: KtFile, immediateUpdatesProcess: Boolean) {
lastAffectedModule = ModuleUtil.findModuleForPsiElement(ktFile)
lastAffectedModuleModCount = kotlinOfOfCodeBlockTracker.modificationCount
if (immediateUpdatesProcess) {
onPsiModificationTrackerUpdate(0)
}
}
internal fun onPsiModificationTrackerUpdate(customIncrement: Int = 0) {
val newModCount = kotlinOfOfCodeBlockTracker.modificationCount
val affectedModule = lastAffectedModule
if (affectedModule != null && newModCount == lastAffectedModuleModCount + customIncrement) {
if (perModuleChangesHighWatermark == null) {
perModuleChangesHighWatermark = lastAffectedModuleModCount
}
perModuleModCount[affectedModule] = newModCount
} else {
// Some updates were not processed in our code so they probably came from other languages. Invalidate all.
clean()
}
}
private fun clean() {
perModuleChangesHighWatermark = null
lastAffectedModule = null
perModuleModCount.clear()
}
override fun dispose() = clean()
}
} | apache-2.0 | 94491c963dcfd230c6cca91d3dc22c7f | 41 | 158 | 0.710458 | 5.489107 | false | false | false | false |
ianhanniballake/muzei | source-gallery/src/main/java/com/google/android/apps/muzei/gallery/Metadata.kt | 2 | 1510 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.gallery
import android.net.Uri
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.google.android.apps.muzei.gallery.converter.DateTypeConverter
import com.google.android.apps.muzei.gallery.converter.UriTypeConverter
import java.util.Date
/**
* Entity representing a row of cached metadata in Room
*/
@Entity(tableName = "metadata_cache", indices = [(Index(value = ["uri"], unique = true))])
internal data class Metadata(
@field:TypeConverters(UriTypeConverter::class)
val uri: Uri,
@field:TypeConverters(DateTypeConverter::class)
@ColumnInfo(name = "datetime")
var date: Date? = null,
var location: String? = null
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
var id: Long = 0
}
| apache-2.0 | dab7fc8e6bd02030784c0a3f8db699fa | 32.555556 | 90 | 0.730464 | 4.05914 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/InlayHintsUtils.kt | 1 | 8760 | // 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.codeInsight.hints
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.RecursivelyUpdatingRootPresentation
import com.intellij.codeInsight.hints.presentation.RootInlayPresentation
import com.intellij.configurationStore.deserializeInto
import com.intellij.configurationStore.serialize
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SyntaxTraverser
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.Nls.Capitalization.Title
import java.awt.Dimension
import java.awt.Rectangle
import java.util.function.Supplier
class ProviderWithSettings<T: Any>(
val info: ProviderInfo<T>,
var settings: T
) {
val configurable by lazy { provider.createConfigurable(settings) }
val provider: InlayHintsProvider<T>
get() = info.provider
val language: Language
get() = info.language
}
fun <T : Any> ProviderWithSettings<T>.withSettingsCopy(): ProviderWithSettings<T> {
val settingsCopy = copySettings(settings, provider)
return ProviderWithSettings(info, settingsCopy)
}
fun <T : Any> ProviderWithSettings<T>.getCollectorWrapperFor(file: PsiFile, editor: Editor, language: Language): CollectorWithSettings<T>? {
val key = provider.key
val sink = InlayHintsSinkImpl(editor)
val collector = provider.getCollectorFor(file, editor, settings, sink) ?: return null
return CollectorWithSettings(collector, key, language, sink)
}
internal fun <T : Any> ProviderWithSettings<T>.getPlaceholdersCollectorFor(file: PsiFile, editor: Editor): CollectorWithSettings<T>? {
val key = provider.key
val sink = InlayHintsSinkImpl(editor)
val collector = provider.getPlaceholdersCollectorFor(file, editor, settings, sink) ?: return null
return CollectorWithSettings(collector, key, language, sink)
}
internal fun <T : Any> InlayHintsProvider<T>.withSettings(language: Language, config: InlayHintsSettings): ProviderWithSettings<T> {
val settings = getActualSettings(config, language)
return ProviderWithSettings(ProviderInfo(language, this), settings)
}
internal fun <T : Any> InlayHintsProvider<T>.getActualSettings(config: InlayHintsSettings, language: Language): T =
config.findSettings(key, language) { createSettings() }
internal fun <T : Any> copySettings(from: T, provider: InlayHintsProvider<T>): T {
val settings = provider.createSettings()
// Workaround to make a deep copy of settings. The other way is to parametrize T with something like
// interface DeepCopyable<T> { fun deepCopy(from: T): T }, but there will be a lot of problems with recursive type bounds
// That way was implemented and rejected
serialize(from)?.deserializeInto(settings)
return settings
}
class CollectorWithSettings<T : Any>(
val collector: InlayHintsCollector,
val key: SettingsKey<T>,
val language: Language,
val sink: InlayHintsSinkImpl
) {
fun collectHints(element: PsiElement, editor: Editor): Boolean {
return collector.collect(element, editor, sink)
}
/**
* Collects hints from the file and apply them to editor.
* Doesn't expect other hints in editor.
* Use only for settings preview.
*/
fun collectTraversingAndApply(editor: Editor, file: PsiFile, enabled: Boolean) {
val hintsBuffer = collectTraversing(editor, file, enabled)
applyToEditor(file, editor, hintsBuffer)
}
/**
* Same as [collectTraversingAndApply] but invoked on bg thread
*/
fun collectTraversingAndApplyOnEdt(editor: Editor, file: PsiFile, enabled: Boolean) {
val hintsBuffer = collectTraversing(editor, file, enabled)
invokeLater { applyToEditor(file, editor, hintsBuffer) }
}
fun collectTraversing(editor: Editor, file: PsiFile, enabled: Boolean): HintsBuffer {
if (enabled) {
val traverser = SyntaxTraverser.psiTraverser(file)
traverser.forEach {
collectHints(it, editor)
}
}
return sink.complete()
}
fun applyToEditor(file: PsiFile, editor: Editor, hintsBuffer: HintsBuffer) {
InlayHintsPass.applyCollected(hintsBuffer, file, editor)
}
}
fun InlayPresentation.fireContentChanged() {
fireContentChanged(Rectangle(width, height))
}
fun InlayPresentation.fireUpdateEvent(previousDimension: Dimension) {
val current = dimension()
if (previousDimension != current) {
fireSizeChanged(previousDimension, current)
}
fireContentChanged()
}
fun InlayPresentation.dimension() = Dimension(width, height)
private typealias ConstrPresent<C> = ConstrainedPresentation<*, C>
@ApiStatus.Experimental
fun InlayHintsSink.addCodeVisionElement(editor: Editor, offset: Int, priority: Int, presentation: InlayPresentation) {
val line = editor.document.getLineNumber(offset)
val column = offset - editor.document.getLineStartOffset(line)
val root = RecursivelyUpdatingRootPresentation(presentation)
val constraints = BlockConstraints(false, priority, InlayGroup.CODE_VISION_GROUP.ordinal, column)
addBlockElement(line, true, root, constraints)
}
object InlayHintsUtils {
fun getDefaultInlayHintsProviderPopupActions(
providerKey: SettingsKey<*>,
providerName: Supplier<@Nls(capitalization = Title) String>
): List<AnAction> =
listOf(
DisableInlayHintsProviderAction(providerKey, providerName, false),
ConfigureInlayHintsProviderAction(providerKey)
)
fun getDefaultInlayHintsProviderCasePopupActions(
providerKey: SettingsKey<*>,
providerName: Supplier<@Nls(capitalization = Title) String>,
caseId: String,
caseName: Supplier<@Nls(capitalization = Title) String>
): List<AnAction> =
listOf(
DisableInlayHintsProviderCaseAction(providerKey, providerName, caseId, caseName),
DisableInlayHintsProviderAction(providerKey, providerName, true),
ConfigureInlayHintsProviderAction(providerKey)
)
/**
* Function updates list of old presentations with new list, taking into account priorities.
* Both lists must be sorted.
*
* @return list of updated constrained presentations
*/
fun <Constraint : Any> produceUpdatedRootList(
new: List<ConstrPresent<Constraint>>,
old: List<ConstrPresent<Constraint>>,
comparator: Comparator<ConstrPresent<Constraint>>,
editor: Editor,
factory: InlayPresentationFactory
): List<ConstrPresent<Constraint>> {
val updatedPresentations: MutableList<ConstrPresent<Constraint>> = SmartList()
// TODO [roman.ivanov]
// this function creates new list anyway, even if nothing from old presentations got updated,
// which makes us update list of presentations on every update (which should be relatively rare!)
// maybe I should really create new list only in case when anything get updated
val oldSize = old.size
val newSize = new.size
var oldIndex = 0
var newIndex = 0
// Simultaneous bypass of both lists and merging them to new one with element update
loop@
while (true) {
val newEl = new[newIndex]
val oldEl = old[oldIndex]
val value = comparator.compare(newEl, oldEl)
when {
value > 0 -> {
oldIndex++
if (oldIndex == oldSize) {
break@loop
}
}
value < 0 -> {
updatedPresentations.add(newEl)
newIndex++
if (newIndex == newSize) {
break@loop
}
}
else -> {
val oldRoot = oldEl.root
val newRoot = newEl.root
if (newRoot.key == oldRoot.key) {
oldRoot.updateIfSame(newRoot, editor, factory)
updatedPresentations.add(oldEl)
}
else {
updatedPresentations.add(newEl)
}
newIndex++
oldIndex++
if (newIndex == newSize || oldIndex == oldSize) {
break@loop
}
}
}
}
for (i in newIndex until newSize) {
updatedPresentations.add(new[i])
}
return updatedPresentations
}
/**
* @return true iff updated
*/
private fun <Content : Any>RootInlayPresentation<Content>.updateIfSame(
newPresentation: RootInlayPresentation<*>,
editor: Editor,
factory: InlayPresentationFactory
) : Boolean {
if (key != newPresentation.key) return false
@Suppress("UNCHECKED_CAST")
return update(newPresentation.content as Content, editor, factory)
}
} | apache-2.0 | 9f657f15374d811b8a11b21db3671b12 | 34.905738 | 158 | 0.727511 | 4.467109 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/util/BigDecimalFormatter.kt | 1 | 592 | package sk.styk.martin.apkanalyzer.util
import java.text.DecimalFormat
object BigDecimalFormatter {
private var commonFormat: DecimalFormat? = null
fun getCommonFormat(): DecimalFormat {
if (commonFormat == null) {
commonFormat = getFormat(2, 2)
}
return commonFormat!!
}
fun getFormat(minFractions: Int, maxFractions: Int): DecimalFormat {
val customFormat = DecimalFormat()
customFormat.maximumFractionDigits = maxFractions
customFormat.minimumFractionDigits = minFractions
return customFormat
}
} | gpl-3.0 | 7e608a41cc6258c693cc1cd54389801d | 25.954545 | 72 | 0.685811 | 4.892562 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WifiIPActionType.kt | 1 | 575 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class WifiIPActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = WifiIPAction()
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 0,
)
companion object {
private const val TYPE = "wifi_ip"
private const val FUNCTION_NAME = "getWifiIPAddress"
}
}
| mit | 9923a565c35464f8b568cf8ac0038c92 | 26.380952 | 64 | 0.713043 | 4.049296 | false | false | false | false |
drymarev/rxbsuir | bsuir-api/src/main/kotlin/by/toggi/rxbsuir/bsuir_api/TypeAdapters.kt | 1 | 2559 | package by.toggi.rxbsuir.bsuir_api
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalTime
import org.threeten.bp.format.DateTimeFormatter
object DayOfWeekAdapter {
private const val MONDAY = "Понедельник"
private const val TUESDAY = "Вторник"
private const val WEDNESDAY = "Среда"
private const val THURSDAY = "Четверг"
private const val FRIDAY = "Пятница"
private const val SATURDAY = "Суббота"
private const val SUNDAY = "Воскресенье"
@ToJson
fun toJson(dayOfWeek: DayOfWeek): String {
return when (dayOfWeek) {
DayOfWeek.MONDAY -> MONDAY
DayOfWeek.TUESDAY -> TUESDAY
DayOfWeek.WEDNESDAY -> WEDNESDAY
DayOfWeek.THURSDAY -> THURSDAY
DayOfWeek.FRIDAY -> FRIDAY
DayOfWeek.SATURDAY -> SATURDAY
DayOfWeek.SUNDAY -> SUNDAY
}
}
@FromJson
fun fromJson(json: String): DayOfWeek {
return when (json) {
MONDAY -> DayOfWeek.MONDAY
TUESDAY -> DayOfWeek.TUESDAY
WEDNESDAY -> DayOfWeek.WEDNESDAY
THURSDAY -> DayOfWeek.THURSDAY
FRIDAY -> DayOfWeek.FRIDAY
SATURDAY -> DayOfWeek.SATURDAY
SUNDAY -> DayOfWeek.SUNDAY
else -> throw IllegalArgumentException("$json is not day of week.")
}
}
}
object LessonTypeAdapter {
private const val EXAM = "Экзамен"
private const val LECTURE = "ЛК"
private const val WORKSHOP = "ПЗ"
private const val LAB = "ЛР"
@ToJson
fun toJson(type: LessonType): String {
return when (type) {
LessonType.EXAM -> EXAM
LessonType.LECTURE -> LECTURE
LessonType.WORKSHOP -> WORKSHOP
LessonType.LAB -> LAB
LessonType.UNKNOWN -> ""
}
}
@FromJson
fun fromJson(json: String): LessonType {
return when (json) {
EXAM -> LessonType.EXAM
LECTURE -> LessonType.LECTURE
WORKSHOP -> LessonType.WORKSHOP
LAB -> LessonType.LAB
else -> LessonType.UNKNOWN
}
}
}
object LocalTimeAdapter {
@ToJson
fun toJson(time: LocalTime): String {
return time.toString()
}
@FromJson
fun fromJson(json: String): LocalTime {
return LocalTime.parse(json)
}
}
object LocalDateAdapter {
private val FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy")
@ToJson
fun toJson(date: LocalDate): String {
return date.format(FORMATTER)
}
@FromJson
fun fromJson(json: String): LocalDate {
return LocalDate.parse(json, FORMATTER)
}
}
| gpl-2.0 | fd37d9a868a60aa4411d41f83a73b2e3 | 22.951923 | 73 | 0.682055 | 3.886115 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/util/FileUtils.kt | 2 | 2733 | /*
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.util
import android.content.Context
import android.util.Log
import java.io.File
private const val LOG_TAG = "FileUtils"
// Implementation should return true in case of success
typealias ActionOnFile = (file: File) -> Boolean
/* ==========================================================================================
* Delete
* ========================================================================================== */
fun deleteAllFiles(context: Context) {
Log.v(LOG_TAG, "Delete cache dir:")
recursiveActionOnFile(context.cacheDir, ::deleteAction)
Log.v(LOG_TAG, "Delete files dir:")
recursiveActionOnFile(context.filesDir, ::deleteAction)
}
private fun deleteAction(file: File): Boolean {
if (file.exists()) {
Log.v(LOG_TAG, "deleteFile: $file")
return file.delete()
}
return true
}
/* ==========================================================================================
* Log
* ========================================================================================== */
fun lsFiles(context: Context) {
Log.v(LOG_TAG, "Content of cache dir:")
recursiveActionOnFile(context.cacheDir, ::logAction)
Log.v(LOG_TAG, "Content of files dir:")
recursiveActionOnFile(context.filesDir, ::logAction)
}
private fun logAction(file: File): Boolean {
if (file.isDirectory) {
Log.d(LOG_TAG, file.toString())
} else {
Log.d(LOG_TAG, file.toString() + " " + file.length() + " bytes")
}
return true
}
/* ==========================================================================================
* Private
* ========================================================================================== */
/**
* Return true in case of success
*/
private fun recursiveActionOnFile(file: File, action: ActionOnFile): Boolean {
if (file.isDirectory) {
file.list().forEach {
val result = recursiveActionOnFile(File(file, it), action)
if (!result) {
// Break the loop
return false
}
}
}
return action.invoke(file)
}
| apache-2.0 | 0c4329fe5fdd2a05fa7550acc73cc72f | 29.032967 | 96 | 0.52543 | 4.640068 | false | false | false | false |
markmckenna/grocery | app/src/main/kotlin/kotterknife/ButterKnife.kt | 1 | 4761 | @file:Suppress("unused")
package kotterknife
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import android.support.v4.app.Fragment as SupportFragment
// Extend this class with a general purpose 'wrapper' type that can receive Kotterknife injections
abstract class ViewWrapper(val view: View) {
fun <V: View> bindView(id: Int)
: ReadOnlyProperty<ViewWrapper, V> = required(id, viewFinder)
private val viewFinder: ViewWrapper.(Int) -> View? get() = { view.findViewById(it) }
}
fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, viewFinder)
fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder)
fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder)
fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder)
fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val Fragment.viewFinder: Fragment.(Int) -> View?
get() = { view.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<in T, out V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
| mit | 64679e3140451b64a4d1a58e43ec725a | 43.083333 | 107 | 0.698593 | 3.609553 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/create/CreateImage.kt | 2 | 1261 | package com.github.kerubistan.kerub.planner.steps.storage.fs.create
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
@JsonTypeName("create-image")
data class CreateImage(
override val disk: VirtualStorageDevice,
override val capability: FsStorageCapability,
override val host: Host,
override val format: VirtualDiskFormat
) : AbstractCreateImage() {
init {
require(host.capabilities?.storageCapabilities?.contains(capability) ?: false) {
"host (${host.id}) capabilities (${host.capabilities?.storageCapabilities}) must include ${capability.id}"
}
}
@get:JsonIgnore
override val allocation: VirtualStorageFsAllocation by lazy {
VirtualStorageFsAllocation(
hostId = host.id,
actualSize = disk.size, //TODO not true when thin provisioning
mountPoint = path,
type = format,
fileName = "$path/${disk.id}.${format}",
capabilityId = capability.id
)
}
} | apache-2.0 | 3d1540561973e6df2ad52cbab8821de7 | 32.210526 | 109 | 0.780333 | 4.148026 | false | false | false | false |
AlexandrDrinov/kotlin-koans-edu | src/syntax/classesObjectsInterfaces.kt | 48 | 1741 | package syntax.classesObjectsInterfaces
// Interfaces in Kotlin are like Java8 interfaces, stateless but with implementations
interface SimpleInterface {
fun foo(): Int
fun bar() = "default implementation ${foo()}"
}
// All classes and members by default are final
open class SimpleClass {
open fun bar() = "other implementation"
}
// ':' means both 'overrides' and 'implements'
class Successor : SimpleInterface, SimpleClass() {
override fun foo() = 1
// If you inherit two implementations of the same function, you must override that function
override fun bar(): String = super<SimpleInterface>.bar() + super<SimpleClass>.bar()
}
// The use of 'object' instead of 'class' indicates a singleton declaration
object Singleton {
fun foo() = 42
}
fun useObject() {
Singleton.foo()
}
class Outer(private val bar : Int) {
// Classes can be nested within other classes
class Nested() {
fun foo() = 2
}
// Inner classes may reference properties of their outer class instance
inner class Inner() {
fun foo() = bar
}
}
fun demo() {
Outer(1).Inner().foo() // == 1
Outer.Nested().foo() // == 2
}
class ClassWithPrivateConstructor private constructor(val bar: Int) {
// Classes do not have static methods.
// In most cases, namespace-level functions form a good substitute for them,
// except cases where access to class' private members is required.
companion object {
fun newInstance() = ClassWithPrivateConstructor(9)
}
}
fun useClassObject() {
ClassWithPrivateConstructor.newInstance()
}
fun localClass() {
// A class or object can be declared locally in a function
data class Local(val i: Int, val s: String) {}
}
| mit | 8b0e9b836d67dc5187975db91561d2c6 | 25.378788 | 95 | 0.681218 | 4.267157 | false | false | false | false |
sriharshaarangi/BatteryChargeLimit | app/src/main/java/com/slash/batterychargelimit/receivers/EnableWidgetIntentReceiver.kt | 1 | 1963 | package com.slash.batterychargelimit.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import android.widget.Toast
import com.slash.batterychargelimit.Constants.CHARGE_LIMIT_ENABLED
import com.slash.batterychargelimit.Constants.INTENT_TOGGLE_ACTION
import com.slash.batterychargelimit.EnableWidget
import com.slash.batterychargelimit.R
import com.slash.batterychargelimit.Utils
import eu.chainfire.libsuperuser.Shell
class EnableWidgetIntentReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == INTENT_TOGGLE_ACTION) {
val settings = Utils.getSettings(context)
if (Shell.SU.available()) {
val enable = !settings.getBoolean(CHARGE_LIMIT_ENABLED, false)
settings.edit().putBoolean(CHARGE_LIMIT_ENABLED, enable).apply()
if (enable) {
Utils.startServiceIfLimitEnabled(context)
} else {
Utils.stopService(context)
}
updateWidget(context, enable)
} else {
Toast.makeText(context, R.string.root_denied, Toast.LENGTH_LONG).show()
}
}
}
companion object {
fun updateWidget(context: Context, enable: Boolean) {
val remoteViews = RemoteViews(context.packageName, R.layout.widget_button)
remoteViews.setImageViewResource(R.id.enable, getImage(enable))
remoteViews.setOnClickPendingIntent(R.id.enable, EnableWidget.buildButtonPendingIntent(context))
EnableWidget.pushWidgetUpdate(context, remoteViews)
}
fun getImage(enabled: Boolean): Int {
return if (enabled) {
R.drawable.widget_enabled
} else {
R.drawable.widget_disabled
}
}
}
}
| gpl-3.0 | ac23499cc1eabe237e180b91e6b47e6e | 36.037736 | 108 | 0.65512 | 4.764563 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AccessibilityCodelab/app/src/main/java/com/example/jetnews/ui/home/HomeScreen.kt | 1 | 7527 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui.home
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.Text
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.posts.PostsRepository
import com.example.jetnews.model.Post
import com.example.jetnews.ui.components.InsetAwareTopAppBar
import com.example.jetnews.ui.theme.JetnewsTheme
import kotlinx.coroutines.launch
/**
* Stateful HomeScreen which manages state using [produceUiState]
*
* @param postsRepository data source for this screen
* @param navigateToArticle (event) request navigation to Article screen
* @param openDrawer (event) request opening the app drawer
* @param scaffoldState (state) state for the [Scaffold] component on this screen
*/
@Composable
fun HomeScreen(
postsRepository: PostsRepository,
navigateToArticle: (String) -> Unit,
openDrawer: () -> Unit,
scaffoldState: ScaffoldState = rememberScaffoldState()
) {
HomeScreen(
posts = postsRepository.getPosts(),
navigateToArticle = navigateToArticle,
openDrawer = openDrawer,
scaffoldState = scaffoldState
)
}
/**
* Responsible for displaying the Home Screen of this application.
*
* Stateless composable is not coupled to any specific state management.
*
* @param posts (state) the data to show on the screen
* @param favorites (state) favorite posts
* @param onToggleFavorite (event) toggles favorite for a post
* @param navigateToArticle (event) request navigation to Article screen
* @param openDrawer (event) request opening the app drawer
* @param scaffoldState (state) state for the [Scaffold] component on this screen
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HomeScreen(
posts: List<Post>,
navigateToArticle: (String) -> Unit,
openDrawer: () -> Unit,
scaffoldState: ScaffoldState
) {
val coroutineScope = rememberCoroutineScope()
Scaffold(
scaffoldState = scaffoldState,
topBar = {
val title = stringResource(id = R.string.app_name)
InsetAwareTopAppBar(
title = { Text(text = title) },
navigationIcon = {
IconButton(onClick = { coroutineScope.launch { openDrawer() } }) {
Icon(
painter = painterResource(R.drawable.ic_jetnews_logo),
contentDescription = stringResource(R.string.cd_open_navigation_drawer)
)
}
}
)
}
) { innerPadding ->
val modifier = Modifier.padding(innerPadding)
PostList(posts, navigateToArticle, modifier)
}
}
/**
* Display a list of posts.
*
* When a post is clicked on, [navigateToArticle] will be called to navigate to the detail screen
* for that post.
*
* @param posts (state) the list to display
* @param navigateToArticle (event) request navigation to Article screen
* @param modifier modifier for the root element
*/
@Composable
private fun PostList(
posts: List<Post>,
navigateToArticle: (postId: String) -> Unit,
modifier: Modifier = Modifier
) {
val postsHistory = posts.subList(0, 3)
val postsPopular = posts.subList(3, 5)
val contentPadding = rememberContentPaddingForScreen(additionalTop = 8.dp)
LazyColumn(
modifier = modifier,
contentPadding = contentPadding
) {
items(postsHistory) { post ->
PostCardHistory(post, navigateToArticle)
PostListDivider()
}
item {
PostListPopularSection(postsPopular, navigateToArticle)
}
}
}
/**
* Horizontal scrolling cards for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListPopularSection(
posts: List<Post>,
navigateToArticle: (String) -> Unit
) {
Column {
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(id = R.string.home_popular_section_title),
style = MaterialTheme.typography.subtitle1
)
LazyRow(contentPadding = PaddingValues(end = 16.dp)) {
items(posts) { post ->
PostCardPopular(
post,
navigateToArticle,
Modifier.padding(start = 16.dp, bottom = 16.dp)
)
}
}
PostListDivider()
}
}
/**
* Full-width divider with padding for [PostList]
*/
@Composable
private fun PostListDivider() {
Divider(
modifier = Modifier.padding(horizontal = 14.dp),
color = MaterialTheme.colors.onSurface.copy(alpha = 0.08f)
)
}
/**
* Determine the content padding to apply to the different screens of the app
*/
@Composable
fun rememberContentPaddingForScreen(additionalTop: Dp = 0.dp) =
WindowInsets.systemBars
.only(WindowInsetsSides.Bottom)
.add(WindowInsets(top = additionalTop))
.asPaddingValues()
@Preview("Home screen")
@Preview("Home screen (dark)", uiMode = UI_MODE_NIGHT_YES)
@Preview("Home screen (big font)", fontScale = 1.5f)
@Preview("Home screen (large screen)", device = Devices.PIXEL_C)
@Composable
fun PreviewHomeScreen() {
JetnewsTheme {
HomeScreen(
posts = PostsRepository().getPosts(),
navigateToArticle = { /*TODO*/ },
openDrawer = { /*TODO*/ },
scaffoldState = rememberScaffoldState()
)
}
}
| apache-2.0 | 9a1f0ac9927e02d32efaeae45b991fce | 32.905405 | 99 | 0.699615 | 4.600856 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/command/monsterspawnarea/MonsterSpawnAreaCommand.kt | 1 | 2248 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.monsters.bukkit.command.monsterspawnarea
import com.rpkit.monsters.bukkit.RPKMonstersBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class MonsterSpawnAreaCommand(private val plugin: RPKMonstersBukkit) : CommandExecutor {
private val monsterSpawnAreaCreateCommand = MonsterSpawnAreaCreateCommand(plugin)
private val monsterSpawnAreaDeleteCommand = MonsterSpawnAreaDeleteCommand(plugin)
private val monsterSpawnAreaAddMonsterCommand = MonsterSpawnAreaAddMonsterCommand(plugin)
private val monsterSpawnAreaRemoveMonsterCommand = MonsterSpawnAreaRemoveMonsterCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["monster-spawn-area-usage"])
return true
}
val newArgs = args.drop(1).toTypedArray()
return when (args[0]) {
"create" -> monsterSpawnAreaCreateCommand.onCommand(sender, command, label, newArgs)
"delete" -> monsterSpawnAreaDeleteCommand.onCommand(sender, command, label, newArgs)
"addmonster", "addm", "add", "monster" -> monsterSpawnAreaAddMonsterCommand.onCommand(sender, command, label, newArgs)
"removemonster", "removem", "remove", "rem", "remm" -> monsterSpawnAreaRemoveMonsterCommand.onCommand(sender, command, label, newArgs)
else -> {
sender.sendMessage(plugin.messages["monster-spawn-area-usage"])
true
}
}
}
} | apache-2.0 | 70f567d6d478fc8f783a33d4b87ca22e | 44.897959 | 146 | 0.725979 | 4.425197 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/common/NestingBoolean.kt | 2 | 2213 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.common
import javafx.beans.property.BooleanProperty
import javafx.beans.property.ReadOnlyBooleanProperty
import javafx.beans.property.SimpleBooleanProperty
import java.util.concurrent.atomic.AtomicInteger
/**
* Utility class that serves as a wrapper around a single boolean flag that can
* be enabled/disabled. It counts the number of times {@link #disable()} is
* called, and only really re-enables the inner value when {@link #enable()} is
* called that many times.
*
* It is meant to be useful in multi-thread scenarios, where concurrent
* "critical sections" may want to disable something like a listener, and not
* have it really be re-enabled until all critical sections are finished. Thus
* it is thread-safe.
*
* The inner value is exposed through the {@link #enabledProperty()} method, which
* returns a {@link ReadOnlyBooleanProperty}. You can attach
* {@link ChangeListener}s to that property to get notified of inner value
* changes.
*
* It is "enabled" at creation time.
*/
class NestingBoolean {
private val disabledCount = AtomicInteger(0)
private val boolean: BooleanProperty = SimpleBooleanProperty(true)
fun enabledProperty(): ReadOnlyBooleanProperty = boolean
/**
* Decrease the "disabled" count by 1. If it reaches (or already was at) 0
* then the value is truly enabled.
*/
@Synchronized
fun enable() {
/* Decrement the count but only if it is currently above 0 */
val ret = disabledCount.updateAndGet { if (it > 0) it - 1 else 0 }
if (ret == 0) {
boolean.set(true)
}
}
/**
* Increase the "disabled" count by 1. The inner value will necessarily be
* disabled after this call.
*/
@Synchronized
fun disable() {
disabledCount.incrementAndGet()
boolean.set(false)
}
}
| epl-1.0 | 4d2b5798980f6cee12377ff6ee1d4e0f | 33.578125 | 89 | 0.705829 | 4.322266 | false | false | false | false |
thaleslima/GuideApp | app/src/main/java/com/guideapp/ui/views/menu/MenuFragment.kt | 1 | 1540 | package com.guideapp.ui.views.menu
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.guideapp.R
import com.guideapp.model.MainMenu
import com.guideapp.ui.views.GridSpacingItemDecoration
import com.guideapp.ui.views.local.LocalActivity
import com.guideapp.ui.views.map.MapActivity
import com.guideapp.utilities.Constants
import com.guideapp.utilities.Utility
import kotlinx.android.synthetic.main.fragment_menu.*
class MenuFragment : Fragment(), MenuAdapter.RecyclerViewItemClickListener {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_menu, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setupRecyclerView()
}
private fun setupRecyclerView() {
recycler.layoutManager = GridLayoutManager(this.activity, 2)
val adapter = MenuAdapter(Utility.menus, this)
recycler.adapter = adapter
recycler.addItemDecoration(GridSpacingItemDecoration(2, 16, true))
}
override fun onItemClick(item: MainMenu) {
if (item.id == 1L) {
MapActivity.navigate(this.activity, Constants.City.ID)
return
}
LocalActivity.navigate(this.activity, item.id, item.idTitle)
}
}
| apache-2.0 | 17a498f15e66d53324c383b9fb09aaf1 | 34 | 117 | 0.75 | 4.350282 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/OjjoCommand.kt | 1 | 1930 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.api.commands.Command
import java.awt.geom.AffineTransform
import java.awt.image.AffineTransformOp
import java.awt.image.BufferedImage
import net.perfectdreams.loritta.morenitta.LorittaBot
class OjjoCommand(loritta: LorittaBot) : AbstractCommand(loritta, "ojjo", category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.ojjo.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
// TODO: Fix Detailed Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val image = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
// We need to create a empty "base" to avoid issues with transparent images
val baseImage = BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_ARGB)
val rightSide = image.getSubimage(image.width / 2, 0, image.width / 2, image.height)
// Girar a imagem horizontalmente
val tx = AffineTransform.getScaleInstance(-1.0, 1.0)
tx.translate(-rightSide.getWidth(null).toDouble(), 0.0)
val op = AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR)
val rightSideFlipped = op.filter(rightSide, null)
baseImage.graphics.drawImage(rightSideFlipped, 0, 0, null)
baseImage.graphics.drawImage(rightSide, baseImage.width / 2, 0, null)
context.sendFile(baseImage, "ojjo.png", context.getAsMention(true))
}
} | agpl-3.0 | f99d8b7fe8fd855b3617fa51846354be | 43.906977 | 152 | 0.8 | 3.86 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/HighlyCoupledFiles.kt | 1 | 2708 | package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import de.maibornwolff.codecharta.importer.gitlogparser.input.Commit
import de.maibornwolff.codecharta.importer.gitlogparser.input.Modification
import de.maibornwolff.codecharta.model.AttributeType
import de.maibornwolff.codecharta.model.Edge
class HighlyCoupledFiles : Metric {
private var fileName: String = ""
private var numberOfCommits: Long = 0
private var commits = mutableListOf<Commit>()
private val simultaneouslyCommittedFiles = mutableMapOf<String, Int>()
override fun description(): String {
return "Highly Coupled Files: Number of highly coupled files (35% times modified the same time) with this file."
}
override fun metricName(): String {
return "highly_coupled_files"
}
override fun edgeMetricName(): String {
return "temporal_coupling"
}
override fun value(): Number {
evaluateIfNecessary()
return simultaneouslyCommittedFiles.values
.count { isHighlyCoupled(it) }
.toLong()
}
override fun getEdges(): List<Edge> {
evaluateIfNecessary()
return simultaneouslyCommittedFiles
.mapNotNull { (coupledFile, value) ->
if (isHighlyCoupled(value)) {
Edge(
fileName,
coupledFile,
mapOf(edgeMetricName() to value.toDouble() / numberOfCommits.toDouble())
)
} else
null
}
}
private fun evaluateIfNecessary() {
if (simultaneouslyCommittedFiles.isNotEmpty()) return
commits.forEach { commit ->
commit.modifications
.forEach {
if (it.currentFilename != fileName) {
simultaneouslyCommittedFiles.merge(it.currentFilename, 1) { x, y -> x + y }
}
}
}
}
private fun isHighlyCoupled(value: Int): Boolean {
return if (value >= MIN_NO_COMMITS_FOR_HIGH_COUPLING) {
value.toDouble() / numberOfCommits.toDouble() > HIGH_COUPLING_VALUE
} else false
}
override fun registerCommit(commit: Commit) {
numberOfCommits++
commits.add(commit)
}
override fun registerModification(modification: Modification) {
fileName = modification.currentFilename
}
override fun edgeAttributeType(): AttributeType? {
return AttributeType.absolute
}
companion object {
private const val HIGH_COUPLING_VALUE = .35
private const val MIN_NO_COMMITS_FOR_HIGH_COUPLING = 5L
}
}
| bsd-3-clause | 5f52c7c54a4f61e1bc38b40ea065b32b | 30.126437 | 120 | 0.614845 | 4.896926 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/prefs/PreferencesFragment.kt | 1 | 5905 | package com.androidvip.hebf.ui.prefs
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.androidvip.hebf.R
import com.androidvip.hebf.lower
import com.androidvip.hebf.runSafeOnUiThread
import com.androidvip.hebf.utils.*
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class PreferencesFragment : PreferenceFragmentCompat(), CoroutineScope, SharedPreferences.OnSharedPreferenceChangeListener {
override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob()
private val workerContext: CoroutineContext = Dispatchers.Default + SupervisorJob()
private val userPrefs: SharedPreferences by lazy { UserPrefs(requireContext()).preferences }
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
userPrefs.registerOnSharedPreferenceChangeListener(this)
if (userPrefs.getInt(K.PREF.USER_TYPE, K.USER_TYPE_NORMAL) < K.USER_TYPE_EXPERT) {
findPreference<Preference>(K.PREF.EXTENDED_LOGGING_ENABLED)?.isVisible = false
}
val busyboxPathPreference = findPreference<Preference>("busybox_path")
val suPathPreference =findPreference<Preference>("su_path")
lifecycleScope.launch(workerContext) {
val busyboxPath = RootUtils.executeWithOutput(
"which busybox", "", requireContext()
).lower()
val suPath = RootUtils.executeWithOutput(
"which su",
"",
activity
).lower()
activity?.runSafeOnUiThread {
busyboxPathPreference?.summary = if (busyboxPath.contains("not found") || busyboxPath.isEmpty()) {
getString(android.R.string.unknownName)
} else {
busyboxPath
}
suPathPreference?.summary = if (suPath.lower().contains("not found")) {
getString(android.R.string.unknownName)
} else {
suPath
}
}
}
findPreference<Preference>("bug_report")?.setOnPreferenceClickListener {
findNavController().navigate(R.id.startNavigationBugReport)
true
}
findPreference<Preference>("notification_settings")?.apply {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
isVisible = false
isEnabled = false
} else {
setOnPreferenceClickListener {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra(Settings.EXTRA_APP_PACKAGE, requireContext().packageName)
startActivity(this)
}
true
}
}
}
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onDestroy() {
super.onDestroy()
coroutineContext[Job]?.cancelChildren()
workerContext[Job]?.cancelChildren()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
try {
if (key == K.PREF.USER_TYPE) {
val e = userPrefs.edit()
when (sharedPreferences.getString(key, "normal")) {
"normal" -> {
e.putInt(K.PREF.USER_TYPE, K.USER_TYPE_NORMAL)
findPreference<Preference>(K.PREF.EXTENDED_LOGGING_ENABLED)?.isVisible = false
}
"expert" -> {
e.putInt(K.PREF.USER_TYPE, K.USER_TYPE_EXPERT)
findPreference<Preference>(K.PREF.EXTENDED_LOGGING_ENABLED)?.isVisible = false
}
"chuck" -> {
e.putInt(K.PREF.USER_TYPE, K.USER_TYPE_CHUCK_NORRIS)
findPreference<Preference>(K.PREF.EXTENDED_LOGGING_ENABLED)?.isVisible = true
}
else -> {
e.putInt(K.PREF.USER_TYPE, K.USER_TYPE_NORMAL)
findPreference<Preference>(K.PREF.EXTENDED_LOGGING_ENABLED)?.isVisible = false
}
}
e.apply()
}
if (key == K.PREF.ENGLISH_LANGUAGE) {
val e = userPrefs.edit()
if (!sharedPreferences.getBoolean(key, false)) {
Toast.makeText(context, R.string.info_restart_app, Toast.LENGTH_LONG).show()
e.putBoolean(K.PREF.ENGLISH_LANGUAGE, false).apply()
} else {
e.putBoolean(K.PREF.ENGLISH_LANGUAGE, true).apply()
activity?.let {
Utils.toEnglish(it)
startActivity(Intent(it, it::class.java))
it.finish()
}
}
}
if (key == K.PREF.EXTENDED_LOGGING_ENABLED) {
userPrefs.edit().putBoolean(key, sharedPreferences.getBoolean(key, false)).apply()
}
} catch (e: Exception) {
Logger.logError(e, context)
}
}
}
| apache-2.0 | 1bb1bd01141ea5daac7d39f313d93552 | 38.366667 | 124 | 0.57917 | 5.258237 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/lang/System.kt | 1 | 2688 | /*
* Copyright 2022 Google 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 java.lang
import java.io.PrintStream
import kotlin.native.identityHashCode
import kotlin.system.getTimeMillis
import kotlin.system.getTimeNanos
// TODO(b/224765929): Avoid this hack for InternalPreconditions.java and logging.
object System {
fun getProperty(name: String?, def: String?): String? = getProperty(name) ?: def
fun getProperty(name: String?): String? =
when (name) {
"jre.checks.api",
"jre.checks.bounds",
"jre.checks.numeric",
"jre.checks.type" -> "AUTO"
"jre.checks.checkLevel" -> "NORMAL"
"jre.logging.logLevel" -> "INFO"
"jre.logging.simpleConsoleHandler" -> "ENABLED"
else -> null
}
fun arraycopy(src: Any?, srcOfs: Int, dest: Any?, destOfs: Int, len: Int) {
when (src) {
is ByteArray -> src.copyInto(dest as ByteArray, destOfs, srcOfs, srcOfs + len)
is ShortArray -> src.copyInto(dest as ShortArray, destOfs, srcOfs, srcOfs + len)
is IntArray -> src.copyInto(dest as IntArray, destOfs, srcOfs, srcOfs + len)
is LongArray -> src.copyInto(dest as LongArray, destOfs, srcOfs, srcOfs + len)
is FloatArray -> src.copyInto(dest as FloatArray, destOfs, srcOfs, srcOfs + len)
is DoubleArray -> src.copyInto(dest as DoubleArray, destOfs, srcOfs, srcOfs + len)
is BooleanArray -> src.copyInto(dest as BooleanArray, destOfs, srcOfs, srcOfs + len)
is CharArray -> src.copyInto(dest as CharArray, destOfs, srcOfs, srcOfs + len)
is Array<*> -> src.copyInto(dest as Array<Any?>, destOfs, srcOfs, srcOfs + len)
else -> throw ArrayStoreException()
}
}
fun currentTimeMillis(): Long = getTimeMillis()
fun nanoTime(): Long = getTimeNanos()
fun gc(): Unit = Unit
fun identityHashCode(o: Any?): Int = o.identityHashCode()
// TODO(b/257217399): Point to stderr
var err: PrintStream = PrintStream(null)
// TODO(b/257217399): Point to stdout
var out: PrintStream = PrintStream(null)
fun setErr(err: PrintStream) {
this.err = err
}
fun setOut(out: PrintStream) {
this.out = out
}
fun lineSeparator(): String = "\n"
}
| apache-2.0 | 80ce187a02926ed639b421741670cc7a | 33.909091 | 90 | 0.686384 | 3.617766 | false | false | false | false |
sek/ScoreDisplay | app/src/main/java/com/stankurdziel/scoredisplay/SettingsActivity.kt | 1 | 7014 | package com.stankurdziel.scoredisplay
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.google.firebase.database.*
import com.google.firebase.iid.FirebaseInstanceId
import com.google.zxing.BarcodeFormat
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import kotlinx.android.synthetic.main.settings_layout.*
data class Display(val key: String, val id: String) {
fun serialized(): String = "$key:$id"
fun default(): Boolean = id == DEFAULT_ID
companion object {
const val DEFAULT_ID = "0"
}
}
class Prefs(context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(context.packageName, 0);
fun display(key: String): Display {
val s = prefs.getString(key, "$key:${Display.DEFAULT_ID}").split(":")
return Display(s[0], s[1])
}
fun saveDisplay(display: Display) = prefs.edit().putString(display.key, display.serialized()).apply()
}
class SettingsActivity : AppCompatActivity() {
private lateinit var prefs: Prefs
private lateinit var left: Display
private lateinit var right: Display
private var leftScore: Int = 0
private var rightScore: Int = 0
private val database = FirebaseDatabase.getInstance()
private lateinit var leftRef: DatabaseReference
private lateinit var rightRef: DatabaseReference
// TODO reduce left/right duplication
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_layout)
prefs = Prefs(this)
left = prefs.display("left")
right = prefs.display("right")
show_id.setOnClickListener { showQrCodeDialog() }
reset_scores.setOnClickListener {
setLeftScore(0)
setRightScore(0)
}
subscribeLeft()
subscribeRight()
updateUi()
}
private fun subscribeLeft() {
left_title.setOnClickListener {
startActivityForResult(Intent(this, QrCodeScannerActivity::class.java), CAMERA_LEFT_REQUEST_CODE)
}
leftRef = database.getReference("scores/${left.id}")
left_up.setOnClickListener { setLeftScore(leftScore + 1) }
left_down.setOnClickListener { setLeftScore(leftScore - 1) }
leftRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val value = dataSnapshot.value ?: return
leftScore = value.toString().toInt()
left_score.text = leftScore.toString()
}
override fun onCancelled(p0: DatabaseError?) {}
})
}
private fun setLeftScore(newScore: Int) {
if (!left.default() && newScore in 0..99) leftRef.setValue(newScore)
}
private fun setRightScore(newScore: Int) {
if (!right.default() && newScore in 0..99) rightRef.setValue(newScore)
}
private fun subscribeRight() {
right_title.setOnClickListener {
startActivityForResult(Intent(this, QrCodeScannerActivity::class.java), CAMERA_RIGHT_REQUEST_CODE)
}
rightRef = database.getReference("scores/${right.id}")
right_up.setOnClickListener { setRightScore(rightScore + 1) }
right_down.setOnClickListener { setRightScore(rightScore - 1) }
rightRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val value = dataSnapshot.value ?: return
rightScore = value.toString().toInt()
right_score.text = rightScore.toString()
}
override fun onCancelled(p0: DatabaseError?) {}
})
}
private fun showQrCodeDialog() {
val factory = LayoutInflater.from(this)
val qrDialogView = factory.inflate(R.layout.qrcode_dialog, null)
val qrCodeDialog = AlertDialog.Builder(this)
.setTitle(R.string.qr_dialog_title)
.setView(qrDialogView)
.create()
val writer = QRCodeWriter()
try {
val firebaseId = FirebaseInstanceId.getInstance().id
val bitMatrix = writer.encode(firebaseId, BarcodeFormat.QR_CODE, 500, 500)
val width = bitMatrix.width
val height = bitMatrix.height
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
for (x in 0 until width) {
for (y in 0 until height) {
bmp.setPixel(x, y, if (bitMatrix.get(x, y)) Color.BLACK else Color.WHITE)
}
}
qrDialogView.findViewById<ImageView>(R.id.qrcode).setImageBitmap(bmp)
qrDialogView.findViewById<TextView>(R.id.qrcode_text).text = firebaseId
} catch (e: WriterException) {
e.printStackTrace()
}
qrDialogView.findViewById<View>(R.id.close).setOnClickListener { qrCodeDialog.dismiss() }
qrCodeDialog.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val result = QrCodeScannerActivity.extractId(data)
if (result != null) {
assignScoreBoard(requestCode, result)
updateUi()
}
}
private fun assignScoreBoard(requestCode: Int, result: String) {
when (requestCode) {
CAMERA_LEFT_REQUEST_CODE -> {
left = Display("left", result)
prefs.saveDisplay(left)
subscribeLeft()
}
CAMERA_RIGHT_REQUEST_CODE -> {
right = Display("right", result)
prefs.saveDisplay(right)
subscribeRight()
}
}
}
private fun updateUi() {
fun goneOrVisible(view: Display) = if (view.default()) View.GONE else View.VISIBLE
left_tablet_icon.visibility = goneOrVisible(left)
right_tablet_icon.visibility = goneOrVisible(right)
}
private var confirmShown: Boolean = false
override fun onBackPressed() {
if (!confirmShown && (!left.default() || !right.default())) {
Toast.makeText(this, "press back again to exit", Toast.LENGTH_SHORT).show()
confirmShown = true
Handler().postDelayed({ confirmShown = false }, 5000)
return
}
super.onBackPressed()
}
companion object {
const val CAMERA_LEFT_REQUEST_CODE = 1
const val CAMERA_RIGHT_REQUEST_CODE = 2
}
} | apache-2.0 | 4562e5712d1f9121799c9c9e9ecdab24 | 34.609137 | 110 | 0.641146 | 4.581319 | false | false | false | false |
jlutteringer/Alloy | alloy/utilities/src/main/java/alloy/utilities/web/WebRequests.kt | 1 | 1807 | package alloy.utilities.web
import alloy.utilities.core.TypeConverters
import alloy.utilities.core._Optionals
import org.springframework.web.context.request.ServletWebRequest
import java.util.*
import javax.servlet.http.HttpServletRequest
/**
* Created by jlutteringer on 1/16/18.
*/
interface WebRequestAttribute<T> {
fun read(request: HttpServletRequest): Optional<T> {
return this.read(ServletWebRequest(request))
}
fun read(request: ServletWebRequest): Optional<T>
}
interface MutableWebRequestAttribute<T>: WebRequestAttribute<T> {
fun setValue(request: HttpServletRequest, value: T?) {
this.setValue(ServletWebRequest(request), value)
}
fun setValue(request: ServletWebRequest, value: T?)
}
object WebRequests {
fun <T> chain(vararg attributes: WebRequestAttribute<T>): WebRequestAttribute<T> = chain(attributes.asList())
fun <T> chain(attributes: List<WebRequestAttribute<T>>): WebRequestAttribute<T> =
object: WebRequestAttribute<T> {
override fun read(request: ServletWebRequest): Optional<T> = _Optionals.firstSome(attributes.map { attribute -> attribute.read(request) })
}
fun <T> headerAccessor(name: String, type: Class<T>): WebRequestAttribute<T> =
object: WebRequestAttribute<T> {
override fun read(request: ServletWebRequest): Optional<T> =
Optional.ofNullable(request.getHeader(name)).flatMap { a -> TypeConverters.convertOptional(a, type) }
}
fun <T> cookieAccessor(name: String, type: Class<T>): WebRequestAttribute<T> =
object: WebRequestAttribute<T> {
override fun read(request: ServletWebRequest): Optional<T> =
Cookies.read(name, type, request)
}
} | mit | 2e67c66048524376b8feeaad89037fc0 | 36.666667 | 154 | 0.682346 | 4.154023 | false | false | false | false |
SimonMarquis/FCM-toolbox | app/src/main/java/fr/smarquis/fcm/data/model/Payload.kt | 1 | 8636 | package fr.smarquis.fcm.data.model
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.Intent.*
import android.content.pm.PackageManager
import android.net.Uri
import android.text.TextUtils
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.annotation.Keep
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.Builder
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import com.google.firebase.messaging.RemoteMessage
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.Moshi
import fr.smarquis.fcm.R
import fr.smarquis.fcm.view.ui.CopyToClipboardActivity
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.io.IOException
@Keep
sealed class Payload {
@IdRes
abstract fun notificationId(): Int
@DrawableRes
abstract fun icon(): Int
abstract fun display(): CharSequence?
abstract fun configure(builder: Builder): Builder
@JsonClass(generateAdapter = true)
data class App(
@Json(name = "title")
internal val title: String? = null,
@Json(name = "package")
internal val packageName: String? = null
) : Payload() {
override fun notificationId(): Int = R.id.notification_id_app
override fun icon(): Int = R.drawable.ic_shop_24dp
@delegate:Transient
private val display: CharSequence by lazy {
buildSpannedString {
bold { append("title: ") }
append("$title\n")
bold { append("package: ") }
append(packageName)
}
}
override fun display(): CharSequence? = display
@SuppressLint("RestrictedApi")
override fun configure(builder: Builder): Builder = builder.apply {
builder.setContentTitle(if (TextUtils.isEmpty(title)) mContext.getString(R.string.payload_app) else title)
.setContentText(packageName)
.addAction(0, mContext.getString(R.string.payload_app_store), PendingIntent.getActivity(mContext, 0, playStore(), 0))
if (isInstalled(mContext)) {
builder.addAction(0, mContext.getString(R.string.payload_app_uninstall), PendingIntent.getActivity(mContext, 0, uninstall(), 0))
}
}
fun playStore(): Intent = Intent(ACTION_VIEW, Uri.parse("market://details?id=$packageName")).apply {
addFlags(FLAG_ACTIVITY_NEW_TASK)
}
fun uninstall(): Intent = Intent(ACTION_DELETE, Uri.parse("package:$packageName")).apply {
addFlags(FLAG_ACTIVITY_NEW_TASK)
}
fun isInstalled(context: Context): Boolean = try {
context.packageManager.getPackageInfo(packageName.orEmpty(), 0) != null
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
@JsonClass(generateAdapter = true)
data class Link(
@Json(name = "title")
internal val title: String? = null,
@Json(name = "url")
internal val url: String? = null,
@Json(name = "open")
@Deprecated(message = "Since Android 10, starting an Activity from background has been disabled https://developer.android.com/guide/components/activities/background-starts")
internal val open: Boolean = false
) : Payload() {
override fun notificationId(): Int = R.id.notification_id_link
override fun icon(): Int = R.drawable.ic_link_24dp
@delegate:Transient
private val display: CharSequence by lazy {
buildSpannedString {
bold { append("title: ") }
append("$title\n")
bold { append("url: ") }
append("$url")
}
}
override fun display(): CharSequence? = display
@SuppressLint("RestrictedApi")
override fun configure(builder: Builder): Builder = builder.apply {
setContentTitle(if (TextUtils.isEmpty(title)) mContext.getString(R.string.payload_link) else title).setContentText(url)
if (!TextUtils.isEmpty(url)) {
addAction(0, mContext.getString(R.string.payload_link_open), PendingIntent.getActivity(mContext, 0, intent(), 0))
}
}
fun intent(): Intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
addFlags(FLAG_ACTIVITY_NEW_TASK)
}
}
@Suppress("CanSealedSubClassBeObject")
@JsonClass(generateAdapter = true)
class Ping : Payload() {
override fun notificationId(): Int = R.id.notification_id_ping
override fun icon(): Int = R.drawable.ic_notifications_none_24dp
override fun display(): CharSequence? = null
@SuppressLint("RestrictedApi")
override fun configure(builder: Builder): Builder = builder.apply { setContentTitle(mContext.getString(R.string.payload_ping)) }
override fun equals(other: Any?): Boolean = if (other is Ping) true else super.equals(other)
override fun hashCode(): Int = 0
}
@JsonClass(generateAdapter = true)
data class Text(
@Json(name = "title")
internal val title: String? = null,
@Json(name = "message")
internal val text: String? = null,
@Json(name = "clipboard")
internal val clipboard: Boolean = false
) : Payload() {
override fun notificationId(): Int = R.id.notification_id_text
override fun icon(): Int = R.drawable.ic_chat_24dp
@delegate:Transient
private val display: CharSequence by lazy {
buildSpannedString {
bold { append("title: ") }
append("$title\n")
bold { append("text: ") }
append("$text\n")
bold { append("clipboard: ") }
append(clipboard.toString())
}
}
override fun display(): CharSequence? = display
@SuppressLint("RestrictedApi")
override fun configure(builder: Builder): Builder = builder.apply {
val intent = Intent(mContext, CopyToClipboardActivity::class.java)
intent.putExtra(EXTRA_TEXT, text)
setContentTitle(if (TextUtils.isEmpty(title)) mContext.getString(R.string.payload_text) else title)
.setContentText(text)
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
.addAction(0, mContext.getString(R.string.payload_text_copy), PendingIntent.getActivity(mContext, 0, intent, 0))
}
}
@JsonClass(generateAdapter = true)
data class Raw(
@Json(name = "data")
internal val data: Map<String, String>? = null
) : Payload(), KoinComponent {
override fun notificationId(): Int = R.id.notification_id_raw
override fun icon(): Int = R.drawable.ic_code_24dp
@delegate:Transient
private val display: CharSequence by lazy {
moshi.adapter<Map<*, *>>(MutableMap::class.java).indent(" ").toJson(data)
}
override fun display(): CharSequence? = display
@SuppressLint("RestrictedApi")
override fun configure(builder: Builder): Builder = builder.apply {
setContentTitle(mContext.getString(R.string.payload_raw))
.setContentText(display())
.setStyle(NotificationCompat.BigTextStyle().bigText(display()))
}
}
companion object : KoinComponent {
private val moshi by inject<Moshi>()
private val lut by inject<Map<String, Class<out Payload>>>()
fun extract(message: RemoteMessage): Payload {
val data = message.data
val entries: Set<Map.Entry<String, String>> = data.entries
for ((key, value) in entries) {
val clazz = lut[key] ?: continue
try {
val adapter = moshi.adapter(clazz)
val payload = adapter.fromJson(value)
if (payload != null) {
return payload
}
} catch (e: JsonDataException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
return Raw(data)
}
}
} | apache-2.0 | 33328b2f50fc83d0d291621ad91e4879 | 34.397541 | 185 | 0.608036 | 4.771271 | false | false | false | false |
bassaer/ChatMessageView | chatmessageview/src/main/kotlin/com/github/bassaer/chatmessageview/util/TimeUtils.kt | 1 | 1325 | package com.github.bassaer.chatmessageview.util
import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*
/**
* time utility class
* Created by nakayama on 2016/12/02.
*/
object TimeUtils {
/***
* Return formatted text of calendar
* @param calendar Calendar object to format
* @param format format text
* @return formatted text
*/
@SuppressLint("SimpleDateFormat")
fun calendarToString(calendar: Calendar, format: String?): String {
val sdf = SimpleDateFormat( format ?: "HH:mm", Locale.ENGLISH)
return sdf.format(calendar.time)
}
/**
* Return time difference days
* @param prev previous date
* @param target target date
* @return time difference days
*/
@JvmStatic
fun getDiffDays(prev: Calendar, target: Calendar): Int {
val timeDiff = prev.timeInMillis - target.timeInMillis
val millisOfDay = 1000 * 60 * 60 * 24
return (timeDiff / millisOfDay).toInt()
}
@JvmStatic
fun isSameDay(cal1: Calendar, cal2: Calendar): Boolean {
return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
}
}
| apache-2.0 | 78a49bccd6484a3fa977906db0ccfec2 | 28.444444 | 80 | 0.646792 | 4.064417 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/setup/MeshSetupActivity.kt | 1 | 3657 | package io.particle.mesh.ui.setup
import android.content.Context
import android.os.Bundle
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import io.github.inflationx.viewpump.ViewPumpContextWrapper
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.mesh.common.QATool
import io.particle.mesh.setup.flow.FlowRunnerSystemInterface
import io.particle.mesh.setup.flow.FlowTerminationAction
import io.particle.mesh.setup.flow.FlowTerminationAction.NoFurtherAction
import io.particle.mesh.setup.flow.FlowTerminationAction.StartControlPanelAction
import io.particle.mesh.setup.flow.FlowUiDelegate
import io.particle.mesh.ui.BaseFlowActivity
import io.particle.mesh.ui.R
import io.particle.mesh.ui.TitleBarOptions
import io.particle.mesh.ui.TitleBarOptionsListener
import io.particle.mesh.ui.controlpanel.ControlPanelActivity
import kotlinx.android.synthetic.main.activity_main.*
import mu.KotlinLogging
class MeshSetupActivity : TitleBarOptionsListener, BaseFlowActivity() {
var confirmExitingSetup = true
override val progressSpinnerViewId: Int
get() = R.id.p_mesh_globalProgressSpinner
override val navHostFragmentId: Int
get() = R.id.main_nav_host_fragment
override val contentViewIdRes: Int
get() = R.layout.activity_main
private val log = KotlinLogging.logger {}
override fun onFlowTerminated(nextAction: FlowTerminationAction) {
val nextActionFunction = when (nextAction) {
is NoFurtherAction -> {
{ /* no-op */ }
}
is StartControlPanelAction -> {
{
val intent = ControlPanelActivity.buildIntent(this, nextAction.device)
startActivity(intent)
}
}
}
finish()
nextActionFunction()
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
p_meshactivity_username.text = ParticleCloudSDK.getCloud().loggedInUsername
p_action_close.setOnClickListener { showCloseSetupConfirmation() }
}
override fun onBackPressed() {
showCloseSetupConfirmation()
}
override fun setTitleBarOptions(options: TitleBarOptions) {
if (options.titleRes != null) {
QATool.report(IllegalArgumentException("Title text not supported in setup!"))
}
if (options.showBackButton) {
QATool.report(IllegalArgumentException("Back button not yet supported in setup!"))
// p_action_back.visibility = if (options.showBackButton) View.VISIBLE else View.INVISIBLE
}
p_action_close.visibility = if (options.showCloseButton) View.VISIBLE else View.INVISIBLE
}
override fun buildFlowUiDelegate(systemInterface: FlowRunnerSystemInterface): FlowUiDelegate {
return SetupFlowUiDelegate(
systemInterface.navControllerLD,
application,
systemInterface.dialogHack,
systemInterface,
systemInterface.meshFlowTerminator
)
}
private fun showCloseSetupConfirmation() {
if (!confirmExitingSetup) {
finish()
return
}
MaterialDialog.Builder(this)
.content(R.string.p_exitsetupconfirmation_content)
.positiveText(R.string.p_exitsetupconfirmation_exit)
.negativeText(android.R.string.cancel)
.onPositive { _, _ -> finish() }
.show()
}
}
| apache-2.0 | 998b13a594e0fed26302f5ad26207e0c | 33.5 | 101 | 0.692918 | 4.682458 | false | false | false | false |
jilees/Fuel | fuel/src/test/kotlin/com/github/kittinunf/fuel/RequestValidationTest.kt | 1 | 3432 | package com.github.kittinunf.fuel
import com.github.kittinunf.fuel.core.*
import com.github.kittinunf.fuel.core.interceptors.validatorResponseInterceptor
import com.github.kittinunf.result.Result
import com.github.kittinunf.result.getAs
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.junit.Assert.assertThat
import org.junit.Test
import org.hamcrest.CoreMatchers.`is` as isEqualTo
class RequestValidationTest : BaseTestCase() {
val manager: FuelManager by lazy {
FuelManager().apply {
basePath = "http://httpbin.org"
}
}
@Test
fun httpValidationWithDefaultCase() {
val preDefinedStatusCode = 418
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
//this validate (200..299) which should fail with 418
manager.request(Method.GET, "/status/$preDefinedStatusCode").response { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(error?.errorData, notNullValue())
assertThat(data, nullValue())
assertThat(response?.httpStatusCode, isEqualTo(preDefinedStatusCode))
}
@Test
fun httpValidationWithCustomValidCase() {
val preDefinedStatusCode = 203
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
manager.removeAllResponseInterceptors()
manager.addResponseInterceptor(validatorResponseInterceptor(200..202))
//this validate (200..202) which should fail with 203
manager.request(Method.GET, "/status/$preDefinedStatusCode").responseString { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(data, nullValue())
assertThat(response?.httpStatusCode, isEqualTo(preDefinedStatusCode))
}
@Test
fun httpValidationWithCustomInvalidCase() {
val preDefinedStatusCode = 418
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
manager.removeAllResponseInterceptors()
manager.addResponseInterceptor(validatorResponseInterceptor(400..419))
manager.request(Method.GET, "/status/$preDefinedStatusCode").response { req, res, result ->
request = req
response = res
when (result) {
is Result.Failure -> {
error = result.getAs()
}
is Result.Success -> {
data = result.getAs()
}
}
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())
assertThat(response?.httpStatusCode, isEqualTo(preDefinedStatusCode))
}
}
| mit | 882e5a0ff7bdaeebcb39859c35fded93 | 29.371681 | 105 | 0.621212 | 5.039648 | false | true | false | false |
iZettle/wrench | wrench-prefs/src/test/java/com/izettle/wrench/preferences/WrenchPreferencesReturnsProviderValues.kt | 1 | 6014 | package com.izettle.wrench.preferences
import android.app.Application
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.Build.VERSION_CODES.O
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.izettle.wrench.core.Bolt
import com.izettle.wrench.core.ColumnNames
import com.izettle.wrench.core.WrenchProviderContract
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.android.controller.ContentProviderController
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(sdk = [O])
class WrenchPreferencesReturnsProviderValues {
private lateinit var wrenchPreferences: WrenchPreferences
private val key = "myKey"
private enum class TestEnum {
FIRST, SECOND
}
private lateinit var contentProviderController: ContentProviderController<MockContentProvider>
@Before
fun setUp() {
val info = ProviderInfo().apply { authority = WrenchProviderContract.WRENCH_AUTHORITY }
contentProviderController = Robolectric.buildContentProvider(MockContentProvider::class.java).create(info)
wrenchPreferences = WrenchPreferences(ApplicationProvider.getApplicationContext<Application>())
}
@Test
fun `return provider enum when available`() {
assertEquals(0, contentProviderController.get().bolts.size)
assertEquals(TestEnum.FIRST, wrenchPreferences.getEnum(key, TestEnum::class.java, TestEnum.FIRST))
assertEquals(TestEnum.FIRST, wrenchPreferences.getEnum(key, TestEnum::class.java, TestEnum.SECOND))
}
@Test
fun `return provider string when available`() {
assertEquals(0, contentProviderController.get().bolts.size)
assertEquals("first", wrenchPreferences.getString(key, "first"))
assertEquals("first", wrenchPreferences.getString(key, "second"))
}
@Test
fun `return provider boolean when available`() {
assertEquals(0, contentProviderController.get().bolts.size)
assertEquals(true, wrenchPreferences.getBoolean(key, true))
assertEquals(true, wrenchPreferences.getBoolean(key, false))
}
@Test
fun `return provider int when available`() {
assertEquals(0, contentProviderController.get().bolts.size)
assertEquals(1, wrenchPreferences.getInt(key, 1))
assertEquals(1, wrenchPreferences.getInt(key, 2))
}
}
class MockContentProvider : ContentProvider() {
companion object {
private const val CURRENT_CONFIGURATION_ID = 1
private const val CURRENT_CONFIGURATION_KEY = 2
private const val CURRENT_CONFIGURATIONS = 3
private const val PREDEFINED_CONFIGURATION_VALUES = 5
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
uriMatcher.addURI(WrenchProviderContract.WRENCH_AUTHORITY, "currentConfiguration/#", CURRENT_CONFIGURATION_ID)
uriMatcher.addURI(WrenchProviderContract.WRENCH_AUTHORITY, "currentConfiguration/*", CURRENT_CONFIGURATION_KEY)
uriMatcher.addURI(WrenchProviderContract.WRENCH_AUTHORITY, "currentConfiguration", CURRENT_CONFIGURATIONS)
uriMatcher.addURI(WrenchProviderContract.WRENCH_AUTHORITY, "predefinedConfigurationValue", PREDEFINED_CONFIGURATION_VALUES)
}
}
val bolts: MutableMap<String, Bolt> = mutableMapOf()
private val nuts: MutableList<String> = mutableListOf()
override fun onCreate(): Boolean {
return true
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
when (uriMatcher.match(uri)) {
CURRENT_CONFIGURATION_ID -> {
throw IllegalArgumentException("bolt exists")
}
CURRENT_CONFIGURATION_KEY -> {
val cursor = MatrixCursor(arrayOf(ColumnNames.Bolt.COL_ID, ColumnNames.Bolt.COL_KEY, ColumnNames.Bolt.COL_TYPE, ColumnNames.Bolt.COL_VALUE))
uri.lastPathSegment?.let { key ->
bolts[key]?.let { bolt ->
cursor.addRow(arrayOf(bolt.id, bolt.key, bolt.type, bolt.value))
}
}
return cursor
}
else -> {
throw UnsupportedOperationException("Not yet implemented " + uri.toString())
}
}
}
override fun insert(uri: Uri, values: ContentValues): Uri {
val insertId: Long
when (uriMatcher.match(uri)) {
CURRENT_CONFIGURATIONS -> {
val bolt = Bolt.fromContentValues(values)
if (bolts.containsKey(bolt.key)) {
throw IllegalArgumentException("bolt exists")
}
bolts[bolt.key] = bolt
insertId = bolts.size.toLong()
bolt.id = insertId
}
PREDEFINED_CONFIGURATION_VALUES -> {
nuts.add(values.getAsString(ColumnNames.Nut.COL_VALUE))
insertId = nuts.size.toLong()
}
else -> {
throw UnsupportedOperationException("Not yet implemented $uri")
}
}
return ContentUris.withAppendedId(uri, insertId)
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
throw IllegalStateException()
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
throw IllegalStateException()
}
override fun getType(uri: Uri): String? {
throw IllegalStateException()
}
} | mit | 26e3e2c280e75ab201c6f4340da4c8fc | 35.90184 | 156 | 0.678583 | 4.889431 | false | true | false | false |
icarumbas/bagel | core/src/ru/icarumbas/bagel/utils/Mappers.kt | 1 | 2309 | package ru.icarumbas.bagel.utils
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.ComponentMapper
import ru.icarumbas.bagel.engine.components.other.*
import ru.icarumbas.bagel.engine.components.physics.BodyComponent
import ru.icarumbas.bagel.engine.components.physics.InactiveMarkerComponent
import ru.icarumbas.bagel.engine.components.physics.StaticComponent
import ru.icarumbas.bagel.engine.components.physics.WeaponComponent
import ru.icarumbas.bagel.engine.components.velocity.FlyComponent
import ru.icarumbas.bagel.engine.components.velocity.JumpComponent
import ru.icarumbas.bagel.engine.components.velocity.RunComponent
import ru.icarumbas.bagel.engine.components.velocity.TeleportComponent
import ru.icarumbas.bagel.view.renderer.components.*
inline fun <reified T : Component> mapperFor(): ComponentMapper<T> = ComponentMapper.getFor(T::class.java)
val damage = mapperFor<HealthComponent>()
val player = mapperFor<PlayerComponent>()
val roomId = mapperFor<RoomIdComponent>()
val state = mapperFor<StateComponent>()
val body = mapperFor<BodyComponent>()
val statik = mapperFor<StaticComponent>()
val animation = mapperFor<AnimationComponent>()
val size = mapperFor<SizeComponent>()
val jump = mapperFor<JumpComponent>()
val run = mapperFor<RunComponent>()
val weapon = mapperFor<WeaponComponent>()
val alwaysRender = mapperFor<AlwaysRenderingMarkerComponent>()
val AI = mapperFor<AIComponent>()
val inActive = mapperFor<InactiveMarkerComponent>()
val teleport = mapperFor<TeleportComponent>()
val attack = mapperFor<AttackComponent>()
val texture = mapperFor<TextureComponent>()
val open = mapperFor<OpenComponent>()
val door = mapperFor<DoorComponent>()
val loot = mapperFor<LootComponent>()
val fly = mapperFor<FlyComponent>()
val translate = mapperFor<TranslateComponent>()
val shader = mapperFor<ShaderComponent>()
| apache-2.0 | 6e738b32a5d1a8fcd957a3d5fe6acd2a | 48.12766 | 110 | 0.658727 | 4.645875 | false | false | false | false |
emufog/emufog | src/test/kotlin/emufog/fog/BaseNodeTest.kt | 1 | 8802 | /*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.fog
import emufog.container.FogContainer
import emufog.graph.EdgeNode
import emufog.graph.Node
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class BaseNodeTest {
private val node: Node = mockk {
every { [email protected]() } returns 42
}
@Test
fun `test the initialization of a base node`() {
val baseNode = BaseNode(node)
assertEquals(node, baseNode.node)
assertEquals(0F, baseNode.averageConnectionCosts)
assertNull(baseNode.averageDeploymentCosts)
assertTrue(baseNode.modified)
assertNull(baseNode.type)
assertEquals(0, baseNode.startingNodes.size)
}
@Test
fun `averageConnectionCosts should be reflecting the cost map`() {
val fogTypes = listOf(FogContainer("name", "tag", 1, 1F, 10, 1F))
val baseNode = BaseNode(node)
assertEquals(0F, baseNode.averageConnectionCosts)
baseNode.setCosts(mockk {
every { addPossibleNode(baseNode) } returns Unit
every { deviceCount } returns 1
}, 1F)
baseNode.determineFogType(fogTypes)
assertEquals(1F, baseNode.averageConnectionCosts)
baseNode.setCosts(mockk {
every { addPossibleNode(baseNode) } returns Unit
every { deviceCount } returns 1
}, 23.5F)
baseNode.determineFogType(fogTypes)
assertEquals(24.5F / 2, baseNode.averageConnectionCosts)
baseNode.setCosts(mockk {
every { addPossibleNode(baseNode) } returns Unit
every { deviceCount } returns 1
}, 100F)
baseNode.determineFogType(fogTypes)
assertEquals(124.5F / 3, baseNode.averageConnectionCosts)
}
@Test
fun `getCosts should return null if none are associated`() {
val baseNode = BaseNode(node)
val startingNode: StartingNode = mockk()
assertNull(baseNode.getCosts(startingNode))
}
@Test
fun `setCosts should set the costs for the given starting node`() {
val baseNode = BaseNode(node)
val edgeNode: EdgeNode = mockk {
every { deviceCount } returns 10
}
val startingNode = StartingNode(edgeNode)
assertNull(baseNode.getCosts(startingNode))
assertFalse(baseNode.hasConnections())
baseNode.setCosts(startingNode, 42F)
assertEquals(42F, baseNode.getCosts(startingNode))
assertTrue(baseNode.hasConnections())
assertEquals(1, startingNode.possibleNodes.size)
assertEquals(baseNode, startingNode.possibleNodes.first())
}
@Test
fun `removeStartingNode should delete a cost mapping for that starting node`() {
val baseNode = BaseNode(node)
val edgeNode: EdgeNode = mockk {
every { deviceCount } returns 10
}
val startingNode = StartingNode(edgeNode)
assertNull(baseNode.getCosts(startingNode))
baseNode.setCosts(startingNode, 42F)
assertEquals(42F, baseNode.getCosts(startingNode))
baseNode.removeStartingNode(startingNode)
assertNull(baseNode.getCosts(startingNode))
}
// @Test
// fun `findFogType should abort on non modified nodes`() {
// val baseNode = BaseNode(node)
// baseNode.modified = false
// baseNode.determineFogType(emptyList())
// }
@Test
fun `findFogType should fail on no connections`() {
val baseNode = BaseNode(node)
assertThrows<IllegalStateException> {
val type = FogContainer("name", "tag", 1, 1F, 5, 1F)
baseNode.determineFogType(listOf(type))
}
}
@Test
fun `findFogType should fail on no given fog types`() {
val baseNode = BaseNode(node)
assertThrows<IllegalStateException> {
baseNode.determineFogType(emptyList())
}
}
@Test
fun `findFogType should set the optimal fog container1`() {
val type1 = FogContainer("name", "tag", 1, 1F, 1, 1F)
val type2 = FogContainer("name", "tag", 1, 1F, 2, 1.5F)
val baseNode = findOptimalFogType(listOf(type1, type2))
assertEquals(type2, baseNode.type)
assertEquals(type2.costs / type2.maxClients, baseNode.averageDeploymentCosts)
val coveredNodes = baseNode.coveredNodes
assertEquals(1, coveredNodes.size)
assertEquals(0, coveredNodes[0].first.node.id)
assertEquals(2, coveredNodes[0].second)
}
@Test
fun `findFogType should set the optimal fog container2`() {
val type1 = FogContainer("name", "tag", 1, 1F, 1, 1F)
val type2 = FogContainer("name", "tag", 1, 1F, 100, 20F)
val baseNode = findOptimalFogType(listOf(type1, type2))
assertEquals(type1, baseNode.type)
assertEquals(1F, baseNode.averageDeploymentCosts)
val coveredNodes = baseNode.coveredNodes
assertEquals(1, coveredNodes.size)
assertEquals(0, coveredNodes[0].first.node.id)
assertEquals(1, coveredNodes[0].second)
}
@Test
fun `findFogType should set the optimal fog container3`() {
val type1 = FogContainer("name", "tag", 1, 1F, 100, 20F)
val baseNode = findOptimalFogType(listOf(type1))
assertEquals(type1, baseNode.type)
assertEquals(20F / 11, baseNode.averageDeploymentCosts)
val coveredNodes = baseNode.coveredNodes
assertEquals(2, coveredNodes.size)
assertEquals(0, coveredNodes[0].first.node.id)
assertEquals(5, coveredNodes[0].second)
assertEquals(1, coveredNodes[1].first.node.id)
assertEquals(6, coveredNodes[1].second)
}
private fun findOptimalFogType(types: List<FogContainer>): BaseNode {
val baseNode = BaseNode(node)
val edgeNode1: EdgeNode = mockk {
every { deviceCount } returns 5
every { id } returns 0
}
baseNode.setCosts(StartingNode(edgeNode1), 1F)
val edgeNode2: EdgeNode = mockk {
every { deviceCount } returns 6
every { id } returns 1
}
baseNode.setCosts(StartingNode(edgeNode2), 2F)
assertNull(baseNode.type)
assertNull(baseNode.averageDeploymentCosts)
baseNode.determineFogType(types)
return baseNode
}
@Test
fun `getCoveredStartingNodes should return empty list without any connections`() {
val baseNode = BaseNode(node)
val coveredNodes = baseNode.coveredNodes
assertEquals(0, coveredNodes.size)
}
@Test
fun `equals with same node should return true`() {
val baseNode = BaseNode(node)
assertTrue(baseNode == baseNode)
assertTrue(baseNode === baseNode)
}
@Test
fun `equals with different node but same underlying node should return true`() {
val baseNode1 = BaseNode(node)
val baseNode2 = BaseNode(node)
assertTrue(baseNode1 == baseNode2)
assertFalse(baseNode1 === baseNode2)
}
@Test
fun `equals with different node should return false`() {
val baseNode1 = BaseNode(node)
val baseNode2 = BaseNode(mockk())
assertFalse(baseNode1 == baseNode2)
assertFalse(baseNode1 === baseNode2)
}
@Test
fun `hashCode should return the hash code of the associated node`() {
val baseNode = BaseNode(node)
assertEquals(42, baseNode.hashCode())
}
} | mit | ed46f23935fe8b17ea322ecea6d05463 | 35.526971 | 86 | 0.667121 | 4.041322 | false | true | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/msc/RoleCommands.kt | 1 | 7403 | package me.mrkirby153.KirBot.command.executors.msc
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.logger.LogEvent
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.Logger
import me.mrkirby153.KirBot.user.CLEARANCE_MOD
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.FuzzyMatchException
import me.mrkirby153.KirBot.utils.canAssign
import me.mrkirby153.KirBot.utils.getMember
import me.mrkirby153.KirBot.utils.kirbotGuild
import me.mrkirby153.KirBot.utils.logName
import me.mrkirby153.KirBot.utils.nameAndDiscrim
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent
import javax.inject.Inject
class RoleCommands @Inject constructor(private val logger: Logger) {
@Command(name = "role", clearance = CLEARANCE_MOD, aliases = ["roles", "r"], category = CommandCategory.MODERATION)
@CommandDescription("List all the roles and their IDs")
@IgnoreWhitelist
fun execute(context: Context, cmdContext: CommandContext) {
var msg = "```"
context.guild.roles.forEach {
if (msg.length >= 1900) {
context.channel.sendMessage("$msg```").queue()
msg = "```"
}
msg += "\n${it.id} - ${it.name}"
}
context.channel.sendMessage("$msg```").queue()
}
@Command(name = "add", clearance = CLEARANCE_MOD,
arguments = ["<user:snowflake>", "<role:string>", "[reason:string...]"],
permissions = [Permission.MANAGE_ROLES], parent = "role", category = CommandCategory.MODERATION)
@CommandDescription("Add a role to the given user")
@IgnoreWhitelist
fun addRole(context: Context, cmdContext: CommandContext) {
val roleString = cmdContext.get<String>("role")!!
val reason = cmdContext.get<String>("reason") ?: "No reason specified"
val role: Role?
try {
role = context.guild.kirbotGuild.matchRole(roleString) ?: throw CommandException(
"No roles found for that query")
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Multiple matches for that query. Try a more specific query or the role id")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No roles found for that query")
}
val member = context.guild.getMemberById(cmdContext.getNotNull<String>("user"))
?: throw CommandException("That user is not in the guild")
val m = context.author.getMember(context.guild) ?: return
checkManipulate(m, member)
checkAssignment(m, role)
if (!context.guild.selfMember.canAssign(role))
throw CommandException("I cannot assign that role")
logger.debouncer.create(GuildMemberRoleAddEvent::class.java,
Pair("user", member.user.id), Pair("role", role.id))
context.guild.addRoleToMember(member, role).queue()
context.kirbotGuild.logManager.genericLog(LogEvent.ROLE_ADD, ":key:",
"Assigned **${role.name}** to ${member.user.logName}: `$reason`")
context.send().success("Added role **${role.name}** to ${member.user.nameAndDiscrim}",
true).queue()
}
@Command(name = "remove", clearance = CLEARANCE_MOD,
arguments = ["<user:snowflake>", "<role:string>", "[reason:string...]"],
permissions = [Permission.MANAGE_ROLES], parent = "role", category = CommandCategory.MODERATION)
@CommandDescription("Remove a role from the given user")
@IgnoreWhitelist
fun removeRole(context: Context, cmdContext: CommandContext) {
val roleString = cmdContext.get<String>("role")!!
val reason = cmdContext.get<String>("reason") ?: "No reason specified"
val role: Role?
try {
role = context.guild.kirbotGuild.matchRole(roleString) ?: throw CommandException(
"No roles found for that query")
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Multiple matches for that query. Try a more specific query or the role id")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No roles found for that query")
}
val member = context.guild.getMemberById(cmdContext.getNotNull<String>("user"))
?: throw CommandException(
"that user is not in the guild")
val m = context.author.getMember(context.guild) ?: return
checkManipulate(m, member)
checkAssignment(m, role, "remove")
ModuleManager[Logger::class].debouncer.create(GuildMemberRoleRemoveEvent::class.java,
Pair("user", member.user.id), Pair("role", role.id))
context.kirbotGuild.logManager.genericLog(LogEvent.ROLE_ADD, ":key:",
"Removed **${role.name}** from ${member.user.logName}: `$reason`")
context.guild.removeRoleFromMember(member, role).queue()
context.send().success("Removed role **${role.name}** from ${member.user.nameAndDiscrim}",
true).queue()
}
companion object {
/**
* Checks if the given member can assign the given role
*
* @param member The member
* @param role The role to assign
*
* @throws CommandException If an error occurs in the comparison
*/
fun checkAssignment(member: Member, role: Role, mode: String = "assign") {
if (member.isOwner)
return // The owner can assign all roles regardless of permissions
val highestPos = member.roles.maxBy { it.position }?.position ?: 0
val rolePos = role.position
if (rolePos >= highestPos) {
throw CommandException("You cannot $mode roles above your own")
}
}
/**
* Checks if the given member can interact with the other member
*
* @param member The member to check
* @param otherMember The member to check against
*
* @throws CommandException If the user cannot manipulate the user
*/
fun checkManipulate(member: Member, otherMember: Member) {
if (member.user.id == otherMember.user.id)
throw CommandException("You cannot execute that on yourself")
if (member.isOwner)
return // The owner can manipulate everyone regardless of permissions
val highestPos = member.roles.maxBy { it.position }?.position ?: 0
val otherPos = otherMember.roles.maxBy { it.position }?.position ?: 0
if (otherPos >= highestPos)
throw CommandException("You cannot execute this on that user")
}
}
} | mit | 8f0c9915f96fe4ae5235ad1938df1b3c | 45.275 | 119 | 0.649872 | 4.459639 | false | false | false | false |
adelnizamutdinov/headphone-reminder | app/src/main/kotlin/common/rx/single.kt | 1 | 670 | package common.rx
import rx.Observable
import rx.Single
import rx.SingleSubscriber
import rx.subscriptions.Subscriptions
fun <T> SingleSubscriber<T>.finally(function: () -> Unit): Unit =
add(Subscriptions.create(function))
fun <T> SingleSubscriber<T>.success(t: T): Unit =
ifNotUnsubscribed { onSuccess(t) }
fun <T> SingleSubscriber<T>.error(e: Throwable): Unit =
ifNotUnsubscribed { onError(e) }
inline fun <T> SingleSubscriber<in T>.ifNotUnsubscribed(f: () -> Unit): Unit =
when {
isUnsubscribed -> Unit
else -> f()
}
fun <T> Single<T>.takeUntil(other: Observable<*>): Observable<T> =
toObservable().takeUntil(other) | mit | db841ed0e6cf940a2f58f30c1bfeb3ed | 26.958333 | 78 | 0.685075 | 3.661202 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/adapter/TagAdapter.kt | 2 | 1620 | package com.commit451.gitlab.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.Ref
import com.commit451.gitlab.model.api.Tag
import com.commit451.gitlab.viewHolder.TagViewHolder
import java.util.*
/**
* Tags
*/
class TagAdapter(val ref: Ref?, val listener: Listener) : RecyclerView.Adapter<TagViewHolder>() {
private val values: ArrayList<Tag> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagViewHolder {
val holder = TagViewHolder.inflate(parent)
holder.itemView.setOnClickListener { v ->
val position = v.getTag(R.id.list_position) as Int
listener.onTagClicked(getEntry(position))
}
return holder
}
override fun onBindViewHolder(holder: TagViewHolder, position: Int) {
holder.itemView.setTag(R.id.list_position, position)
val tag = getEntry(position)
var selected = false
if (ref != null) {
if (ref.type == Ref.TYPE_TAG && ref.ref == tag.name) {
selected = true
}
}
holder.bind(tag, selected)
}
override fun getItemCount(): Int {
return values.size
}
fun setEntries(entries: Collection<Tag>?) {
values.clear()
if (entries != null) {
values.addAll(entries)
}
notifyDataSetChanged()
}
private fun getEntry(position: Int): Tag {
return values[position]
}
interface Listener {
fun onTagClicked(entry: Tag)
}
}
| apache-2.0 | 87331e8c3fa2a67618fe6a08f2d37568 | 26.931034 | 97 | 0.638889 | 4.263158 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/spellchecking/MdGrammarCheckingStrategy.kt | 1 | 3551 | // 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.
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.spellchecking
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import com.vladsch.md.nav.parser.LexParserState
import com.vladsch.md.nav.psi.element.MdDefinition
import com.vladsch.md.nav.psi.element.MdDefinitionTerm
import com.vladsch.md.nav.psi.element.MdListItem
import com.vladsch.md.nav.psi.element.MdParagraph
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.plugin.util.psi.isTypeIn
class MdGrammarCheckingStrategy : GrammarCheckingStrategy {
private val lexerState: LexParserState.State = LexParserState.getInstance().state
private val contextRoots: TokenSet = TokenSet.orSet(
TokenSet.create(MdTypes.TEXT_BLOCK),
MdTokenSets.TABLE_TEXT_SET,
MdTokenSets.HEADER_TEXT_SET
)
private val inlineNonText: TokenSet = TokenSet.create(*lexerState.INLINE_NON_PLAIN_TEXT.toTypedArray())
override fun isMyContextRoot(element: PsiElement): Boolean {
val isRoot = element.node.isTypeIn(contextRoots)
// println("Trying: $element isRoot: $isRoot")
return isRoot
}
override fun isEnabledByDefault(): Boolean = true
override fun getContextRootTextDomain(root: PsiElement): GrammarCheckingStrategy.TextDomain {
return GrammarCheckingStrategy.TextDomain.PLAIN_TEXT
}
override fun getElementBehavior(root: PsiElement, child: PsiElement): GrammarCheckingStrategy.ElementBehavior {
return when {
// FIX: need to have inline code text ignored by marking ABSORB
isInlineMarker(child) -> GrammarCheckingStrategy.ElementBehavior.STEALTH
else -> GrammarCheckingStrategy.ElementBehavior.TEXT
}
}
override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement): RuleGroup? {
// NOTE: ignore CASING for simple, single line list items
return if (isSimpleTextItem(root)) RuleGroup.CASING else null
}
private fun isInlineMarker(element: PsiElement): Boolean {
return element.node.isTypeIn(inlineNonText)
}
/**
* @param root root element for the text
* @return true if this element is simple text for which casing rules should not be applied
*/
private fun isSimpleTextItem(root: PsiElement): Boolean {
val isSimpleTextItem = if (root.node.isTypeIn(MdTypes.TEXT_BLOCK) && MdApplicationSettings.instance.documentSettings.grammarIgnoreSimpleTextCasing) {
var parent = root.parent
if (parent is MdParagraph) parent = parent.parent
when (parent) {
is MdDefinitionTerm -> true
is MdListItem, is MdDefinition -> {
val eolPos = root.text.indexOf('\n')
(eolPos == -1 || eolPos == root.textLength - 1) && MdPsiImplUtil.isFirstIndentedBlock(root, false)
}
else -> false
}
} else false
return isSimpleTextItem
}
}
| apache-2.0 | 8919d370045a440ed0d6b0394bf56f2f | 43.949367 | 177 | 0.716418 | 4.362408 | false | false | false | false |
ZsemberiDaniel/EgerBusz | app/src/main/java/com/zsemberidaniel/egerbuszuj/fragments/ChooseStopFragment.kt | 1 | 3003 | package com.zsemberidaniel.egerbuszuj.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.zsemberidaniel.egerbuszuj.R
import com.zsemberidaniel.egerbuszuj.adapters.ChooseStopAdapter
import com.zsemberidaniel.egerbuszuj.interfaces.views.IChooseStopView
import com.zsemberidaniel.egerbuszuj.presenters.ChooseStopPresenter
import eu.davidea.flexibleadapter.FlexibleAdapter
import java.util.*
/**
* Created by zsemberi.daniel on 2017. 05. 12..
*/
class ChooseStopFragment : Fragment(), IChooseStopView {
private lateinit var recyclerView: RecyclerView
private lateinit var layoutManager: RecyclerView.LayoutManager
private lateinit var allStopsAdapter: ChooseStopAdapter
private lateinit var presenter: ChooseStopPresenter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.choose_stop, container, false)
recyclerView = view.findViewById(R.id.chooseStopRecyclerView) as RecyclerView
// improve performance because the content does not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true)
// use a linear layout manager
layoutManager = LinearLayoutManager(view.context)
recyclerView.layoutManager = layoutManager
allStopsAdapter = ChooseStopAdapter(ArrayList<ChooseStopAdapter.ChooseStopItem>())
allStopsAdapter.setDisplayHeadersAtStartUp(true)
allStopsAdapter.setStickyHeaders(true)
presenter = ChooseStopPresenter(this, allStopsAdapter)
presenter.init()
allStopsAdapter.addListener(FlexibleAdapter.OnItemClickListener { position ->
presenter.stopClicked(context, allStopsAdapter.getItem(position))
true
})
recyclerView.adapter = allStopsAdapter
return view
}
override fun onResume() {
super.onResume()
allStopsAdapter.clear()
allStopsAdapter.addItems(0, presenter.getAdapterItemsCopy())
}
override fun updateStopFilter(newFilter: String) {
allStopsAdapter.searchText = newFilter
// we need this because otherwise the items just disappear if the filter is "" for some reason
if (newFilter == "") {
allStopsAdapter.clear()
allStopsAdapter.addItems(0, presenter.getAdapterItemsCopy())
allStopsAdapter.showAllHeaders()
return
}
allStopsAdapter.filterItems(presenter.getAdapterItemsCopy())
// Disable headers if the user is searching because they are not really needed
// And if enabled they get doubled for some reason
if (newFilter != "")
allStopsAdapter.hideAllHeaders()
}
}
| apache-2.0 | 913e9c8e0be4c1e647842de8957188de | 34.329412 | 116 | 0.734932 | 5.064081 | false | false | false | false |
danfma/kodando | kodando-mithril/src/main/kotlin/kodando/mithril/context/SharedContextMap.kt | 1 | 602 | package kodando.mithril.context
import kodando.runtime.es2015.Symbol
internal object SharedContextMap {
private var contextMap = mutableMapOf<Symbol, MutableList<Any?>>()
fun put(key: Symbol, value: Any?) {
contextMap
.getOrPut(key) { mutableListOf() }
.add(value)
}
fun get(key: Symbol): Any? {
return contextMap[key]?.last() ?: throw Error("No context value for contextKey = '$key'")
}
fun remove(key: Symbol) {
val values = contextMap.getValue(key)
values.removeAt(values.size - 1)
if (values.size == 0) {
contextMap.remove(key)
}
}
}
| mit | c16f9d4aaec6b5338f903ce488f9bb4f | 20.5 | 93 | 0.652824 | 3.648485 | false | false | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/format/Tokenizer.kt | 1 | 3767 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.ktfmt.format
import java.util.regex.Pattern
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
/**
* Tokenizer traverses a Kotlin parse tree (which blessedly contains whitespaces and comments,
* unlike Javac) and constructs a list of 'Tok's.
*
* <p>The google-java-format infra expects newline Toks to be separate from maximal-whitespace Toks,
* but Kotlin emits them together. So, we split them using Java's \R regex matcher. We don't use
* 'split' et al. because we want Toks for the newlines themselves.
*/
class Tokenizer(private val fileText: String, val file: KtFile) : KtTreeVisitorVoid() {
companion object {
private val WHITESPACE_NEWLINE_REGEX: Pattern = Pattern.compile("\\R|( )+")
}
val toks = mutableListOf<KotlinTok>()
var index = 0
override fun visitElement(element: PsiElement) {
val startIndex = element.startOffset
when (element) {
is PsiComment -> {
toks.add(
KotlinTok(
index,
fileText.substring(startIndex, element.endOffset),
element.text,
startIndex,
0,
false,
KtTokens.EOF))
index++
return
}
is KtStringTemplateExpression -> {
toks.add(
KotlinTok(
index,
WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(
fileText.substring(startIndex, element.endOffset)),
element.text,
startIndex,
0,
true,
KtTokens.EOF))
index++
return
}
is LeafPsiElement -> {
val elementText = element.text
val endIndex = element.endOffset
if (element is PsiWhiteSpace) {
val matcher = WHITESPACE_NEWLINE_REGEX.matcher(elementText)
while (matcher.find()) {
val text = matcher.group()
toks.add(
KotlinTok(
-1,
fileText.substring(startIndex + matcher.start(), startIndex + matcher.end()),
text,
startIndex + matcher.start(),
0,
false,
KtTokens.EOF))
}
} else {
toks.add(
KotlinTok(
index,
fileText.substring(startIndex, endIndex),
elementText,
startIndex,
0,
true,
KtTokens.EOF))
index++
}
}
}
super.visitElement(element)
}
}
| apache-2.0 | b3319c40e38cdfc9e8bf0fc9d741362f | 32.936937 | 100 | 0.608973 | 4.768354 | false | false | false | false |
JTechMe/JumpGo | app/src/main/java/com/jtechme/jumpgo/animation/AnimationUtils.kt | 1 | 1727 | package com.jtechme.jumpgo.animation
import android.support.annotation.DrawableRes
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.ImageView
/**
* Animation specific helper code.
*/
object AnimationUtils {
/**
* Creates an animation that rotates an [ImageView]
* around the Y axis by 180 degrees and changes the image
* resource shown when the view is rotated 90 degrees to the user.
* @param imageView the view to rotate.
* *
* @param drawableRes the drawable to set when the view
* * is rotated by 90 degrees.
* *
* @return an animation that will change the image shown by the view.
*/
fun createRotationTransitionAnimation(imageView: ImageView,
@DrawableRes drawableRes: Int): Animation {
val animation = object : Animation() {
private var mSetFinalDrawable: Boolean = false
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
if (interpolatedTime < 0.5f) {
imageView.rotationY = 90f * interpolatedTime * 2f
} else {
if (!mSetFinalDrawable) {
mSetFinalDrawable = true
imageView.setImageResource(drawableRes)
}
imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f
}
}
}
animation.duration = 300
animation.interpolator = AccelerateDecelerateInterpolator()
return animation
}
}
| mpl-2.0 | 8567a757fb2bcba0db0c76d4db42f07b | 32.862745 | 90 | 0.609728 | 5.363354 | false | false | false | false |
CajetanP/coding-exercises | Others/Kotlin/kotlin-koans/src/iii_conventions/n30DestructuringDeclarations.kt | 1 | 826 | 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 'data' modifier.
""",
documentation = doc30()
)
class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun component1(): Int = year
operator fun component2(): Int = month
operator fun component3(): Int = dayOfMonth
}
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
return isLeapYear(year) && month == 1 && dayOfMonth == 29
}
// Years which are multiples of four (with the exception of years divisible by 100 but not by 400)
fun isLeapYear(year: Int): Boolean = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) | mit | 9a2b3a4483044fdc1724001c92507065 | 30.807692 | 112 | 0.674334 | 3.914692 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/list/PagedListFactoryTest.kt | 1 | 1345 | package org.wordpress.android.fluxc.list
import androidx.paging.DataSource.InvalidatedCallback
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Test
import org.wordpress.android.fluxc.model.list.PagedListFactory
internal class PagedListFactoryTest {
@Test
fun `create factory triggers create data source`() {
val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>()
whenever(mockCreateDataSource.invoke()).thenReturn(mock())
val pagedListFactory = PagedListFactory(mockCreateDataSource)
pagedListFactory.create()
verify(mockCreateDataSource, times(1)).invoke()
}
@Test
fun `invalidate triggers create data source`() {
val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>()
whenever(mockCreateDataSource.invoke()).thenReturn(mock())
val invalidatedCallback = mock<InvalidatedCallback>()
val pagedListFactory = PagedListFactory(mockCreateDataSource)
val currentSource = pagedListFactory.create()
currentSource.addInvalidatedCallback(invalidatedCallback)
pagedListFactory.invalidate()
verify(invalidatedCallback, times(1)).onInvalidated()
}
}
| gpl-2.0 | 7e02cdc5356ad2d84652238011c11236 | 35.351351 | 80 | 0.751673 | 5.46748 | false | true | false | false |
ChrisZhong/organization-model | chazm-api/src/main/kotlin/runtimemodels/chazm/api/function/Goodness.kt | 2 | 1363 | package runtimemodels.chazm.api.function
import runtimemodels.chazm.api.entity.Agent
import runtimemodels.chazm.api.entity.InstanceGoal
import runtimemodels.chazm.api.entity.Role
import runtimemodels.chazm.api.organization.Organization
import runtimemodels.chazm.api.relation.Assignment
/**
* The [Goodness] interface defines the API for computing a score (`0.0` <= score <= `1.0`) of how effective an
* [Agent] is at playing a [Role] to achieve an [InstanceGoal] in an [Organization].
*
* @author Christopher Zhong
* @since 6.0
*/
@FunctionalInterface
interface Goodness {
/**
* Returns a score (`0.0` <= score <=`1.0`) of how effective an [Agent] is at playing a [Role] to achieve
* an [InstanceGoal] in an [Organization].
*
* @param organization an [Organization] in which to compute a score.
* @param agent the [Agent] that is playing the given [Role].
* @param role the [Role] that achieves the given [InstanceGoal].
* @param goal the [InstanceGoal] to compute a score.
* @param assignments a set of [Assignment]s that may affect the score.
* @return a score (`0.0` <= score <= `1.0`).
*/
fun compute(
organization: Organization,
agent: Agent,
role: Role,
goal: InstanceGoal,
assignments: Collection<Assignment>
): Double
}
| apache-2.0 | 8ffc6cd59f11bcdb6f57ed2d237cd817 | 36.861111 | 111 | 0.67058 | 4.020649 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonMain/src/kotlinx/serialization/internal/AbstractPolymorphicSerializer.kt | 1 | 4860 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.internal
import kotlinx.serialization.*
import kotlinx.serialization.encoding.*
import kotlin.jvm.*
import kotlin.reflect.*
/**
* Base class for providing multiplatform polymorphic serialization.
*
* This class cannot be implemented by library users. To learn how to use it for your case,
* please refer to [PolymorphicSerializer] for interfaces/abstract classes and [SealedClassSerializer] for sealed classes.
*
* By default, without special support from [Encoder], polymorphic types are serialized as list with
* two elements: class [serial name][SerialDescriptor.serialName] (String) and the object itself.
* Serial name equals to fully-qualified class name by default and can be changed via @[SerialName] annotation.
*/
@InternalSerializationApi
@OptIn(ExperimentalSerializationApi::class)
public abstract class AbstractPolymorphicSerializer<T : Any> internal constructor() : KSerializer<T> {
/**
* Base class for all classes that this polymorphic serializer can serialize or deserialize.
*/
public abstract val baseClass: KClass<T>
public final override fun serialize(encoder: Encoder, value: T) {
val actualSerializer = findPolymorphicSerializer(encoder, value)
encoder.encodeStructure(descriptor) {
encodeStringElement(descriptor, 0, actualSerializer.descriptor.serialName)
encodeSerializableElement(descriptor, 1, actualSerializer.cast(), value)
}
}
public final override fun deserialize(decoder: Decoder): T = decoder.decodeStructure(descriptor) {
var klassName: String? = null
var value: Any? = null
if (decodeSequentially()) {
return@decodeStructure decodeSequentially(this)
}
mainLoop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
CompositeDecoder.DECODE_DONE -> {
break@mainLoop
}
0 -> {
klassName = decodeStringElement(descriptor, index)
}
1 -> {
klassName = requireNotNull(klassName) { "Cannot read polymorphic value before its type token" }
val serializer = findPolymorphicSerializer(this, klassName)
value = decodeSerializableElement(descriptor, index, serializer)
}
else -> throw SerializationException(
"Invalid index in polymorphic deserialization of " +
(klassName ?: "unknown class") +
"\n Expected 0, 1 or DECODE_DONE(-1), but found $index"
)
}
}
@Suppress("UNCHECKED_CAST")
requireNotNull(value) { "Polymorphic value has not been read for class $klassName" } as T
}
private fun decodeSequentially(compositeDecoder: CompositeDecoder): T {
val klassName = compositeDecoder.decodeStringElement(descriptor, 0)
val serializer = findPolymorphicSerializer(compositeDecoder, klassName)
return compositeDecoder.decodeSerializableElement(descriptor, 1, serializer)
}
/**
* Lookups an actual serializer for given [klassName] withing the current [base class][baseClass].
* May use context from the [decoder].
*/
@InternalSerializationApi
public open fun findPolymorphicSerializerOrNull(
decoder: CompositeDecoder,
klassName: String?
): DeserializationStrategy<out T>? = decoder.serializersModule.getPolymorphic(baseClass, klassName)
/**
* Lookups an actual serializer for given [value] within the current [base class][baseClass].
* May use context from the [encoder].
*/
@InternalSerializationApi
public open fun findPolymorphicSerializerOrNull(
encoder: Encoder,
value: T
): SerializationStrategy<T>? =
encoder.serializersModule.getPolymorphic(baseClass, value)
}
@JvmName("throwSubtypeNotRegistered")
internal fun throwSubtypeNotRegistered(subClassName: String?, baseClass: KClass<*>): Nothing {
val scope = "in the scope of '${baseClass.simpleName}'"
throw SerializationException(
if (subClassName == null)
"Class discriminator was missing and no default polymorphic serializers were registered $scope"
else
"Class '$subClassName' is not registered for polymorphic serialization $scope.\n" +
"Mark the base class as 'sealed' or register the serializer explicitly."
)
}
@JvmName("throwSubtypeNotRegistered")
internal fun throwSubtypeNotRegistered(subClass: KClass<*>, baseClass: KClass<*>): Nothing =
throwSubtypeNotRegistered(subClass.simpleName ?: "$subClass", baseClass)
| apache-2.0 | b6bce3752afc4a4405ee1fd295493ab2 | 42.00885 | 122 | 0.677366 | 5.175719 | false | false | false | false |
devmil/PaperLaunch | app/src/main/java/de/devmil/paperlaunch/utils/RectEvaluator.kt | 1 | 1322 | /*
* Copyright 2015 Devmil Solutions
*
* 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 de.devmil.paperlaunch.utils
import android.animation.IntEvaluator
import android.animation.TypeEvaluator
import android.graphics.Rect
open class RectEvaluator : TypeEvaluator<Rect> {
override fun evaluate(fraction: Float, startValue: Rect, endValue: Rect): Rect {
val intEvaluator = IntEvaluator()
val left = intEvaluator.evaluate(fraction, startValue.left, endValue.left)!!
val top = intEvaluator.evaluate(fraction, startValue.top, endValue.top)!!
val right = intEvaluator.evaluate(fraction, startValue.right, endValue.right)!!
val bottom = intEvaluator.evaluate(fraction, startValue.bottom, endValue.bottom)!!
return Rect(left, top, right, bottom)
}
}
| apache-2.0 | 3560ad5e59d9ee48651fb9acf7e2a139 | 39.060606 | 90 | 0.737519 | 4.223642 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/compiler/cflat/CData.kt | 1 | 1382 | package net.torvald.terranvm.runtime.compiler.cflat
/**
* Created by minjaesong on 2017-06-15.
*/
abstract class CData(val name: String) {
abstract fun sizeOf(): Int
}
class CStruct(name: String, val identifier: String): CData(name) {
val members = ArrayList<CData>()
fun addMember(member: CData) {
members.add(member)
}
override fun sizeOf(): Int {
return members.map { it.sizeOf() }.sum()
}
override fun toString(): String {
val sb = StringBuilder()
sb.append("Struct $name: ")
members.forEachIndexed { index, cData ->
if (cData is CPrimitive) {
sb.append(cData.type)
sb.append(' ')
sb.append(cData.name)
}
else if (cData is CStruct) {
sb.append(cData.identifier)
sb.append(' ')
sb.append(cData.name)
}
else throw IllegalArgumentException("Unknown CData extension: ${cData.javaClass.simpleName}")
}
return sb.toString()
}
}
class CPrimitive(name: String, val type: Cflat.ReturnType, val value: Any?, val derefDepth: Int = 0): CData(name) {
override fun sizeOf(): Int {
var typestr = type.toString()
if (typestr.endsWith("_PTR")) typestr = typestr.drop(4)
return Cflat.sizeofPrimitive(typestr)
}
} | mit | 241f94bbe33c3005b9c8b90604c3d7d6 | 28.425532 | 115 | 0.577424 | 3.892958 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/ui/views/SearchTermsView.kt | 1 | 2183 | package com.duopoints.android.ui.views
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.duopoints.android.utils.UiUtils
import com.google.android.flexbox.*
class SearchTermsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FlexboxLayout(context, attrs, defStyleAttr) {
private var clickListener: SearchTermClick? = null
init {
flexDirection = FlexDirection.ROW
flexWrap = FlexWrap.WRAP
justifyContent = JustifyContent.CENTER
alignItems = AlignItems.FLEX_START
alignContent = AlignContent.FLEX_START
}
fun setClickListener(clickListener: SearchTermClick?) {
this.clickListener = clickListener
}
fun addTerms(terms: List<String>) {
for (term in terms) {
val newTerm = ActionButton(context, actionable = true)
val margin = UiUtils.convertDpToPixel(6f).toInt()
val layoutParams = FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.setMargins(margin, margin, margin, margin)
newTerm.layoutParams = layoutParams
newTerm.minWidth = UiUtils.convertDpToPixel(60f).toInt()
newTerm.setPadding(UiUtils.convertDpToPixel(14f).toInt(), UiUtils.convertDpToPixel(8f).toInt(), UiUtils.convertDpToPixel(14f).toInt(), UiUtils.convertDpToPixel(8f).toInt())
newTerm.textAlignment = View.TEXT_ALIGNMENT_CENTER
newTerm.setTextColor(Color.WHITE)
newTerm.text = term
newTerm.setOnClickListener { view ->
val button = view as? Button
if (clickListener != null && button != null && !TextUtils.isEmpty(button.text)) {
clickListener!!.clickedSearchTerm(button.text.toString())
}
}
addView(newTerm)
}
}
interface SearchTermClick {
fun clickedSearchTerm(searchTerm: String)
}
}
| gpl-3.0 | cd95843727b872004240bff4930a5cf2 | 36 | 184 | 0.677966 | 4.63482 | false | false | false | false |
cout970/Statistics | src/main/kotlin/com/cout970/statistics/tileentity/TileInventoryDetector.kt | 1 | 3677 | package com.cout970.statistics.tileentity
import com.cout970.statistics.data.ItemIdentifier
import com.cout970.statistics.data.identifier
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.ITickable
/**
* Created by cout970 on 05/08/2016.
*/
class TileInventoryDetector : TileBase(), ITickable {
var items = mutableMapOf<ItemIdentifier, Int>()
private var redstoneLevel = 0
var limit = 0
var operation = Operation.DIFFERENT
var itemCache: ItemIdentifier? = null
//client only
var active = false
var amount = -1
fun getItem(index: Int): ItemIdentifier? {
val keys = items.keys.sortedBy { it.stack.item.registryName.toString() }
if (index in keys.indices) {
return keys[index]
}
return null
}
override fun receiveMsg(id: Int, value: Int) {
if (id == 0) {
limit = value
} else if (id == 1) {
operation = Operation.values()[value % Operation.values().size]
} else if (id == 2) {
val key = getItem(value)
if (key != null) {
amount = items[key]!!
itemCache = key
} else {
amount = 0
itemCache = null
}
}
}
override fun update() {
if (worldObj.isRemote) return
if ((worldObj.totalWorldTime + pos.hashCode()) % 20 == 0L) {
items.clear()
for (s in getStacks()) {
val id = s.identifier
if (id in items) {
items[id] = items[id]!! + s.stackSize
} else {
items.put(id, s.stackSize)
}
}
val key = itemCache
if (key != null && key in items) {
amount = items[key]!!
} else {
amount = 0
}
if (operation.func(amount, limit)) {
redstoneLevel = 15
} else {
redstoneLevel = 0
}
markDirty()
worldObj.notifyNeighborsOfStateChange(pos, getBlockType())
}
}
fun getRedstoneLevel(): Int {
return redstoneLevel
}
override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound {
compound.setTag("Cache", itemCache?.serializeNBT() ?: NBTTagCompound())
compound.setInteger("Operation", operation.ordinal)
compound.setInteger("Limit", limit)
return super.writeToNBT(compound)
}
override fun readFromNBT(compound: NBTTagCompound) {
if (compound.hasKey("Cache")) {
if (!compound.getCompoundTag("Cache").hasNoTags()) {
itemCache = ItemIdentifier.deserializeNBT(compound.getCompoundTag("Cache"))
} else {
itemCache = null
}
}
if (compound.hasKey("Limit")) {
limit = compound.getInteger("Limit")
}
if (compound.hasKey("Operation")) {
operation = Operation.values()[compound.getInteger("Operation")]
}
super.readFromNBT(compound)
}
enum class Operation(val func: (value: Int, limit: Int) -> Boolean, val text: String) {
EQUALS({ value, limit -> value == limit }, "="),
GREATER({ value, limit -> value > limit }, ">"),
GREATER_EQUALS({ value, limit -> value >= limit }, ">="),
LESS({ value, limit -> value < limit }, "<"),
LESS_EQUALS({ value, limit -> value <= limit }, "<="),
DIFFERENT({ value, limit -> value != limit }, "!=");
override fun toString(): String {
return text
}
}
} | gpl-3.0 | 3b2da55ffb2847b6c11bd720c98528e6 | 30.169492 | 91 | 0.530868 | 4.573383 | false | false | false | false |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/repo/internals/migrations/Migration25to26.kt | 1 | 1107 | package voice.data.repo.internals.migrations
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.squareup.anvil.annotations.ContributesMultibinding
import org.json.JSONObject
import voice.common.AppScope
import javax.inject.Inject
@ContributesMultibinding(
scope = AppScope::class,
boundType = Migration::class,
)
class Migration25to26
@Inject constructor() : IncrementalMigration(25) {
override fun migrate(db: SupportSQLiteDatabase) {
// get all books
val cursor = db.query(
"TABLE_BOOK",
arrayOf("BOOK_ID", "BOOK_JSON"),
)
val allBooks = ArrayList<JSONObject>(cursor.count)
cursor.use {
while (it.moveToNext()) {
val content = it.getString(1)
val book = JSONObject(content)
book.put("id", it.getLong(0))
allBooks.add(book)
}
}
// delete empty books
for (b in allBooks) {
val chapters = b.getJSONArray("chapters")
if (chapters.length() == 0) {
db.delete("TABLE_BOOK", "BOOK_ID" + "=?", arrayOf(b.get("id").toString()))
}
}
}
}
| gpl-3.0 | 93974a41d75321c6d0726d533eae9392 | 26 | 82 | 0.66486 | 3.925532 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/utils/EditTextExtensions.kt | 1 | 1727 | package com.quickblox.sample.conference.kotlin.presentation.utils
import android.util.Patterns
import android.widget.EditText
import java.util.regex.Pattern
private const val MAX_LOGIN_LENGTH = 50
private const val MAX_FULL_NAME_LENGTH = 20
private const val MIN_DIALOG_NAME_LENGTH = 3
private const val MAX_DIALOG_NAME_LENGTH = 20
private const val ONE_SPACE = "\\s{2,}"
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
fun EditText.isValidLogin(): Boolean {
var isCorrect = false
val patternLogin = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]{2," + (MAX_LOGIN_LENGTH - 1) + "}+$")
val patternEmail = Patterns.EMAIL_ADDRESS
val matcherLogin = patternLogin.matcher(this.text.toString().trim { it <= ' ' })
val matcherEmail = patternEmail.matcher(this.text.toString().trim { it <= ' ' })
if (matcherLogin.matches() || matcherEmail.matches() && this.text.toString().trim { it <= ' ' }.length < MAX_LOGIN_LENGTH) {
isCorrect = true
}
return isCorrect
}
fun EditText.isValidName(): Boolean {
var isCorrect = false
val patternUsername = Pattern.compile("^[a-zA-Z][a-zA-Z 0-9]{2," + (MAX_FULL_NAME_LENGTH - 1) + "}+$")
val matcherUserName = patternUsername.matcher(this.text.toString().trim { it <= ' ' })
if (matcherUserName.matches()) {
isCorrect = true
}
return isCorrect
}
fun EditText?.isValidChatName(): Boolean {
var isCorrect = false
val string: String = this?.text.toString().trim { it <= ' ' }
if (string.length in MIN_DIALOG_NAME_LENGTH..MAX_DIALOG_NAME_LENGTH) {
isCorrect = true
}
return isCorrect
}
fun String.oneSpace(): String = this.replace(ONE_SPACE.toRegex(), " ") | bsd-3-clause | 18d5398610e39d8cc54d98a2a003f16f | 32.862745 | 128 | 0.671495 | 3.588358 | false | false | false | false |
cmelchior/realmfieldnameshelper | library/src/main/kotlin/dk/ilios/realmfieldnames/RealmFieldNamesProcessor.kt | 1 | 7727 | package dk.ilios.realmfieldnames
import java.util.*
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.annotation.processing.SupportedAnnotationTypes
import javax.lang.model.SourceVersion
import javax.lang.model.element.*
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic
/**
* The Realm Field Names Generator is a processor that looks at all available Realm model classes
* and create an companion class with easy, type-safe access to all field names.
*/
@SupportedAnnotationTypes("io.realm.annotations.RealmClass")
class RealmFieldNamesProcessor : AbstractProcessor() {
private val classes = HashSet<ClassData>()
lateinit private var typeUtils: Types
lateinit private var messager: Messager
lateinit private var elementUtils: Elements
private var ignoreAnnotation: TypeMirror? = null
private var realmClassAnnotation: TypeElement? = null
private var realmModelInterface: TypeMirror? = null
private var realmListClass: DeclaredType? = null
private var realmResultsClass: DeclaredType? = null
private var fileGenerator: FileGenerator? = null
private var done = false
@Synchronized override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
typeUtils = processingEnv.typeUtils!!
messager = processingEnv.messager!!
elementUtils = processingEnv.elementUtils!!
// If the Realm class isn't found something is wrong the project setup.
// Most likely Realm isn't on the class path, so just disable the
// annotation processor
val isRealmAvailable = elementUtils.getTypeElement("io.realm.Realm") != null
if (!isRealmAvailable) {
done = true
} else {
ignoreAnnotation = elementUtils.getTypeElement("io.realm.annotations.Ignore")?.asType()
realmClassAnnotation = elementUtils.getTypeElement("io.realm.annotations.RealmClass")
realmModelInterface = elementUtils.getTypeElement("io.realm.RealmModel")?.asType()
realmListClass = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmList"),
typeUtils.getWildcardType(null, null))
realmResultsClass = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmResults"),
typeUtils.getWildcardType(null, null))
fileGenerator = FileGenerator(processingEnv.filer)
}
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latestSupported()
}
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
if (done) {
return CONSUME_ANNOTATIONS
}
// Create all proxy classes
roundEnv.getElementsAnnotatedWith(realmClassAnnotation).forEach { classElement ->
if (typeUtils.isAssignable(classElement.asType(), realmModelInterface)) {
val classData = processClass(classElement as TypeElement)
classes.add(classData)
}
}
// If a model class references a library class, the library class will not be part of this
// annotation processor round. For all those references we need to pull field information
// from the classpath instead.
val libraryClasses = HashMap<String, ClassData>()
classes.forEach {
it.fields.forEach { _, value ->
// Analyze the library class file the first time it is encountered.
if (value != null ) {
if (classes.all{ it.qualifiedClassName != value } && !libraryClasses.containsKey(value)) {
libraryClasses.put(value, processLibraryClass(value))
}
}
}
}
classes.addAll(libraryClasses.values)
done = fileGenerator!!.generate(classes)
return CONSUME_ANNOTATIONS
}
private fun processClass(classElement: TypeElement): ClassData {
val packageName = getPackageName(classElement)
val className = classElement.simpleName.toString()
val data = ClassData(packageName, className)
// Find all appropriate fields
classElement.enclosedElements.forEach {
val elementKind = it.kind
if (elementKind == ElementKind.FIELD) {
val variableElement = it as VariableElement
val modifiers = variableElement.modifiers
if (modifiers.contains(Modifier.STATIC)) {
return@forEach // completely ignore any static fields
}
// Don't add any fields marked with @Ignore
val ignoreField = variableElement.annotationMirrors
.map { it.annotationType.toString() }
.contains("io.realm.annotations.Ignore")
if (!ignoreField) {
data.addField(it.getSimpleName().toString(), getLinkedFieldType(it))
}
}
}
return data
}
private fun processLibraryClass(qualifiedClassName: String): ClassData {
val libraryClass = Class.forName(qualifiedClassName) // Library classes should be on the classpath
val packageName = libraryClass.`package`.name
val className = libraryClass.simpleName
val data = ClassData(packageName, className, libraryClass = true)
libraryClass.declaredFields.forEach { field ->
if (java.lang.reflect.Modifier.isStatic(field.modifiers)) {
return@forEach // completely ignore any static fields
}
// Add field if it is not being ignored.
if (field.annotations.all { it.toString() != "io.realm.annotations.Ignore" }) {
data.addField(field.name, field.type.name)
}
}
return data
}
/**
* Returns the qualified name of the linked Realm class field or `null` if it is not a linked
* class.
*/
private fun getLinkedFieldType(field: Element): String? {
if (typeUtils.isAssignable(field.asType(), realmModelInterface)) {
// Object link
val typeElement = elementUtils.getTypeElement(field.asType().toString())
return typeElement.qualifiedName.toString()
} else if (typeUtils.isAssignable(field.asType(), realmListClass) || typeUtils.isAssignable(field.asType(), realmResultsClass)) {
// List link or LinkingObjects
val fieldType = field.asType()
val typeArguments = (fieldType as DeclaredType).typeArguments
if (typeArguments.size == 0) {
return null
}
return typeArguments[0].toString()
} else {
return null
}
}
private fun getPackageName(classElement: TypeElement): String? {
val enclosingElement = classElement.enclosingElement
if (enclosingElement.kind != ElementKind.PACKAGE) {
messager.printMessage(Diagnostic.Kind.ERROR,
"Could not determine the package name. Enclosing element was: " + enclosingElement.kind)
return null
}
val packageElement = enclosingElement as PackageElement
return packageElement.qualifiedName.toString()
}
companion object {
private const val CONSUME_ANNOTATIONS = false
}
}
| apache-2.0 | d25755a3b7aeddf5f00203d146359e42 | 40.320856 | 137 | 0.655494 | 5.43772 | false | false | false | false |
edvin/tornadofx-samples | login/src/main/kotlin/no/tornado/fxsample/login/SecureScreen.kt | 1 | 1220 | package no.tornado.fxsample.login
import javafx.application.Platform
import javafx.geometry.Pos
import javafx.scene.text.Font
import tornadofx.*
class SecureScreen : View(screenTitle) {
private val loginController: LoginController by inject()
override val root = borderpane {
setPrefSize(800.0, 600.0)
top {
label(title) {
font = Font.font(22.0)
}
}
center {
vbox(spacing = 15) {
alignment = Pos.CENTER
label("If you can see this, you are successfully logged in!")
hbox {
alignment = Pos.CENTER
button(logoutLabel) {
setOnAction {
loginController.logout()
}
}
button(exitLabel) {
setOnAction {
Platform.exit()
}
}
}
}
}
}
companion object {
const val screenTitle = "Secure Screen"
const val exitLabel = "Exit"
const val logoutLabel = "Logout"
}
} | apache-2.0 | e4052dc477c805591574ae0418324e91 | 23.42 | 77 | 0.458197 | 5.39823 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/InputValueDefinition.kt | 1 | 1322 | package graphql.language
import java.util.ArrayList
class InputValueDefinition (val name: String,
var type: Type? = null,
defaultValue: Value? = null) : AbstractNode() {
var defaultValue: Value? = null
private set
val directives: MutableList<Directive> = ArrayList()
init {
this.defaultValue = defaultValue
}
fun setValue(defaultValue: Value) {
this.defaultValue = defaultValue
}
override val children: List<Node>
get() {
val result = ArrayList<Node>()
type?.let { result.add(it) }
defaultValue?.let { result.add(it) }
result.addAll(directives)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as InputValueDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "InputValueDefinition{" +
"name='" + name + '\'' +
", type=" + type +
", defaultValue=" + defaultValue +
", directives=" + directives +
'}'
}
}
| mit | 1c4a24bdf4dbf1421ae33eca42c48767 | 24.921569 | 75 | 0.524962 | 5.065134 | false | false | false | false |
is00hcw/anko | dsl/static/src/common/Async.kt | 2 | 3968 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmMultifileClass
@file:JvmName("AsyncKt")
package org.jetbrains.anko
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Handler
import android.os.Looper
import org.jetbrains.anko.internals.NoBinding
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
@Deprecated("Use onUiThread() instead", ReplaceWith("onUiThread(f)"))
@NoBinding
public fun Context.uiThread(f: Context.() -> Unit) {
if (ContextHelper.mainThread == Thread.currentThread()) f() else ContextHelper.handler.post { f() }
}
@Deprecated("Use onUiThread() instead", ReplaceWith("onUiThread(f)"))
@NoBinding
public inline fun Fragment.uiThread(@inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: () -> Unit) {
activity?.onUiThread { f() }
}
// Fragment.uiThread() has a different argument list (because of inline)
@NoBinding
public fun Context.onUiThread(f: Context.() -> Unit) {
if (ContextHelper.mainThread == Thread.currentThread()) f() else ContextHelper.handler.post { f() }
}
@NoBinding
public inline fun Fragment.onUiThread(@inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: () -> Unit) {
activity?.onUiThread { f() }
}
public class AnkoAsyncContext<T>(val weakRef: WeakReference<T>)
public fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit) {
val ref = weakRef.get() ?: return
if (ContextHelper.mainThread == Thread.currentThread()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
}
public fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit) {
val activity = weakRef.get() ?: return
if (activity.isFinishing) return
activity.runOnUiThread { f(activity) }
}
public fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit) {
val fragment = weakRef.get() ?: return
if (fragment.isDetached) return
val activity = fragment.getActivity() ?: return
activity.runOnUiThread { f(fragment) }
}
public fun <T> T.async(task: AnkoAsyncContext<T>.() -> Unit): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit { context.task() }
}
public fun <T> T.async(executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> Unit): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<Unit> { context.task() }
}
public fun <T, R> T.asyncResult(task: AnkoAsyncContext<T>.() -> R): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit { context.task() }
}
public fun <T, R> T.asyncResult(executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> R): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<R> { context.task() }
}
object BackgroundExecutor {
var executor: ExecutorService =
Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors())
fun execute(task: () -> Unit): Future<Unit> {
return executor.submit<Unit> { task() }
}
fun <T> submit(task: () -> T): Future<T> {
return executor.submit(task)
}
}
private object ContextHelper {
val handler = Handler(Looper.getMainLooper())
val mainThread = Looper.getMainLooper().thread
} | apache-2.0 | 0ea365a4e93e829104afcd700cbe8313 | 33.215517 | 113 | 0.714718 | 3.964036 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/cardstack/tools/RxAdapterUpDownAnimator.kt | 1 | 2676 | package com.tamsiree.rxui.view.cardstack.tools
import android.animation.ObjectAnimator
import android.view.View
import com.tamsiree.rxui.view.cardstack.RxCardStackView
/**
* @author tamsiree
* @date 2018/6/11 11:36:40 整合修改
*/
class RxAdapterUpDownAnimator(rxCardStackView: RxCardStackView) : RxAdapterAnimator(rxCardStackView) {
override fun itemExpandAnimatorSet(viewHolder: RxCardStackView.ViewHolder, position: Int) {
val itemView = viewHolder.itemView
itemView.clearAnimation()
val oa = ObjectAnimator.ofFloat(itemView, View.Y, itemView.y, mRxCardStackView.scrollY + mRxCardStackView.paddingTop.toFloat())
mSet!!.play(oa)
var collapseShowItemCount = 0
for (i in 0 until mRxCardStackView.childCount) {
var childTop: Int
if (i == mRxCardStackView.selectPosition) {
continue
}
val child = mRxCardStackView.getChildAt(i)
child.clearAnimation()
if (i > mRxCardStackView.selectPosition && collapseShowItemCount < mRxCardStackView.numBottomShow) {
childTop = mRxCardStackView.showHeight - getCollapseStartTop(collapseShowItemCount) + mRxCardStackView.scrollY
val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, childTop.toFloat())
mSet!!.play(oAnim)
collapseShowItemCount++
} else if (i < mRxCardStackView.selectPosition) {
val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, mRxCardStackView.scrollY - child.height.toFloat())
mSet!!.play(oAnim)
} else {
val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, mRxCardStackView.showHeight + mRxCardStackView.scrollY.toFloat())
mSet!!.play(oAnim)
}
}
}
override fun itemCollapseAnimatorSet(viewHolder: RxCardStackView.ViewHolder) {
var childTop = mRxCardStackView.paddingTop
for (i in 0 until mRxCardStackView.childCount) {
val child = mRxCardStackView.getChildAt(i)
child.clearAnimation()
val lp = child.layoutParams as RxCardStackView.LayoutParams
childTop += lp.topMargin
if (i != 0) {
childTop -= mRxCardStackView.overlapGaps * 2
val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, childTop.toFloat())
mSet!!.play(oAnim)
} else {
val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, childTop.toFloat())
mSet!!.play(oAnim)
}
childTop += lp.mHeaderHeight
}
}
} | apache-2.0 | 5bd35720bea6859aa04a5fa65e55606a | 45.017241 | 140 | 0.635307 | 4.241653 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/media/GifPageFragment.kt | 1 | 3143 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.media
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.layout_media_viewer_gif.*
import org.mariotaku.mediaviewer.library.CacheDownloadLoader
import org.mariotaku.mediaviewer.library.CacheDownloadMediaViewerFragment
import org.mariotaku.mediaviewer.library.subsampleimageview.SubsampleImageViewerFragment
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.EXTRA_ACCOUNT_KEY
import de.vanita5.twittnuker.TwittnukerConstants.EXTRA_MEDIA
import de.vanita5.twittnuker.activity.MediaViewerActivity
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.UserKey
import pl.droidsonroids.gif.InputSource
class GifPageFragment : CacheDownloadMediaViewerFragment() {
private val media: ParcelableMedia
get() = arguments.getParcelable(EXTRA_MEDIA)
private val accountKey: UserKey
get() = arguments.getParcelable(EXTRA_ACCOUNT_KEY)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
gifView.setOnClickListener { (activity as MediaViewerActivity).toggleBar() }
startLoading(false)
}
override fun getDownloadUri(): Uri? {
return arguments.getParcelable(SubsampleImageViewerFragment.EXTRA_MEDIA_URI)
}
override fun getDownloadExtra(): Any? {
return null
}
override fun displayMedia(result: CacheDownloadLoader.Result) {
val context = context ?: return
val cacheUri = result.cacheUri
if (cacheUri != null) {
gifView.setInputSource(InputSource.UriSource(context.contentResolver, cacheUri))
} else {
gifView.setInputSource(null)
}
}
override fun isAbleToLoad(): Boolean {
return downloadUri != null
}
override fun onCreateMediaView(inflater: LayoutInflater, parent: ViewGroup, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.layout_media_viewer_gif, parent, false)
}
override fun releaseMediaResources() {
gifView?.setInputSource(null)
}
} | gpl-3.0 | a5265c6ec763b99a1c34b8d91f71b532 | 35.55814 | 116 | 0.746102 | 4.383543 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/di/AppHttpClientImpl.kt | 1 | 1556 | package org.softeg.slartus.forpdaplus.di
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.softeg.slartus.forpdaplus.core.services.AppHttpClient
import ru.slartus.http.Http
import javax.inject.Inject
class AppHttpClientImpl @Inject constructor() : AppHttpClient {
override suspend fun performGet(url: String): String = withContext(Dispatchers.IO) {
return@withContext Http.instance.performGet(url).responseBody
}
override suspend fun performGetDesktopVersion(url: String): String =
withContext(Dispatchers.IO) {
return@withContext Http.instance.performGetFull(url).responseBody
}
override suspend fun performPost(url: String, headers: Map<String, String>): String =
withContext(Dispatchers.IO) {
return@withContext Http.instance.performPost(
url,
headers.map { androidx.core.util.Pair(it.key, it.value) }
).responseBody
}
override suspend fun uploadFile(
url: String,
filePath: String,
fileName: String,
onProgressChange: (percents: Int) -> Unit
): String =
withContext(Dispatchers.IO)
{
return@withContext Http.instance.uploadFile(
url = url,
filePath = filePath,
fileNameO = fileName,
formDataParts = emptyList(),
progressListener = {
onProgressChange(it.toInt())
}
).responseBody
}
} | apache-2.0 | 8d72f9f1180031d5a187d478065f7b10 | 33.6 | 89 | 0.631105 | 4.955414 | false | false | false | false |
robohorse/gpversionchecker | gpversionchecker/src/main/kotlin/com/robohorse/gpversionchecker/manager/UIManager.kt | 1 | 2135 | package com.robohorse.gpversionchecker.manager
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.robohorse.gpversionchecker.R
import com.robohorse.gpversionchecker.domain.Version
class UIManager {
fun showInfoView(activity: Activity, version: Version) {
activity.runOnUiThread { showDialogOnUIThread(activity, version) }
}
private fun showDialogOnUIThread(context: Context, version: Version) {
val inflater = context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view: View = inflater.inflate(R.layout.gpvch_layout_dialog, null)
bindVersionData(view, version, context)
val dialog: AlertDialog = AlertDialog.Builder(context)
.setTitle(R.string.gpvch_header)
.setView(view)
.setPositiveButton(R.string.gpvch_button_positive, { _, _ -> openGooglePlay(context) })
.setNegativeButton(R.string.gpvch_button_negative, null)
.create()
dialog.show()
}
private fun bindVersionData(view: View, version: Version, context: Context) {
val tvVersion = view.findViewById<View>(R.id.tvVersionCode) as TextView
tvVersion.text = "${context.getString(R.string.app_name)}:${version.newVersionCode}"
val tvNews = view.findViewById<View>(R.id.tvChanges) as TextView
val lastChanges = version.changes
if (!TextUtils.isEmpty(lastChanges)) {
tvNews.text = lastChanges
} else {
view.findViewById<View>(R.id.lnChangesInfo).visibility = View.GONE
}
}
private fun openGooglePlay(context: Context) {
val packageName = context.applicationContext.packageName
val url = context.getString(R.string.gpvch_google_play_url) + packageName
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(intent)
}
}
| mit | 7ccaa28b8a1a436c00b7a85675b57592 | 40.057692 | 103 | 0.694614 | 4.252988 | false | false | false | false |
AndroidX/androidx | paging/paging-common/src/test/kotlin/androidx/paging/GarbageCollectionTestHelper.kt | 3 | 2810 | /*
* 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.paging
import com.google.common.truth.Truth.assertWithMessage
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread
import kotlin.reflect.KClass
internal class GarbageCollectionTestHelper {
private val queue = ReferenceQueue<Any>()
private val references = mutableListOf<WeakReference<Any>>()
private var size = 0
fun track(item: Any) {
references.add(WeakReference(item, queue))
size++
}
fun assertLiveObjects(
vararg expected: Pair<KClass<*>, Int>
) {
val continueTriggeringGc = AtomicBoolean(true)
thread {
val leak: ArrayList<ByteArray> = ArrayList()
do {
val arraySize = (Math.random() * 1000).toInt()
leak.add(ByteArray(arraySize))
System.gc()
} while (continueTriggeringGc.get())
}
var collectedItemCount = 0
val expectedItemCount = size - expected.sumOf { it.second }
while (collectedItemCount < expectedItemCount &&
queue.remove(TimeUnit.SECONDS.toMillis(10)) != null
) {
collectedItemCount++
}
continueTriggeringGc.set(false)
val leakedObjects = countLiveObjects()
val leakedObjectToStrings = references.mapNotNull {
it.get()
}.joinToString("\n")
assertWithMessage(
"""
expected to collect $expectedItemCount, collected $collectedItemCount.
live objects: $leakedObjectToStrings
""".trimIndent()
).that(leakedObjects).containsExactlyElementsIn(expected)
}
/**
* Tries to trigger garbage collection until an element is available in the given queue.
*/
fun assertEverythingIsCollected() {
assertLiveObjects()
}
private fun countLiveObjects(): List<Pair<KClass<*>, Int>> {
return references.mapNotNull {
it.get()
}.groupBy {
it::class
}.map { entry ->
entry.key to entry.value.size
}
}
} | apache-2.0 | 130137bd0c2673fd56753876375a9202 | 32.070588 | 92 | 0.647687 | 4.746622 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerRootHelper.kt | 2 | 4721 | package versioned.host.exp.exponent.modules.api.components.gesturehandler.react
import android.os.SystemClock
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.ViewParent
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.common.ReactConstants
import com.facebook.react.uimanager.RootView
import versioned.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler
import versioned.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator
class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: ViewGroup) {
private val orchestrator: GestureHandlerOrchestrator?
private val jsGestureHandler: GestureHandler<*>?
val rootView: ViewGroup
private var shouldIntercept = false
private var passingTouch = false
init {
UiThreadUtil.assertOnUiThread()
val wrappedViewTag = wrappedView.id
check(wrappedViewTag >= 1) { "Expect view tag to be set for $wrappedView" }
val module = context.getNativeModule(RNGestureHandlerModule::class.java)!!
val registry = module.registry
rootView = findRootViewTag(wrappedView)
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Initialize gesture handler for root view $rootView"
)
orchestrator = GestureHandlerOrchestrator(
wrappedView, registry, RNViewConfigurationHelper()
).apply {
minimumAlphaForTraversal = MIN_ALPHA_FOR_TOUCH
}
jsGestureHandler = RootViewGestureHandler().apply { tag = -wrappedViewTag }
with(registry) {
registerHandler(jsGestureHandler)
attachHandlerToView(jsGestureHandler.tag, wrappedViewTag)
}
module.registerRootHelper(this)
}
fun tearDown() {
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView"
)
val module = context.getNativeModule(RNGestureHandlerModule::class.java)!!
with(module) {
registry.dropHandler(jsGestureHandler!!.tag)
unregisterRootHelper(this@RNGestureHandlerRootHelper)
}
}
private inner class RootViewGestureHandler : GestureHandler<RootViewGestureHandler>() {
override fun onHandle(event: MotionEvent) {
val currentState = state
if (currentState == STATE_UNDETERMINED) {
begin()
shouldIntercept = false
}
if (event.actionMasked == MotionEvent.ACTION_UP) {
end()
}
}
override fun onCancel() {
shouldIntercept = true
val time = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
action = MotionEvent.ACTION_CANCEL
}
if (rootView is RootView) {
rootView.onChildStartedNativeGesture(event)
}
}
}
fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
// If this method gets called it means that some native view is attempting to grab lock for
// touch event delivery. In that case we cancel all gesture recognizers
if (orchestrator != null && !passingTouch) {
// if we are in the process of delivering touch events via GH orchestrator, we don't want to
// treat it as a native gesture capturing the lock
tryCancelAllHandlers()
}
}
fun dispatchTouchEvent(ev: MotionEvent): Boolean {
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
// if `requestDisallow` has been called as a result of a normal gesture handling process or
// as a result of one of the gesture handlers activating
passingTouch = true
orchestrator!!.onTouchEvent(ev)
passingTouch = false
return shouldIntercept
}
private fun tryCancelAllHandlers() {
// In order to cancel handlers we activate handler that is hooked to the root view
jsGestureHandler?.apply {
if (state == GestureHandler.STATE_BEGAN) {
// Try activate main JS handler
activate()
end()
}
}
}
/*package*/
fun handleSetJSResponder(viewTag: Int, blockNativeResponder: Boolean) {
if (blockNativeResponder) {
UiThreadUtil.runOnUiThread { tryCancelAllHandlers() }
}
}
companion object {
private const val MIN_ALPHA_FOR_TOUCH = 0.1f
private fun findRootViewTag(viewGroup: ViewGroup): ViewGroup {
UiThreadUtil.assertOnUiThread()
var parent: ViewParent? = viewGroup
while (parent != null && parent !is RootView) {
parent = parent.parent
}
checkNotNull(parent) {
"View $viewGroup has not been mounted under ReactRootView"
}
return parent as ViewGroup
}
}
}
| bsd-3-clause | 41bf955f50e39282ee583fdf3d88fd29 | 34.231343 | 99 | 0.715526 | 4.579049 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/layers/SlotGridLayer.kt | 1 | 2003 | package com.teamwizardry.librarianlib.facade.container.layers
import com.teamwizardry.librarianlib.facade.container.slot.SlotRegion
import com.teamwizardry.librarianlib.facade.layer.GuiLayer
import com.teamwizardry.librarianlib.facade.value.RMValueInt
import com.teamwizardry.librarianlib.math.ceilInt
import com.teamwizardry.librarianlib.core.util.vec
public class SlotGridLayer @JvmOverloads constructor(
posX: Int,
posY: Int,
public val region: SlotRegion,
columns: Int,
showBackground: Boolean = true,
padding: Int = 0
): GuiLayer(posX, posY) {
public val columns_rm: RMValueInt = rmInt(columns) { _, _ -> markLayoutDirty() }
public var columns: Int by columns_rm
public val padding_rm: RMValueInt = rmInt(padding) { _, _ -> markLayoutDirty() }
public var padding: Int by padding_rm
// the margin around all sides of a slot, distinct from the padding, which is only *between* slots
private var slotMargin: Int = if(showBackground) 1 else 0
private val slots = region.map {
SlotLayer(it, 0, 0, showBackground)
}
init {
slots.forEach {
add(it)
}
val rows = ceilInt(slots.size / columns.toDouble())
this.size = vec(
columns * 16 + (columns - 1) * padding + columns * 2 * slotMargin,
rows * 16 + (rows - 1) * padding + rows * 2 * slotMargin
)
}
override fun layoutChildren() {
val rows = ceilInt(slots.size / columns.toDouble())
this.size = vec(
columns * 16 + (columns - 1) * padding + columns * 2 * slotMargin,
rows * 16 + (rows - 1) * padding + rows * 2 * slotMargin
)
slots.forEachIndexed { i, slot ->
val column = i % columns
val row = i / columns
slot.pos = vec(
slotMargin + column * (16 + padding) + column * 2 * slotMargin,
slotMargin + row * (16 + padding) + row * 2 * slotMargin
)
}
}
} | lgpl-3.0 | 2048792fa998e6cbe278756ea688dd82 | 35.436364 | 102 | 0.617574 | 4.038306 | false | false | false | false |
rwinch/spring-security | config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/FrameOptionsDslTests.kt | 1 | 5987 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.headers
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.invoke
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter
import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
/**
* Tests for [FrameOptionsDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class FrameOptionsDslTests {
@JvmField
val spring = SpringTestContext(this)
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `headers when frame options configured then frame options deny header`() {
this.spring.register(FrameOptionsConfig::class.java).autowire()
this.mockMvc.get("/") {
secure = true
}.andExpect {
header { string(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.name) }
}
}
@EnableWebSecurity
open class FrameOptionsConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
headers {
defaultsDisabled = true
frameOptions { }
}
}
return http.build()
}
}
@Test
fun `headers when frame options deny configured then frame options deny header`() {
this.spring.register(FrameOptionsDenyConfig::class.java).autowire()
this.mockMvc.get("/") {
secure = true
}.andExpect {
header { string(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.name) }
}
}
@EnableWebSecurity
open class FrameOptionsDenyConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
headers {
defaultsDisabled = true
frameOptions {
deny = true
}
}
}
return http.build()
}
}
@Test
fun `headers when frame options same origin configured then frame options same origin header`() {
this.spring.register(FrameOptionsSameOriginConfig::class.java).autowire()
this.mockMvc.get("/") {
secure = true
}.andExpect {
header { string(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN.name) }
}
}
@EnableWebSecurity
open class FrameOptionsSameOriginConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
headers {
defaultsDisabled = true
frameOptions {
sameOrigin = true
}
}
}
return http.build()
}
}
@Test
fun `headers when frame options same origin and deny configured then frame options deny header`() {
this.spring.register(FrameOptionsSameOriginAndDenyConfig::class.java).autowire()
this.mockMvc.get("/") {
secure = true
}.andExpect {
header { string(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.name) }
}
}
@EnableWebSecurity
open class FrameOptionsSameOriginAndDenyConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
headers {
defaultsDisabled = true
frameOptions {
sameOrigin = true
deny = true
}
}
}
return http.build()
}
}
@Test
fun `headers when frame options disabled then no frame options header in response`() {
this.spring.register(FrameOptionsDisabledConfig::class.java).autowire()
this.mockMvc.get("/") {
secure = true
}.andExpect {
header { doesNotExist(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS) }
}
}
@EnableWebSecurity
open class FrameOptionsDisabledConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
headers {
frameOptions {
disable()
}
}
}
return http.build()
}
}
}
| apache-2.0 | 3b3ce5976bb549bf9a9aefb23988c5f7 | 32.446927 | 144 | 0.631368 | 5.355098 | false | true | false | false |
klazuka/intellij-elm | src/test/kotlin/org/elm/workspace/StdlibInstallHelper.kt | 1 | 3912 | package org.elm.workspace
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import org.elm.fileTree
import org.elm.openapiext.pathAsPath
import org.elm.workspace.ElmToolchain.Companion.ELM_JSON
import org.intellij.lang.annotations.Language
import java.nio.file.Path
import java.nio.file.Paths
/*
Some of the Elm tests depend on having certain Elm packages installed in the global location.
And since Elm has pretty poor facilities for installing packages, we have to resort to tricks
like asking it to compile a dummy application.
*/
interface ElmStdlibVariant {
/**
* A description of the packages that we want to be installed
*/
val jsonManifest: String
/**
* Install Elm 0.19 stdlib in the default location ($HOME/.elm)
*/
fun ensureElmStdlibInstalled(project: Project, toolchain: ElmToolchain)
}
object EmptyElmStdlibVariant : ElmStdlibVariant {
override fun ensureElmStdlibInstalled(project: Project, toolchain: ElmToolchain) {
// Don't do anything. The Elm compiler would refuse to use this manifest
// since it's missing `elm/core` and other required packages. Also, it's
// faster if we short-circuit things here rather than invoking the Elm
// compiler in an external process.
}
override val jsonManifest: String
@Language("JSON")
get() = """
{
"type": "application",
"source-directories": [
"."
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {},
"indirect": {}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
""".trimIndent()
}
/**
* Describes a "minimal" installation of the Elm stdlib. This is the bare minimum
* required to compile an Elm application.
*/
object MinimalElmStdlibVariant : ElmStdlibVariant {
override val jsonManifest: String
@Language("JSON")
get() = """
{
"type": "application",
"source-directories": [
"."
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/core": "1.0.0",
"elm/json": "1.0.0"
},
"indirect": {}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
""".trimIndent()
override fun ensureElmStdlibInstalled(project: Project, toolchain: ElmToolchain) {
val elmCLI = toolchain.elmCLI
?: error("Must have a path to the Elm compiler to install Elm stdlib")
val compilerVersion = elmCLI.queryVersion(project).orNull()
?: error("Could not query the Elm compiler version")
require(compilerVersion != Version(0, 18, 0))
// Create the dummy Elm project on-disk (real file system) and invoke the Elm compiler on it.
val onDiskTmpDir = LocalFileSystem.getInstance()
.refreshAndFindFileByIoFile(FileUtil.createTempDirectory("elm-stdlib-variant", null, true))
?: error("Could not create on-disk temp dir for Elm stdlib installation")
fileTree {
project(ELM_JSON, jsonManifest)
elm("Main.elm")
}.create(project, onDiskTmpDir)
val entryPoint: Triple<Path, String?, Int> = Triple(
Paths.get("Main.elm"),
null,
0 // mainEntryPoint.textOffset
)
elmCLI.make(project, onDiskTmpDir.pathAsPath, null, listOf(entryPoint))
}
}
| mit | 336d96892319687fe786840c21ac04a4 | 33.315789 | 107 | 0.566973 | 4.741818 | false | false | false | false |
esofthead/mycollab | mycollab-services/src/main/java/com/mycollab/module/project/service/impl/TicketRelationServiceImpl.kt | 3 | 5547 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.service.impl
import com.mycollab.db.persistence.ICrudGenericDAO
import com.mycollab.db.persistence.service.DefaultCrudService
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.TicketRelationConstants
import com.mycollab.module.project.dao.TicketRelationMapper
import com.mycollab.module.project.dao.TicketRelationMapperExt
import com.mycollab.module.project.domain.*
import com.mycollab.module.project.service.TicketRelationService
import org.springframework.stereotype.Service
/**
* @author MyCollab Ltd.
* @since 1.0
*/
@Service
class TicketRelationServiceImpl(private val ticketRelationMapper: TicketRelationMapper,
private val ticketRelationMapperExt: TicketRelationMapperExt) : DefaultCrudService<Int, TicketRelation>(), TicketRelationService {
override val crudMapper: ICrudGenericDAO<Int, TicketRelation>
get() = ticketRelationMapper as ICrudGenericDAO<Int, TicketRelation>
override fun saveAffectedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
insertAffectedVersionsOfTicket(ticketId, ticketType, versions)
}
private fun insertAffectedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
versions?.forEach {
val relatedItem = TicketRelation()
relatedItem.ticketid = ticketId
relatedItem.tickettype = ticketType
relatedItem.typeid = it.id
relatedItem.type = ProjectTypeConstants.VERSION
relatedItem.rel = TicketRelationConstants.AFF_VERSION
ticketRelationMapper.insert(relatedItem)
}
}
override fun saveFixedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
insertFixedVersionsOfTicket(ticketId, ticketType, versions)
}
private fun insertFixedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
versions?.forEach {
val relatedItem = TicketRelation()
relatedItem.ticketid = ticketId
relatedItem.tickettype = ticketType
relatedItem.typeid = it.id
relatedItem.type = ProjectTypeConstants.VERSION
relatedItem.rel = TicketRelationConstants.FIX_VERSION
ticketRelationMapper.insert(relatedItem)
}
}
override fun saveComponentsOfTicket(ticketId: Int, ticketType: String, components: List<Component>?) {
insertComponentsOfTicket(ticketId, ticketType, components)
}
private fun insertComponentsOfTicket(ticketId: Int, ticketType: String, components: List<Component>?) {
components?.forEach {
val relatedItem = TicketRelation()
relatedItem.ticketid = ticketId
relatedItem.tickettype = ticketType
relatedItem.typeid = it.id
relatedItem.type = ProjectTypeConstants.COMPONENT
relatedItem.rel = TicketRelationConstants.COMPONENT
ticketRelationMapper.insert(relatedItem)
}
}
private fun deleteTrackerBugRelatedItem(ticketId: Int, ticketType: String, type: String) {
val ex = TicketRelationExample()
ex.createCriteria().andTicketidEqualTo(ticketId).andTickettypeEqualTo(ticketType).andTypeEqualTo(type)
ticketRelationMapper.deleteByExample(ex)
}
override fun updateAffectedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
deleteTrackerBugRelatedItem(ticketId, ticketType, TicketRelationConstants.AFF_VERSION)
if (versions != null) {
insertAffectedVersionsOfTicket(ticketId, ticketType, versions)
}
}
override fun updateFixedVersionsOfTicket(ticketId: Int, ticketType: String, versions: List<Version>?) {
deleteTrackerBugRelatedItem(ticketId, ticketType, TicketRelationConstants.FIX_VERSION)
if (versions != null) {
insertFixedVersionsOfTicket(ticketId, ticketType, versions)
}
}
override fun updateComponentsOfTicket(ticketId: Int, ticketType: String, components: List<Component>?) {
deleteTrackerBugRelatedItem(ticketId, ticketType, TicketRelationConstants.COMPONENT)
if (components != null) {
insertComponentsOfTicket(ticketId, ticketType, components)
}
}
override fun findRelatedTickets(ticketId: Int, ticketType: String): List<SimpleTicketRelation> = ticketRelationMapperExt.findRelatedTickets(ticketId, ticketType)
override fun removeRelationsByRel(ticketId: Int, ticketType: String, rel: String) {
val ex = TicketRelationExample()
ex.createCriteria().andTicketidEqualTo(ticketId).andTickettypeEqualTo(ticketType).andRelEqualTo(rel)
ticketRelationMapper.deleteByExample(ex)
}
}
| agpl-3.0 | bb92ec42324069c1011cab2acf78bb5a | 44.089431 | 165 | 0.727732 | 4.72 | false | false | false | false |
jiaminglu/kotlin-native | runtime/src/main/kotlin/kotlin/text/regex/Quantifier.kt | 2 | 2562 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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 kotlin.text.regex
import kotlin.IllegalArgumentException
/**
* Represents RE quantifier; contains two fields responsible for min and max number of repetitions.
* Negative value for maximum number of repetition represents infinity(i.e. +,*)
*/
internal class Quantifier(val min: Int, val max: Int = min) : SpecialToken() {
init {
if (min < 0 || max < -1) {
throw IllegalArgumentException()
}
}
override fun toString() = "{$min, ${if (max == -1) "" else max}}"
override val type: Type = SpecialToken.Type.QUANTIFIER
companion object {
val starQuantifier = Quantifier(0, -1)
val plusQuantifier = Quantifier(1, -1)
val altQuantifier = Quantifier(0, 1)
val INF = -1
fun fromLexerToken(token: Int) = when(token) {
Lexer.QUANT_STAR, Lexer.QUANT_STAR_P, Lexer.QUANT_STAR_R -> starQuantifier
Lexer.QUANT_ALT, Lexer.QUANT_ALT_P, Lexer.QUANT_ALT_R -> altQuantifier
Lexer.QUANT_PLUS, Lexer.QUANT_PLUS_P, Lexer.QUANT_PLUS_R -> plusQuantifier
else -> throw IllegalArgumentException()
}
}
}
| apache-2.0 | 7f9ca4491661a75b3a760a4ff56e4c2e | 36.130435 | 99 | 0.693208 | 3.99688 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/notifications/NotificationBroadcastReceiver.kt | 1 | 1881 | package org.stepic.droid.notifications
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.storage.operations.DatabaseFacade
import org.stepic.droid.util.AppConstants
import timber.log.Timber
import java.util.concurrent.ThreadPoolExecutor
import javax.inject.Inject
class NotificationBroadcastReceiver : BroadcastReceiver() {
@Inject
lateinit var databaseFacade: DatabaseFacade
@Inject
lateinit var threadPool: ThreadPoolExecutor
@Inject
lateinit var analytic: Analytic
@Inject
lateinit var sharedPreferences: SharedPreferenceHelper
init {
App.component().inject(this)
}
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action
if (action == AppConstants.NOTIFICATION_CANCELED) {
analytic.reportEvent(Analytic.Notification.DISCARD)
val courseId = intent.extras?.getLong(AppConstants.COURSE_ID_KEY)
courseId?.let {
threadPool.execute {
databaseFacade.removeAllNotificationsWithCourseId(courseId)
}
}
} else if (action == AppConstants.NOTIFICATION_CANCELED_REMINDER) {
Timber.d(Analytic.Notification.REMINDER_SWIPE_TO_CANCEL)
analytic.reportEvent(Analytic.Notification.REMINDER_SWIPE_TO_CANCEL)
} else if (action == AppConstants.NOTIFICATION_CANCELED_STREAK) {
analytic.reportEvent(Analytic.Notification.STREAK_SWIPE_TO_CANCEL)
//continue send notification about streaks
threadPool.execute {
sharedPreferences.resetNumberOfStreakNotifications()
}
}
}
} | apache-2.0 | b3e6250715c62cee2056fefab76688b0 | 34.509434 | 80 | 0.706539 | 5.056452 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/domain/track/service/TrackPreferences.kt | 1 | 1207 | package eu.kanade.domain.track.service
import eu.kanade.tachiyomi.core.preference.PreferenceStore
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.anilist.Anilist
class TrackPreferences(
private val preferenceStore: PreferenceStore,
) {
fun trackUsername(sync: TrackService) = preferenceStore.getString(trackUsername(sync.id), "")
fun trackPassword(sync: TrackService) = preferenceStore.getString(trackPassword(sync.id), "")
fun setTrackCredentials(sync: TrackService, username: String, password: String) {
trackUsername(sync).set(username)
trackPassword(sync).set(password)
}
fun trackToken(sync: TrackService) = preferenceStore.getString(trackToken(sync.id), "")
fun anilistScoreType() = preferenceStore.getString("anilist_score_type", Anilist.POINT_10)
fun autoUpdateTrack() = preferenceStore.getBoolean("pref_auto_update_manga_sync_key", true)
companion object {
fun trackUsername(syncId: Long) = "pref_mangasync_username_$syncId"
private fun trackPassword(syncId: Long) = "pref_mangasync_password_$syncId"
private fun trackToken(syncId: Long) = "track_token_$syncId"
}
}
| apache-2.0 | 23b3e73d4b5ef39c5363cf3e3f45139f | 35.575758 | 97 | 0.743165 | 4.091525 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/App.kt | 1 | 10456 | package eu.kanade.tachiyomi
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Looper
import android.webkit.WebView
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.getSystemService
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.disk.DiskCache
import coil.util.DebugLogger
import eu.kanade.data.DatabaseHandler
import eu.kanade.domain.DomainModule
import eu.kanade.domain.base.BasePreferences
import eu.kanade.domain.ui.UiPreferences
import eu.kanade.domain.ui.model.setAppCompatDelegateThemeMode
import eu.kanade.tachiyomi.crash.CrashActivity
import eu.kanade.tachiyomi.crash.GlobalExceptionHandler
import eu.kanade.tachiyomi.data.coil.DomainMangaKeyer
import eu.kanade.tachiyomi.data.coil.MangaCoverFetcher
import eu.kanade.tachiyomi.data.coil.MangaCoverKeyer
import eu.kanade.tachiyomi.data.coil.MangaKeyer
import eu.kanade.tachiyomi.data.coil.TachiyomiImageDecoder
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.glance.UpdatesGridGlanceWidget
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.NetworkPreferences
import eu.kanade.tachiyomi.ui.base.delegate.SecureActivityDelegate
import eu.kanade.tachiyomi.util.system.WebViewUtil
import eu.kanade.tachiyomi.util.system.animatorDurationScale
import eu.kanade.tachiyomi.util.system.isPreviewBuildType
import eu.kanade.tachiyomi.util.system.isReleaseBuildType
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.notification
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import logcat.AndroidLogcatLogger
import logcat.LogPriority
import logcat.LogcatLogger
import org.acra.config.httpSender
import org.acra.ktx.initAcra
import org.acra.sender.HttpSender
import org.conscrypt.Conscrypt
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.security.Security
class App : Application(), DefaultLifecycleObserver, ImageLoaderFactory {
private val basePreferences: BasePreferences by injectLazy()
private val networkPreferences: NetworkPreferences by injectLazy()
private val disableIncognitoReceiver = DisableIncognitoReceiver()
@SuppressLint("LaunchActivityFromNotification")
override fun onCreate() {
super<Application>.onCreate()
GlobalExceptionHandler.initialize(applicationContext, CrashActivity::class.java)
// TLS 1.3 support for Android < 10
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
Security.insertProviderAt(Conscrypt.newProvider(), 1)
}
// Avoid potential crashes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val process = getProcessName()
if (packageName != process) WebView.setDataDirectorySuffix(process)
}
Injekt.importModule(AppModule(this))
Injekt.importModule(PreferenceModule(this))
Injekt.importModule(DomainModule())
setupAcra()
setupNotificationChannels()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
// Show notification to disable Incognito Mode when it's enabled
basePreferences.incognitoMode().changes()
.onEach { enabled ->
val notificationManager = NotificationManagerCompat.from(this)
if (enabled) {
disableIncognitoReceiver.register()
val notification = notification(Notifications.CHANNEL_INCOGNITO_MODE) {
setContentTitle(getString(R.string.pref_incognito_mode))
setContentText(getString(R.string.notification_incognito_text))
setSmallIcon(R.drawable.ic_glasses_24dp)
setOngoing(true)
val pendingIntent = PendingIntent.getBroadcast(
this@App,
0,
Intent(ACTION_DISABLE_INCOGNITO_MODE),
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE,
)
setContentIntent(pendingIntent)
}
notificationManager.notify(Notifications.ID_INCOGNITO_MODE, notification)
} else {
disableIncognitoReceiver.unregister()
notificationManager.cancel(Notifications.ID_INCOGNITO_MODE)
}
}
.launchIn(ProcessLifecycleOwner.get().lifecycleScope)
setAppCompatDelegateThemeMode(Injekt.get<UiPreferences>().themeMode().get())
// Updates widget update
Injekt.get<DatabaseHandler>()
.subscribeToList { updatesViewQueries.updates(after = UpdatesGridGlanceWidget.DateLimit.timeInMillis) }
.drop(1)
.distinctUntilChanged()
.onEach {
val manager = GlanceAppWidgetManager(this)
if (manager.getGlanceIds(UpdatesGridGlanceWidget::class.java).isNotEmpty()) {
UpdatesGridGlanceWidget().loadData(it)
}
}
.launchIn(ProcessLifecycleOwner.get().lifecycleScope)
if (!LogcatLogger.isInstalled && networkPreferences.verboseLogging().get()) {
LogcatLogger.install(AndroidLogcatLogger(LogPriority.VERBOSE))
}
}
override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(this).apply {
val callFactoryInit = { Injekt.get<NetworkHelper>().client }
val diskCacheInit = { CoilDiskCache.get(this@App) }
components {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
add(ImageDecoderDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
add(TachiyomiImageDecoder.Factory())
add(MangaCoverFetcher.Factory(lazy(callFactoryInit), lazy(diskCacheInit)))
add(MangaCoverFetcher.DomainMangaFactory(lazy(callFactoryInit), lazy(diskCacheInit)))
add(MangaCoverFetcher.MangaCoverFactory(lazy(callFactoryInit), lazy(diskCacheInit)))
add(MangaKeyer())
add(DomainMangaKeyer())
add(MangaCoverKeyer())
}
callFactory(callFactoryInit)
diskCache(diskCacheInit)
crossfade((300 * [email protected]).toInt())
allowRgb565(getSystemService<ActivityManager>()!!.isLowRamDevice)
if (networkPreferences.verboseLogging().get()) logger(DebugLogger())
}.build()
}
override fun onStart(owner: LifecycleOwner) {
SecureActivityDelegate.onApplicationStart()
}
override fun onStop(owner: LifecycleOwner) {
SecureActivityDelegate.onApplicationStopped()
}
override fun getPackageName(): String {
// This causes freezes in Android 6/7 for some reason
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
// Override the value passed as X-Requested-With in WebView requests
val stackTrace = Looper.getMainLooper().thread.stackTrace
val chromiumElement = stackTrace.find {
it.className.equals(
"org.chromium.base.BuildInfo",
ignoreCase = true,
)
}
if (chromiumElement?.methodName.equals("getAll", ignoreCase = true)) {
return WebViewUtil.SPOOF_PACKAGE_NAME
}
} catch (e: Exception) {
}
}
return super.getPackageName()
}
private fun setupAcra() {
if (isPreviewBuildType || isReleaseBuildType) {
initAcra {
buildConfigClass = BuildConfig::class.java
excludeMatchingSharedPreferencesKeys = listOf(".*username.*", ".*password.*", ".*token.*")
httpSender {
uri = BuildConfig.ACRA_URI
httpMethod = HttpSender.Method.PUT
}
}
}
}
private fun setupNotificationChannels() {
try {
Notifications.createChannels(this)
} catch (e: Exception) {
logcat(LogPriority.ERROR, e) { "Failed to modify notification channels" }
}
}
private inner class DisableIncognitoReceiver : BroadcastReceiver() {
private var registered = false
override fun onReceive(context: Context, intent: Intent) {
basePreferences.incognitoMode().set(false)
}
fun register() {
if (!registered) {
registerReceiver(this, IntentFilter(ACTION_DISABLE_INCOGNITO_MODE))
registered = true
}
}
fun unregister() {
if (registered) {
unregisterReceiver(this)
registered = false
}
}
}
}
private const val ACTION_DISABLE_INCOGNITO_MODE = "tachi.action.DISABLE_INCOGNITO_MODE"
/**
* Direct copy of Coil's internal SingletonDiskCache so that [MangaCoverFetcher] can access it.
*/
internal object CoilDiskCache {
private const val FOLDER_NAME = "image_cache"
private var instance: DiskCache? = null
@Synchronized
fun get(context: Context): DiskCache {
return instance ?: run {
val safeCacheDir = context.cacheDir.apply { mkdirs() }
// Create the singleton disk cache instance.
DiskCache.Builder()
.directory(safeCacheDir.resolve(FOLDER_NAME))
.build()
.also { instance = it }
}
}
}
| apache-2.0 | 8848691a04dfb2985173cc8d2b08c440 | 38.014925 | 115 | 0.6579 | 5.058539 | false | false | false | false |
jkcclemens/khttp | src/main/kotlin/khttp/structures/cookie/CookieJar.kt | 1 | 1596 | /*
* 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 khttp.structures.cookie
import java.util.HashMap
class CookieJar(vararg val cookies: Cookie = arrayOf()) : MutableMap<String, String> by (cookies.associate { it.key to it.valueWithAttributes } as HashMap<String, String>) {
companion object {
private fun Map<String, Any>.toCookieArray(): Array<Cookie> {
return this.map {
val valueList = it.value.toString().split(";").map(String::trim)
val value = valueList[0]
val attributes = if (valueList.size < 2) mapOf<String, String>() else {
valueList.subList(1, valueList.size).associate {
val k = it.split("=")[0].trim()
val split = it.split("=")
val v = (if (split.size > 1) split[1] else null)?.trim()
k to v
}
}
Cookie(it.key, value, attributes)
}.toTypedArray()
}
}
constructor(cookies: Map<String, Any>) : this(*cookies.toCookieArray())
fun getCookie(key: String): Cookie? {
val value = this[key] ?: return null
return Cookie("$key=$value")
}
fun setCookie(cookie: Cookie) {
this[cookie.key] = cookie.valueWithAttributes
}
override fun toString() = this.cookies.joinToString("; ") { "${it.key}=${it.value}" }
}
| mpl-2.0 | 0982ecdcfc1a960cc697eac1e4efd9c3 | 37 | 173 | 0.564536 | 4.2 | false | false | false | false |
exponentjs/exponent | packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/assets/CreateAsset.kt | 2 | 5949 | package expo.modules.medialibrary.assets
import android.os.AsyncTask
import android.content.ContentValues
import android.provider.MediaStore
import android.content.ContentUris
import android.content.Context
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import expo.modules.core.Promise
import expo.modules.core.utilities.ifNull
import expo.modules.medialibrary.ERROR_IO_EXCEPTION
import expo.modules.medialibrary.ERROR_NO_FILE_EXTENSION
import expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD_PERMISSION
import expo.modules.medialibrary.ERROR_UNABLE_TO_SAVE
import expo.modules.medialibrary.MediaLibraryUtils
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
class CreateAsset @JvmOverloads constructor(
private val context: Context,
uri: String,
private val promise: Promise,
private val resolveWithAdditionalData: Boolean = true
) : AsyncTask<Void?, Void?, Void?>() {
private val mUri = normalizeAssetUri(uri)
private fun normalizeAssetUri(uri: String): Uri {
return if (uri.startsWith("/")) {
Uri.fromFile(File(uri))
} else {
Uri.parse(uri)
}
}
private val isFileExtensionPresent: Boolean
get() = mUri.lastPathSegment?.contains(".") ?: false
/**
* Creates asset entry in database
* @return uri to created asset or null if it fails
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
private fun createContentResolverAssetEntry(): Uri? {
val contentResolver = context.contentResolver
val mimeType = MediaLibraryUtils.getMimeType(contentResolver, mUri)
val filename = mUri.lastPathSegment
val path = MediaLibraryUtils.getRelativePathForAssetType(mimeType, true)
val contentUri = MediaLibraryUtils.mimeTypeToExternalUri(mimeType)
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, path)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
return contentResolver.insert(contentUri, contentValues)
}
/**
* Same as [MediaLibraryUtils.safeCopyFile] but takes Content URI as destination
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
@Throws(IOException::class)
private fun writeFileContentsToAsset(localFile: File, assetUri: Uri) {
val contentResolver = context.contentResolver
FileInputStream(localFile).channel.use { input ->
(contentResolver.openOutputStream(assetUri) as FileOutputStream).channel.use { output ->
val transferred = input.transferTo(0, input.size(), output)
if (transferred != input.size()) {
contentResolver.delete(assetUri, null, null)
throw IOException("Could not save file to $assetUri Not enough space.")
}
}
}
// After writing contents, set IS_PENDING flag back to 0
val values = ContentValues().apply {
put(MediaStore.MediaColumns.IS_PENDING, 0)
}
contentResolver.update(assetUri, values, null, null)
}
/**
* Recommended method of creating assets since API 30
*/
@RequiresApi(api = Build.VERSION_CODES.R)
@Throws(IOException::class)
private fun createAssetUsingContentResolver() {
val assetUri = createContentResolverAssetEntry().ifNull {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not create content entry.")
return
}
writeFileContentsToAsset(File(mUri.path!!), assetUri)
if (resolveWithAdditionalData) {
val selection = "${MediaStore.MediaColumns._ID}=?"
val args = arrayOf(ContentUris.parseId(assetUri).toString())
queryAssetInfo(context, selection, args, false, promise)
} else {
promise.resolve(null)
}
}
/**
* Creates asset using filesystem. Legacy method - do not use above API 29
*/
@Throws(IOException::class)
private fun createAssetFileLegacy(): File? {
val localFile = File(mUri.path!!)
val destDir = MediaLibraryUtils.getEnvDirectoryForAssetType(
MediaLibraryUtils.getMimeType(context.contentResolver, mUri),
true
).ifNull {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not guess file type.")
return null
}
val destFile = MediaLibraryUtils.safeCopyFile(localFile, destDir)
if (!destDir.exists() || !destFile.isFile) {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not create asset record. Related file is not existing.")
return null
}
return destFile
}
override fun doInBackground(vararg params: Void?): Void? {
if (!isFileExtensionPresent) {
promise.reject(ERROR_NO_FILE_EXTENSION, "Could not get the file's extension.")
return null
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
createAssetUsingContentResolver()
return null
}
val asset = createAssetFileLegacy() ?: return null
MediaScannerConnection.scanFile(
context, arrayOf(asset.path),
null
) { path: String, uri: Uri? ->
if (uri == null) {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not add image to gallery.")
return@scanFile
}
if (resolveWithAdditionalData) {
val selection = MediaStore.Images.Media.DATA + "=?"
val args = arrayOf(path)
queryAssetInfo(context, selection, args, false, promise)
} else {
promise.resolve(null)
}
}
} catch (e: IOException) {
promise.reject(ERROR_IO_EXCEPTION, "Unable to copy file into external storage.", e)
} catch (e: SecurityException) {
promise.reject(
ERROR_UNABLE_TO_LOAD_PERMISSION,
"Could not get asset: need READ_EXTERNAL_STORAGE permission.", e
)
} catch (e: Exception) {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not create asset.", e)
}
return null
}
}
| bsd-3-clause | 2dae6f49e0fb9e72c939751fc12fc04f | 33.387283 | 106 | 0.700118 | 4.276779 | false | false | false | false |
aarmea/noise | app/src/main/java/com/alternativeinfrastructures/noise/storage/BloomFilter.kt | 1 | 5196 | package com.alternativeinfrastructures.noise.storage
import android.os.Looper
import android.util.Log
import com.alternativeinfrastructures.noise.NoiseDatabase
import com.raizlabs.android.dbflow.annotation.ForeignKey
import com.raizlabs.android.dbflow.annotation.ForeignKeyAction
import com.raizlabs.android.dbflow.annotation.PrimaryKey
import com.raizlabs.android.dbflow.annotation.Table
import com.raizlabs.android.dbflow.rx2.language.RXSQLite
import com.raizlabs.android.dbflow.rx2.structure.BaseRXModel
import com.raizlabs.android.dbflow.sql.language.CursorResult
import com.raizlabs.android.dbflow.sql.language.Method
import com.raizlabs.android.dbflow.sql.language.SQLite
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper
import java.util.ArrayList
import java.util.BitSet
import java.util.Vector
import io.reactivex.Flowable
import io.reactivex.Single
import util.hash.MurmurHash3
// Actual bloom filter implementation based heavily on this guide:
// http://blog.michaelschmatz.com/2016/04/11/how-to-write-a-bloom-filter-cpp/
@Table(database = NoiseDatabase::class)
class BloomFilter internal constructor() : BaseRXModel() {
@PrimaryKey
@ForeignKey(onDelete = ForeignKeyAction.CASCADE, stubbedRelationship = true)
protected var message: UnknownMessage? = null
@PrimaryKey
protected var hash: Int = 0
companion object {
val TAG = "BloomFilter"
// TODO: Tune these
// They need to be large enough to describe billions of messages
// but also small enough to transmit in a few seconds over Bluetooth
internal val SIZE = 1 shl 20 // in bits
internal val USABLE_SIZE = SIZE - 1
internal val NUM_HASHES = 5
val SIZE_IN_BYTES = SIZE / 8
internal fun hashMessage(message: UnknownMessage): List<Int> {
val hashList = Vector<Int>(NUM_HASHES)
// TODO: Is using a non-cryptographic hash like murmurhash okay? An attacker can generate messages that match the hashes to try to block it
val primaryHash = MurmurHash3.LongPair()
MurmurHash3.murmurhash3_x64_128(message.payload.blob, 0 /*offset*/, UnknownMessage.PAYLOAD_SIZE, 0 /*seed*/, primaryHash)
for (hashFunction in 0 until NUM_HASHES)
hashList.add(nthHash(primaryHash.val1, primaryHash.val2, hashFunction).toInt())
return hashList
}
internal fun addMessage(message: UnknownMessage, databaseWrapper: DatabaseWrapper) {
if (Looper.getMainLooper() == Looper.myLooper())
Log.e(TAG, "Attempting to save on the UI thread")
for (hash in hashMessage(message)) {
val row = BloomFilter()
row.message = message
row.hash = hash
// blockingGet is okay here because this is always called from within a Transaction
row.save(databaseWrapper).blockingGet()
}
}
fun makeEmptyMessageVector(): BitSet {
val messageVector = BitSet(SIZE)
messageVector.set(USABLE_SIZE) // Hack to keep the generated byte array the same size
return messageVector
}
val messageVectorAsync: Single<BitSet>
get() = RXSQLite.rx(SQLite.select(BloomFilter_Table.hash.distinct()).from(BloomFilter::class.java))
.queryResults().map { bloomCursor: CursorResult<BloomFilter> ->
val messageVector = makeEmptyMessageVector()
for (bloomIndex in 0 until bloomCursor.count) {
val filterElement = bloomCursor.getItem(bloomIndex)
if (filterElement != null)
messageVector.set(filterElement.hash)
}
bloomCursor.close()
messageVector
}
fun getMatchingMessages(messageVector: BitSet): Flowable<UnknownMessage> {
val hashes = ArrayList<Int>(messageVector.cardinality())
run {
var hash = messageVector.nextSetBit(0)
while (hash != -1) {
hashes.add(hash)
hash = messageVector.nextSetBit(hash + 1)
}
}
// TODO: Implement Noise message priority - order by date and zero bits
return RXSQLite.rx(SQLite.select(*UnknownMessage_Table.ALL_COLUMN_PROPERTIES)
.from(UnknownMessage::class.java).leftOuterJoin(BloomFilter::class.java)
.on(UnknownMessage_Table.id.eq(BloomFilter_Table.message_id))
.where(BloomFilter_Table.hash.`in`(hashes))
.groupBy(BloomFilter_Table.message_id)
.having(Method.count().eq(NUM_HASHES)))
.queryStreamResults()
}
private fun nthHash(hashA: Long, hashB: Long, hashFunction: Int): Long {
// Double modulus ensures that the result is positive when any of the hashes are negative
return ((hashA + hashFunction * hashB) % USABLE_SIZE + USABLE_SIZE) % USABLE_SIZE
}
}
}
| mit | 5becdd0b981c3b993801b6cfb45c53b8 | 42.663866 | 151 | 0.641455 | 4.506505 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt | 1 | 6105 | /*
* Copyright 2015 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.internal
import com.squareup.wire.KotlinConstructorBuilder
import com.squareup.wire.Message
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.WireField
import java.lang.reflect.Field
import java.lang.reflect.Modifier
/**
* Read, write, and describe a tag within a message. This class knows how to assign fields to a
* builder object, and how to extract values from a message object.
*/
class FieldBinding<M : Message<M, B>, B : Message.Builder<M, B>> internal constructor(
wireField: WireField,
messageType: Class<M>,
private val messageField: Field,
builderType: Class<B>,
override val writeIdentityValues: Boolean,
) : FieldOrOneOfBinding<M, B>() {
override val label: WireField.Label = wireField.label
override val name: String = messageField.name
override val wireFieldJsonName: String = wireField.jsonName
override val declaredName: String =
if (wireField.declaredName.isEmpty()) messageField.name else wireField.declaredName
override val tag: Int = wireField.tag
private val keyAdapterString = wireField.keyAdapter
private val adapterString = wireField.adapter
override val redacted: Boolean = wireField.redacted
private val builderSetter = getBuilderSetter(builderType, wireField)
private val builderGetter = getBuilderGetter(builderType, wireField)
private val instanceGetter = getInstanceGetter(messageType)
override val keyAdapter: ProtoAdapter<*>
get() = ProtoAdapter.get(keyAdapterString)
override val singleAdapter: ProtoAdapter<*>
get() = ProtoAdapter.get(adapterString)
override val isMap: Boolean
get() = keyAdapterString.isNotEmpty()
override val isMessage: Boolean
get() = Message::class.java.isAssignableFrom(singleAdapter.type?.javaObjectType)
private fun getBuilderSetter(builderType: Class<*>, wireField: WireField): (B, Any?) -> Unit {
return when {
builderType.isAssignableFrom(KotlinConstructorBuilder::class.java) -> { builder, value ->
(builder as KotlinConstructorBuilder<*, *>).set(wireField, value)
}
wireField.label.isOneOf -> {
val type = messageField.type
val method = try {
builderType.getMethod(name, type)
} catch (_: NoSuchMethodException) {
throw AssertionError("No builder method ${builderType.name}.$name(${type.name})")
}
{ builder, value ->
method.invoke(builder, value)
}
}
else -> {
val field = try {
builderType.getField(name)
} catch (_: NoSuchFieldException) {
throw AssertionError("No builder field ${builderType.name}.$name")
}
{ builder, value ->
field.set(builder, value)
}
}
}
}
private fun getBuilderGetter(builderType: Class<*>, wireField: WireField): (B) -> Any? {
return if (builderType.isAssignableFrom(KotlinConstructorBuilder::class.java)) {
{ builder ->
(builder as KotlinConstructorBuilder<*, *>).get(wireField)
}
} else {
val field = try {
builderType.getField(name)
} catch (_: NoSuchFieldException) {
throw AssertionError("No builder field ${builderType.name}.$name")
}
{ builder ->
field.get(builder)
}
}
}
private fun getInstanceGetter(messageType: Class<M>): (M) -> Any? {
if (Modifier.isPrivate(messageField.modifiers)) {
val fieldName = messageField.name
val getterName = if (IS_GETTER_FIELD_NAME_REGEX.matches(fieldName)) {
fieldName
} else {
"get" + fieldName.replaceFirstChar { it.uppercase() }
}
val getter = messageType.getMethod(getterName)
return { instance -> getter.invoke(instance) }
} else {
return { instance -> messageField.get(instance) }
}
}
/** Accept a single value, independent of whether this value is single or repeated. */
override fun value(builder: B, value: Any) {
when {
label.isRepeated -> {
when (val list = getFromBuilder(builder)) {
is MutableList<*> -> (list as MutableList<Any>).add(value)
is List<*> -> {
val mutableList = list.toMutableList()
mutableList.add(value)
set(builder, mutableList)
}
else -> {
val type = list?.let { it::class.java }
throw ClassCastException("Expected a list type, got $type.")
}
}
}
keyAdapterString.isNotEmpty() -> {
when (val map = getFromBuilder(builder)) {
is MutableMap<*, *> -> map.putAll(value as Map<Nothing, Nothing>)
is Map<*, *> -> {
val mutableMap = map.toMutableMap()
mutableMap.putAll(value as Map<out Any?, Any?>)
set(builder, mutableMap)
}
else -> {
val type = map?.let { it::class.java }
throw ClassCastException("Expected a map type, got $type.")
}
}
}
else -> set(builder, value)
}
}
/** Assign a single value for required/optional fields, or a list for repeated/packed fields. */
override fun set(builder: B, value: Any?) = builderSetter(builder, value)
override operator fun get(message: M): Any? = instanceGetter(message)
override fun getFromBuilder(builder: B): Any? = builderGetter(builder)
companion object {
// If a field's name matches this regex, its getter name will match the field name.
private val IS_GETTER_FIELD_NAME_REGEX = Regex("^is[^a-z].*$")
}
}
| apache-2.0 | 535e8d9b01d315eb8d69932065f8dd1e | 35.556886 | 98 | 0.657166 | 4.363831 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinMavenUtils.kt | 4 | 5997 | // 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.compiler.configuration
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.JDOMUtil
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants.KOTLIN_MAVEN_GROUP_ID
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.utils.yieldIfNotNull
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.isRegularFile
import kotlin.io.path.name
import kotlin.io.path.nameWithoutExtension
import com.google.common.base.Function as GuavaFunction
object KotlinMavenUtils {
/**
* Deducts main binary artifact version in a given IntelliJ IDEA project library.
* This function works only when the IDE is run from sources (for instance, in tests), as in production there is no '.idea' directory.
*/
fun findLibraryVersion(libraryFileName: String): String? {
val librariesDir = Paths.get(PathManager.getHomePath(), ".idea/libraries")
val libraryFile = librariesDir.resolve(libraryFileName)
val libraryDocument = JDOMUtil.load(libraryFile)
val libraryElement = libraryDocument.getChild("library")
?: error("Invalid library file: $libraryFile")
if (libraryElement.getAttributeValue("type") == "repository") {
val propertiesElement = libraryElement.getChild("properties")
val mavenId = propertiesElement?.getAttributeValue("maven-id")
if (!mavenId.isNullOrEmpty()) {
val mavenIdChunks = mavenId.split(':')
if (mavenIdChunks.size == 3) {
return mavenIdChunks[2]
}
}
}
// Assume the library has the Maven-like repository path, yet it's not a "repository" library
// This is useful for Kotlin cooperative mode where artifacts are placed in '<kotlinRepo>/build/repo'
val firstRootUrl = libraryElement.getChild("CLASSES")?.getChild("root")?.getAttributeValue("url")?.substringBefore("!/")
if (!firstRootUrl.isNullOrEmpty()) {
val urlChunks = firstRootUrl.split('/')
if (urlChunks.size >= 3) {
val fileName = urlChunks[urlChunks.lastIndex]
val version = urlChunks[urlChunks.lastIndex - 1]
val artifactId = urlChunks[urlChunks.lastIndex - 2]
if (fileName.startsWith("$artifactId-$version") && fileName.endsWith(".jar", ignoreCase = true)) {
return version
}
}
}
return null
}
/**
* Returns the single non-classified binary artifact with given coordinates, or throws an exception if the artifact file is not found.
* This function works both in production and when the IDEA is run from sources (for instance, in tests).
*/
fun findArtifactOrFail(groupId: String, artifactId: String, version: String): Path {
return findArtifact(groupId, artifactId, version)
?: error("Artifact $groupId:$artifactId:$version not found")
}
/**
* Returns the single non-classified binary artifact with given coordinates, or `null` if the artifact file is not found.
* This function works both in production and when the IntelliJ IDEA is run from sources (for instance, in tests).
*/
fun findArtifact(groupId: String, artifactId: String, version: String, suffix: String = ".jar"): Path? {
return KotlinMavenArtifactFinder.instance.findArtifact(groupId, artifactId, version, suffix)
}
}
private abstract class KotlinMavenArtifactFinder {
companion object {
val instance: KotlinMavenArtifactFinder
get() = when {
isRunningFromSources -> SourcesKotlinMavenArtifactFinder
else -> ProductionKotlinMavenArtifactFinder
}
}
protected abstract val repositories: Sequence<Path>
fun findArtifact(groupId: String, artifactId: String, version: String, suffix: String): Path? {
for (repository in repositories) {
val artifact = repository.resolve(groupId.replace(".", "/"))
.resolve(artifactId)
.resolve(version)
.resolve("$artifactId-$version$suffix")
.takeIf { it.isRegularFile() }
if (artifact != null) {
return artifact
}
}
return null
}
}
private object ProductionKotlinMavenArtifactFinder : KotlinMavenArtifactFinder() {
override val repositories: Sequence<Path> = sequence {
yield(JarRepositoryManager.getLocalRepositoryPath().toPath())
}
}
private object SourcesKotlinMavenArtifactFinder : KotlinMavenArtifactFinder() {
override val repositories: Sequence<Path> = sequence {
yieldIfNotNull(repositoryForKotlinCompiler)
yieldIfNotNull(repositoryForLibraries)
}
private val repositoryForKotlinCompiler: Path? by lazy { findMavenRepository(KtElement::class.java, KOTLIN_MAVEN_GROUP_ID) }
private val repositoryForLibraries: Path? by lazy { findMavenRepository(GuavaFunction::class.java, "com.google.guava") }
private fun findMavenRepository(libraryClass: Class<*>, groupId: String): Path? {
val compilerArtifactJarPathString = PathManager.getJarPathForClass(libraryClass) ?: return null
val compilerArtifactJar = Path.of(compilerArtifactJarPathString)
val versionDir = compilerArtifactJar.parent ?: return null
val artifactDir = versionDir.parent ?: return null
val repositoryDir = groupId.split('.').fold<String, Path?>(artifactDir.parent) { path, _ -> path?.parent } ?: return null
if (compilerArtifactJar.nameWithoutExtension == "${artifactDir.name}-${versionDir.name}") {
return repositoryDir
}
return null
}
} | apache-2.0 | baa8d93ba2b276a96cd99d5e2893bf43 | 44.78626 | 138 | 0.678839 | 4.972637 | false | false | false | false |
abigpotostew/easypolitics | ui/src/main/kotlin/bz/stew/bracken/ui/common/index/MappedIndex.kt | 1 | 1311 | package bz.stew.bracken.ui.common.index
/**
* <K> is the key
* <I> is the large number of instances mapped to the key
* Created by stew on 2/8/17.
*/
abstract class MappedIndex<K, I> (private val allKey: K?) {
protected val forwardMap: MutableMap<K, MutableSet<I>> = mutableMapOf()
protected val reverseMap: MutableMap<I, K> = mutableMapOf()
//private var dirty:Boolean = false
//private var instancesWithCache:Map<C,Collection<I>> = mapOf()
/**
* put instance in map at this key
*/
fun input(key: K, instance: I) {
//println("<$key, $i>")
var insts = forwardMap.get(key)
if (insts == null) {
insts = mutableSetOf()
}
if (!insts.contains(instance)) {
insts.add(instance)
//dirty = true
}
forwardMap.put(key, insts)
reverseMap.put(instance, key)
}
fun instancesWith(c: K): Collection<I> {
if (c == allKey) {
return reverseMap.keys.toList()
}
val insts = forwardMap.get(c)
return insts ?.toList() ?: emptyList<I>()
}
open fun allKeys(): Set<K> {
return forwardMap.keys.union(setOf())
//TODO cache this list
}
fun reset() {
forwardMap.clear()
reverseMap.clear()
}
} | apache-2.0 | 26ec7d81954176fe05ac6edfb2dfe301 | 25.24 | 75 | 0.565217 | 3.778098 | false | false | false | false |
gdgand/android-rxjava | 2016-07-12_rxjava_in_action/src/main/kotlin/com/androidhuman/example/rxjavainaction/ViewPagerFlipIntervalDragHandlingActivity.kt | 1 | 3170 | package com.androidhuman.example.rxjavainaction
import android.graphics.Color
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.androidhuman.example.rxjavainaction.rxbinding.support.v4.view.RxViewPager
import kotlinx.android.synthetic.main.activity_view_pager.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
import java.util.concurrent.TimeUnit
class ViewPagerFlipIntervalDragHandlingActivity : AppCompatActivity() {
private val subscription by lazy { CompositeSubscription() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_pager)
vp_activity_view_pager.adapter = PageAdapter()
val timer = Observable.interval(1000, TimeUnit.MILLISECONDS)
val dragging = RxViewPager.pageScrollStateChanges(vp_activity_view_pager)
.map { ViewPager.SCROLL_STATE_DRAGGING == it }
.distinctUntilChanged()
.startWith(false)
subscription.add(timer.withLatestFrom(dragging, { timer, dragging -> dragging })
.filter { !it }
.retry()
.onBackpressureDrop()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
with(vp_activity_view_pager) {
val currentIdx = currentItem
currentItem = if (currentIdx == adapter.count - 1) 0 else currentItem + 1
}
})
}
override fun onStop() {
super.onStop()
if (isFinishing) {
clearSubscription()
}
}
override fun onDestroy() {
super.onDestroy()
clearSubscription()
}
private fun clearSubscription() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
inner class PageAdapter : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = TextView(container.context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
gravity = Gravity.CENTER
text = "Page $position"
setBackgroundColor(Color.GREEN)
setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
}
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any?) {
container.removeView(`object` as View)
}
override fun getCount(): Int {
return 10
}
override fun isViewFromObject(view: View?, `object`: Any?): Boolean {
return view == `object`
}
}
} | mit | 9a36295505c94380126def320cf3941c | 31.030303 | 97 | 0.630599 | 5.063898 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/grid/ThreadSafeTileGrid.kt | 1 | 8293 | package org.hexworks.zircon.internal.grid
import org.hexworks.cobalt.databinding.api.collection.ObservableList
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.api.animation.Animation
import org.hexworks.zircon.api.animation.AnimationHandle
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.behavior.Layerable
import org.hexworks.zircon.api.behavior.ShutdownHook
import org.hexworks.zircon.api.data.CharacterTile
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.api.graphics.LayerHandle
import org.hexworks.zircon.api.graphics.StyleSet
import org.hexworks.zircon.api.graphics.TileComposite
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.view.ViewContainer
import org.hexworks.zircon.internal.animation.DefaultAnimationRunner
import org.hexworks.zircon.internal.animation.InternalAnimation
import org.hexworks.zircon.internal.animation.InternalAnimationRunner
import org.hexworks.zircon.internal.application.InternalApplication
import org.hexworks.zircon.internal.behavior.InternalCursorHandler
import org.hexworks.zircon.internal.behavior.InternalLayerable
import org.hexworks.zircon.internal.behavior.impl.DefaultCursorHandler
import org.hexworks.zircon.internal.behavior.impl.DefaultShutdownHook
import org.hexworks.zircon.internal.behavior.impl.ThreadSafeLayerable
import org.hexworks.zircon.internal.graphics.InternalLayer
import org.hexworks.zircon.internal.graphics.Renderable
import org.hexworks.zircon.internal.uievent.UIEventProcessor
import kotlin.jvm.Synchronized
class ThreadSafeTileGrid(
override val config: AppConfig,
override var layerable: InternalLayerable = buildLayerable(config.size),
override var animationHandler: InternalAnimationRunner = DefaultAnimationRunner(),
override var cursorHandler: InternalCursorHandler = DefaultCursorHandler(
initialCursorSpace = config.size
),
private val eventProcessor: UIEventProcessor = UIEventProcessor.createDefault()
) : InternalTileGrid,
ShutdownHook by DefaultShutdownHook(),
UIEventProcessor by eventProcessor,
ViewContainer by ViewContainer.create() {
init {
initializeLayerable(config)
}
// Note that this is passed in right after creation
// the lateinit is necessary because Application also has a reference to the grid
override lateinit var application: InternalApplication
override var backend: Layer = layerable.getLayerAtOrNull(0)!!
override val tiles: Map<Position, Tile>
get() = backend.tiles
override val size: Size
get() = backend.size
override var tileset: TilesetResource
get() = backend.tileset
set(value) {
backend.tileset = value
}
override val tilesetProperty: Property<TilesetResource>
get() = backend.tilesetProperty
override val layers: ObservableList<out InternalLayer>
get() = layerable.layers
override val renderables: List<Renderable>
get() = layerable.renderables
private var originalCursorHandler = cursorHandler
private var originalBackend = backend
private var originalLayerable = layerable
private var originalAnimationHandler = animationHandler
override var isCursorVisible: Boolean
get() = cursorHandler.isCursorVisible
set(value) {
cursorHandler.isCursorVisible = value
}
override var cursorPosition: Position
get() = cursorHandler.cursorPosition
set(value) {
cursorHandler.cursorPosition = value
}
override val isCursorAtTheEndOfTheLine: Boolean
get() = cursorHandler.isCursorAtTheEndOfTheLine
override val isCursorAtTheStartOfTheLine: Boolean
get() = cursorHandler.isCursorAtTheStartOfTheLine
override val isCursorAtTheFirstRow: Boolean
get() = cursorHandler.isCursorAtTheFirstRow
override val isCursorAtTheLastRow: Boolean
get() = cursorHandler.isCursorAtTheLastRow
override val closedValue: Property<Boolean> = false.toProperty()
override val closed: Boolean by closedValue.asDelegate()
override fun getTileAtOrNull(position: Position): Tile? {
return backend.getTileAtOrNull(position)
}
@Synchronized
override fun putTile(tile: Tile) {
if (tile is CharacterTile && tile.character == '\n') {
moveCursorToNextLine()
} else {
backend.draw(tile, cursorPosition)
moveCursorForward()
}
}
override fun moveCursorForward() {
cursorHandler.moveCursorForward()
}
override fun moveCursorBackward() {
cursorHandler.moveCursorBackward()
}
@Synchronized
override fun close() {
animationHandler.close()
closedValue.value = true
}
@Synchronized
override fun delegateTo(tileGrid: InternalTileGrid) {
backend = tileGrid.backend
layerable = tileGrid.layerable
animationHandler = tileGrid.animationHandler
cursorHandler = tileGrid.cursorHandler
}
@Synchronized
override fun reset() {
backend = originalBackend
layerable = originalLayerable
animationHandler = originalAnimationHandler
cursorHandler = originalCursorHandler
}
@Synchronized
override fun clear() {
backend.clear()
layerable = buildLayerable(size)
initializeLayerable(config)
backend = layerable.getLayerAtOrNull(0)!!
}
// ANIMATION HANDLER
override fun start(animation: Animation): AnimationHandle {
return animationHandler.start(animation)
}
override fun stop(animation: InternalAnimation) {
animationHandler.stop(animation)
}
override fun updateAnimations(currentTimeMs: Long, layerable: Layerable) {
animationHandler.updateAnimations(currentTimeMs, layerable)
}
// DRAW SURFACE
override fun draw(tileComposite: TileComposite, drawPosition: Position, drawArea: Size) {
backend.draw(tileComposite, drawPosition, drawArea)
}
override fun draw(tileMap: Map<Position, Tile>, drawPosition: Position, drawArea: Size) {
backend.draw(tileMap, drawPosition, drawArea)
}
override fun draw(tile: Tile, drawPosition: Position) {
backend.draw(tile, drawPosition)
}
override fun draw(tileComposite: TileComposite) {
backend.draw(tileComposite)
}
override fun draw(tileComposite: TileComposite, drawPosition: Position) {
backend.draw(tileComposite, drawPosition)
}
override fun draw(tileMap: Map<Position, Tile>) {
backend.draw(tileMap)
}
override fun draw(tileMap: Map<Position, Tile>, drawPosition: Position) {
backend.draw(tileMap, drawPosition)
}
override fun fill(filler: Tile) {
backend.fill(filler)
}
override fun transform(transformer: (Position, Tile) -> Tile) {
backend.transform(transformer)
}
override fun applyStyle(styleSet: StyleSet) {
backend.applyStyle(styleSet)
}
// LAYERABLE
override fun getLayerAtOrNull(level: Int): LayerHandle? = layerable.getLayerAtOrNull(level)
override fun addLayer(layer: Layer) = layerable.addLayer(layer)
override fun insertLayerAt(level: Int, layer: Layer) = layerable.insertLayerAt(level, layer)
override fun setLayerAt(level: Int, layer: Layer) = layerable.setLayerAt(level, layer)
override fun removeLayer(layer: Layer): Boolean {
return layerable.removeLayer(layer)
}
private fun moveCursorToNextLine() {
cursorPosition = cursorPosition.withRelativeY(1).withX(0)
}
private fun initializeLayerable(config: AppConfig) {
layerable.addLayer(
Layer.newBuilder()
.withSize(config.size)
.withTileset(config.defaultTileset)
.build()
)
}
}
private fun buildLayerable(initialSize: Size): ThreadSafeLayerable {
return ThreadSafeLayerable(
initialSize = initialSize
)
}
| apache-2.0 | 1a39bf8381b307eee5509ff1f66e9ba9 | 32.574899 | 96 | 0.725311 | 4.579238 | false | false | false | false |
JStege1206/AdventOfCode | aoc-common/src/main/kotlin/nl/jstege/adventofcode/aoccommon/AdventOfCode.kt | 1 | 2878 | package nl.jstege.adventofcode.aoccommon
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.types.int
import com.github.ajalt.clikt.parameters.types.restrictTo
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.format
import nl.jstege.adventofcode.aoccommon.utils.extensions.times
import nl.jstege.adventofcode.aoccommon.utils.extensions.wrap
import org.reflections.Reflections
import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.system.measureTimeMillis
/**
*
* @author Jelle Stege
*/
abstract class AdventOfCode(private val assignmentLocation: String? = null) : CliktCommand() {
val days by argument(
help = "The day assignments to execute. If not present, will execute all 25 days."
)
.int()
.restrictTo(1..25)
.multiple()
override fun toString(): String = this::class.java.simpleName
.replace("([A-Z0-9]+)".toRegex(), " $1").trim()
override fun run() {
val location = assignmentLocation ?: this::class.java.`package`.name+".days"
val assignments: List<Day> =
if (days.isNotEmpty()) getAssignments(location, days)
else getAssignments(location, (1..25).toList())
println(this.toString())
println("Started on ${dateTimeFormatter.format(LocalDateTime.now())}")
println("-" * COLUMN_SIZE)
println("Running assignments: ")
println(assignments.joinToString(", ") { it::class.java.simpleName }.wrap(COLUMN_SIZE))
println("-" * COLUMN_SIZE)
val totalTimeTaken = Duration.ofMillis(measureTimeMillis {
assignments.forEach { it.run() } //Start all days
assignments
.asSequence()
.onEach { it.awaitAndPrintOutput() }
.forEach { _ -> println("-" * COLUMN_SIZE) }
})
println("Total time taken: ${totalTimeTaken.format("HH:mm:ss.SSS")}")
}
companion object {
private const val COLUMN_SIZE = 80
private val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")!!
private inline fun <reified E> getAssignments(
location: String,
assignmentIds: List<Int>
): List<E> {
val assignments = assignmentIds.map { String.format("Day%02d", it) }
return Reflections(location)
.getSubTypesOf(E::class.java)
.asSequence()
.filterNotNull()
.filter { it.simpleName in assignments }
.sortedBy { it.simpleName }
.map { it.newInstance() }
.toList()
}
}
}
| mit | 02e0b9f54841e8f19ddb1fc5d1618265 | 36.868421 | 95 | 0.643502 | 4.427692 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/posts/mediauploadcompletionprocessors/MediaUploadCompletionProcessorTest.kt | 1 | 4887 | package org.wordpress.android.ui.posts.mediauploadcompletionprocessors
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.util.helpers.MediaFile
@RunWith(MockitoJUnitRunner::class)
class MediaUploadCompletionProcessorTest {
private val mediaFile: MediaFile = mock()
private lateinit var processor: MediaUploadCompletionProcessor
@Before
fun before() {
whenever(mediaFile.mediaId).thenReturn(TestContent.remoteMediaId)
whenever(mediaFile.optimalFileURL).thenReturn(TestContent.remoteImageUrl)
whenever(mediaFile.getAttachmentPageURL(any())).thenReturn(TestContent.attachmentPageUrl)
processor = MediaUploadCompletionProcessor(TestContent.localMediaId, mediaFile, TestContent.siteUrl)
}
@Test
fun `processPost splices id and url for an image block`() {
val blocks = processor.processContent(TestContent.oldPostImage)
Assertions.assertThat(blocks).isEqualTo(TestContent.newPostImage)
}
@Test
fun `processPost splices id and url for a video block`() {
whenever(mediaFile.optimalFileURL).thenReturn(TestContent.remoteVideoUrl)
processor = MediaUploadCompletionProcessor(TestContent.localMediaId, mediaFile, TestContent.siteUrl)
val blocks = processor.processContent(TestContent.oldPostVideo)
Assertions.assertThat(blocks).isEqualTo(TestContent.newPostVideo)
}
@Test
fun `processPost splices id and url for a media-text block`() {
val blocks = processor.processContent(TestContent.oldPostMediaText)
Assertions.assertThat(blocks).isEqualTo(TestContent.newPostMediaText)
}
@Test
fun `processPost splices id and url for a gallery block`() {
val blocks = processor.processContent(TestContent.oldPostGallery)
Assertions.assertThat(blocks).isEqualTo(TestContent.newPostGallery)
}
@Test
fun `processPost splices id and url for a cover block`() {
val blocks = processor.processContent(TestContent.oldPostCover)
Assertions.assertThat(blocks).isEqualTo(TestContent.newPostCover)
}
@Test
fun `processPost works for nested inner cover blocks`() {
val blocks = processor.processContent(TestContent.oldCoverBlockWithNestedCoverBlockInner)
Assertions.assertThat(blocks).isEqualTo(TestContent.newCoverBlockWithNestedCoverBlockInner)
}
@Test
fun `processPost works for nested outer cover blocks`() {
whenever(mediaFile.mediaId).thenReturn(TestContent.remoteMediaId2)
whenever(mediaFile.optimalFileURL).thenReturn(TestContent.remoteImageUrl2)
processor = MediaUploadCompletionProcessor(TestContent.localMediaId2, mediaFile, TestContent.siteUrl)
val blocks = processor.processContent(TestContent.oldCoverBlockWithNestedCoverBlockOuter)
Assertions.assertThat(blocks).isEqualTo(TestContent.newCoverBlockWithNestedCoverBlockOuter)
}
@Test
fun `processPost works for image blocks nested within a cover block`() {
val processedContent = processor.processContent(TestContent.oldImageBlockNestedInCoverBlock)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newImageBlockNestedInCoverBlock)
}
@Test
fun `processPost leaves malformed cover block unchanged`() {
val processedContent = processor.processContent(TestContent.malformedCoverBlock)
Assertions.assertThat(processedContent).isEqualTo(TestContent.malformedCoverBlock)
}
@Test
fun `processPost can handle blocks with json-null ids`() {
val processedContent = processor.processContent(TestContent.oldPostWithJsonNullId)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newPostWithJsonNullId)
}
@Test
fun `processPost can handle blocks with json-null ids in gallery`() {
val processedContent = processor.processContent(TestContent.oldPostWithGalleryJsonNullId)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newPostWithGalleryJsonNullId)
}
@Test
fun `processPost can handle original galleries with refactored galleries present`() {
val processedContent = processor.processContent(TestContent.oldPostWithMixedGalleriesOriginal)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newPostWithMixedGalleriesOriginal)
}
@Test
fun `processPost can handle refactored galleries with original galleries present`() {
val processedContent = processor.processContent(TestContent.oldPostWithMixedGalleriesRefactored)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newPostWithMixedGalleriesRefactored)
}
}
| gpl-2.0 | c25cff332fb16fa4f956059999362a00 | 44.25 | 109 | 0.769388 | 4.584428 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradlePluginVersions.kt | 1 | 733 | // 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.codeInsight.gradle
import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion
import org.jetbrains.kotlin.tooling.core.isStable
object KotlinGradlePluginVersions {
val V_1_4_32 = KotlinToolingVersion(1, 4, 32, null)
val V_1_5_32 = KotlinToolingVersion(1, 5, 32, null)
val V_1_6_21 = KotlinToolingVersion(1, 6, 21, null)
val latest = KotlinToolingVersion("1.8.0-dev-446")
val all = listOf(
V_1_4_32,
V_1_5_32,
V_1_6_21,
latest
)
val allStable = all.filter { it.isStable }
val lastStable = allStable.max()
}
| apache-2.0 | a21d7d8a3b19d7d413cb57bba4342383 | 30.869565 | 120 | 0.687585 | 3.393519 | false | true | false | false |
bgorkowy/KotlinTodo.sh | app/src/main/java/com/cohesiva/kotlintodosh/TodoAdapter.kt | 1 | 1194 | package com.cohesiva.kotlintodosh
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import org.jetbrains.anko.text
/**
* Created by goorek on 24.07.15.
*/
public class TodoAdapter(val items: List<Todo> = listOf<Todo>()) : RecyclerView.Adapter<TodoAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? {
val view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_todo, parent, false);
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.priorityTextview.setText(items.get(position).priority.toString().toUpperCase())
holder.textTextview.setText(items.get(position).text)
}
override fun getItemCount(): Int = items.size()
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val priorityTextview = view.findViewById(R.id.listitem_todo_priority) as TextView
val textTextview = view.findViewById(R.id.listitem_todo_text) as TextView
}
} | apache-2.0 | a8f7823795d2379af123a67728df23e2 | 36.34375 | 115 | 0.743719 | 4.131488 | false | false | false | false |
bertilxi/DC-Android | app/src/main/java/utnfrsf/dondecurso/domain/Materia.kt | 1 | 1691 | package utnfrsf.dondecurso.domain
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class Materia(@SerializedName("id")
@Expose
var id: Int? = null,
@SerializedName("nombre")
@Expose
var nombre: String? = null,
@SerializedName("id_carrera")
@Expose
var idCarrera: Int? = null,
@SerializedName("comisiones")
@Expose
var comisiones: ArrayList<Comision>? = ArrayList(),
@SerializedName("nivel")
@Expose
var nivel: Int? = null) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readArrayList(Comision::class.java.classLoader) as ArrayList<Comision>,
parcel.readInt())
override fun toString(): String {
return nombre!!
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(id)
parcel.writeString(nombre)
parcel.writeValue(idCarrera)
parcel.writeValue(nivel)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Materia> {
override fun createFromParcel(parcel: Parcel): Materia {
return Materia(parcel)
}
override fun newArray(size: Int): Array<Materia?> {
return arrayOfNulls(size)
}
}
} | mit | 174ce9916ddf8f4a80f0b10ea6454bd2 | 29.214286 | 90 | 0.557067 | 4.901449 | false | false | false | false |
GunoH/intellij-community | platform/statistics/test/com/intellij/internal/statistic/TestStatisticsEventLogger.kt | 3 | 1681 | // 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.internal.statistic
import com.intellij.internal.statistic.eventLog.*
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import java.util.concurrent.CompletableFuture
class TestStatisticsEventLogger(private val session: String = "testSession",
private val build: String = "999.999",
private val bucket: String = "1",
private val recorderVersion: String = "1") : StatisticsEventLogger {
val logged = ArrayList<LogEvent>()
override fun logAsync(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean): CompletableFuture<Void> {
val eventTime = System.currentTimeMillis()
val event = newLogEvent(session, build, bucket, eventTime, group.id, group.version.toString(), recorderVersion, eventId, isState, data)
.escape()
logged.add(event)
return CompletableFuture.completedFuture(null)
}
override fun logAsync(group: EventLogGroup,
eventId: String,
dataProvider: () -> Map<String, Any>?,
isState: Boolean): CompletableFuture<Void> {
val data = dataProvider() ?: return CompletableFuture.completedFuture(null)
return logAsync(group, eventId, data, isState)
}
override fun getActiveLogFile(): EventLogFile? = null
override fun getLogFilesProvider(): EventLogFilesProvider = EmptyEventLogFilesProvider
override fun cleanup() {}
override fun rollOver() {}
} | apache-2.0 | 5cf84f51051c3e4d15bd4027260500e0 | 43.263158 | 158 | 0.684117 | 4.944118 | false | true | false | false |
hsrzq/droidBDF | chaotic/src/main/java/top/techqi/chaotic/base/BaseActivity.kt | 1 | 2570 | package top.techqi.chaotic.base
import android.content.Intent
import android.os.Bundle
import android.support.annotation.CallSuper
import android.support.v7.app.AppCompatActivity
import top.techqi.chaotic.BuildConfig
import top.techqi.chaotic.util.LogU
/**
* Activity 基类
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
abstract class BaseActivity : AppCompatActivity() {
@Suppress("PropertyName", "HasPlatformType")
protected open val TAG = javaClass.simpleName
@Suppress("PropertyName", "HasPlatformType")
protected open val NAME by lazy { TAG }
@Suppress("PropertyName")
protected open val DEBUG = BuildConfig.DEBUG
@Suppress("PropertyName")
val SOURCE: String? by lazy { intent.getStringExtra(EXTRA_SOURCE) }
var created = false
private set
var started = false
private set
var resumed = false
private set
val paused
get() = !resumed
val stopped
get() = !started
val destroyed
get() = !created
var restarted = 0
private set
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
if (DEBUG) LogU.vv(TAG, "onCreate")
super.onCreate(savedInstanceState)
created = true
}
@CallSuper
override fun onStart() {
if (DEBUG) LogU.vv(TAG, "onStart")
super.onStart()
started = true
}
@CallSuper
override fun onResume() {
if (DEBUG) LogU.vv(TAG, "onResume")
super.onResume()
resumed = true
}
@CallSuper
override fun onPause() {
resumed = false
super.onPause()
if (DEBUG) LogU.vv(TAG, "onPause")
}
@CallSuper
override fun onStop() {
started = false
super.onStop()
if (DEBUG) LogU.vv(TAG, "onStop")
}
@CallSuper
override fun onDestroy() {
created = false
super.onDestroy()
if (DEBUG) LogU.vv(TAG, "onDestroy")
}
@CallSuper
override fun onRestart() {
if (DEBUG) LogU.vv(TAG, "onRestart")
super.onRestart()
restarted++
}
override fun startActivityForResult(intent: Intent, requestCode: Int) {
intent.putExtra(EXTRA_SOURCE, NAME)
super.startActivityForResult(intent, requestCode)
}
override fun startActivities(intents: Array<out Intent>, options: Bundle?) {
intents.forEach { it.putExtra(EXTRA_SOURCE, NAME) }
super.startActivities(intents, options)
}
companion object {
const val EXTRA_SOURCE = "extra_source"
}
}
| mit | 1b4ac5bb3878adddf7dab054164dde2d | 23.438095 | 80 | 0.629774 | 4.356537 | false | false | false | false |
SpineEventEngine/base | base/src/test/kotlin/io/spine/io/ResourceTest.kt | 1 | 3300 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.io
import com.google.common.io.CharStreams
import com.google.common.testing.NullPointerTester
import com.google.common.truth.Truth.assertThat
import io.spine.testing.Assertions.assertIllegalState
import io.spine.testing.TestValues
import java.io.InputStream
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@DisplayName("`Resource` should")
class ResourceTest {
private lateinit var resource: Resource
companion object {
private const val resourceFile = "test_resource.txt"
private val classLoader = ResourceTest::class.java.classLoader
}
@BeforeEach
fun createResource() {
resource = Resource.file(resourceFile, classLoader)
}
@Test
fun `handle 'null' args`() {
NullPointerTester()
.setDefault(ClassLoader::class.java, classLoader)
.testAllPublicStaticMethods(Resource::class.java)
}
@Test
fun `throw ISE if queried for a non-existing file`() {
val name = TestValues.randomString()
val file = Resource.file(name, classLoader)
assertThat(file.exists()).isFalse()
assertIllegalState { file.locate() }
}
@Test
fun `identify a file under the resources directory`() {
assertThat(resource)
.isNotNull()
assertThat(resource.exists())
.isTrue()
assertThat(resource.locate())
.isNotNull()
assertThat(resource.locateAll())
.hasSize(1)
resource.open().use { stream -> assertNotEmpty(stream) }
}
@Test
fun `open as a byte stream`() {
resource.open().use { stream -> assertNotEmpty(stream) }
}
private fun assertNotEmpty(stream: InputStream) {
assertThat(stream.available()).isGreaterThan(0)
}
@Test
fun `open as a char stream`() {
resource.openAsText().use { reader ->
val content = CharStreams.toString(reader)
assertThat(content).isNotEmpty()
}
}
}
| apache-2.0 | 9f3db841bc9bdf820375fa3533754ab9 | 33.020619 | 73 | 0.692121 | 4.417671 | false | true | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/data/api/handler/ChannelHandler.kt | 1 | 3723 | /*
* Copyright � 2013 dvbviewer-controller 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 org.dvbviewer.controller.data.api.handler
import android.sax.RootElement
import android.util.Xml
import org.apache.commons.lang3.math.NumberUtils
import org.dvbviewer.controller.data.entities.Channel
import org.dvbviewer.controller.data.entities.ChannelGroup
import org.dvbviewer.controller.data.entities.ChannelRoot
import org.xml.sax.ContentHandler
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* The Class ChannelHandler.
*
* @author RayBa
*/
class ChannelHandler : DefaultHandler() {
private lateinit var rootElements: LinkedList<ChannelRoot>
private lateinit var currentRoot: ChannelRoot
private lateinit var currentGroup: ChannelGroup
private lateinit var currentChannel: Channel
private lateinit var favRootName: String
private var favPosition: Int = 1
@Throws(SAXException::class, IOException::class)
fun parse(inputStream: InputStream): MutableList<ChannelRoot> {
Xml.parse(inputStream, Xml.Encoding.UTF_8, getContentHandler())
return rootElements
}
private fun getContentHandler(): ContentHandler {
val channels = RootElement("channels")
val rootElement = channels.getChild("root")
val groupElement = rootElement.getChild("group")
val channelElement = groupElement.getChild("channel")
val subChanElement = channelElement.getChild("subchannel")
val logoElement = channelElement.getChild("logo")
channels.setStartElementListener { rootElements = LinkedList() }
rootElement.setStartElementListener { attributes ->
currentRoot = ChannelRoot()
currentRoot.name = attributes.getValue("name")
rootElements.add(currentRoot)
}
groupElement.setStartElementListener { attributes ->
currentGroup = ChannelGroup()
currentGroup.name = attributes.getValue("name")
currentRoot.groups.add(currentGroup)
}
channelElement.setStartElementListener { attributes ->
currentChannel = Channel()
currentChannel.channelID = NumberUtils.toLong(attributes.getValue("ID"))
currentChannel.position = favPosition
currentChannel.name = attributes.getValue("name")
currentChannel.epgID = NumberUtils.toLong(attributes.getValue("EPGID"))
currentGroup.channels.add(currentChannel)
favPosition++
}
logoElement.setEndTextElementListener { body -> currentChannel.logoUrl = body }
subChanElement.setStartElementListener { attributes ->
val c = Channel()
c.channelID = NumberUtils.toLong(attributes.getValue("ID"))
c.position = currentChannel.position
c.name = attributes.getValue("name")
c.epgID = currentChannel.epgID
c.logoUrl = currentChannel.logoUrl
c.setFlag(Channel.FLAG_ADDITIONAL_AUDIO)
currentGroup.channels.add(c)
}
return channels.contentHandler
}
}
| apache-2.0 | 7b2efadbea2d18ccd23b737ec9250120 | 36.969388 | 87 | 0.704381 | 4.734097 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/descriptions/DescriptionEditActivity.kt | 1 | 5871 | package org.wikipedia.descriptions
import android.content.Context
import android.content.Intent
import androidx.annotation.ColorInt
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.analytics.SuggestedEditsFunnel
import org.wikipedia.history.HistoryEntry
import org.wikipedia.json.GsonMarshaller
import org.wikipedia.json.GsonUnmarshaller
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.page.linkpreview.LinkPreviewDialog
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.util.ClipboardUtil
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ShareUtil
import org.wikipedia.views.ImagePreviewDialog
class DescriptionEditActivity : SingleFragmentActivity<DescriptionEditFragment>(), DescriptionEditFragment.Callback, LinkPreviewDialog.Callback {
enum class Action {
ADD_DESCRIPTION, TRANSLATE_DESCRIPTION, ADD_CAPTION, TRANSLATE_CAPTION, ADD_IMAGE_TAGS, IMAGE_RECOMMENDATION
}
private lateinit var action: Action
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
public override fun createFragment(): DescriptionEditFragment {
val invokeSource = intent.getSerializableExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource
action = intent.getSerializableExtra(Constants.INTENT_EXTRA_ACTION) as Action
val title = intent.getParcelableExtra<PageTitle>(EXTRA_TITLE)!!
SuggestedEditsFunnel.get()!!.click(title.displayText, action)
return DescriptionEditFragment.newInstance(title,
intent.getStringExtra(EXTRA_HIGHLIGHT_TEXT),
intent.getStringExtra(EXTRA_SOURCE_SUMMARY),
intent.getStringExtra(EXTRA_TARGET_SUMMARY),
action,
invokeSource)
}
override fun onBackPressed() {
if (fragment.binding.fragmentDescriptionEditView.showingReviewContent()) {
fragment.binding.fragmentDescriptionEditView.loadReviewContent(false)
} else {
DeviceUtil.hideSoftKeyboard(this)
SuggestedEditsFunnel.get()!!.cancel(action)
super.onBackPressed()
}
}
override fun onDescriptionEditSuccess() {
setResult(DescriptionEditSuccessActivity.RESULT_OK_FROM_EDIT_SUCCESS)
finish()
}
override fun onBottomBarContainerClicked(action: Action) {
val summary: PageSummaryForEdit = if (action == Action.TRANSLATE_DESCRIPTION) {
GsonUnmarshaller.unmarshal(PageSummaryForEdit::class.java, intent.getStringExtra(EXTRA_TARGET_SUMMARY))
} else {
GsonUnmarshaller.unmarshal(PageSummaryForEdit::class.java, intent.getStringExtra(EXTRA_SOURCE_SUMMARY))
}
if (action == Action.ADD_CAPTION || action == Action.TRANSLATE_CAPTION) {
bottomSheetPresenter.show(supportFragmentManager,
ImagePreviewDialog.newInstance(summary, action))
} else {
bottomSheetPresenter.show(supportFragmentManager,
LinkPreviewDialog.newInstance(HistoryEntry(summary.pageTitle,
if (intent.hasExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE) && intent.getSerializableExtra
(Constants.INTENT_EXTRA_INVOKE_SOURCE) === InvokeSource.PAGE_ACTIVITY)
HistoryEntry.SOURCE_EDIT_DESCRIPTION else HistoryEntry.SOURCE_SUGGESTED_EDITS), null))
}
}
override fun onLinkPreviewLoadPage(title: PageTitle, entry: HistoryEntry, inNewTab: Boolean) {
startActivity(PageActivity.newIntentForCurrentTab(this, entry, entry.title))
}
override fun onLinkPreviewCopyLink(title: PageTitle) {
ClipboardUtil.setPlainText(this, null, title.uri)
FeedbackUtil.showMessage(this, R.string.address_copied)
}
override fun onLinkPreviewAddToList(title: PageTitle) {
bottomSheetPresenter.show(supportFragmentManager,
AddToReadingListDialog.newInstance(title, InvokeSource.LINK_PREVIEW_MENU))
}
override fun onLinkPreviewShareLink(title: PageTitle) {
ShareUtil.shareText(this, title)
}
fun updateStatusBarColor(@ColorInt color: Int) {
setStatusBarColor(color)
}
fun updateNavigationBarColor(@ColorInt color: Int) {
setNavigationBarColor(color)
}
companion object {
private const val EXTRA_TITLE = "title"
private const val EXTRA_HIGHLIGHT_TEXT = "highlightText"
private const val EXTRA_SOURCE_SUMMARY = "sourceSummary"
private const val EXTRA_TARGET_SUMMARY = "targetSummary"
@JvmStatic
fun newIntent(context: Context,
title: PageTitle,
highlightText: String?,
sourceSummary: PageSummaryForEdit?,
targetSummary: PageSummaryForEdit?,
action: Action,
invokeSource: InvokeSource): Intent {
return Intent(context, DescriptionEditActivity::class.java)
.putExtra(EXTRA_TITLE, title)
.putExtra(EXTRA_HIGHLIGHT_TEXT, highlightText)
.putExtra(EXTRA_SOURCE_SUMMARY, if (sourceSummary == null) null else GsonMarshaller.marshal(sourceSummary))
.putExtra(EXTRA_TARGET_SUMMARY, if (targetSummary == null) null else GsonMarshaller.marshal(targetSummary))
.putExtra(Constants.INTENT_EXTRA_ACTION, action)
.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, invokeSource)
}
}
}
| apache-2.0 | 87cde3374617c0736fa5a6d20da10941 | 44.511628 | 145 | 0.701243 | 5.279676 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/imports/internal/conflicts/LackingTEICascadeDeleteAuthorityConflictShould.kt | 1 | 2475 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.imports.internal.conflicts
import org.junit.Test
internal class LackingTEICascadeDeleteAuthorityConflictShould : BaseConflictShould() {
private val importConflict = TrackedImportConflictSamples.userIsLackingTEICascadeDeleteAuthority(teiUid)
@Test
fun `Should match error message`() {
assert(LackingTEICascadeDeleteAuthorityConflict.matches(importConflict))
}
@Test
fun `Should match enrollment uid`() {
val value = LackingTEICascadeDeleteAuthorityConflict.getTrackedEntityInstance(importConflict)
assert(value == teiUid)
}
@Test
fun `Should create display description`() {
val displayDescription = LackingTEICascadeDeleteAuthorityConflict.getDisplayDescription(importConflict, context)
assert(displayDescription == "You lack the authority to delete the entity: $teiUid")
}
}
| bsd-3-clause | 271400cd9fe0f421a40bb0d7b8d4d1f9 | 46.596154 | 120 | 0.765253 | 4.591837 | false | true | false | false |
paplorinc/intellij-community | python/testSrc/com/jetbrains/python/testing/PyTestMagnitudeTest.kt | 2 | 3797 | // 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.testing
import com.intellij.execution.testframework.sm.runner.SMTestProxy
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo
import com.jetbrains.env.PyAbstractTestProcessRunner
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class PyTestMagnitudeTest {
private lateinit var root: SMTestProxy.SMRootTestProxy
private val tree: String get() = PyAbstractTestProcessRunner.getFormattedTestTree(root)
private val test11 = "test11"
@Before
fun setUp() {
root = SMTestProxy.SMRootTestProxy()
val file1 = SMTestProxy("file1", false, null)
val test11 = SMTestProxy(test11, false, null)
val test12 = SMTestProxy("test12", false, null)
val file2 = SMTestProxy("file2", false, null)
val test21 = SMTestProxy("test21", false, null)
val test22 = SMTestProxy("test22", false, null)
file1.addChild(test11)
file1.addChild(test12)
file2.addChild(test21)
file2.addChild(test22)
root.addChild(file1)
root.addChild(file2)
}
@Test
fun testSuccessPass() {
root.children.forEach { file ->
file.children.forEach { test ->
test.setStarted()
test.setFinished()
}
}
Assert.assertEquals(TestStateInfo.Magnitude.PASSED_INDEX, root.calculateAndReturnMagnitude())
Assert.assertEquals("Test tree:\n" +
"[root](+)\n" +
".file1(+)\n" +
"..test11(+)\n" +
"..test12(+)\n" +
".file2(+)\n" +
"..test21(+)\n" +
"..test22(+)\n", tree)
}
@Test
fun testFailedOne() {
root.children.forEach { file ->
file.children.forEach { test ->
test.setStarted()
if (test.name == test11) test.setTestFailed("fail", null, false) else test.setFinished()
}
}
Assert.assertEquals(TestStateInfo.Magnitude.FAILED_INDEX, root.calculateAndReturnMagnitude())
Assert.assertEquals("Test tree:\n" +
"[root](-)\n" +
".file1(-)\n" +
"..test11(-)\n" +
"..test12(+)\n" +
".file2(+)\n" +
"..test21(+)\n" +
"..test22(+)\n", tree)
}
@Test
fun testTerminatedOne() {
root.children.forEach { file ->
file.children.forEach { test ->
test.setStarted()
if (test.name != test11) {
test.setFinished()
}
}
}
Assert.assertEquals(TestStateInfo.Magnitude.TERMINATED_INDEX, root.calculateAndReturnMagnitude())
Assert.assertEquals("Test tree:\n" +
"[root][T]\n" +
".file1[T]\n" +
"..test11[T]\n" +
"..test12(+)\n" +
".file2(+)\n" +
"..test21(+)\n" +
"..test22(+)\n", tree)
}
@Test
fun testIgnoredAll() {
root.children.forEach { file ->
file.children.forEach { test ->
test.setStarted()
test.setTestIgnored("for a good reason", null)
}
}
Assert.assertEquals(TestStateInfo.Magnitude.IGNORED_INDEX, root.calculateAndReturnMagnitude())
Assert.assertEquals("Test tree:\n" +
"[root](~)\n" +
".file1(~)\n" +
"..test11(~)\n" +
"..test12(~)\n" +
".file2(~)\n" +
"..test21(~)\n" +
"..test22(~)\n", tree)
}
}
| apache-2.0 | 1f87e5a75693e015ff51b709df5ff335 | 30.380165 | 140 | 0.529892 | 4.261504 | false | true | false | false |
google/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindClassUsagesHandler.kt | 2 | 7945 | // 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.findUsages.handlers
import com.intellij.find.findUsages.AbstractFindUsagesDialog
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.find.findUsages.JavaFindUsagesHelper
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.PsiElementProcessorAdapter
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.util.FilteredQuery
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.findUsages.KotlinClassFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.isConstructorUsage
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.processCompanionObjectInternalReferences
import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindClassUsagesDialog
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.psi.psiUtil.effectiveDeclarations
import java.util.*
class KotlinFindClassUsagesHandler(
ktClass: KtClassOrObject,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindUsagesHandler<KtClassOrObject>(ktClass, factory) {
override fun getFindUsagesDialog(
isSingleFile: Boolean, toShowInNewTab: Boolean, mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
return KotlinFindClassUsagesDialog(
getElement(),
project,
factory.findClassOptions,
toShowInNewTab,
mustOpenInNewTab,
isSingleFile,
this
)
}
override fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher {
return MySearcher(element, processor, options)
}
private class MySearcher(
element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions
) : Searcher(element, processor, options) {
private val kotlinOptions = options as KotlinClassFindUsagesOptions
private val referenceProcessor = createReferenceProcessor(processor)
override fun buildTaskList(forHighlight: Boolean): Boolean {
val classOrObject = element as KtClassOrObject
if (kotlinOptions.isUsages || kotlinOptions.searchConstructorUsages) {
processClassReferencesLater(classOrObject)
}
if (kotlinOptions.isFieldsUsages || kotlinOptions.isMethodsUsages) {
processMemberReferencesLater(classOrObject)
}
if (kotlinOptions.isUsages && classOrObject is KtObjectDeclaration && classOrObject.isCompanion() && classOrObject in options.searchScope) {
if (!processCompanionObjectInternalReferences(classOrObject, referenceProcessor)) return false
}
if (kotlinOptions.searchConstructorUsages) {
classOrObject.toLightClass()?.constructors?.filterIsInstance<KtLightMethod>()?.forEach { constructor ->
val scope = constructor.useScope.intersectWith(options.searchScope)
var query = MethodReferencesSearch.search(constructor, scope, true)
if (kotlinOptions.isSkipImportStatements) {
query = FilteredQuery(query) { !it.isImportUsage() }
}
addTask { query.forEach(Processor { referenceProcessor.process(it) }) }
}
}
if (kotlinOptions.isDerivedClasses || kotlinOptions.isDerivedInterfaces) {
processInheritorsLater()
}
return true
}
private fun processInheritorsLater() {
val request = HierarchySearchRequest(element, options.searchScope, kotlinOptions.isCheckDeepInheritance)
addTask {
request.searchInheritors().forEach(
PsiElementProcessorAdapter(
PsiElementProcessor<PsiClass> { element ->
runReadAction {
if (!element.isValid) return@runReadAction false
val isInterface = element.isInterface
when {
isInterface && kotlinOptions.isDerivedInterfaces || !isInterface && kotlinOptions.isDerivedClasses ->
processUsage(processor, element.navigationElement)
else -> true
}
}
}
)
)
}
}
private fun processClassReferencesLater(classOrObject: KtClassOrObject) {
val searchParameters = KotlinReferencesSearchParameters(
classOrObject,
scope = options.searchScope,
kotlinOptions = KotlinReferencesSearchOptions(
acceptCompanionObjectMembers = true,
searchForExpectedUsages = kotlinOptions.searchExpected
)
)
var usagesQuery = ReferencesSearch.search(searchParameters)
if (kotlinOptions.isSkipImportStatements) {
usagesQuery = FilteredQuery(usagesQuery) { !it.isImportUsage() }
}
if (!kotlinOptions.searchConstructorUsages) {
usagesQuery = FilteredQuery(usagesQuery) { !it.isConstructorUsage(classOrObject) }
} else if (!options.isUsages) {
usagesQuery = FilteredQuery(usagesQuery) { it.isConstructorUsage(classOrObject) }
}
addTask { usagesQuery.forEach(referenceProcessor) }
}
private fun processMemberReferencesLater(classOrObject: KtClassOrObject) {
for (declaration in classOrObject.effectiveDeclarations()) {
if ((declaration is KtNamedFunction && kotlinOptions.isMethodsUsages) ||
((declaration is KtProperty || declaration is KtParameter) && kotlinOptions.isFieldsUsages)
) {
addTask { ReferencesSearch.search(declaration, options.searchScope).forEach(referenceProcessor) }
}
}
}
}
override fun getStringsToSearch(element: PsiElement): Collection<String> {
val psiClass = when (element) {
is PsiClass -> element
is KtClassOrObject -> getElement().toLightClass()
else -> null
} ?: return Collections.emptyList()
return JavaFindUsagesHelper.getElementNames(psiClass)
}
override fun isSearchForTextOccurrencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean {
return !isSingleFile
}
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions {
return factory.findClassOptions
}
}
| apache-2.0 | c7952a1cf9bfe8fefb07aa6f040164fd | 44.4 | 158 | 0.672373 | 5.867799 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/MutableWorkspaceCollections.kt | 2 | 3879 | // 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.workspaceModel.storage.impl.containers
import java.util.*
import java.util.function.Predicate
import java.util.function.UnaryOperator
import kotlin.collections.List
/**
* Sublist isn't update indexes for now
*/
class MutableWorkspaceList<E>(collection: Collection<E>) : ArrayList<E>(collection) {
private lateinit var updateAction: (value: List<E>) -> Unit
override fun add(element: E): Boolean {
val result = super.add(element)
callForOutsideUpdate()
return result
}
override fun add(index: Int, element: E) {
super.add(index, element)
callForOutsideUpdate()
}
override fun addAll(elements: Collection<E>): Boolean {
val result = super.addAll(elements)
callForOutsideUpdate()
return result
}
override fun addAll(index: Int, elements: Collection<E>): Boolean {
val result = super.addAll(index, elements)
callForOutsideUpdate()
return result
}
override fun clear() {
super.clear()
callForOutsideUpdate()
}
override fun remove(element: E): Boolean {
val result = super.remove(element)
callForOutsideUpdate()
return result
}
override fun removeAll(elements: Collection<E>): Boolean {
val result = super.removeAll(elements)
callForOutsideUpdate()
return result
}
override fun retainAll(elements: Collection<E>): Boolean {
val result = super.retainAll(elements)
callForOutsideUpdate()
return result
}
override fun removeIf(filter: Predicate<in E>): Boolean {
val result = super.removeIf(filter)
callForOutsideUpdate()
return result
}
override fun removeAt(index: Int): E {
val result = super.removeAt(index)
callForOutsideUpdate()
return result
}
override fun set(index: Int, element: E): E {
val result = super.set(index, element)
callForOutsideUpdate()
return result
}
override fun replaceAll(operator: UnaryOperator<E>) {
super.replaceAll(operator)
callForOutsideUpdate()
}
fun setModificationUpdateAction(updater: (value: List<E>) -> Unit) {
updateAction = updater
}
private fun callForOutsideUpdate() {
updateAction.invoke(this)
}
}
fun <T> Collection<T>.toMutableWorkspaceList(): MutableWorkspaceList<T> {
return MutableWorkspaceList(this)
}
/**
* [MutableIterable.removeAll] and [MutableIterator.remove] aren't update indexes for now
*/
class MutableWorkspaceSet<E>(collection: Collection<E>) : LinkedHashSet<E>(collection) {
private var updateAction: ((Set<E>) -> Unit)? = null
override fun add(element: E): Boolean {
val result = super.add(element)
callForOutsideUpdate()
return result
}
override fun addAll(elements: Collection<E>): Boolean {
val result = super.addAll(elements)
callForOutsideUpdate()
return result
}
override fun clear() {
super.clear()
callForOutsideUpdate()
}
override fun remove(element: E): Boolean {
val result = super.remove(element)
callForOutsideUpdate()
return result
}
override fun removeAll(elements: Collection<E>): Boolean {
val result = super.removeAll(elements)
callForOutsideUpdate()
return result
}
override fun retainAll(elements: Collection<E>): Boolean {
val result = super.retainAll(elements)
callForOutsideUpdate()
return result
}
override fun removeIf(filter: Predicate<in E>): Boolean {
val result = super.removeIf(filter)
callForOutsideUpdate()
return result
}
fun setModificationUpdateAction(updater: (value: Set<E>) -> Unit) {
updateAction = updater
}
private fun callForOutsideUpdate() {
updateAction?.invoke(this)
}
}
fun <T> Collection<T>.toMutableWorkspaceSet(): MutableWorkspaceSet<T> {
return MutableWorkspaceSet(this)
} | apache-2.0 | d4eabdc7508d515b203e48389839a094 | 24.032258 | 120 | 0.704047 | 4.153105 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/features/stories/ui/adapter/StoriesAdapter.kt | 2 | 3109 | package org.stepic.droid.features.stories.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.material.imageview.ShapeableImageView
import kotlinx.android.synthetic.main.view_story_item.view.*
import org.stepic.droid.R
import ru.nobird.android.stories.model.Story
import kotlin.properties.Delegates
class StoriesAdapter(
private val onStoryClicked: (Story, Int) -> Unit
) : RecyclerView.Adapter<StoriesAdapter.StoryViewHolder>() {
var stories: List<Story> = emptyList()
private set
var viewedStoryIds: Set<Long> = emptySet()
private set
var selected: Int by Delegates.observable(-1) { _, old, new ->
notifyItemChanged(old)
notifyItemChanged(new)
}
fun setData(stories: List<Story>, viewedStoryIds: Set<Long>) {
var updateNeeded = false
if (this.stories != stories) {
this.stories = stories
updateNeeded = true
}
if (this.viewedStoryIds != viewedStoryIds) {
if (updateNeeded) {
this.viewedStoryIds = viewedStoryIds
} else {
val diff = viewedStoryIds - this.viewedStoryIds
this.viewedStoryIds = viewedStoryIds
diff.forEach { storyId ->
val index = stories.indexOfFirst { it.id == storyId }
if (index != -1) {
notifyItemChanged(index)
}
}
}
}
if (updateNeeded) {
notifyDataSetChanged()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = StoryViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.view_story_item, parent, false)
)
override fun getItemCount() = stories.size
override fun onBindViewHolder(holder: StoryViewHolder, position: Int) {
holder.bind(position)
}
inner class StoryViewHolder(root: View) : RecyclerView.ViewHolder(root) {
val cover: ShapeableImageView = root.storyCover
private val title = root.storyTitle
private val activeStoryMarker = root.activeStoryMarker
init {
root.setOnClickListener {
if (adapterPosition in stories.indices) {
onStoryClicked(stories[adapterPosition], adapterPosition)
}
}
}
fun bind(position: Int) {
val story = stories[position]
title.text = story.title
Glide.with(itemView.context)
.asBitmap()
.load(story.cover)
.placeholder(R.drawable.ic_general_placeholder_dark)
.centerCrop()
.into(cover)
activeStoryMarker.isGone = story.id in viewedStoryIds
itemView.isInvisible = position == selected
}
}
} | apache-2.0 | a32790866f44c6fe4f26419286385f89 | 31.395833 | 96 | 0.610807 | 4.724924 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/MoreSquareStripeButton.kt | 3 | 2438 | // 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 com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.ToolwindowSwitcher
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.wm.ToolWindow
import com.intellij.ui.UIBundle
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.UIUtil
import java.awt.Dimension
import java.awt.Point
import java.util.function.Predicate
class MoreSquareStripeButton(toolwindowSideBar: ToolwindowToolbar) :
ActionButton(createAction(toolwindowSideBar), createPresentation(), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) {
override fun updateToolTipText() {
HelpTooltip().
setTitle(UIBundle.message("title.tool.window.square.more")).
setLocation(HelpTooltip.Alignment.RIGHT).
setInitialDelay(0).setHideDelay(0).
installOn(this)
}
companion object {
val largeStripeToolwindowPredicate: Predicate<ToolWindow> = Predicate { !it.isVisibleOnLargeStripe }
fun createPresentation(): Presentation {
return Presentation().apply {
icon = AllIcons.Actions.MoreHorizontal
isEnabledAndVisible = true
}
}
fun createAction(toolwindowSideBar: ToolwindowToolbar): DumbAwareAction =
object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val moreSquareStripeButton = UIUtil.findComponentOfType(toolwindowSideBar, MoreSquareStripeButton::class.java)
ToolwindowSwitcher.invokePopup(e.project!!, Comparator.comparing { toolwindow: ToolWindow -> toolwindow.stripeTitle },
largeStripeToolwindowPredicate,
RelativePoint(toolwindowSideBar, Point(toolwindowSideBar.width, moreSquareStripeButton?.y ?: 0)))
}
override fun update(e: AnActionEvent) {
e.project?.let {
e.presentation.isEnabledAndVisible = ToolwindowSwitcher.getToolWindows(it, largeStripeToolwindowPredicate).isNotEmpty()
}
}
}
}
} | apache-2.0 | 760081f9a574434bf283a76a207064b6 | 41.789474 | 140 | 0.741181 | 4.905433 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/view/main/MainView.kt | 1 | 4573 | /*
* (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.acra.ui.view.main
import com.faendir.acra.i18n.Messages
import com.faendir.acra.model.User
import com.faendir.acra.security.SecurityUtils
import com.faendir.acra.ui.component.tabs.Path
import com.faendir.acra.ui.component.Translatable
import com.faendir.acra.ui.ext.SizeUnit
import com.faendir.acra.ui.ext.content
import com.faendir.acra.ui.ext.setFlexGrow
import com.faendir.acra.ui.ext.setHeight
import com.faendir.acra.ui.ext.setPaddingRight
import com.faendir.acra.ui.view.AboutView
import com.faendir.acra.ui.view.Overview
import com.faendir.acra.ui.view.SettingsView
import com.faendir.acra.ui.view.user.AccountView
import com.faendir.acra.ui.view.user.UserManager
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.Composite
import com.vaadin.flow.component.HasElement
import com.vaadin.flow.component.applayout.AppLayout
import com.vaadin.flow.component.applayout.DrawerToggle
import com.vaadin.flow.component.button.ButtonVariant
import com.vaadin.flow.component.dependency.CssImport
import com.vaadin.flow.component.dependency.JsModule
import com.vaadin.flow.component.html.Div
import com.vaadin.flow.component.icon.VaadinIcon
import com.vaadin.flow.component.tabs.Tab
import com.vaadin.flow.component.tabs.Tabs
import com.vaadin.flow.router.RouterLayout
import com.vaadin.flow.router.RouterLink
import com.vaadin.flow.spring.annotation.SpringComponent
import com.vaadin.flow.spring.annotation.UIScope
import org.springframework.context.support.GenericApplicationContext
import org.springframework.security.core.context.SecurityContextHolder
import kotlin.reflect.KClass
import kotlin.streams.asSequence
/**
* @author lukas
* @since 13.07.18
*/
@JsModule("./styles/shared-styles.js")
@CssImport("./styles/global.css")
@UIScope
@SpringComponent
class MainView(applicationContext: GenericApplicationContext) : Composite<AppLayout>(), RouterLayout {
private val targets: MutableMap<Class<out HasElement>, Tab> = mutableMapOf()
private val tabs: Tabs
init {
tabs = Tabs().apply {
orientation = Tabs.Orientation.VERTICAL
add(createTab<Overview>(Messages.HOME))
add(Path(applicationContext))
add(createTab<AccountView>(Messages.ACCOUNT))
if (SecurityUtils.hasRole(User.Role.ADMIN)) {
add(createTab<UserManager>(Messages.USER_MANAGER))
}
add(createTab<SettingsView>(Messages.SETTINGS))
add(createTab<AboutView>(Messages.ABOUT))
}
content {
element.style["width"] = "100%"
element.style["height"] = "100%"
primarySection = AppLayout.Section.DRAWER
addToDrawer(tabs)
addToNavbar(
DrawerToggle(),
Translatable.createImage("images/logo.png", Messages.ACRARIUM).with {
setHeight(32, SizeUnit.PIXEL)
},
Div().apply { setFlexGrow(1) },
Translatable.createButton(Messages.LOGOUT) { logout() }.with {
icon = VaadinIcon.POWER_OFF.create()
removeThemeVariants(ButtonVariant.LUMO_PRIMARY)
addThemeVariants(ButtonVariant.LUMO_TERTIARY)
setPaddingRight(10.0, SizeUnit.PIXEL)
}
)
}
}
private inline fun <reified T : Component> createTab(captionId: String) : Tab {
val tab = Tab(Translatable.createRouterLink(T::class, captionId = captionId))
targets[T::class.java] = tab
return tab
}
private fun logout() {
SecurityContextHolder.clearContext()
ui.ifPresent {
it.page.reload()
it.session.close()
}
}
override fun showRouterLayoutContent(content: HasElement) {
super.showRouterLayoutContent(content)
targets[content.javaClass]?.let { tabs.selectedTab = it }
}
} | apache-2.0 | 237a04f652bb1d2b78e22c27defa46ae | 38.094017 | 102 | 0.703914 | 4.050487 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/scanner/Scanner.kt | 1 | 3052 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.scanner
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.permission.PermissionService
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.wifi.manager.WiFiManagerWrapper
import com.vrem.wifianalyzer.wifi.model.WiFiData
@OpenClass
internal class Scanner(
val wiFiManagerWrapper: WiFiManagerWrapper,
val settings: Settings,
val permissionService: PermissionService,
val transformer: Transformer
) : ScannerService {
private val updateNotifiers: MutableList<UpdateNotifier> = mutableListOf()
private var wiFiData: WiFiData = WiFiData.EMPTY
private var initialScan: Boolean = false
lateinit var periodicScan: PeriodicScan
lateinit var scannerCallback: ScannerCallback
lateinit var scanResultsReceiver: ScanResultsReceiver
override fun update() {
wiFiManagerWrapper.enableWiFi()
if (permissionService.enabled()) {
scanResultsReceiver.register()
wiFiManagerWrapper.startScan()
if (!initialScan) {
scannerCallback.onSuccess()
initialScan = true
}
}
wiFiData = transformer.transformToWiFiData()
updateNotifiers.forEach { it.update(wiFiData) }
}
override fun wiFiData(): WiFiData = wiFiData
override fun register(updateNotifier: UpdateNotifier): Boolean = updateNotifiers.add(updateNotifier)
override fun unregister(updateNotifier: UpdateNotifier): Boolean = updateNotifiers.remove(updateNotifier)
override fun pause() {
periodicScan.stop()
scanResultsReceiver.unregister()
}
override fun running(): Boolean = periodicScan.running
override fun resume(): Unit = periodicScan.start()
override fun resumeWithDelay(): Unit = periodicScan.startWithDelay()
override fun stop() {
periodicScan.stop()
updateNotifiers.clear()
if (settings.wiFiOffOnExit()) {
wiFiManagerWrapper.disableWiFi()
}
scanResultsReceiver.unregister()
}
override fun toggle(): Unit =
if (periodicScan.running) {
periodicScan.stop()
} else {
periodicScan.start()
}
fun registered(): Int = updateNotifiers.size
} | gpl-3.0 | 066494fe5b233a6f82cec789e2b0e796 | 32.549451 | 109 | 0.70806 | 4.875399 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/InteropLowering.kt | 2 | 34201 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.descriptors.allParameters
import org.jetbrains.kotlin.backend.common.lower.*
import org.jetbrains.kotlin.backend.common.peek
import org.jetbrains.kotlin.backend.common.pop
import org.jetbrains.kotlin.backend.common.push
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue
import org.jetbrains.kotlin.backend.konan.descriptors.isInterface
import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptorImpl
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.annotations.AnnotationsImpl
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.isUnit
internal class InteropLoweringPart1(val context: Context) : IrBuildingTransformer(context), FileLoweringPass {
private val symbols get() = context.ir.symbols
private val symbolTable get() = symbols.symbolTable
lateinit var currentFile: IrFile
private val topLevelInitializers = mutableListOf<IrExpression>()
override fun lower(irFile: IrFile) {
currentFile = irFile
irFile.transformChildrenVoid(this)
topLevelInitializers.forEach { irFile.addTopLevelInitializer(it) }
topLevelInitializers.clear()
}
private fun IrBuilderWithScope.callAlloc(classSymbol: IrClassSymbol): IrExpression {
return irCall(symbols.interopAllocObjCObject, listOf(classSymbol.descriptor.defaultType)).apply {
putValueArgument(0, getObjCClass(classSymbol))
}
}
private fun IrBuilderWithScope.getObjCClass(classSymbol: IrClassSymbol): IrExpression {
val classDescriptor = classSymbol.descriptor
assert(!classDescriptor.isObjCMetaClass())
if (classDescriptor.isExternalObjCClass()) {
val companionObject = classDescriptor.companionObjectDescriptor!!
if (companionObject.unsubstitutedPrimaryConstructor != scope.scopeOwner) {
// Optimization: get class pointer from companion object thus avoiding lookup by name.
return irCall(symbols.interopObjCObjectRawValueGetter).apply {
extensionReceiver = irGetObject(symbolTable.referenceClass(companionObject))
}
}
}
return irCall(symbols.interopGetObjCClass, listOf(classDescriptor.defaultType))
}
private val outerClasses = mutableListOf<IrClass>()
override fun visitClass(declaration: IrClass): IrStatement {
if (declaration.descriptor.isKotlinObjCClass()) {
lowerKotlinObjCClass(declaration)
}
outerClasses.push(declaration)
try {
return super.visitClass(declaration)
} finally {
outerClasses.pop()
}
}
private fun lowerKotlinObjCClass(irClass: IrClass) {
checkKotlinObjCClass(irClass)
val interop = context.interopBuiltIns
irClass.declarations.mapNotNull {
when {
it is IrSimpleFunction && it.descriptor.annotations.hasAnnotation(interop.objCAction) ->
generateActionImp(it)
it is IrProperty && it.descriptor.annotations.hasAnnotation(interop.objCOutlet) ->
generateOutletSetterImp(it)
else -> null
}
}.let { irClass.declarations.addAll(it) }
if (irClass.descriptor.annotations.hasAnnotation(interop.exportObjCClass.fqNameSafe)) {
val irBuilder = context.createIrBuilder(currentFile.symbol).at(irClass)
topLevelInitializers.add(irBuilder.getObjCClass(irClass.symbol))
}
}
private fun generateActionImp(function: IrSimpleFunction): IrSimpleFunction {
val action = "@${context.interopBuiltIns.objCAction.name}"
function.extensionReceiverParameter?.let {
context.reportCompilationError("$action method must not have extension receiver",
currentFile, it)
}
function.valueParameters.forEach {
val kotlinType = it.descriptor.type
if (!kotlinType.isObjCObjectType()) {
context.reportCompilationError("Unexpected $action method parameter type: $kotlinType\n" +
"Only Objective-C object types are supported here",
currentFile, it)
}
}
val returnType = function.descriptor.returnType!!
if (!returnType.isUnit()) {
context.reportCompilationError("Unexpected $action method return type: $returnType\n" +
"Only 'Unit' is supported here",
currentFile, function
)
}
return generateFunctionImp(inferObjCSelector(function.descriptor), function)
}
private fun generateOutletSetterImp(property: IrProperty): IrSimpleFunction {
val descriptor = property.descriptor
val outlet = "@${context.interopBuiltIns.objCOutlet.name}"
if (!descriptor.isVar) {
context.reportCompilationError("$outlet property must be var",
currentFile, property)
}
property.getter?.extensionReceiverParameter?.let {
context.reportCompilationError("$outlet must not have extension receiver",
currentFile, it)
}
val type = descriptor.type
if (!type.isObjCObjectType()) {
context.reportCompilationError("Unexpected $outlet type: $type\n" +
"Only Objective-C object types are supported here",
currentFile, property)
}
val name = descriptor.name.asString()
val selector = "set${name.capitalize()}:"
return generateFunctionImp(selector, property.setter!!)
}
private fun getMethodSignatureEncoding(function: IrFunction): String {
assert(function.extensionReceiverParameter == null)
assert(function.valueParameters.all { it.type.isObjCObjectType() })
assert(function.descriptor.returnType!!.isUnit())
// Note: these values are valid for x86_64 and arm64.
return when (function.valueParameters.size) {
0 -> "v16@0:8"
1 -> "v24@0:8@16"
2 -> "v32@0:8@16@24"
else -> context.reportCompilationError("Only 0, 1 or 2 parameters are supported here",
currentFile, function
)
}
}
private fun generateFunctionImp(selector: String, function: IrFunction): IrSimpleFunction {
val signatureEncoding = getMethodSignatureEncoding(function)
val returnType = function.descriptor.returnType!!
assert(returnType.isUnit())
val nativePtrType = context.builtIns.nativePtr.defaultType
val parameterTypes = mutableListOf(nativePtrType) // id self
parameterTypes.add(nativePtrType) // SEL _cmd
function.valueParameters.mapTo(parameterTypes) {
when {
it.descriptor.type.isObjCObjectType() -> nativePtrType
else -> TODO()
}
}
// Annotations to be detected in KotlinObjCClassInfoGenerator:
val annotations = createObjCMethodImpAnnotations(selector = selector, encoding = signatureEncoding)
val newDescriptor = SimpleFunctionDescriptorImpl.create(
function.descriptor.containingDeclaration,
annotations,
("imp:" + selector).synthesizedName,
CallableMemberDescriptor.Kind.SYNTHESIZED,
SourceElement.NO_SOURCE
)
val valueParameters = parameterTypes.mapIndexed { index, it ->
ValueParameterDescriptorImpl(
newDescriptor,
null,
index,
Annotations.EMPTY,
Name.identifier("p$index"),
it,
false,
false,
false,
null,
SourceElement.NO_SOURCE
)
}
newDescriptor.initialize(
null, null,
emptyList(),
valueParameters,
returnType,
Modality.FINAL,
Visibilities.PRIVATE
)
val newFunction = IrFunctionImpl(
function.startOffset, function.endOffset,
IrDeclarationOrigin.DEFINED,
newDescriptor
).apply { createParameterDeclarations() }
val builder = context.createIrBuilder(newFunction.symbol)
newFunction.body = builder.irBlockBody(newFunction) {
+irCall(function.symbol).apply {
dispatchReceiver = interpretObjCPointer(
irGet(newFunction.valueParameters[0].symbol),
function.dispatchReceiverParameter!!.type
)
function.valueParameters.forEachIndexed { index, parameter ->
putValueArgument(index,
interpretObjCPointer(
irGet(newFunction.valueParameters[index + 2].symbol),
parameter.type
)
)
}
}
}
return newFunction
}
private fun IrBuilderWithScope.interpretObjCPointer(expression: IrExpression, type: KotlinType): IrExpression {
val callee: IrFunctionSymbol = if (TypeUtils.isNullableType(type)) {
symbols.interopInterpretObjCPointerOrNull
} else {
symbols.interopInterpretObjCPointer
}
return irCall(callee, listOf(type)).apply {
putValueArgument(0, expression)
}
}
private fun createObjCMethodImpAnnotations(selector: String, encoding: String): Annotations {
val annotation = AnnotationDescriptorImpl(
context.interopBuiltIns.objCMethodImp.defaultType,
mapOf("selector" to selector, "encoding" to encoding)
.mapKeys { Name.identifier(it.key) }
.mapValues { StringValue(it.value, context.builtIns) },
SourceElement.NO_SOURCE
)
return AnnotationsImpl(listOf(annotation))
}
private fun checkKotlinObjCClass(irClass: IrClass) {
val kind = irClass.descriptor.kind
if (kind != ClassKind.CLASS && kind != ClassKind.OBJECT) {
context.reportCompilationError(
"Only classes are supported as subtypes of Objective-C types",
currentFile, irClass
)
}
if (!irClass.descriptor.isFinalClass) {
context.reportCompilationError(
"Non-final Kotlin subclasses of Objective-C classes are not yet supported",
currentFile, irClass
)
}
var hasObjCClassSupertype = false
irClass.descriptor.defaultType.constructor.supertypes.forEach {
val descriptor = it.constructor.declarationDescriptor as ClassDescriptor
if (!descriptor.isObjCClass()) {
context.reportCompilationError(
"Mixing Kotlin and Objective-C supertypes is not supported",
currentFile, irClass
)
}
if (descriptor.kind == ClassKind.CLASS) {
hasObjCClassSupertype = true
}
}
if (!hasObjCClassSupertype) {
context.reportCompilationError(
"Kotlin implementation of Objective-C protocol must have Objective-C superclass (e.g. NSObject)",
currentFile, irClass
)
}
}
override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression {
expression.transformChildrenVoid()
builder.at(expression)
val constructedClass = outerClasses.peek()!!
val constructedClassDescriptor = constructedClass.descriptor
if (!constructedClassDescriptor.isObjCClass()) {
return expression
}
constructedClassDescriptor.containingDeclaration.let { classContainer ->
if (classContainer is ClassDescriptor && classContainer.isObjCClass() &&
constructedClassDescriptor == classContainer.companionObjectDescriptor) {
val outerConstructedClass = outerClasses[outerClasses.lastIndex - 1]
assert (outerConstructedClass.descriptor == classContainer)
assert(expression.getArguments().isEmpty())
return builder.irBlock(expression) {
+expression // Required for the IR to be valid, will be ignored in codegen.
+irCall(symbols.interopObjCObjectInitFromPtr).apply {
extensionReceiver = irGet(constructedClass.thisReceiver!!.symbol)
putValueArgument(0, getObjCClass(outerConstructedClass.symbol))
}
}
}
}
if (!constructedClassDescriptor.isExternalObjCClass() &&
expression.descriptor.constructedClass.isExternalObjCClass()) {
// Calling super constructor from Kotlin Objective-C class.
assert(constructedClassDescriptor.getSuperClassNotAny() == expression.descriptor.constructedClass)
val initMethod = expression.descriptor.getObjCInitMethod()!!
val initMethodInfo = initMethod.getExternalObjCMethodInfo()!!
assert(expression.dispatchReceiver == null)
assert(expression.extensionReceiver == null)
val initCall = builder.genLoweredObjCMethodCall(
initMethodInfo,
superQualifier = symbolTable.referenceClass(expression.descriptor.constructedClass),
receiver = builder.irGet(constructedClass.thisReceiver!!.symbol),
arguments = initMethod.valueParameters.map { expression.getValueArgument(it)!! }
)
val superConstructor = symbolTable.referenceConstructor(
expression.descriptor.constructedClass.constructors.single { it.valueParameters.size == 0 }
)
return builder.irBlock(expression) {
// Required for the IR to be valid, will be ignored in codegen:
+IrDelegatingConstructorCallImpl(startOffset, endOffset, superConstructor, superConstructor.descriptor)
+irCall(symbols.interopObjCObjectSuperInitCheck).apply {
extensionReceiver = irGet(constructedClass.thisReceiver!!.symbol)
putValueArgument(0, initCall)
}
}
}
return expression
}
private fun IrBuilderWithScope.genLoweredObjCMethodCall(info: ObjCMethodInfo, superQualifier: IrClassSymbol?,
receiver: IrExpression, arguments: List<IrExpression>): IrExpression {
val superClass = superQualifier?.let { getObjCClass(it) } ?:
irCall(symbols.getNativeNullPtr)
val bridge = symbolTable.referenceSimpleFunction(info.bridge)
return irCall(bridge).apply {
putValueArgument(0, superClass)
putValueArgument(1, receiver)
assert(arguments.size + 2 == info.bridge.valueParameters.size)
arguments.forEachIndexed { index, argument ->
putValueArgument(index + 2, argument)
}
}
}
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid()
val descriptor = expression.descriptor.original
if (descriptor is ConstructorDescriptor) {
val initMethod = descriptor.getObjCInitMethod()
if (initMethod != null) {
val arguments = descriptor.valueParameters.map { expression.getValueArgument(it)!! }
assert(expression.extensionReceiver == null)
assert(expression.dispatchReceiver == null)
builder.at(expression)
return builder.genLoweredObjCMethodCall(
initMethod.getExternalObjCMethodInfo()!!,
superQualifier = null,
receiver = builder.callAlloc(symbolTable.referenceClass(descriptor.constructedClass)),
arguments = arguments
)
}
}
descriptor.getExternalObjCMethodInfo()?.let { methodInfo ->
val isInteropStubsFile =
currentFile.fileAnnotations.any { it.fqName == FqName("kotlinx.cinterop.InteropStubs") }
// Special case: bridge from Objective-C method implementation template to Kotlin method;
// handled in CodeGeneratorVisitor.callVirtual.
val useKotlinDispatch = isInteropStubsFile &&
builder.scope.scopeOwner.annotations.hasAnnotation(FqName("konan.internal.ExportForCppRuntime"))
if (!useKotlinDispatch) {
val arguments = descriptor.valueParameters.map { expression.getValueArgument(it)!! }
assert(expression.dispatchReceiver == null || expression.extensionReceiver == null)
if (expression.superQualifier?.isObjCMetaClass() == true) {
context.reportCompilationError(
"Super calls to Objective-C meta classes are not supported yet",
currentFile, expression
)
}
if (expression.superQualifier?.isInterface == true) {
context.reportCompilationError(
"Super calls to Objective-C protocols are not allowed",
currentFile, expression
)
}
builder.at(expression)
return builder.genLoweredObjCMethodCall(
methodInfo,
superQualifier = expression.superQualifierSymbol,
receiver = expression.dispatchReceiver ?: expression.extensionReceiver!!,
arguments = arguments
)
}
}
return when (descriptor) {
context.interopBuiltIns.typeOf -> {
val typeArgument = expression.getSingleTypeArgument()
val classDescriptor = TypeUtils.getClassDescriptor(typeArgument)
if (classDescriptor == null) {
expression
} else {
val companionObjectDescriptor = classDescriptor.companionObjectDescriptor ?:
error("native variable class $classDescriptor must have the companion object")
IrGetObjectValueImpl(
expression.startOffset, expression.endOffset, companionObjectDescriptor.defaultType,
symbolTable.referenceClass(companionObjectDescriptor)
)
}
}
else -> expression
}
}
}
/**
* Lowers some interop intrinsic calls.
*/
internal class InteropLoweringPart2(val context: Context) : FileLoweringPass {
override fun lower(irFile: IrFile) {
val transformer = InteropTransformer(context, irFile)
irFile.transformChildrenVoid(transformer)
}
}
private class InteropTransformer(val context: Context, val irFile: IrFile) : IrBuildingTransformer(context) {
val interop = context.interopBuiltIns
val symbols = context.ir.symbols
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
builder.at(expression)
val descriptor = expression.descriptor.original
if (descriptor is ClassConstructorDescriptor) {
val type = descriptor.constructedClass.defaultType
if (type.isRepresentedAs(ValueType.C_POINTER) || type.isRepresentedAs(ValueType.NATIVE_POINTED)) {
throw Error("Native interop types constructors must not be called directly")
}
}
if (descriptor == interop.nativePointedRawPtrGetter ||
OverridingUtil.overrides(descriptor, interop.nativePointedRawPtrGetter)) {
// Replace by the intrinsic call to be handled by code generator:
return builder.irCall(symbols.interopNativePointedGetRawPointer).apply {
extensionReceiver = expression.dispatchReceiver
}
}
fun reportError(message: String): Nothing = context.reportCompilationError(message, irFile, expression)
return when (descriptor) {
interop.cPointerRawValue.getter ->
// Replace by the intrinsic call to be handled by code generator:
builder.irCall(symbols.interopCPointerGetRawValue).apply {
extensionReceiver = expression.dispatchReceiver
}
interop.bitsToFloat -> {
val argument = expression.getValueArgument(0)
if (argument is IrConst<*> && argument.kind == IrConstKind.Int) {
val floatValue = kotlinx.cinterop.bitsToFloat(argument.value as Int)
builder.irFloat(floatValue)
} else {
expression
}
}
interop.bitsToDouble -> {
val argument = expression.getValueArgument(0)
if (argument is IrConst<*> && argument.kind == IrConstKind.Long) {
val doubleValue = kotlinx.cinterop.bitsToDouble(argument.value as Long)
builder.irDouble(doubleValue)
} else {
expression
}
}
in interop.staticCFunction -> {
val irCallableReference = unwrapStaticFunctionArgument(expression.getValueArgument(0)!!)
if (irCallableReference == null || irCallableReference.getArguments().isNotEmpty()) {
context.reportCompilationError(
"${descriptor.fqNameSafe} must take an unbound, non-capturing function or lambda",
irFile, expression
)
// TODO: should probably be reported during analysis.
}
val targetSymbol = irCallableReference.symbol
val target = targetSymbol.descriptor
val signatureTypes = target.allParameters.map { it.type } + target.returnType!!
signatureTypes.forEachIndexed { index, type ->
type.ensureSupportedInCallbacks(
isReturnType = (index == signatureTypes.lastIndex),
reportError = ::reportError
)
}
descriptor.typeParameters.forEachIndexed { index, typeParameterDescriptor ->
val typeArgument = expression.getTypeArgument(typeParameterDescriptor)!!
val signatureType = signatureTypes[index]
if (typeArgument != signatureType) {
context.reportCompilationError(
"C function signature element mismatch: expected '$signatureType', got '$typeArgument'",
irFile, expression
)
}
}
IrFunctionReferenceImpl(
builder.startOffset, builder.endOffset,
expression.type,
targetSymbol, target,
typeArguments = null)
}
interop.scheduleFunction -> {
val irCallableReference = unwrapStaticFunctionArgument(expression.getValueArgument(2)!!)
if (irCallableReference == null || irCallableReference.getArguments().isNotEmpty()) {
context.reportCompilationError(
"${descriptor.fqNameSafe} must take an unbound, non-capturing function or lambda",
irFile, expression
)
}
val targetSymbol = irCallableReference.symbol
val target = targetSymbol.descriptor
val jobPointer = IrFunctionReferenceImpl(
builder.startOffset, builder.endOffset,
interop.cPointer.defaultType,
targetSymbol, target,
typeArguments = null)
builder.irCall(symbols.scheduleImpl).apply {
putValueArgument(0, expression.dispatchReceiver)
putValueArgument(1, expression.getValueArgument(0))
putValueArgument(2, expression.getValueArgument(1))
putValueArgument(3, jobPointer)
}
}
interop.signExtend, interop.narrow -> {
val integerTypePredicates = arrayOf(
KotlinBuiltIns::isByte, KotlinBuiltIns::isShort, KotlinBuiltIns::isInt, KotlinBuiltIns::isLong
)
val receiver = expression.extensionReceiver!!
val typeOperand = expression.getSingleTypeArgument()
val receiverTypeIndex = integerTypePredicates.indexOfFirst { it(receiver.type) }
val typeOperandIndex = integerTypePredicates.indexOfFirst { it(typeOperand) }
if (receiverTypeIndex == -1) {
context.reportCompilationError("Receiver's type ${receiver.type} is not an integer type",
irFile, receiver)
}
if (typeOperandIndex == -1) {
context.reportCompilationError("Type argument $typeOperand is not an integer type",
irFile, expression)
}
when (descriptor) {
interop.signExtend -> if (receiverTypeIndex > typeOperandIndex) {
context.reportCompilationError("unable to sign extend ${receiver.type} to $typeOperand",
irFile, expression)
}
interop.narrow -> if (receiverTypeIndex < typeOperandIndex) {
context.reportCompilationError("unable to narrow ${receiver.type} to $typeOperand",
irFile, expression)
}
else -> throw Error()
}
val receiverClass = symbols.integerClasses.single {
receiver.type.isSubtypeOf(it.owner.defaultType)
}
val conversionSymbol = receiverClass.functions.single {
it.descriptor.name == Name.identifier("to$typeOperand")
}
builder.irCall(conversionSymbol).apply {
dispatchReceiver = receiver
}
}
in interop.cFunctionPointerInvokes -> {
// Replace by `invokeImpl${type}Ret`:
val returnType =
expression.getTypeArgument(descriptor.typeParameters.single { it.name.asString() == "R" })!!
returnType.checkCTypeNullability(::reportError)
val invokeImpl = symbols.interopInvokeImpls[TypeUtils.getClassDescriptor(returnType)] ?:
context.reportCompilationError(
"Invocation of C function pointer with return type '$returnType' is not supported yet",
irFile, expression
)
builder.irCall(invokeImpl).apply {
putValueArgument(0, expression.extensionReceiver)
val varargParameter = invokeImpl.descriptor.valueParameters[1]
val varargArgument = IrVarargImpl(
startOffset, endOffset, varargParameter.type, varargParameter.varargElementType!!
).apply {
descriptor.valueParameters.forEach {
this.addElement(expression.getValueArgument(it)!!)
}
}
putValueArgument(varargParameter, varargArgument)
}
}
interop.objCObjectInitBy -> {
val intrinsic = interop.objCObjectInitBy.name
val argument = expression.getValueArgument(0)!!
val constructedClass =
((argument as? IrCall)?.descriptor as? ClassConstructorDescriptor)?.constructedClass
if (constructedClass == null) {
context.reportCompilationError("Argument of '$intrinsic' must be a constructor call",
irFile, argument)
}
val extensionReceiver = expression.extensionReceiver!!
if (extensionReceiver !is IrGetValue ||
extensionReceiver.descriptor != constructedClass.thisAsReceiverParameter) {
context.reportCompilationError("Receiver of '$intrinsic' must be a 'this' of the constructed class",
irFile, extensionReceiver)
}
expression
}
else -> expression
}
}
private fun KotlinType.ensureSupportedInCallbacks(isReturnType: Boolean, reportError: (String) -> Nothing) {
this.checkCTypeNullability(reportError)
if (isReturnType && KotlinBuiltIns.isUnit(this)) {
return
}
if (KotlinBuiltIns.isPrimitiveType(this)) {
return
}
if (TypeUtils.getClassDescriptor(this) == interop.cPointer) {
return
}
reportError("Type $this is not supported in callback signature")
}
private fun KotlinType.checkCTypeNullability(reportError: (String) -> Nothing) {
if (KotlinBuiltIns.isPrimitiveTypeOrNullablePrimitiveType(this) && this.isMarkedNullable) {
reportError("Type $this must not be nullable when used in C function signature")
}
if (TypeUtils.getClassDescriptor(this) == interop.cPointer && !this.isMarkedNullable) {
reportError("Type $this must be nullable when used in C function signature")
}
}
private fun unwrapStaticFunctionArgument(argument: IrExpression): IrFunctionReference? {
if (argument is IrFunctionReference) {
return argument
}
// Otherwise check whether it is a lambda:
// 1. It is a container with two statements and expected origin:
if (argument !is IrContainerExpression || argument.statements.size != 2) {
return null
}
if (argument.origin != IrStatementOrigin.LAMBDA && argument.origin != IrStatementOrigin.ANONYMOUS_FUNCTION) {
return null
}
// 2. First statement is an empty container (created during local functions lowering):
val firstStatement = argument.statements.first()
if (firstStatement !is IrContainerExpression || firstStatement.statements.size != 0) {
return null
}
// 3. Second statement is IrCallableReference:
return argument.statements.last() as? IrFunctionReference
}
}
private fun IrCall.getSingleTypeArgument(): KotlinType {
val typeParameter = descriptor.original.typeParameters.single()
return getTypeArgument(typeParameter)!!
}
private fun IrBuilder.irFloat(value: Float) =
IrConstImpl.float(startOffset, endOffset, context.builtIns.floatType, value)
private fun IrBuilder.irDouble(value: Double) =
IrConstImpl.double(startOffset, endOffset, context.builtIns.doubleType, value)
private fun Annotations.hasAnnotation(descriptor: ClassDescriptor) = this.hasAnnotation(descriptor.fqNameSafe)
| apache-2.0 | 8db961d9e51bef660a2f878779543120 | 40.25573 | 120 | 0.6089 | 5.901812 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/starfield/StarSelectedBottomPane.kt | 1 | 4800 | package au.com.codeka.warworlds.client.game.starfield
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.ctrl.PlanetListSimple
import au.com.codeka.warworlds.client.game.fleets.FleetListSimple
import au.com.codeka.warworlds.client.game.fleets.FleetListSimple.FleetSelectedHandler
import au.com.codeka.warworlds.client.game.world.EmpireManager
import au.com.codeka.warworlds.client.game.world.ImageHelper
import au.com.codeka.warworlds.client.util.eventbus.EventHandler
import au.com.codeka.warworlds.common.proto.Empire
import au.com.codeka.warworlds.common.proto.Fleet
import au.com.codeka.warworlds.common.proto.Planet
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.common.sim.StarHelper
import com.google.common.base.Preconditions
import com.squareup.picasso.Picasso
import java.util.*
/**
* The bottom pane when you have a star selected.
*/
@SuppressLint("ViewConstructor") // Must be constructed in code.
class StarSelectedBottomPane(context: Context, private var star: Star, callback: Callback)
: ConstraintLayout(context, null) {
interface Callback {
fun onStarClicked(star: Star, planet: Planet?)
fun onFleetClicked(star: Star, fleet: Fleet)
fun onScoutReportClicked(star: Star)
}
private val planetList: PlanetListSimple
private val fleetList: FleetListSimple
private val starName: TextView
private val starKind: TextView
private val starIcon: ImageView
private val renameButton: Button
private val scoutReportButton: Button
init {
View.inflate(context, R.layout.starfield_bottom_pane_star, this)
findViewById<View>(R.id.view_btn).setOnClickListener { callback.onStarClicked(this.star, null) }
planetList = findViewById(R.id.planet_list)
fleetList = findViewById(R.id.fleet_list)
starName = findViewById(R.id.star_name)
starKind = findViewById(R.id.star_kind)
starIcon = findViewById(R.id.star_icon)
renameButton = findViewById(R.id.rename_btn)
scoutReportButton = findViewById(R.id.scout_report_btn)
scoutReportButton.setOnClickListener { callback.onScoutReportClicked(this.star) }
planetList.setPlanetSelectedHandler(object : PlanetListSimple.PlanetSelectedHandler {
override fun onPlanetSelected(planet: Planet?) {
callback.onStarClicked(star, planet)
}
})
fleetList.setFleetSelectedHandler(object : FleetSelectedHandler {
override fun onFleetSelected(fleet: Fleet?) {
callback.onFleetClicked(star, fleet!!)
}
})
if (!isInEditMode) {
refresh()
}
}
public override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isInEditMode) {
return
}
App.eventBus.register(eventListener)
}
public override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (isInEditMode) {
return
}
App.eventBus.unregister(eventListener)
}
private fun refresh() {
if (star.classification == Star.Classification.WORMHOLE) {
planetList.visibility = View.GONE
findViewById<View>(R.id.wormhole_details).visibility = View.VISIBLE
// refreshWormholeDetails();
} else {
findViewById<View>(R.id.wormhole_details).visibility = View.GONE
planetList.visibility = View.VISIBLE
planetList.setStar(star)
}
fleetList.setStar(star)
val myEmpire = Preconditions.checkNotNull(EmpireManager.getMyEmpire())
var numMyEmpire = 0
var numOtherEmpire = 0
for (planet in star.planets) {
val colony = planet.colony ?: continue
if (colony.empire_id == 0L) {
continue
}
if (colony.empire_id == myEmpire.id) {
numMyEmpire++
} else {
numOtherEmpire++
}
}
if (numMyEmpire > numOtherEmpire) {
renameButton.visibility = View.VISIBLE
} else {
renameButton.visibility = View.GONE
}
scoutReportButton.isEnabled = star.scout_reports.isNotEmpty()
starName.text = star.name
starKind.text = String.format(Locale.ENGLISH, "%s %s", star.classification,
StarHelper.getCoordinateString(star))
Picasso.get()
.load(ImageHelper.getStarImageUrl(context, star, 40, 40))
.into(starIcon)
}
private val eventListener: Any = object : Any() {
@EventHandler
fun onStarUpdated(s: Star) {
if (s.id == star.id) {
star = s
refresh()
}
}
@EventHandler
fun onEmpireUpdated(@Suppress("unused_parameter") empire: Empire?) {
refresh()
}
}
} | mit | 4502cfd40e1dd45ae9257b6714af32ca | 32.573427 | 100 | 0.721875 | 3.953871 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/stash/ui/GitShowStashToolWindowTabAction.kt | 4 | 685 | // 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 git4idea.stash.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.vcs.VcsShowToolWindowTabAction
import git4idea.stash.isStashToolWindowAvailable
class GitShowStashToolWindowTabAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = GitStashContentProvider.TAB_NAME
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.project
if (project == null || !isStashToolWindowAvailable(project)) {
e.presentation.isEnabledAndVisible = false
}
}
} | apache-2.0 | 8dc33aff635cb43561bd80f3be30cf1f | 37.111111 | 140 | 0.778102 | 4.335443 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/methodCallExpression/specialBuiltinMembers.kt | 10 | 1186 | // ERROR: Using 'toShort(): Short' is an error. Unclear conversion. To achieve the same result convert to Int explicitly and then to Short.
import java.util.*
internal enum class E {
A, B, C
}
internal class A {
fun foo(list: List<String>, collection: Collection<Int>, map: Map<Int, Int>) {
val a = "".length
val b = E.A.name
val c = E.A.ordinal
val d = list.size + collection.size
val e = map.size
val f = map.keys.size
val g = map.values.size
val h = map.entries.size
}
fun bar(list: MutableList<String>, map: HashMap<String, Int>) {
val c = "a"[0]
val b = 10.toByte()
val i = 10.1.toInt()
val f = 10.1.toFloat()
val l = 10.1.toLong()
val s = 10.1.toShort()
try {
val removed = list.removeAt(10)
val isRemoved = list.remove("a")
} catch (e: Exception) {
System.err.println(e.message)
throw RuntimeException(e.cause)
}
for (entry in map.entries) {
val key = entry.key
val value = entry.value
entry.setValue(value + 1)
}
}
}
| apache-2.0 | 3b4393b03dc304a14ef5bfb53529a964 | 27.238095 | 139 | 0.53457 | 3.671827 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.