content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.network.service
import java.io.File
abstract class RequestService {
abstract fun postZipped(url: String, file: File): ResponseData?
abstract fun get(url: String): ResponseData?
} | plugins/stats-collector/src/com/intellij/stats/network/service/RequestService.kt | 1834180303 |
/*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.push
import com.batch.android.Batch
import com.benoitletondor.easybudgetapp.BuildConfig
import com.benoitletondor.easybudgetapp.helper.*
import com.benoitletondor.easybudgetapp.iab.Iab
import com.benoitletondor.easybudgetapp.parameters.*
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import dagger.hilt.android.AndroidEntryPoint
import java.util.Calendar
import java.util.Date
import javax.inject.Inject
/**
* Service that handles Batch pushes
*
* @author Benoit LETONDOR
*/
@AndroidEntryPoint
class PushService : FirebaseMessagingService() {
@Inject lateinit var iab: Iab
@Inject lateinit var parameters: Parameters
// ----------------------------------->
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Check that the push is valid
if (Batch.Push.shouldDisplayPush(this, remoteMessage)) {
if (!shouldDisplayPush(remoteMessage)) {
Logger.debug("Not displaying push cause conditions are not matching")
return
}
// Display the notification
Batch.Push.displayNotification(this, remoteMessage)
}
}
/**
* Check if the push should be displayed
*
* @param remoteMessage
* @return true if should display the push, false otherwise
*/
private fun shouldDisplayPush(remoteMessage: RemoteMessage): Boolean {
return isUserOk(remoteMessage) && isVersionCompatible(remoteMessage) && isPremiumCompatible(remoteMessage)
}
/**
* Check if the push should be displayed according to user choice
*
* @param remoteMessage
* @return true if should display the push, false otherwise
*/
private fun isUserOk(remoteMessage: RemoteMessage): Boolean {
try {
// Check if it's a daily reminder
if (remoteMessage.data.containsKey(DAILY_REMINDER_KEY) && "true" == remoteMessage.data[DAILY_REMINDER_KEY]) {
// Only for premium users
if ( !iab.isUserPremium() ) {
return false
}
// Check user choice
if ( !parameters.isUserAllowingDailyReminderPushes() ) {
return false
}
// Check if the app hasn't been opened today
val lastOpenTimestamp = parameters.getLastOpenTimestamp()
if (lastOpenTimestamp == 0L) {
return false
}
val lastOpen = Date(lastOpenTimestamp)
val cal = Calendar.getInstance()
val currentDay = cal.get(Calendar.DAY_OF_YEAR)
cal.time = lastOpen
val lastOpenDay = cal.get(Calendar.DAY_OF_YEAR)
return currentDay != lastOpenDay
} else if (remoteMessage.data.containsKey(MONTHLY_REMINDER_KEY) && "true" == remoteMessage.data[MONTHLY_REMINDER_KEY]) {
return iab.isUserPremium() && parameters.isUserAllowingMonthlyReminderPushes()
}
// Else it must be an update push
return parameters.isUserAllowingUpdatePushes()
} catch (e: Exception) {
Logger.error("Error while checking user ok for push", e)
return false
}
}
/**
* Check if the push should be displayed according to version constrains
*
* @param remoteMessage
* @return true if should display the push, false otherwise
*/
private fun isVersionCompatible(remoteMessage: RemoteMessage): Boolean {
try {
var maxVersion = BuildConfig.VERSION_CODE
var minVersion = 1
if (remoteMessage.data.containsKey(INTENT_MAX_VERSION_KEY)) {
maxVersion = Integer.parseInt(remoteMessage.data[INTENT_MAX_VERSION_KEY]!!)
}
if (remoteMessage.data.containsKey(INTENT_MIN_VERSION_KEY)) {
minVersion = Integer.parseInt(remoteMessage.data[INTENT_MIN_VERSION_KEY]!!)
}
return BuildConfig.VERSION_CODE in minVersion..maxVersion
} catch (e: Exception) {
Logger.error("Error while checking app version for push", e)
return false
}
}
/**
* Check the user status if a push is marked as for premium or not.
*
* @param remoteMessage push intent
* @return true if compatible, false otherwise
*/
private fun isPremiumCompatible(remoteMessage: RemoteMessage): Boolean {
try {
if (remoteMessage.data.containsKey(INTENT_PREMIUM_KEY)) {
val isForPremium = "true" == remoteMessage.data[INTENT_PREMIUM_KEY]
return isForPremium == iab.isUserPremium()
}
return true
} catch (e: Exception) {
Logger.error("Error while checking premium compatible for push", e)
return false
}
}
companion object {
/**
* Key to retrieve the max version for a push
*/
private const val INTENT_MAX_VERSION_KEY = "maxVersion"
/**
* Key to retrieve the max version for a push
*/
private const val INTENT_MIN_VERSION_KEY = "minVersion"
/**
* Key to retrieve if a push is intented for premium user or not
*/
private const val INTENT_PREMIUM_KEY = "premium"
/**
* Key to retrieve the daily reminder key for a push
*/
const val DAILY_REMINDER_KEY = "daily"
/**
* Key to retrieve the monthly reminder key for a push
*/
const val MONTHLY_REMINDER_KEY = "monthly"
}
}
| Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/push/PushService.kt | 2727149242 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.refactoring.inline
import com.google.common.annotations.VisibleForTesting
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.lang.Language
import com.intellij.lang.refactoring.InlineActionHandler
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.SyntaxTraverser
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyNames
import com.jetbrains.python.PythonLanguage
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.references.PyImportReference
import com.jetbrains.python.psi.search.PyOverridingMethodsSearch
import com.jetbrains.python.psi.search.PySuperMethodsSearch
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.pyi.PyiFile
import com.jetbrains.python.pyi.PyiUtil
import com.jetbrains.python.sdk.PythonSdkUtil
/**
* @author Aleksei.Kniazev
*/
class PyInlineFunctionHandler : InlineActionHandler() {
override fun isEnabledForLanguage(l: Language?) = l is PythonLanguage
override fun canInlineElement(element: PsiElement?): Boolean {
if (element is PyFunction) {
val containingFile = if (element.containingFile is PyiFile) PyiUtil.getOriginalElement(element)?.containingFile else element.containingFile
return containingFile is PyFile
}
return false
}
override fun inlineElement(project: Project?, editor: Editor?, element: PsiElement?) {
if (project == null || editor == null || element !is PyFunction) return
val functionScope = ControlFlowCache.getScope(element)
val error = when {
element.isAsync -> "refactoring.inline.function.async"
element.isGenerator -> "refactoring.inline.function.generator"
PyUtil.isInitOrNewMethod(element) -> "refactoring.inline.function.constructor"
PyBuiltinCache.getInstance(element).isBuiltin(element) -> "refactoring.inline.function.builtin"
isSpecialMethod(element) -> "refactoring.inline.function.special.method"
isUnderSkeletonDir(element) -> "refactoring.inline.function.skeleton.only"
hasDecorators(element) -> "refactoring.inline.function.decorator"
hasReferencesToSelf(element) -> "refactoring.inline.function.self.referrent"
hasStarArgs(element) -> "refactoring.inline.function.star"
overridesMethod(element, project) -> "refactoring.inline.function.overrides.method"
isOverridden(element) -> "refactoring.inline.function.is.overridden"
functionScope.hasGlobals() -> "refactoring.inline.function.global"
functionScope.hasNonLocals() -> "refactoring.inline.function.nonlocal"
hasNestedFunction(element) -> "refactoring.inline.function.nested"
hasNonExhaustiveIfs(element) -> "refactoring.inline.function.interrupts.flow"
else -> null
}
if (error != null) {
CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message(error), PyBundle.message("refactoring.inline.function.title"), REFACTORING_ID)
return
}
if (!ApplicationManager.getApplication().isUnitTestMode){
PyInlineFunctionDialog(project, editor, element, findReference(editor)).show()
}
}
private fun isSpecialMethod(function: PyFunction): Boolean {
return function.containingClass != null && PyNames.getBuiltinMethods(LanguageLevel.forElement(function)).contains(function.name)
}
private fun hasNestedFunction(function: PyFunction): Boolean = SyntaxTraverser.psiTraverser(function.statementList).traverse().any { it is PyFunction }
private fun hasNonExhaustiveIfs(function: PyFunction): Boolean {
val returns = mutableListOf<PyReturnStatement>()
function.accept(object : PyRecursiveElementVisitor() {
override fun visitPyReturnStatement(node: PyReturnStatement) {
returns.add(node)
}
})
if (returns.isEmpty()) return false
val cache = mutableSetOf<PyIfStatement>()
return returns.asSequence()
.map { PsiTreeUtil.getParentOfType(it, PyIfStatement::class.java) }
.distinct()
.filterNotNull()
.any { checkInterruptsControlFlow(it, cache) }
}
private fun checkInterruptsControlFlow(ifStatement: PyIfStatement, cache: MutableSet<PyIfStatement>): Boolean {
if (ifStatement in cache) return false
cache.add(ifStatement)
val elsePart = ifStatement.elsePart
if (elsePart == null) return true
if (checkLastStatement(ifStatement.ifPart.statementList, cache)) return true
if (checkLastStatement(elsePart.statementList, cache)) return true
ifStatement.elifParts.forEach { if (checkLastStatement(it.statementList, cache)) return true }
val parentIfStatement = PsiTreeUtil.getParentOfType(ifStatement, PyIfStatement::class.java)
if (parentIfStatement != null && checkInterruptsControlFlow(parentIfStatement, cache)) return true
return false
}
private fun checkLastStatement(statementList: PyStatementList, cache: MutableSet<PyIfStatement>): Boolean {
val statements = statementList.statements
if (statements.isEmpty()) return true
when(val last = statements.last()) {
is PyIfStatement -> if (checkInterruptsControlFlow(last, cache)) return true
!is PyReturnStatement -> return true
}
return false
}
private fun hasDecorators(function: PyFunction): Boolean = function.decoratorList?.decorators?.isNotEmpty() == true
private fun overridesMethod(function: PyFunction, project: Project): Boolean {
return function.containingClass != null
&& PySuperMethodsSearch.search(function, TypeEvalContext.codeAnalysis(project, function.containingFile)).any()
}
private fun isOverridden(function: PyFunction): Boolean {
return function.containingClass != null && PyOverridingMethodsSearch.search(function, true).any()
}
private fun hasStarArgs(function: PyFunction): Boolean {
return function.parameterList.parameters.asSequence()
.filterIsInstance<PyNamedParameter>()
.any { it.isPositionalContainer || it.isKeywordContainer }
}
private fun hasReferencesToSelf(function: PyFunction): Boolean = SyntaxTraverser.psiTraverser(function.statementList)
.any { it is PyReferenceExpression && it.reference.isReferenceTo(function) }
private fun isUnderSkeletonDir(function: PyFunction): Boolean {
val containingFile = PyiUtil.getOriginalElementOrLeaveAsIs(function, PyElement::class.java).containingFile
val sdk = PythonSdkUtil.findPythonSdk(containingFile) ?: return false
val skeletonsDir = PythonSdkUtil.findSkeletonsDir(sdk) ?: return false
return VfsUtil.isAncestor(skeletonsDir, containingFile.virtualFile, true)
}
companion object {
@JvmStatic
fun getInstance(): PyInlineFunctionHandler {
return EP_NAME.findExtensionOrFail(PyInlineFunctionHandler::class.java)
}
@JvmStatic
val REFACTORING_ID = "refactoring.inlineMethod"
@JvmStatic
@VisibleForTesting
fun findReference(editor: Editor): PsiReference? {
val reference = TargetElementUtil.findReference(editor)
return if (reference !is PyImportReference) reference else null
}
}
}
| python/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt | 2192771003 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cds
import com.intellij.diagnostic.VMOptions
import com.intellij.execution.CommandLineWrapperUtil
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.VersionComparatorUtil
import com.sun.management.OperatingSystemMXBean
import com.sun.tools.attach.VirtualMachine
import java.io.File
import java.lang.management.ManagementFactory
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis
sealed class CDSTaskResult(val statusName: String) {
object Success : CDSTaskResult("success")
abstract class Cancelled(statusName: String) : CDSTaskResult(statusName)
object InterruptedForRetry : Cancelled("cancelled")
object TerminatedByUser : Cancelled("terminated-by-user")
object PluginsChanged : Cancelled("plugins-changed")
data class Failed(val error: String) : CDSTaskResult("failed")
}
object CDSManager {
private val LOG = Logger.getInstance(javaClass)
val isValidEnv: Boolean by lazy {
// AppCDS requires classes packed into JAR files, not from the out folder
if (PluginManagerCore.isRunningFromSources()) return@lazy false
// CDS features are only available on 64 bit JVMs
if (!SystemInfo.is64Bit) return@lazy false
// The AppCDS (JEP 310) is only added in JDK10,
// The closest JRE we ship/support is 11
if (!SystemInfo.isJavaVersionAtLeast(11)) return@lazy false
//AppCDS does not support Windows and macOS
if (!SystemInfo.isLinux) {
//Specific patches are included into JetBrains runtime
//to support Windows and macOS
if (!SystemInfo.isJetBrainsJvm) return@lazy false
if (VersionComparatorUtil.compare(SystemInfo.JAVA_RUNTIME_VERSION, "11.0.4+10-b520.2") < 0) return@lazy false
}
// we do not like to overload a potentially small computer with our process
val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
if (osBean.totalPhysicalMemorySize < 4L * 1024 * 1024 * 1024) return@lazy false
if (osBean.availableProcessors < 4) return@lazy false
if (!VMOptions.canWriteOptions()) return@lazy false
true
}
val currentCDSArchive: File? by lazy {
val arguments = ManagementFactory.getRuntimeMXBean().inputArguments
val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }
if (!xShare) return@lazy null
val key = "-XX:SharedArchiveFile="
return@lazy arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File)
}
fun cleanupStaleCDSFiles(isCDSEnabled: Boolean): CDSTaskResult {
val paths = CDSPaths.current
val currentCDSPath = currentCDSArchive
val files = paths.baseDir.listFiles() ?: arrayOf()
if (files.isEmpty()) return CDSTaskResult.Success
for (path in files) {
if (path == currentCDSPath) continue
if (isCDSEnabled && paths.isOurFile(path)) continue
FileUtil.delete(path)
}
return CDSTaskResult.Success
}
fun removeCDS() {
if (currentCDSArchive?.isFile != true ) return
VMOptions.writeDisableCDSArchiveOption()
LOG.warn("Disabled CDS")
}
private interface CDSProgressIndicator {
/// returns non-null value if cancelled
val cancelledStatus: CDSTaskResult.Cancelled?
var text2: String?
}
fun installCDS(canStillWork: () -> Boolean, onResult: (CDSTaskResult) -> Unit) {
CDSFUSCollector.logCDSBuildingStarted()
val startTime = System.currentTimeMillis()
ProgressManager.getInstance().run(object : Task.Backgroundable(
null,
"Optimizing startup performance...",
true,
PerformInBackgroundOption.ALWAYS_BACKGROUND
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val progress = object : CDSProgressIndicator {
override val cancelledStatus: CDSTaskResult.Cancelled?
get() {
if (!canStillWork()) return CDSTaskResult.InterruptedForRetry
if (indicator.isCanceled) return CDSTaskResult.TerminatedByUser
if (ApplicationManager.getApplication().isDisposed) return CDSTaskResult.InterruptedForRetry
return null
}
override var text2: String?
get() = indicator.text2
set(value) {
indicator.text2 = value
}
}
val paths = CDSPaths.current
val result = try {
installCDSImpl(progress, paths)
} catch (t: Throwable) {
LOG.warn("Settings up CDS Archive crashed unexpectedly. ${t.message}", t)
val message = "Unexpected crash $t"
paths.markError(message)
CDSTaskResult.Failed(message)
}
val installTime = System.currentTimeMillis() - startTime
CDSFUSCollector.logCDSBuildingCompleted(installTime, result)
onResult(result)
}
})
}
private fun installCDSImpl(indicator: CDSProgressIndicator, paths: CDSPaths): CDSTaskResult {
if (paths.isSame(currentCDSArchive)) {
val message = "CDS archive is already generated and being used. Nothing to do"
LOG.debug(message)
return CDSTaskResult.Success
}
if (paths.classesErrorMarkerFile.isFile) {
return CDSTaskResult.Failed("CDS archive has already failed, skipping")
}
LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files")
paths.mkdirs()
val listResult = generateFileIfNeeded(indicator, paths, paths.classesListFile, ::generateClassList) { t ->
"Failed to attach CDS Java Agent to the running IDE instance. ${t.message}"
}
if (listResult != CDSTaskResult.Success) return listResult
val archiveResult = generateFileIfNeeded(indicator, paths, paths.classesArchiveFile, ::generateSharedArchive) { t ->
"Failed to generated CDS archive. ${t.message}"
}
if (archiveResult != CDSTaskResult.Success) return archiveResult
VMOptions.writeEnableCDSArchiveOption(paths.classesArchiveFile.absolutePath)
LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, VMOptions were updated")
return CDSTaskResult.Success
}
private val agentPath: File
get() {
val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar"
if (libPath.isFile) return libPath
LOG.warn("Failed to find bundled CDS classes agent in $libPath")
//consider local debug IDE case
val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar"
if (probe.isFile) return probe
error("Failed to resolve path to the CDS agent")
}
private fun generateClassList(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = "Collecting classes list..."
val selfAttachKey = "jdk.attach.allowAttachSelf"
if (!System.getProperties().containsKey(selfAttachKey)) {
throw RuntimeException("Please make sure you have -D$selfAttachKey=true set in the VM options")
}
val duration = measureTimeMillis {
val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid())
try {
vm.loadAgent(agentPath.path, "${paths.classesListFile}")
}
finally {
vm.detach()
}
}
LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(duration)}")
}
private fun generateSharedArchive(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = "Generating classes archive..."
val logLevel = if (LOG.isDebugEnabled) "=debug" else ""
val args = listOf(
"-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}",
"-Xlog:cds$logLevel",
"-Xlog:class+path$logLevel",
"-Xshare:dump",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:SharedClassListFile=${paths.classesListFile}",
"-XX:SharedArchiveFile=${paths.classesArchiveFile}"
)
CommandLineWrapperUtil.writeArgumentsFile(paths.classesPathFile, args, StandardCharsets.UTF_8)
val durationLink = measureTimeMillis {
val ext = if (SystemInfo.isWindows) ".exe" else ""
val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext"
val javaArgs = listOf(
javaExe.path,
"@${paths.classesPathFile}"
)
val cwd = File(".").canonicalFile
LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}")
//recreate files for sanity
FileUtil.delete(paths.dumpOutputFile)
FileUtil.delete(paths.classesArchiveFile)
val commandLine = object : GeneralCommandLine() {
override fun buildProcess(builder: ProcessBuilder) : ProcessBuilder {
return super.buildProcess(builder)
.redirectErrorStream(true)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(paths.dumpOutputFile)
}
}
commandLine.workDirectory = cwd
commandLine.exePath = javaExe.absolutePath
commandLine.addParameter("@${paths.classesPathFile}")
if (!SystemInfo.isWindows) {
// the utility does not recover process exit code from the call on Windows
ExecUtil.setupLowPriorityExecution(commandLine)
}
val timeToWaitFor = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
fun shouldWaitForProcessToComplete() = timeToWaitFor > System.currentTimeMillis()
val process = commandLine.createProcess()
try {
runCatching { process.outputStream.close() }
while (shouldWaitForProcessToComplete()) {
if (indicator.cancelledStatus != null) throw InterruptedException()
if (process.waitFor(200, TimeUnit.MILLISECONDS)) break
}
}
finally {
if (process.isAlive) {
process.destroyForcibly()
}
}
if (!shouldWaitForProcessToComplete()) {
throw RuntimeException("The process took too long and will be killed. See ${paths.dumpOutputFile} for details")
}
val exitValue = process.exitValue()
if (exitValue != 0) {
val outputLines = runCatching {
paths.dumpOutputFile.readLines().takeLast(30).joinToString("\n")
}.getOrElse { "" }
throw RuntimeException("The process existed with code $exitValue. See ${paths.dumpOutputFile} for details:\n$outputLines")
}
}
LOG.info("Generated CDS archive in ${paths.classesArchiveFile}, " +
"size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " +
"it took ${StringUtil.formatDuration(durationLink)}")
}
private operator fun File.div(s: String) = File(this, s)
private val File.isValidFile get() = isFile && length() > 42
private inline fun generateFileIfNeeded(indicator: CDSProgressIndicator,
paths: CDSPaths,
theOutputFile: File,
generate: (CDSProgressIndicator, CDSPaths) -> Unit,
errorMessage: (Throwable) -> String): CDSTaskResult {
try {
if (theOutputFile.isValidFile) return CDSTaskResult.Success
indicator.cancelledStatus?.let { return it }
if (!paths.hasSameEnvironmentToBuildCDSArchive()) return CDSTaskResult.PluginsChanged
generate(indicator, paths)
LOG.assertTrue(theOutputFile.isValidFile, "Result file must be generated and be valid")
return CDSTaskResult.Success
}
catch (t: Throwable) {
FileUtil.delete(theOutputFile)
indicator.cancelledStatus?.let { return it }
if (t is InterruptedException) {
return CDSTaskResult.InterruptedForRetry
}
val message = errorMessage(t)
LOG.warn(message, t)
paths.markError(message)
return CDSTaskResult.Failed(message)
}
}
} | platform/platform-impl/src/com/intellij/ide/cds/CDSManager.kt | 1715369474 |
/**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.vfs
import jetbrains.exodus.ByteIterable
import jetbrains.exodus.env.Cursor
import jetbrains.exodus.env.Transaction
import jetbrains.exodus.env.TransactionBase
import jetbrains.exodus.kotlin.notNull
import java.io.Closeable
// the ley for transaction's user object containing instance of IOCancellingPolicy
private const val CANCELLING_POLICY_KEY = "CP_KEY"
internal class ClusterIterator @JvmOverloads constructor(private val vfs: VirtualFileSystem,
val txn: Transaction,
private val fd: Long,
position: Long = 0L) : Closeable {
private val cursor: Cursor = vfs.contents.openCursor(txn)
private val cancellingPolicy: IOCancellingPolicy? by lazy(LazyThreadSafetyMode.NONE) {
vfs.cancellingPolicyProvider?.run {
txn.getUserObject(CANCELLING_POLICY_KEY) as IOCancellingPolicy? ?: policy.apply {
txn.setUserObject(CANCELLING_POLICY_KEY, this)
}
}
}
var current: Cluster? = null
private set
var isClosed: Boolean = false
private set
constructor(vfs: VirtualFileSystem,
txn: Transaction,
file: File) : this(vfs, txn, file.descriptor)
init {
(txn as TransactionBase).checkIsFinished()
if (position >= 0L) {
seek(position)
}
isClosed = false
}
/**
* Seeks to the cluster that contains data by position. Doesn't navigate within cluster itself.
*
* @param position position in the file
*/
fun seek(position: Long) {
var pos = position
val cs = vfs.config.clusteringStrategy
val it: ByteIterable?
if (cs.isLinear) {
// if clustering strategy is linear then all clusters has the same size
val firstClusterSize = cs.firstClusterSize
it = cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd, pos / firstClusterSize))
if (it == null) {
current = null
} else {
current = readCluster(it)
adjustCurrentCluster()
val currentCluster = current
if (currentCluster != null) {
currentCluster.startingPosition = currentCluster.clusterNumber * firstClusterSize
}
}
} else {
it = cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd, 0L))
if (it == null) {
current = null
} else {
val maxClusterSize = cs.maxClusterSize
var clusterSize = 0L
current = readCluster(it)
var startingPosition = 0L
adjustCurrentCluster()
while (current != null) {
// if cluster size is equal to max cluster size, then all further cluster will have that size,
// so we don't need to load their size
val notNullCluster = current.notNull
if (clusterSize < maxClusterSize) {
clusterSize = notNullCluster.getSize().toLong()
}
notNullCluster.startingPosition = startingPosition
if (pos < clusterSize) {
break
}
pos -= clusterSize
startingPosition += clusterSize
moveToNext()
}
}
}
}
fun size(): Long {
var result = 0L
val cs = vfs.config.clusteringStrategy
if (cs.isLinear) {
val clusterSize = cs.firstClusterSize.toLong()
// if clustering strategy is linear we can try to navigate to the last file cluster
if ((cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd + 1, 0L)) != null && cursor.prev) ||
cursor.prev) {
val clusterKey = ClusterKey(cursor.key)
if (clusterKey.descriptor == fd) {
return clusterKey.clusterNumber * clusterSize + readCluster(cursor.value).getSize()
}
}
seek(0L)
// if clustering strategy is linear we can avoid reading cluster size for each cluster
var previous: Cluster? = null
while (hasCluster()) {
if (previous != null) {
result += clusterSize
}
previous = current
moveToNext()
}
if (previous != null) {
result += previous.getSize().toLong()
}
} else {
seek(0L)
while (hasCluster()) {
result += current.notNull.getSize().toLong()
moveToNext()
}
}
return result
}
fun hasCluster() = current != null
fun moveToNext() {
cancelIfNeeded()
if (current != null) {
if (!cursor.next) {
current = null
} else {
current = readCluster(cursor.value)
adjustCurrentCluster()
}
}
}
fun deleteCurrent() {
if (current != null) {
cursor.deleteCurrent()
}
}
override fun close() {
if (!isClosed) {
cursor.close()
isClosed = true
}
}
fun isObsolete() = txn.isFinished
private fun readCluster(it: ByteIterable): Cluster {
val clusterConverter = vfs.clusterConverter
return Cluster(clusterConverter?.onRead(it) ?: it)
}
private fun adjustCurrentCluster() {
val clusterKey = ClusterKey(cursor.key)
if (clusterKey.descriptor != fd) {
current = null
} else {
current.notNull.clusterNumber = clusterKey.clusterNumber
}
}
private fun cancelIfNeeded() {
cancellingPolicy?.run {
if (needToCancel()) {
doCancel()
}
}
}
} | vfs/src/main/kotlin/jetbrains/exodus/vfs/ClusterIterator.kt | 419561924 |
// 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.testGenerator.generator
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.test.*
import org.jetbrains.kotlin.testGenerator.model.*
import org.junit.runner.RunWith
import java.io.File
import java.util.*
object TestGenerator {
private val commonImports = importsListOf(
TestDataPath::class,
JUnit3RunnerWithInners::class,
KotlinTestUtils::class,
TestMetadata::class,
TestRoot::class,
RunWith::class
)
fun write(workspace: TWorkspace) {
for (group in workspace.groups) {
for (suite in group.suites) {
write(suite, group)
}
}
}
private fun write(suite: TSuite, group: TGroup) {
val packageName = suite.generatedClassName.substringBeforeLast('.')
val rootModelName = suite.generatedClassName.substringAfterLast('.')
val content = buildCode {
appendCopyrightComment()
newLine()
appendLine("package $packageName;")
newLine()
appendImports(getImports(suite))
appendGeneratedComment()
appendAnnotation(TAnnotation<SuppressWarnings>("all"))
appendAnnotation(TAnnotation<TestRoot>(group.modulePath))
appendAnnotation(TAnnotation<TestDataPath>("\$CONTENT_ROOT"))
val singleModel = suite.models.singleOrNull()
if (singleModel != null) {
append(SuiteElement.create(group, suite, singleModel, rootModelName, isNested = false))
} else {
appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java))
appendBlock("public abstract class $rootModelName extends ${suite.abstractTestClass.simpleName}") {
val children = suite.models
.map { SuiteElement.create(group, suite, it, it.testClassName, isNested = true) }
appendList(children, separator = "\n\n")
}
}
newLine()
}
val filePath = suite.generatedClassName.replace('.', '/') + ".java"
val file = File(group.testSourcesRoot, filePath)
write(file, postProcessContent(content))
}
private fun write(file: File, content: String) {
val oldContent = file.takeIf { it.isFile }?.readText() ?: ""
if (normalizeContent(content) != normalizeContent(oldContent)) {
file.writeText(content)
val path = file.toRelativeStringSystemIndependent(KotlinRoot.DIR)
println("Updated $path")
}
}
private fun normalizeContent(content: String): String = content.replace(Regex("\\R"), "\n")
private fun getImports(suite: TSuite): List<String> {
val imports = (commonImports + suite.imports).toMutableList()
if (suite.models.any { it.targetBackend != TargetBackend.ANY }) {
imports += importsListOf(TargetBackend::class)
}
val superPackageName = suite.abstractTestClass.`package`.name
val selfPackageName = suite.generatedClassName.substringBeforeLast('.')
if (superPackageName != selfPackageName) {
imports += importsListOf(suite.abstractTestClass.kotlin)
}
return imports
}
private fun postProcessContent(text: String): String {
return text.lineSequence()
.map { it.trimEnd() }
.joinToString(System.getProperty("line.separator"))
}
private fun Code.appendImports(imports: List<String>) {
if (imports.isNotEmpty()) {
imports.forEach { appendLine("import $it;") }
newLine()
}
}
private fun Code.appendCopyrightComment() {
val year = GregorianCalendar()[Calendar.YEAR]
appendLine("// Copyright 2000-$year 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.")
}
private fun Code.appendGeneratedComment() {
appendMultilineComment("""
This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}.
DO NOT MODIFY MANUALLY.
""".trimIndent())
}
} | plugins/kotlin/generators/test/org/jetbrains/kotlin/testGenerator/generator/TestGenerator.kt | 1843123423 |
class Test {
fun a(
action: () -> Unit = fun(
<caret>
))
}
// SET_TRUE: ALIGN_MULTILINE_METHOD_BRACKETS
// IGNORE_FORMATTER
// KT-39459 | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyParameterInInnerAnnonymousFunction2.after.kt | 2433951583 |
// 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.completion
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.LookupListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import org.jetbrains.kotlin.psi.KtTypeArgumentList
class LookupCancelService {
internal class Reminiscence(editor: Editor, offset: Int) {
var editor: Editor? = editor
private var marker: RangeMarker? = editor.document.createRangeMarker(offset, offset)
// forget about auto-popup cancellation when the caret is moved to the start or before it
private var editorListener: CaretListener? = object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (marker != null && (!marker!!.isValid || editor.logicalPositionToOffset(e.newPosition) <= offset)) {
dispose()
}
}
}
init {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
editor.caretModel.addCaretListener(editorListener!!)
}
fun matches(editor: Editor, offset: Int): Boolean {
return editor == this.editor && marker?.startOffset == offset
}
fun dispose() {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
if (marker != null) {
editor!!.caretModel.removeCaretListener(editorListener!!)
marker = null
editor = null
editorListener = null
}
}
}
internal val lookupCancelListener = object : LookupListener {
override fun lookupCanceled(event: LookupEvent) {
val lookup = event.lookup
if (event.isCanceledExplicitly && lookup.isCompletion) {
val offset = lookup.currentItem?.getUserData(LookupCancelService.AUTO_POPUP_AT)
if (offset != null) {
lastReminiscence?.dispose()
if (offset <= lookup.editor.document.textLength) {
lastReminiscence = Reminiscence(lookup.editor, offset)
}
}
}
}
}
internal fun disposeLastReminiscence(editor: Editor) {
if (lastReminiscence?.editor == editor) {
lastReminiscence!!.dispose()
lastReminiscence = null
}
}
private var lastReminiscence: Reminiscence? = null
companion object {
fun getInstance(project: Project): LookupCancelService = project.getServiceSafe()
fun getServiceIfCreated(project: Project): LookupCancelService? = project.getServiceIfCreated(LookupCancelService::class.java)
val AUTO_POPUP_AT = Key<Int>("LookupCancelService.AUTO_POPUP_AT")
}
fun wasAutoPopupRecentlyCancelled(editor: Editor, offset: Int): Boolean {
return lastReminiscence?.matches(editor, offset) ?: false
}
}
| plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupCancelService.kt | 3380320135 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.ui.LoadingDecorator
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.util.getName
import java.awt.BorderLayout
import java.awt.GridBagLayout
import java.awt.event.KeyEvent
import java.util.function.Function
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.KeyStroke
class GHLoadingPanel<T> @Deprecated("Replaced with factory because JBLoadingPanel is not really needed for initial loading",
ReplaceWith("GHLoadingPanelFactory().create()"))
constructor(model: GHLoadingModel,
content: T,
parentDisposable: Disposable,
textBundle: EmptyTextBundle = EmptyTextBundle.Default)
: JBLoadingPanel(BorderLayout(), createDecorator(parentDisposable))
where T : JComponent, T : ComponentWithEmptyText {
companion object {
private fun createDecorator(parentDisposable: Disposable): Function<JPanel, LoadingDecorator> {
return Function<JPanel, LoadingDecorator> {
object : LoadingDecorator(it, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) {
override fun customizeLoadingLayer(parent: JPanel, text: JLabel, icon: AsyncProcessIcon): NonOpaquePanel {
parent.layout = GridBagLayout()
text.text = ApplicationBundle.message("label.loading.page.please.wait")
text.icon = AnimatedIcon.Default()
text.foreground = UIUtil.getContextHelpForeground()
val result = NonOpaquePanel(text)
parent.add(result)
return result
}
}
}
}
class Controller(private val model: GHLoadingModel,
private val loadingPanel: JBLoadingPanel,
private val updateLoadingPanel: ProgressStripe,
private val statusText: StatusText,
private val textBundle: EmptyTextBundle,
private val errorHandlerProvider: () -> GHLoadingErrorHandler?) {
init {
model.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = update()
override fun onLoadingCompleted() = update()
override fun onReset() = update()
})
update()
}
private fun update() {
if (model.loading) {
loadingPanel.isFocusable = true
statusText.clear()
if (model.resultAvailable) {
updateLoadingPanel.startLoading()
}
else {
loadingPanel.startLoading()
}
}
else {
loadingPanel.stopLoading()
updateLoadingPanel.stopLoading()
if (model.resultAvailable) {
loadingPanel.isFocusable = false
loadingPanel.resetKeyboardActions()
statusText.text = textBundle.empty
}
else {
val error = model.error
if (error != null) {
statusText.clear()
.appendText(textBundle.errorPrefix, SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(error.message ?: GithubBundle.message("unknown.loading.error"),
SimpleTextAttributes.ERROR_ATTRIBUTES,
null)
errorHandlerProvider()?.getActionForError(error)?.let {
statusText.appendSecondaryText(" ${it.getName()}", SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, it)
loadingPanel.registerKeyboardAction(it, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
}
}
else statusText.text = textBundle.default
}
}
}
}
}
private val updateLoadingPanel =
ProgressStripe(content, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
isOpaque = false
}
var errorHandler: GHLoadingErrorHandler? = null
init {
isOpaque = false
add(updateLoadingPanel, BorderLayout.CENTER)
Controller(model, this, updateLoadingPanel, content.emptyText, textBundle) { errorHandler }
}
interface EmptyTextBundle {
val default: String
val empty: String
val errorPrefix: String
class Simple(override val default: String, override val errorPrefix: String, override val empty: String = "") : EmptyTextBundle
object Default : EmptyTextBundle {
override val default: String = ""
override val empty: String = ""
override val errorPrefix: String = GithubBundle.message("cannot.load.data")
}
}
}
| plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingPanel.kt | 1476291495 |
package eu.kanade.tachiyomi.data.mangasync.anilist.model
data class ALUserLists(val lists: Map<String, List<ALUserManga>>) {
fun flatten() = lists.values.flatten()
} | app/src/main/java/eu/kanade/tachiyomi/data/mangasync/anilist/model/ALUserLists.kt | 20696257 |
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.Example
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
class Ability : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : Ability {
__init(_i, _bb)
return this
}
val id : UInt get() = bb.getInt(bb_pos + 0).toUInt()
fun mutateId(id: UInt) : ByteBuffer = bb.putInt(bb_pos + 0, id.toInt())
val distance : UInt get() = bb.getInt(bb_pos + 4).toUInt()
fun mutateDistance(distance: UInt) : ByteBuffer = bb.putInt(bb_pos + 4, distance.toInt())
companion object {
fun createAbility(builder: FlatBufferBuilder, id: UInt, distance: UInt) : Int {
builder.prep(4, 8)
builder.putInt(distance.toInt())
builder.putInt(id.toInt())
return builder.offset()
}
}
}
| tests/MyGame/Example/Ability.kt | 4066505463 |
package me.bemind.glitchappcore
import android.graphics.Bitmap
import android.util.LruCache
import java.util.*
/**
* Created by angelomoroni on 09/04/17.
*/
interface Stack<T> : Iterable<T> {
fun push(item: T)
fun pop(): T?
fun peek(): T?
fun isEmpty(): Boolean {
return size() == 0
}
fun size(): Int
fun clear()
fun clearKeepingFirst()
}
class LinkedStack<T> :Stack<T>{
val stack = LinkedList<T>()
override fun push(item: T) {
stack.add(item)
}
override fun pop(): T? {
return if(stack.size>0){
stack.removeLast()
}else{
null
}
}
override fun peek(): T? {
return if(stack.size>0){
stack.last
}else{
null
}
}
override fun size(): Int {
return stack.size
}
override fun clear() {
stack.clear()
}
override fun clearKeepingFirst() {
val t = stack.first
stack.clear()
push(t)
}
override fun iterator(): Iterator<T> {
return stack.iterator()
}
fun first():T? = if(stack.size>0){
stack.first
}else{
null
}
fun addAll(collection: Collection<T> = ArrayList<T>()) = stack.addAll(collection)
fun getAllAsList() :ArrayList<T> = ArrayList(stack)
fun removeOld():T?{
val t = getOld()
stack.removeAt(1)
return t
}
fun getOld(): T? {
return stack[1]
}
}
| glitchappcore/src/main/java/me/bemind/glitchappcore/DataStructure.kt | 272037606 |
// "Create type parameter 'X'" "false"
// ACTION: Create class 'X'
// ACTION: Create enum 'X'
// ACTION: Create interface 'X'
// ACTION: Create object 'X'
// ACTION: Do not show return expression hints
// ACTION: Enable a trailing comma by default in the formatter
// ERROR: Unresolved reference: X
class A
fun foo(x: <caret>X.Y) {
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createTypeParameter/inContainingDeclaration/typeQualifier.kt | 425593613 |
package org.jetbrains.ide
import io.netty.handler.codec.http.HttpResponseStatus
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.hamcrest.CoreMatchers.equalTo
import org.jetbrains.ide.TestManager.TestDescriptor
import org.junit.Assert.assertThat
import java.net.URL
import java.net.HttpURLConnection
import com.google.gson.stream.JsonWriter
import java.io.OutputStreamWriter
import com.intellij.openapi.vfs.CharsetToolkit
import java.io.BufferedOutputStream
public class RestApiTest {
private val fixtureManager = FixtureRule()
private val manager = TestManager(fixtureManager.projectFixture)
private val _chain = RuleChain
.outerRule(fixtureManager)
.around(manager)
Rule
public fun getChain(): RuleChain = _chain
Test(timeout = 60000)
TestDescriptor(filePath = "", status = 400)
public fun fileEmptyRequest() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "foo.txt", relativeToProject = true, status = 200)
public fun relativeToProject() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "foo.txt", relativeToProject = true, line = 1, status = 200)
public fun relativeToProjectWithLine() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "foo.txt", relativeToProject = true, line = 1, column = 13, status = 200)
public fun relativeToProjectWithLineAndColumn() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "fileInExcludedDir.txt", excluded = true, status = 200)
public fun inExcludedDir() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "bar/42/foo.txt", doNotCreate = true, status = 404)
public fun relativeNonExistent() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "_tmp_", doNotCreate = true, status = 404)
public fun absoluteNonExistent() {
doTest()
}
Test(timeout = 60000)
TestDescriptor(filePath = "_tmp_", status = 200)
public fun absolute() {
doTest()
}
private fun doTest() {
val serviceUrl = "http://localhost:" + BuiltInServerManager.getInstance().getPort() + "/api/file"
var url = serviceUrl + (if (manager.filePath == null) "" else ("/" + manager.filePath))
val line = manager.annotation?.line ?: -1
if (line != -1) {
url += ":$line"
}
val column = manager.annotation?.column ?: -1
if (column != -1) {
url += ":$column"
}
var connection = URL(url).openConnection() as HttpURLConnection
val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200)
assertThat(HttpResponseStatus.valueOf(connection.getResponseCode()), equalTo(expectedStatus))
connection = URL("$serviceUrl?file=${manager.filePath ?: ""}&line=$line&column=$column").openConnection() as HttpURLConnection
assertThat(HttpResponseStatus.valueOf(connection.getResponseCode()), equalTo(expectedStatus))
connection = URL("$serviceUrl").openConnection() as HttpURLConnection
connection.setRequestMethod("POST")
connection.setDoOutput(true)
val writer = JsonWriter(OutputStreamWriter(BufferedOutputStream(connection.getOutputStream()), CharsetToolkit.UTF8_CHARSET))
writer.beginObject()
writer.name("file").value(manager.filePath)
writer.name("line").value(line)
writer.name("column").value(column)
writer.endObject()
writer.close()
assertThat(HttpResponseStatus.valueOf(connection.getResponseCode()), equalTo(expectedStatus))
}
}
| platform/built-in-server/testSrc/RestApiTest.kt | 1909907988 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.util.createSmartPointer
import com.intellij.psi.util.descendantsOfType
import com.intellij.psi.util.elementType
import com.intellij.psi.util.prevLeaf
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.thisOrParentIsRoot
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddFullQualifierIntention : SelfTargetingIntention<KtNameReferenceExpression>(
KtNameReferenceExpression::class.java,
KotlinBundle.lazyMessage("add.full.qualifier")
), LowPriorityAction {
override fun isApplicableTo(element: KtNameReferenceExpression, caretOffset: Int): Boolean = isApplicableTo(
referenceExpression = element,
contextDescriptor = null,
)
override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) {
val fqName = element.findSingleDescriptor()?.importableFqName ?: return
applyTo(element, fqName)
}
override fun startInWriteAction(): Boolean = false
companion object {
fun isApplicableTo(referenceExpression: KtNameReferenceExpression, contextDescriptor: DeclarationDescriptor?): Boolean {
if (referenceExpression.parent is KtInstanceExpressionWithLabel) return false
val prevElement = referenceExpression.prevElementWithoutSpacesAndComments()
if (prevElement.elementType == KtTokens.DOT) return false
val resultDescriptor = contextDescriptor ?: referenceExpression.findSingleDescriptor() ?: return false
if (resultDescriptor.isExtension || resultDescriptor.isInRoot) return false
if (prevElement.elementType == KtTokens.COLONCOLON) {
if (resultDescriptor.isTopLevelCallable) return false
val prevSibling = prevElement?.getPrevSiblingIgnoringWhitespaceAndComments()
if (prevSibling is KtNameReferenceExpression || prevSibling is KtDotQualifiedExpression) return false
}
val file = referenceExpression.containingKtFile
val identifier = referenceExpression.getIdentifier()?.text
val fqName = resultDescriptor.importableFqName
if (file.importDirectives.any { it.aliasName == identifier && it.importedFqName == fqName }) return false
return true
}
fun applyTo(referenceExpression: KtNameReferenceExpression, fqName: FqName): KtElement {
val qualifier = fqName.parent().quoteSegmentsIfNeeded()
return referenceExpression.project.executeWriteCommand(KotlinBundle.message("add.full.qualifier"), groupId = null) {
val psiFactory = KtPsiFactory(referenceExpression)
when (val parent = referenceExpression.parent) {
is KtCallableReferenceExpression -> addOrReplaceQualifier(psiFactory, parent, qualifier)
is KtCallExpression -> replaceExpressionWithDotQualifier(psiFactory, parent, qualifier)
is KtUserType -> addQualifierToType(psiFactory, parent, qualifier)
else -> replaceExpressionWithQualifier(psiFactory, referenceExpression, fqName)
}
}
}
fun addQualifiersRecursively(root: KtElement): KtElement {
if (root is KtNameReferenceExpression) return applyIfApplicable(root) ?: root
root.descendantsOfType<KtNameReferenceExpression>()
.map { it.createSmartPointer() }
.toList()
.asReversed()
.forEach {
it.element?.let(::applyIfApplicable)
}
return root
}
private fun applyIfApplicable(referenceExpression: KtNameReferenceExpression): KtElement? {
val descriptor = referenceExpression.findSingleDescriptor() ?: return null
val fqName = descriptor.importableFqName ?: return null
if (!isApplicableTo(referenceExpression, descriptor)) return null
return applyTo(referenceExpression, fqName)
}
}
}
private fun addOrReplaceQualifier(factory: KtPsiFactory, expression: KtCallableReferenceExpression, qualifier: String): KtElement {
val receiver = expression.receiverExpression
return if (receiver != null) {
replaceExpressionWithDotQualifier(factory, receiver, qualifier)
} else {
val qualifierExpression = factory.createExpression(qualifier)
expression.addBefore(qualifierExpression, expression.firstChild) as KtElement
}
}
private fun replaceExpressionWithDotQualifier(psiFactory: KtPsiFactory, expression: KtExpression, qualifier: String): KtElement {
val expressionWithQualifier = psiFactory.createExpressionByPattern("$0.$1", qualifier, expression)
return expression.replaced(expressionWithQualifier)
}
private fun addQualifierToType(psiFactory: KtPsiFactory, userType: KtUserType, qualifier: String): KtElement {
val type = userType.parent.safeAs<KtNullableType>() ?: userType
val typeWithQualifier = psiFactory.createType("$qualifier.${type.text}")
return type.parent.replaced(typeWithQualifier)
}
private fun replaceExpressionWithQualifier(
psiFactory: KtPsiFactory,
referenceExpression: KtNameReferenceExpression,
fqName: FqName
): KtElement {
val expressionWithQualifier = psiFactory.createExpression(fqName.asString())
return referenceExpression.replaced(expressionWithQualifier)
}
private val DeclarationDescriptor.isInRoot: Boolean get() = importableFqName?.thisOrParentIsRoot() != false
private val DeclarationDescriptor.isTopLevelCallable: Boolean
get() = safeAs<CallableMemberDescriptor>()?.containingDeclaration is PackageFragmentDescriptor ||
safeAs<ConstructorDescriptor>()?.containingDeclaration?.containingDeclaration is PackageFragmentDescriptor
private fun KtNameReferenceExpression.prevElementWithoutSpacesAndComments(): PsiElement? = prevLeaf {
it.elementType !in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET
}
private fun KtNameReferenceExpression.findSingleDescriptor(): DeclarationDescriptor? = resolveMainReferenceToDescriptors().singleOrNull()
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddFullQualifierIntention.kt | 2411469935 |
package alraune.back
import vgrechka.*
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.ResultSetMetaData
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KType
import kotlin.reflect.full.*
//class QueryBuilder() {
// val sqlBuf = StringBuilder()
// val params = mutableListOf<Any?>()
//
//
// class OptsPile(
// val isUpdate: Boolean? = null,
// val ctorParamMatching: CtorParamMatching? = null,
// val compoundClass: Class<*>? = null,
// val componentClasses: List<Class<*>>? = null,
// val params_barney: Params_barney? = null
// )
//
// enum class CtorParamMatching {
// Positional, ByName
// }
//
// class ShitHolder(val shit: Any?)
//
//
// fun text(x: String): QueryBuilder {
// sqlBuf += " " + x
// return this
// }
//
// fun text(s: String, p: Any?): QueryBuilder {
// text(s)
// param(p)
// return this
// }
//
// fun format(format: String, vararg args: Any): QueryBuilder {
// text(String.format(format, *args))
// return this
// }
//
// fun param(x: Any?): QueryBuilder {
// sqlBuf += " ?"
// params += when {
// x is Enum<*> -> x.name
// else -> x
// }
// return this
// }
//
// fun execute() {
// selectOrUpdate(OptsPile(isUpdate = true))
// }
//
// fun <Entity : Any> selectSimple(entityClass: Class<Entity>, opts: OptsPile = OptsPile()): List<Entity> {
// val list = selectOrUpdate(OptsPile(
// isUpdate = false,
// compoundClass = ShitHolder::class.java,
// componentClasses = listOf(entityClass),
// ctorParamMatching = opts.ctorParamMatching ?: CtorParamMatching.ByName))!!
// return list.map {entityClass.cast((it as ShitHolder).shit)}
// }
//
// fun dbValueToKtValue(type: KType, row: ReifiedResultSet.Row, colIndex: Int): Any? {
// val dbValue = row.getObject(colIndex)
// val ktClass = type.classifier as KClass<*>
// return when {
// dbValue == null -> {
// check(type.isMarkedNullable)
// null
// }
// ktClass.isSubclassOf(Enum::class) -> {
// ktClass.java.enumConstants.find {(it as Enum<*>).name == dbValue}
// ?: bitch("dbValue = $dbValue")
// }
// else -> ktClass.cast(dbValue)
// }
// }
//
// fun instantiateShitFromDBValues(clazz: Class<*>, row: ReifiedResultSet.Row, fromColumn: Int, untilColumn: Int, opts: OptsPile): Any {
// check(clazz.kotlin.constructors.size == 1)
// val ctor = clazz.kotlin.primaryConstructor!!
// val takenColumnsIndices = mutableSetOf<Int>()
// val ctorArgs = mutableListOf<Any?>()
//
// fun loopThroughColumns(block: (colIndex: Int, colName: String) -> Unit) {
// for (colIndex in fromColumn until untilColumn) {
// if (colIndex !in takenColumnsIndices) {
// var colName = row.metaData.getColumnName(colIndex)
// colName.indexOfOrNull(".")?.let {
// colName = colName.substring(it + 1)
// }
// block(colIndex, colName)
// }
// }
// }
//
// for (ctorParam in ctor.valueParameters) {
// loopThroughColumns {colIndex, colName ->
// val matches = when (opts.ctorParamMatching!!) {
// CtorParamMatching.Positional -> ctorArgs.size < ctor.valueParameters.size
// CtorParamMatching.ByName -> ctorParam.name!!.toLowerCase() == colName.toLowerCase()
// }
// if (matches) {
// takenColumnsIndices += colIndex
// ctorArgs += dbValueToKtValue(ctorParam.type, row, colIndex)
// }
// }
// }
//
// val inst =
// try {ctor.call(*ctorArgs.toTypedArray())}
// catch (e: Throwable) {
// "break on me"
// throw e
// }
//
// loopThroughColumns {colIndex, colName ->
// val prop = clazz.kotlin.memberProperties
// .find {it.name.toLowerCase() == colName.toLowerCase()}
// ?: bitch("colName = $colName")
// @Suppress("UNCHECKED_CAST")
// (prop as KMutableProperty1<Any, Any?>).set(inst, dbValueToKtValue(prop.returnType, row, colIndex))
// }
//
// return inst
// }
//
// class ReifiedResultSet(private val rs: ResultSet) {
// val metaData = rs.metaData!!
// val rows = mutableListOf<Row>()
// init {
// val maxRows = 1000
// while (rs.next()) {
// if (rows.size == maxRows)
// bitch("62617923-aea0-4d34-aa6b-9d3d68f4df16")
// rows += Row(
// metaData,
// values = (1..metaData.columnCount).map {rs.getObject(it)},
// nameToValue = mapOf(*(1..metaData.columnCount).map {
// metaData.getColumnName(it) to rs.getObject(it)}.toTypedArray()))
// }
// }
//
// class Row(val metaData: ResultSetMetaData, val values: List<Any?>, val nameToValue: Map<String, Any?>) {
// fun getObject(colIndex: Int): Any? = values[colIndex - 1]
// }
// }
//
// private fun selectOrUpdate(opts: OptsPile): List<Any>? {
// val t0 = System.currentTimeMillis()
// try {
// var st: PreparedStatement? = null
// var _rs: ResultSet? = null
//
// var exception: Throwable? = null
// try {
// st = rctx.connection.prepareStatement(sqlBuf.toString())
// for ((index, ktValue) in params.withIndex()) {
// val dbValue = when {
// ktValue is Enum<*> -> ktValue.name
// else -> ktValue
// }
// st.setObject(index + 1, dbValue)
// }
//
// if (opts.isUpdate!!) {
// st.execute()
// return null
// } else {
// _rs = st.executeQuery()
// val rs = ReifiedResultSet(_rs)
// val list = mutableListOf<Any>()
// val meta = rs.metaData
// for (row in rs.rows) {
// val compoundCtorArgs = mutableListOf<Any>()
// var fromColumn = 1
// var consideringComponent = 0
//
// fun considerColumns(untilColumn: Int) {
// val componentClass = opts.componentClasses!![consideringComponent]
// compoundCtorArgs += instantiateShitFromDBValues(componentClass, row, fromColumn, untilColumn, opts)
// fromColumn = untilColumn + 1
// ++consideringComponent
// }
//
// for (i in 1..meta.columnCount) {
// if (meta.getColumnName(i).startsWith("separator_")) {
// considerColumns(untilColumn = i)
// }
// }
// considerColumns(untilColumn = meta.columnCount + 1)
//
// val compoundClassInstance = opts.compoundClass!!.kotlin.primaryConstructor!!.call(*compoundCtorArgs.toTypedArray())
// list += compoundClassInstance
// }
//
// opts.params_barney?.let {
// if (it.checkLimitExactlyMatchesActualByTryingToSelectOneMore) {
// val limit = it.limit!!
// if (list.size > limit)
// bitch("This query should have returned exactly $limit rows, but got at least one more")
// }
// }
//
// return list
// }
// }
// catch (e: Throwable) {
// exception = e
// throw exception
// }
// finally {
// fun close(x: AutoCloseable?) {
// if (x != null) {
// try {
// x.close()
// } catch (e: Throwable) {
// exception?.addSuppressed(e)
// }
// }
// }
// close(_rs)
// close(st)
// }
// }
// finally {
// val elapsed = System.currentTimeMillis() - t0
// if (AlGlobalContext.queryLoggingEnabled)
// clog("elapsed = $elapsed")
// }
// }
//
// fun <Entity : Any> selectOneSimple(entityClass: Class<Entity>, opts: OptsPile = OptsPile()): Entity {
// return selectSimple(entityClass, opts).first()
// }
//
// fun selectOneLong(): Long {
// val res = selectOneSimple(ShitHolder::class.java, OptsPile(ctorParamMatching = CtorParamMatching.Positional))
// return res.shit as Long
// }
//
// fun <Compound : Any> selectCompound(compoundClass: Class<Compound>, params_barney: Params_barney? = null): List<Compound> {
// // TODO:vgrechka Use entityWithParamsClass from params_barney
// check(compoundClass.constructors.size == 1)
// val componentClasses = compoundClass.kotlin.primaryConstructor!!.valueParameters.map {
// it.type.classifier as KClass<*>
// }
// val list = selectOrUpdate(OptsPile(
// isUpdate = false,
// compoundClass = compoundClass,
// componentClasses = componentClasses.map {it.java},
// ctorParamMatching = CtorParamMatching.ByName,
// params_barney = params_barney
// ))!!
// return list.map {compoundClass.cast(it)}
// }
//}
| attic/alraune/alraune-back/src/QueryBuilder.kt | 1119190124 |
/*
* 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.internal
/**
* Returns undefined value of type `T`.
* This method is unsafe and should be used with care.
*/
@SymbolName("Kotlin_native_internal_undefined")
internal external fun <T> undefined(): T | runtime/src/main/kotlin/kotlin/native/internal/Undefined.kt | 4169545151 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.ide.impl
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider
import com.intellij.lang.documentation.psi.psiDocumentationTarget
import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTargets
import com.intellij.model.Pointer
import com.intellij.model.Symbol
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.PsiFile
import com.intellij.util.castSafelyTo
open class IdeDocumentationTargetProviderImpl(private val project: Project) : IdeDocumentationTargetProvider {
override fun documentationTarget(editor: Editor, file: PsiFile, lookupElement: LookupElement): DocumentationTarget? {
val symbolTargets = (lookupElement.`object` as? Pointer<*>)
?.dereference()
?.castSafelyTo<Symbol>()
?.let { symbolDocumentationTargets(file.project, listOf(it)) }
if (!symbolTargets.isNullOrEmpty()) {
return symbolTargets.first()
}
val sourceElement = file.findElementAt(editor.caretModel.offset)
val targetElement = DocumentationManager.getElementFromLookup(project, editor, file, lookupElement)
?: return null
return psiDocumentationTarget(targetElement, sourceElement)
}
override fun documentationTargets(editor: Editor, file: PsiFile, offset: Int): List<DocumentationTarget> {
val symbolTargets = symbolDocumentationTargets(file, offset)
if (symbolTargets.isNotEmpty()) {
return symbolTargets
}
val documentationManager = DocumentationManager.getInstance(project)
val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file)
?: return emptyList()
return listOf(psiDocumentationTarget(targetElement, sourceElement))
}
}
| platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/IdeDocumentationTargetProviderImpl.kt | 4229090250 |
/*
* 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 codegen.inline.twiceInlinedObject
import kotlin.test.*
inline fun exec(f: () -> Unit) = f()
inline fun test2() {
val obj = object {
fun sayOk() = println("Ok")
}
obj.sayOk()
}
inline fun noExec(f: () -> Unit) { }
@Test fun runTest() {
exec {
test2()
}
noExec {
test2()
}
} | backend.native/tests/codegen/inline/twiceInlinedObject.kt | 2089289941 |
class A {
val x = go() // A
fun go() = 4 // A
fun foo() {
"" // A
}
}
| plugins/kotlin/jvm-debugger/test/testData/positionManager/class.kt | 355198880 |
package com.aemtools.index.search
import com.aemtools.index.model.sortByMods
import com.aemtools.test.base.BaseLightTest
import com.aemtools.test.fixture.OSGiConfigFixtureMixin
/**
* @author Dmytro Troynikov
*/
class OSGiConfigSearchTest : BaseLightTest(),
OSGiConfigFixtureMixin {
fun testBasicSearch() = fileCase {
addEmptyOSGiConfigs("/config/com.test.Service.xml")
verify {
OSGiConfigSearch.findConfigsForClass("com.test.Service", project)
.firstOrNull()
?: throw AssertionError("Unable to find configuration")
}
}
fun testSearchForOSGiServiceFactory() = fileCase {
addEmptyOSGiConfigs(
"/config/com.test.Service-first.xml",
"/config/com.test.Service-second.xml"
)
verify {
val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project)
assertEquals(2, configs.size)
}
}
fun testSearchForOSGiConfigurationFactory() = fileCase {
addEmptyOSGiConfigs(
"/config/com.test.Service-my-long-name.xml",
"/config/com.test.Service-my-very-long-name-2.xml"
)
verify {
val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project)
assertEquals(2, configs.size)
assertEquals(listOf(
"my-long-name",
"my-very-long-name-2"
),
configs.sortByMods().map { it.suffix() }
)
}
}
fun testBasicSearchForOSGiServiceWithFile() = fileCase {
val filesNames = listOf(
"/config/com.test.Service.xml",
"/config.author/com.test.Service.xml"
)
addEmptyOSGiConfigs(*filesNames.toTypedArray())
verify {
val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project, true)
assertEquals(
filesNames.map { "/src$it" },
configs.sortByMods().map { it.xmlFile?.virtualFile?.path }
)
}
}
fun testSearchForOSGiServiceFactoryConfigs() = fileCase {
val fileNames = listOf(
"/config/com.test.Service-first.xml",
"/config/com.test.Service-second.xml"
)
addEmptyOSGiConfigs(*fileNames.toTypedArray())
verify {
val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project, true)
assertEquals(2, configs.size)
assertEquals(
fileNames.map { "/src$it" },
configs.sortByMods().map { it.xmlFile?.virtualFile?.path }
)
}
}
}
| aem-intellij-core/src/test/kotlin/com/aemtools/index/search/OSGiConfigSearchTest.kt | 670134753 |
package com.developerphil.adbidea.action
import com.developerphil.adbidea.adb.AdbFacade
import com.developerphil.adbidea.adb.AdbUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
class ClearDataAndRestartWithDebuggerAction : AdbAction() {
override fun actionPerformed(e: AnActionEvent, project: Project) = AdbFacade.clearDataAndRestartWithDebugger(project)
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = AdbUtil.isDebuggingAvailable
}
}
| src/main/kotlin/com/developerphil/adbidea/action/ClearDataAndRestartWithDebuggerAction.kt | 4028400460 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime.internal
@Suppress("ACTUAL_WITHOUT_EXPECT") // https://youtrack.jetbrains.com/issue/KT-37316
internal actual typealias JvmDefaultWithCompatibility = kotlin.jvm.JvmDefaultWithCompatibility | compose/runtime/runtime/src/jvmMain/kotlin/androidx/compose/runtime/internal/JvmDefaultWithCompatibility.jvm.kt | 4242292252 |
package com.simplemobiletools.commons.extensions
import android.net.Uri
import java.util.*
fun List<Uri>.getMimeType(): String {
val mimeGroups = HashSet<String>(size)
val subtypes = HashSet<String>(size)
forEach {
val parts = it.path.getMimeTypeFromPath().split("/")
if (parts.size == 2) {
mimeGroups.add(parts.getOrElse(0, { "" }))
subtypes.add(parts.getOrElse(1, { "" }))
} else {
return "*/*"
}
}
return when {
subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}"
mimeGroups.size == 1 -> "${mimeGroups.first()}/*"
else -> "*/*"
}
}
| commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt | 732394422 |
package net.yested.bootstrap
import net.yested.Component
import net.yested.HTMLComponent
import net.yested.createElement
class Glyphicon(icon:String) : Component {
override val element = createElement("span")
init {
element.className = "glyphicon glyphicon-${icon}"
}
}
fun HTMLComponent.glyphicon(icon:String): Unit {
+Glyphicon(icon = icon)
} | src/main/kotlin/net/yested/bootstrap/glyphicon.kt | 305148092 |
package taiwan.no1.app.ssfm.internal.di.modules.activity.dependency
import android.content.Context
import dagger.Module
import dagger.Provides
import taiwan.no1.app.ssfm.features.playlist.PlaylistViewModel
import taiwan.no1.app.ssfm.internal.di.annotations.scopes.PerActivity
import taiwan.no1.app.ssfm.models.data.repositories.DataRepository
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistCase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemUsecase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistUsecase
import taiwan.no1.app.ssfm.models.usecases.BaseUsecase
/**
*
* @author jieyi
* @since 8/9/17
*/
@Module
class PlaylistActivityModule {
/**
* Providing a [BaseUsecase] to the [PlaylistViewModel].
*
* @param dataRepository get a repository object by dagger 2.
* @return a [AddPlaylistCase] but the data type is abstract class, we'd like to developer
* to use the abstract method directly.
*/
@Provides
@PerActivity
fun provideAddPlaylistUsecase(dataRepository: DataRepository): AddPlaylistCase = AddPlaylistUsecase(dataRepository)
/**
* Providing a [BaseUsecase] to the [PlaylistViewModel].
*
* @param dataRepository get a repository object by dagger 2.
* @return a [AddPlaylistItemCase] but the data type is abstract class, we'd like to developer
* to use the abstract method directly.
*/
@Provides
@PerActivity
fun provideAddPlaylistItemUsecase(dataRepository: DataRepository): AddPlaylistItemCase =
AddPlaylistItemUsecase(dataRepository)
/**
* Providing a [PlaylistViewModel] to the [PlaylistActivity].
*
* @param context originally from activity module.
* @return a important [PlaylistViewModel] for binding view and viewmodel by activity.
*/
@Provides
@PerActivity
fun provideViewModel(context: Context, addPlaylistUsecase: AddPlaylistCase) =
PlaylistViewModel(context, addPlaylistUsecase)
} | app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/modules/activity/dependency/PlaylistActivityModule.kt | 3019677585 |
package jp.kai.forcelayout
import java.util.ArrayList
/**
* Created by kai on 2017/05/12.
*/
class Links : ArrayList<Links.LinkPair>() {
class LinkPair(private val parent: String, private val child: String) {
fun parent(): String {
return parent
}
fun child(): String {
return child
}
}
} | forcelayout/src/main/kotlin/jp/kai/forcelayout/Links.kt | 1191366176 |
// 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.quickDoc
import com.google.common.html.HtmlEscapers
import com.intellij.codeInsight.documentation.DocumentationManagerUtil
import com.intellij.codeInsight.navigation.targetPresentation
import com.intellij.lang.documentation.DocumentationResult
import com.intellij.lang.documentation.DocumentationSettings
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.java.JavaDocumentationProvider
import com.intellij.model.Pointer
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.refactoring.suggested.createSmartPointer
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.components.KtDeclarationRendererOptions
import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.kdoc.*
import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendHighlighted
import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.generateJavadoc
import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.renderKDoc
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
internal class KotlinDocumentationTarget(val element: PsiElement, private val originalElement: PsiElement?) : DocumentationTarget {
override fun createPointer(): Pointer<out DocumentationTarget> {
val elementPtr = element.createSmartPointer()
val originalElementPtr = originalElement?.createSmartPointer()
return Pointer {
val element = elementPtr.dereference() ?: return@Pointer null
KotlinDocumentationTarget(element, originalElementPtr?.dereference())
}
}
override fun presentation(): TargetPresentation {
return targetPresentation(element)
}
override fun computeDocumentationHint(): String? {
return computeLocalDocumentation(element, originalElement, true)
}
override val navigatable: Navigatable?
get() = element as? Navigatable
override fun computeDocumentation(): DocumentationResult? {
val html = computeLocalDocumentation(element, originalElement, false) ?: return null
return DocumentationResult.documentation(html)
}
companion object {
internal val RENDERING_OPTIONS = KtDeclarationRendererOptions(
typeRendererOptions = KtTypeRendererOptions.SHORT_NAMES,
renderUnitReturnType = true,
renderDefaultParameterValue = true,
renderDeclarationHeader = true,
approximateTypes = true
)
}
}
@Nls
private fun computeLocalDocumentation(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean): String? {
when {
element is KtFunctionLiteral -> {
val itElement = findElementWithText(originalElement, "it")
val itReference = itElement?.getParentOfType<KtNameReferenceExpression>(false)
if (itReference != null) {
return buildString {
renderKotlinDeclaration(
element,
quickNavigation,
symbolFinder = { it -> (it as? KtFunctionLikeSymbol)?.valueParameters?.firstOrNull() })
}
}
}
element is KtTypeReference -> {
val declaration = element.parent
if (declaration is KtCallableDeclaration &&
declaration.receiverTypeReference == element &&
findElementWithText(originalElement, "this") != null
) {
return computeLocalDocumentation(declaration, originalElement, quickNavigation)
}
}
element is KtClass && element.isEnum() -> {
return buildString {
renderEnumSpecialFunction(originalElement, element, quickNavigation)
}
}
element is KtEnumEntry && !quickNavigation -> {
val ordinal = element.containingClassOrObject?.body?.run { getChildrenOfType<KtEnumEntry>().indexOf(element) }
val project = element.project
return buildString {
renderKotlinDeclaration(element, false) {
definition {
it.inherit()
ordinal?.let {
append("<br>")
appendHighlighted("// ", project) { asInfo }
appendHighlighted(KotlinBundle.message("quick.doc.text.enum.ordinal", ordinal), project) { asInfo }
}
}
}
}
}
element is KtDeclaration -> {
return buildString {
renderKotlinDeclaration(element, quickNavigation)
}
}
element is KtLightDeclaration<*, *> -> {
val origin = element.kotlinOrigin ?: return null
return computeLocalDocumentation(origin, element, quickNavigation)
}
element is KtValueArgumentList -> {
val referenceExpression = element.prevSibling as? KtSimpleNameExpression ?: return null
val calledElement = referenceExpression.mainReference.resolve()
if (calledElement is KtNamedFunction || calledElement is KtConstructor<*>) {
// In case of Kotlin function or constructor
return computeLocalDocumentation(calledElement as KtExpression, element, quickNavigation)
}
else if (calledElement is PsiMethod) {
return JavaDocumentationProvider().generateDoc(calledElement, referenceExpression)
}
}
element is KtCallExpression -> {
val calledElement = element.referenceExpression()?.mainReference?.resolve() ?: return null
return computeLocalDocumentation(calledElement, originalElement, quickNavigation)
}
element.isModifier() -> {
when (element.text) {
KtTokens.LATEINIT_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.lateinit")
KtTokens.TAILREC_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.tailrec")
}
}
}
return null
}
private fun getContainerInfo(ktDeclaration: KtDeclaration): HtmlChunk {
analyze(ktDeclaration) {
val containingSymbol = ktDeclaration.getSymbol().getContainingSymbol()
val fqName = (containingSymbol as? KtClassLikeSymbol)?.classIdIfNonLocal?.asFqNameString()
?: (ktDeclaration.containingFile as? KtFile)?.packageFqName?.takeIf { !it.isRoot }?.asString()
val fqNameSection = fqName
?.let {
@Nls val link = StringBuilder()
val highlighted =
if (DocumentationSettings.isSemanticHighlightingOfLinksEnabled()) KDocRenderer.highlight(it, ktDeclaration.project) { asClassName }
else it
DocumentationManagerUtil.createHyperlink(link, it, highlighted, false, false)
HtmlChunk.fragment(
HtmlChunk.icon("class", KotlinIcons.CLASS),
HtmlChunk.nbsp(),
HtmlChunk.raw(link.toString()),
HtmlChunk.br()
)
} ?: HtmlChunk.empty()
val fileNameSection = ktDeclaration
.containingFile
?.name
?.takeIf { containingSymbol == null }
?.let {
HtmlChunk.fragment(
HtmlChunk.icon("file", KotlinIcons.FILE),
HtmlChunk.nbsp(),
HtmlChunk.text(it),
HtmlChunk.br()
)
}
?: HtmlChunk.empty()
return HtmlChunk.fragment(fqNameSection, fileNameSection)
}
}
private fun StringBuilder.renderEnumSpecialFunction(
originalElement: PsiElement?,
element: KtClass,
quickNavigation: Boolean
) {
val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>()
if (referenceExpression != null) {
// When caret on special enum function (e.g. SomeEnum.values<caret>())
// element is not an KtReferenceExpression, but KtClass of enum
// so reference extracted from originalElement
analyze(referenceExpression) {
val symbol = referenceExpression.mainReference.resolveToSymbol() as? KtNamedSymbol
val name = symbol?.name?.asString()
if (name != null) {
val containingClass = symbol.getContainingSymbol() as? KtClassOrObjectSymbol
val superClasses = containingClass?.superTypes?.mapNotNull { t -> t.expandedClassSymbol }
val kdoc = superClasses?.firstNotNullOfOrNull { superClass ->
superClass.psi?.navigationElement?.findDescendantOfType<KDoc> { doc ->
doc.getChildrenOfType<KDocSection>().any { it.findTagByName(name) != null }
}
}
renderKotlinDeclaration(element, false) {
if (!quickNavigation && kdoc != null) {
description {
renderKDoc(kdoc.getDefaultSection())
}
}
}
return
}
}
}
renderKotlinDeclaration(element, quickNavigation)
}
private fun findElementWithText(element: PsiElement?, text: String): PsiElement? {
return when {
element == null -> null
element.text == text -> element
element.prevLeaf()?.text == text -> element.prevLeaf()
else -> null
}
}
internal fun PsiElement?.isModifier() =
this != null && parent is KtModifierList && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null
private fun StringBuilder.renderKotlinDeclaration(
declaration: KtDeclaration,
onlyDefinition: Boolean,
symbolFinder: KtAnalysisSession.(KtSymbol) -> KtSymbol? = { it },
preBuild: KDocTemplate.() -> Unit = {}
) {
analyze(declaration) {
val symbol = symbolFinder(declaration.getSymbol())
if (symbol is KtDeclarationSymbol) {
insert(KDocTemplate()) {
definition {
append(HtmlEscapers.htmlEscaper().escape(symbol.render(KotlinDocumentationTarget.RENDERING_OPTIONS)))
}
if (!onlyDefinition) {
description {
renderKDoc(symbol, this)
}
}
getContainerInfo(declaration).toString().takeIf { it.isNotBlank() }?.let { info ->
containerInfo {
append(info)
}
}
preBuild()
}
}
}
}
private fun KtAnalysisSession.renderKDoc(
symbol: KtSymbol,
stringBuilder: StringBuilder,
) {
val declaration = symbol.psi as? KtElement
val kDoc = findKDoc(symbol)
if (kDoc != null) {
stringBuilder.renderKDoc(kDoc.contentTag, kDoc.sections)
return
}
if (declaration is KtSecondaryConstructor) {
declaration.getContainingClassOrObject().findKDoc()?.let {
stringBuilder.renderKDoc(it.contentTag, it.sections)
}
} else if (declaration is KtFunction &&
symbol is KtCallableSymbol &&
symbol.getAllOverriddenSymbols().any { it.psi is PsiMethod }) {
LightClassUtil.getLightClassMethod(declaration)?.let {
stringBuilder.insert(KDocTemplate.DescriptionBodyTemplate.FromJava()) {
body = generateJavadoc(it)
}
}
}
}
private fun KtAnalysisSession.findKDoc(symbol: KtSymbol): KDocContent? {
val ktElement = symbol.psi as? KtElement
ktElement?.findKDoc()?.let {
return it
}
if (symbol is KtCallableSymbol) {
symbol.getAllOverriddenSymbols().forEach { overrider ->
findKDoc(overrider)?.let {
return it
}
}
}
return null
} | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickDoc/KotlinDocumentationTarget.kt | 844943380 |
// 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.kdoc
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.resolve.BindingContext
interface KDocLinkResolutionService {
fun resolveKDocLink(
context: BindingContext,
fromDescriptor: DeclarationDescriptor,
resolutionFacade: ResolutionFacade,
qualifiedName: List<String>
): Collection<DeclarationDescriptor>
}
| plugins/kotlin/base/fe10/kdoc/src/org/jetbrains/kotlin/idea/kdoc/KDocLinkResolutionService.kt | 2759752550 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.openapi.util.TextRange
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.parents
import org.intellij.plugins.markdown.editor.tables.TableProps
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.util.hasType
class MarkdownTableSeparatorRow(text: CharSequence): MarkdownLeafPsiElement(MarkdownTokenTypes.TABLE_SEPARATOR, text) {
private val cachedCellsRanges
get() = CachedValuesManager.getCachedValue(this) {
CachedValueProvider.Result.create(buildCellsRanges(), PsiModificationTracker.MODIFICATION_COUNT)
}
private fun buildCellsRanges(): List<TextRange> {
val elementText = text
val cells = elementText.split(TableProps.SEPARATOR_CHAR).toMutableList()
val startedWithSeparator = cells.firstOrNull()?.isEmpty() == true
if (startedWithSeparator) {
cells.removeFirst()
}
val endedWithSeparator = cells.lastOrNull()?.isEmpty() == true
if (endedWithSeparator) {
cells.removeLast()
}
if (cells.isEmpty()) {
return emptyList()
}
val elementRange = textRange
var left = elementRange.startOffset
if (startedWithSeparator) {
left += 1
}
var right = left + cells.first().length
val ranges = mutableListOf<TextRange>()
ranges.add(TextRange(left, right))
val cellsSequence = cells.asSequence().drop(1)
for (cell in cellsSequence) {
left = right + 1
right = left + cell.length
ranges.add(TextRange(left, right))
}
return ranges
}
val parentTable: MarkdownTable?
get() = parents(withSelf = true).find { it.hasType(MarkdownElementTypes.TABLE) } as? MarkdownTable
val cellsRanges: List<TextRange>
get() = cachedCellsRanges
private val cellsLocalRanges: List<TextRange>
get() = cachedCellsRanges.map { it.shiftLeft(startOffset) }
val cellsCount: Int
get() = cellsRanges.size
fun getCellRange(index: Int, local: Boolean = false): TextRange? {
return when {
local -> cellsLocalRanges.getOrNull(index)
else -> cellsRanges.getOrNull(index)
}
}
fun getCellRangeWithPipes(index: Int, local: Boolean = false): TextRange? {
val range = getCellRange(index, local) ?: return null
val shifted = range.shiftLeft(startOffset)
val elementText = text
val left = when {
elementText.getOrNull(shifted.startOffset - 1) == TableProps.SEPARATOR_CHAR -> range.startOffset - 1
else -> range.startOffset
}
val right = when {
elementText.getOrNull(shifted.endOffset) == TableProps.SEPARATOR_CHAR -> range.endOffset + 1
else -> range.endOffset
}
return TextRange(left, right)
}
fun getCellText(index: Int): String? {
return getCellRange(index, local = true)?.let { text.substring(it.startOffset, it.endOffset) }
}
/**
* [offset] - offset in document
*/
fun getColumnIndexFromOffset(offset: Int): Int? {
return cellsRanges.indexOfFirst { it.containsOffset(offset) }.takeUnless { it == -1 }
}
/**
* [offset] - offset in document
*/
fun getCellRangeFromOffset(offset: Int): TextRange? {
return getColumnIndexFromOffset(offset)?.let { cellsRanges[it] }
}
enum class CellAlignment {
NONE,
LEFT,
RIGHT,
CENTER
}
private fun getCellAlignment(range: TextRange): CellAlignment {
val cellText = text.subSequence(range.startOffset, range.endOffset)
val firstIndex = cellText.indexOfFirst { it == ':' }
if (firstIndex == -1) {
return CellAlignment.NONE
}
val secondIndex = cellText.indexOfLast { it == ':' }
return when {
firstIndex != secondIndex -> CellAlignment.CENTER
cellText.subSequence(0, firstIndex).all { it == ' ' } -> CellAlignment.LEFT
else -> CellAlignment.RIGHT
}
}
fun getCellAlignment(index: Int): CellAlignment {
val range = getCellRange(index, local = true)!!
return getCellAlignment(range)
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownTableSeparatorRow.kt | 1551826553 |
class Bar {
operator fun get(vararg args: Int) {}
}
fun foo(a: Bar, i: Int) {
a<caret>[i, 1]
}
| plugins/kotlin/idea/tests/testData/intentions/operatorToFunction/arrayAccessMultipleIndex.kt | 2341326170 |
package com.jakewharton.rxbinding.widget
import android.widget.ProgressBar
import rx.functions.Action1
/**
* An action which increments the progress value of {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.incrementProgress(): Action1<in Int> = RxProgressBar.incrementProgressBy(this)
/**
* An action which increments the secondary progress value of {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.incrementSecondaryProgress(): Action1<in Int> = RxProgressBar.incrementSecondaryProgressBy(this)
/**
* An action which sets whether {@code view} is indeterminate.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.indeterminate(): Action1<in Boolean> = RxProgressBar.indeterminate(this)
/**
* An action which sets the max value of {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.max(): Action1<in Int> = RxProgressBar.max(this)
/**
* An action which sets the progress value of {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.progress(): Action1<in Int> = RxProgressBar.progress(this)
/**
* An action which sets the secondary progress value of {@code view}.
* <p>
* <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe
* to free this reference.
*/
public inline fun ProgressBar.secondaryProgress(): Action1<in Int> = RxProgressBar.secondaryProgress(this)
| rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/widget/RxProgressBar.kt | 3561489973 |
// WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'mapIndexed{}.sum()'"
// INTENTION_TEXT_2: "Replace with 'asSequence().mapIndexed{}.sum()'"
fun foo(list: List<Int>): Int {
var s = 0
<caret>for ((index, item) in list.withIndex()) {
s += item * index
}
return s
}
| plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/sum/indexUsed.kt | 3964226296 |
// 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 org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
open class GHApiLoadingErrorHandler(private val project: Project,
private val account: GithubAccount,
resetRunnable: () -> Unit)
: GHRetryLoadingErrorHandler(resetRunnable) {
override fun getActionForError(error: Throwable): Action? {
if (error is GithubAuthenticationException) {
return ReLoginAction()
}
return super.getActionForError(error)
}
private inner class ReLoginAction : AbstractAction(GithubBundle.message("accounts.relogin")) {
override fun actionPerformed(e: ActionEvent?) {
if (GithubAuthenticationManager.getInstance().requestReLogin(account, project))
resetRunnable()
}
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHApiLoadingErrorHandler.kt | 1981980529 |
package vgrechka
//import com.google.common.cache.CacheBuilder
//import com.google.common.cache.CacheLoader
//import com.google.common.cache.LoadingCache
//import com.google.debugging.sourcemap.*
//import java.io.File
//val SourceMapping.penetration by AttachedComputedShit<SourceMapping, SourceMapConsumerPenetration> {sourceMapping->
// val penetration = SourceMapConsumerPenetration()
//
// val privateLines = run {
// val f = sourceMapping.javaClass.getDeclaredField("lines")
// f.isAccessible = true
// f.get(sourceMapping) as List<List<Any>?>
// }
// val privateSources = run {
// val f = sourceMapping.javaClass.getDeclaredField("sources")
// f.isAccessible = true
// f.get(sourceMapping) as Array<String>
// }
//
// for ((generatedLine, privateLine) in privateLines.withIndex()) {
// if (privateLine != null) {
// for (privateEntry in privateLine) {
// val sourceLine = run {
// val m = privateEntry.javaClass.getMethod("getSourceLine")
// m.isAccessible = true
// m.invoke(privateEntry) as Int
// }
// val sourceColumn = run {
// val m = privateEntry.javaClass.getMethod("getSourceColumn")
// m.isAccessible = true
// m.invoke(privateEntry) as Int
// }
// val sourceFileId = run {
// val m = privateEntry.javaClass.getMethod("getSourceFileId")
// m.isAccessible = true
// m.invoke(privateEntry) as Int
// }
//
// val entry = SourceMapConsumerPenetration.DugEntry(
// file = privateSources[sourceFileId],
// generatedLine = generatedLine + 1,
// sourceLine = sourceLine + 1,
// sourceColumn = sourceColumn + 1)
//
// val entries = penetration.generatedLineToDugEntries.getOrPut(generatedLine + 1) {mutableListOf()}
// entries += entry
// }
// }
// }
// penetration
//}
//
//class SourceMapConsumerPenetration {
// val generatedLineToDugEntries = mutableMapOf<Int, MutableList<DugEntry>>()
//
// class DugEntry(val file: String,
// val generatedLine: Int,
// val sourceLine: Int,
// val sourceColumn: Int)
//
// val sourceFileLineToGeneratedLine: MutableMap<FileLine, Int> by lazy {
// val res = mutableMapOf<FileLine, Int>()
// for ((generatedLine, entries) in generatedLineToDugEntries) {
// val firstEntry = entries.first()
// for (entry in entries) {
// if (entry.sourceLine != firstEntry.sourceLine
// || entry.file != firstEntry.file
// || entry.generatedLine != generatedLine)
// wtf("8ea09bef-be33-4a6f-8eb4-5cd2b8502e02")
// }
// res[FileLine(firstEntry.file, firstEntry.sourceLine)] = generatedLine
// }
// res
// }
//
// fun dumpSourceLineToGeneratedLine() {
// if (sourceFileLineToGeneratedLine.isEmpty()) return clog("Freaking source map is empty")
// val entries = sourceFileLineToGeneratedLine.entries.toMutableList()
// entries.sortWith(Comparator<Map.Entry<FileLine, Int>> {a, b ->
// val c = a.key.file.compareTo(b.key.file)
// if (c != 0)
// c
// else
// a.key.line.compareTo(b.key.line)
// })
// for ((sourceFileLine, generatedLine) in entries) {
// val fullFilePath = true
// val fileDesignator = when {
// fullFilePath -> sourceFileLine.file
// else -> {
// val sourceFile = File(sourceFileLine.file)
// sourceFile.name
// }
// }
// val source = fileDesignator + ":" + sourceFileLine.line
// clog("source = $source; generatedLine = $generatedLine")
// }
// }
//}
//
//val theSourceMappings = SourceMappings()
//
//class SourceMappings(val allowInexactMatches: Boolean = true) {
// private val cache = CacheBuilder.newBuilder().build(object:CacheLoader<String, SourceMapping>() {
// override fun load(mapFilePath: String): SourceMapping {
// val text = File(mapFilePath).readText()
// return when {
// allowInexactMatches -> SourceMapConsumerFactory.parse(text)
// else -> parse(text, null)
// }
// }
// })
//
// fun getCached(mapFilePath: String): SourceMapping = cache[mapFilePath.replace("\\", "/")]
//
// private fun parse(contents: String, supplier: SourceMapSupplier?): SourceMapping {
// // Version 1, starts with a magic string
// if (contents.startsWith("/** Begin line maps. **/")) {
// throw SourceMapParseException(
// "This appears to be a V1 SourceMap, which is not supported.")
// } else if (contents.startsWith("{")) {
// val sourceMapObject = SourceMapObjectParser.parse(contents)
//
// // Check basic assertions about the format.
// when (sourceMapObject.version) {
// 3 -> {
// val consumer = SourceMapConsumerV3Hack()
// consumer.allowInexactMatches = allowInexactMatches
// consumer.parse(sourceMapObject, supplier)
// return consumer
// }
// else -> throw SourceMapParseException(
// "Unknown source map version:" + sourceMapObject.version)
// }
// }
//
// throw SourceMapParseException("unable to detect source map format")
// }
//}
//
//object DumpSourceMapTool {
// @JvmStatic
// fun main(args: Array<String>) {
// val mapFilePath = args[0]
// val mapping = SourceMappings().getCached(mapFilePath)
// mapping.penetration.dumpSourceLineToGeneratedLine()
// }
//}
| 1/shared-jvm/src/main/java/source-mapping.kt | 886273352 |
@java.lang.Deprecated fun test1() {}
@java.lang.Deprecated fun test2() {}
fun test3() {
@java.lang.Deprecated fun test3inner() {}
}
class Test4() {
@java.lang.Deprecated fun test4() {}
}
class Test5() {
fun test5() {
@java.lang.Deprecated fun test5inner() {}
}
}
class Test6() {
companion object {
@java.lang.Deprecated fun test6() {}
}
}
object Test7 {
@java.lang.Deprecated fun test7() {}
}
// ANNOTATION: java.lang.Deprecated
// SEARCH: method:test1
// SEARCH: method:test2
// SEARCH: method:test4
// SEARCH: method:test6
// SEARCH: method:test7 | plugins/kotlin/idea/tests/testData/search/annotations/testAnnotationsOnFunction.kt | 3636873653 |
package org.intellij.plugins.markdown.util
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import com.intellij.util.Consumer
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeader
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownList
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem
import org.intellij.plugins.markdown.lang.psi.util.children
import org.intellij.plugins.markdown.lang.psi.util.hasType
import org.intellij.plugins.markdown.lang.psi.util.parentOfType
internal object MarkdownPsiStructureUtil {
@JvmField
val PRESENTABLE_TYPES: TokenSet = MarkdownTokenTypeSets.HEADERS
@JvmField
val TRANSPARENT_CONTAINERS = TokenSet.create(
MarkdownElementTypes.MARKDOWN_FILE,
MarkdownElementTypes.UNORDERED_LIST,
MarkdownElementTypes.ORDERED_LIST,
MarkdownElementTypes.LIST_ITEM,
MarkdownElementTypes.BLOCK_QUOTE
)
private val PRESENTABLE_CONTAINERS = TokenSet.create(
MarkdownElementTypes.UNORDERED_LIST,
MarkdownElementTypes.ORDERED_LIST
)
private val IGNORED_CONTAINERS = TokenSet.create(MarkdownElementTypes.BLOCK_QUOTE)
private val HEADER_ORDER = arrayOf(
TokenSet.create(MarkdownElementTypes.MARKDOWN_FILE_ELEMENT_TYPE),
MarkdownTokenTypeSets.HEADER_LEVEL_1_SET,
MarkdownTokenTypeSets.HEADER_LEVEL_2_SET,
MarkdownTokenTypeSets.HEADER_LEVEL_3_SET,
MarkdownTokenTypeSets.HEADER_LEVEL_4_SET,
MarkdownTokenTypeSets.HEADER_LEVEL_5_SET,
MarkdownTokenTypeSets.HEADER_LEVEL_6_SET
)
/**
* @return true if element is on the file top level.
*/
internal fun ASTNode.isTopLevel(): Boolean {
return treeParent?.hasType(MarkdownElementTypes.MARKDOWN_FILE) == true
}
@JvmStatic
fun isSimpleNestedList(itemChildren: Array<PsiElement>): Boolean {
if (itemChildren.size != 2) {
return false
}
val (firstItem, secondItem) = itemChildren
return firstItem.hasType(MarkdownElementTypes.PARAGRAPH) && secondItem is MarkdownList
}
/*
* nextHeaderConsumer 'null' means reaching EOF
*/
@JvmOverloads
@JvmStatic
fun processContainer(
element: PsiElement?,
consumer: Consumer<PsiElement>,
nextHeaderConsumer: Consumer<PsiElement?>? = null
) {
if (element == null) {
return
}
val structureContainer = when (element) {
is MarkdownFile -> findFirstMarkdownChild(element)
else -> element.parentOfType(withSelf = true, TRANSPARENT_CONTAINERS)
}
if (structureContainer == null) {
return
}
val areListsVisible = Registry.`is`("markdown.structure.view.list.visibility")
when {
element is MarkdownHeader -> processHeader(structureContainer, element, element, consumer, nextHeaderConsumer)
element is MarkdownList && areListsVisible -> processList(element, consumer)
element is MarkdownListItem && areListsVisible -> {
if (!element.hasTrivialChildren()) {
processListItem(element, consumer)
}
}
else -> processHeader(structureContainer, null, null, consumer, nextHeaderConsumer)
}
}
private fun findFirstMarkdownChild(element: PsiElement): PsiElement? {
return element.children().firstOrNull { it.language.isMarkdownLanguage() }
}
private fun processHeader(
container: PsiElement,
sameLevelRestriction: PsiElement?,
from: PsiElement?,
resultConsumer: Consumer<PsiElement>,
nextHeaderConsumer: Consumer<PsiElement?>?
) {
val startElement = when (from) {
null -> container.firstChild
else -> from.nextSibling
}
var maxContentLevel: PsiElement? = null
for (element in startElement?.siblings(forward = true, withSelf = true).orEmpty()) {
when {
element.isTransparentInPartial() && maxContentLevel == null -> {
processHeader(element, null, null, resultConsumer, nextHeaderConsumer)
}
element.isTransparentInFull() && maxContentLevel == null -> {
if (container.elementType !in IGNORED_CONTAINERS && element.elementType in PRESENTABLE_CONTAINERS) {
resultConsumer.consume(element)
}
processHeader(element, null, null, resultConsumer, nextHeaderConsumer)
}
element is MarkdownHeader -> {
if (sameLevelRestriction != null && isSameLevelOrHigher(element, sameLevelRestriction)) {
nextHeaderConsumer?.consume(element)
return
}
if (maxContentLevel == null || isSameLevelOrHigher(element, maxContentLevel)) {
maxContentLevel = element
if (element.elementType in PRESENTABLE_TYPES) {
resultConsumer.consume(element)
}
}
}
}
}
nextHeaderConsumer?.consume(null)
}
private fun processList(list: MarkdownList, resultConsumer: Consumer<in PsiElement>) {
for (child in list.children()) {
val children = child.children
val containerIsFirst = children.firstOrNull()?.elementType in PRESENTABLE_TYPES || children.singleOrNull()?.elementType in PRESENTABLE_CONTAINERS
when {
containerIsFirst -> resultConsumer.consume(children.first())
isSimpleNestedList(children) -> resultConsumer.consume(children[1])
child is MarkdownListItem -> resultConsumer.consume(child)
}
}
}
private fun processListItem(from: MarkdownListItem, resultConsumer: Consumer<in PsiElement>) {
for (child in from.children()) {
if (child.elementType in PRESENTABLE_TYPES) {
resultConsumer.consume(child)
break
}
if (child.elementType in PRESENTABLE_CONTAINERS) {
resultConsumer.consume(child)
}
}
}
/**
* Returns true if the key of the lists representation in the structure is true
* and the processed element is a transparent container, but not a list item.
* Returns false otherwise.
*/
private fun PsiElement.isTransparentInFull(): Boolean {
if (!Registry.`is`("markdown.structure.view.list.visibility")) {
return false
}
return elementType in TRANSPARENT_CONTAINERS && this !is MarkdownListItem
}
/**
* Returns true if the key of the lists representation in the structure is false (this means that only headers are shown in the structure view)
* and the processed element is a transparent container.
* Returns false otherwise.
*/
private fun PsiElement.isTransparentInPartial(): Boolean {
return !Registry.`is`("markdown.structure.view.list.visibility") && elementType in TRANSPARENT_CONTAINERS
}
private fun isSameLevelOrHigher(left: PsiElement, right: PsiElement): Boolean {
return obtainHeaderLevel(left.elementType!!) <= obtainHeaderLevel(right.elementType!!)
}
private fun obtainHeaderLevel(headerType: IElementType): Int {
return when (val index = HEADER_ORDER.indexOfFirst { headerType in it }) {
-1 -> Int.MAX_VALUE
else -> index
}
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/util/MarkdownPsiStructureUtil.kt | 1506530719 |
// 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.bridgeEntities
import com.intellij.workspaceModel.storage.*
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
interface FacetEntity: WorkspaceEntityWithSymbolicId {
val name: String
val module: ModuleEntity
val facetType: String
val configurationXmlTag: String?
val moduleId: ModuleId
// underlyingFacet is a parent facet!!
val underlyingFacet: FacetEntity?
override val symbolicId: FacetId
get() = FacetId(name, facetType, moduleId)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetEntity, WorkspaceEntity.Builder<FacetEntity>, ObjBuilder<FacetEntity> {
override var entitySource: EntitySource
override var name: String
override var module: ModuleEntity
override var facetType: String
override var configurationXmlTag: String?
override var moduleId: ModuleId
override var underlyingFacet: FacetEntity?
}
companion object : Type<FacetEntity, Builder>() {
operator fun invoke(name: String,
facetType: String,
moduleId: ModuleId,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): FacetEntity {
val builder = builder()
builder.name = name
builder.facetType = facetType
builder.moduleId = moduleId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetEntity, modification: FacetEntity.Builder.() -> Unit) = modifyEntity(
FacetEntity.Builder::class.java, entity, modification)
var FacetEntity.Builder.childrenFacets: @Child List<FacetEntity>
by WorkspaceEntity.extension()
var FacetEntity.Builder.facetExternalSystemIdEntity: @Child FacetExternalSystemIdEntity?
by WorkspaceEntity.extension()
//endregion
val FacetEntity.childrenFacets: List<@Child FacetEntity>
by WorkspaceEntity.extension()
| platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/facet.kt | 3601247890 |
// "Add 'return' before the expression" "true"
fun test(): Boolean {
<caret>true
}
| plugins/kotlin/idea/tests/testData/quickfix/addReturnToUnusedLastExpressionInFunction/simpleBoolean.kt | 439836092 |
// IntelliJ API Decompiler stub source generated from a class file
// Implementation of methods is not available
package test
public final class Modifiers public constructor() {
public final var extVar: kotlin.Int /* compiled code */
public final external fun extFun(): kotlin.Unit { /* compiled code */ }
}
| plugins/kotlin/idea/tests/testData/decompiler/decompiledTextJvm/Modifiers.expected.kt | 1165892122 |
// PROBLEM: none
interface A {
fun foo()
}
class B : A {
override fun foo() {}
}
class C(<caret>val b: B) : A by b | plugins/kotlin/idea/tests/testData/inspectionsLocal/delegationToVarProperty/valParameter.kt | 1309681138 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetcaster.data
import androidx.compose.runtime.Immutable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "podcasts",
indices = [
Index("uri", unique = true)
]
)
@Immutable
data class Podcast(
@PrimaryKey @ColumnInfo(name = "uri") val uri: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "description") val description: String? = null,
@ColumnInfo(name = "author") val author: String? = null,
@ColumnInfo(name = "image_url") val imageUrl: String? = null,
@ColumnInfo(name = "copyright") val copyright: String? = null
)
| Jetcaster/app/src/main/java/com/example/jetcaster/data/Podcast.kt | 4105608437 |
// WITH_STDLIB
fun test(list: List<Int>): List<Int> {
return list
.<caret>filter { it > 1 }
.mapNotNull {
if (it == 2) return@mapNotNull null
it * 2
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/returnAtLabels.kt | 2184923003 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType
import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic
private val tupleRegex = "groovy.lang.Tuple(\\d+)".toRegex()
/**
* @return number or tuple component count of [groovy.lang.Tuple] inheritor type,
* or `null` if the [type] doesn't represent an inheritor of [groovy.lang.Tuple] type
*/
fun getTupleComponentCountOrNull(type: PsiType): Int? {
val classType = type as? PsiClassType
?: return null
val fqn = classType.resolve()?.qualifiedName
?: return null
return tupleRegex.matchEntire(fqn)
?.groupValues
?.getOrNull(1)
?.toIntOrNull()
}
sealed class MultiAssignmentTypes {
abstract fun getComponentType(position: Int): PsiType?
}
private class FixedMultiAssignmentTypes(val types: List<PsiType>) : MultiAssignmentTypes() {
override fun getComponentType(position: Int): PsiType? = types.getOrNull(position)
}
private class UnboundedMultiAssignmentTypes(private val type: PsiType) : MultiAssignmentTypes() {
override fun getComponentType(position: Int): PsiType = type
}
fun getMultiAssignmentType(rValue: GrExpression, position: Int): PsiType? {
return getMultiAssignmentTypes(rValue)?.getComponentType(position)
}
fun getMultiAssignmentTypes(rValue: GrExpression): MultiAssignmentTypes? {
if (isCompileStatic(rValue)) {
return getMultiAssignmentTypesCS(rValue)
}
else {
return getLiteralMultiAssignmentTypes(rValue)
?: getTupleMultiAssignmentTypes(rValue)
?: getIterableMultiAssignmentTypes(rValue)
}
}
fun getMultiAssignmentTypesCountCS(rValue: GrExpression): Int? {
return getMultiAssignmentTypesCS(rValue)?.types?.size
}
private fun getMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? {
return getLiteralMultiAssignmentTypesCS(rValue)
?: getTupleMultiAssignmentTypesCS(rValue)
}
private fun getLiteralMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? {
if (rValue !is GrListOrMap || rValue.isMap) {
return null
}
return getLiteralMultiAssignmentTypes(rValue)
}
private fun getLiteralMultiAssignmentTypes(rValue: GrExpression): FixedMultiAssignmentTypes? {
val tupleType = rValue.type as? GrTupleType ?: return null
return FixedMultiAssignmentTypes(tupleType.componentTypes)
}
private fun getTupleMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? {
if (GroovyConfigUtils.getInstance().getSDKVersion(rValue) < GroovyConfigUtils.GROOVY3_0) {
return null
}
return getTupleMultiAssignmentTypes(rValue)
}
private fun getTupleMultiAssignmentTypes(rValue: GrExpression): FixedMultiAssignmentTypes? {
val classType = rValue.type as? PsiClassType
?: return null
val fqn = classType.resolve()?.qualifiedName
?: return null
if (!fqn.matches(tupleRegex)) {
return null
}
return FixedMultiAssignmentTypes(classType.parameters.toList())
}
private fun getIterableMultiAssignmentTypes(rValue: GrExpression): MultiAssignmentTypes? {
val iterableTypeParameter = extractIterableTypeParameter(rValue.type, false) ?: return null
return UnboundedMultiAssignmentTypes(iterableTypeParameter)
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/tuples.kt | 4110593134 |
package c
import b.Test as _Test
import b.test as _test
import b.TEST as _TEST
fun bar() {
val t: _Test = _Test()
_test()
t._test()
println(_TEST)
println(t._TEST)
_TEST = ""
t._TEST = ""
}
| plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveFile/moveFileWithPackageRename/after/c/specificImportsWithAliases.kt | 3019757653 |
package <%= appPackage %>
import android.app.Application
import android.util.Log
object AppLog {
val SHOULD_LOG = true //BuildConfig.DEBUG;
fun d(message: String) {
if (SHOULD_LOG) {
Log.d(Application::class.java.`package`.name, message)
}
}
fun e(error: Throwable) {
if (SHOULD_LOG) {
Log.e(Application::class.java.`package`.name, "Error", error)
}
}
}
| app/templates/app_mvp/src/main/kotlin/AppLog.kt | 603600476 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.jvm
import com.intellij.lang.jvm.JvmElement
import com.intellij.lang.jvm.source.JvmDeclarationSearcher
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.GrNamedElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getMethodOrReflectedMethods
class GroovyDeclarationSearcher : JvmDeclarationSearcher {
override fun findDeclarations(declaringElement: PsiElement): Collection<JvmElement> {
return when {
declaringElement is GrMethod -> getMethodOrReflectedMethods(declaringElement).toList()
declaringElement is GrNamedElement && declaringElement is JvmElement -> listOf(declaringElement)
else -> emptyList()
}
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/jvm/GroovyDeclarationSearcher.kt | 574062512 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.recyclerview
/**
* Created by sinyuk on 2017/12/23.
*/
interface ListStateListener {
fun onRefresh(items: Int)
fun onScroll(position: Int)
} | presentation/src/main/java/com/sinyuk/fanfou/ui/recyclerview/ListStateListener.kt | 1420415561 |
package org.livingdoc.engine.execution.groups
import org.livingdoc.api.After
import org.livingdoc.api.Before
import org.livingdoc.engine.execution.checkThatMethodsAreStatic
import org.livingdoc.engine.execution.checkThatMethodsHaveNoParameters
/**
* GroupFixtureChecker validates that a [GroupFixture] is defined correctly.
*
* @see GroupFixture
* @see GroupFixtureModel
*/
internal object GroupFixtureChecker {
/**
* Check performs the actual validation on a [GroupFixtureModel].
*
* @param model the model of the [GroupFixture] to validate
* @return a list of strings describing all validation errors
* @see GroupFixtureModel
*/
fun check(model: GroupFixtureModel): List<String> {
return mutableListOf<String>().apply {
addAll(checkBeforeMethodsHaveValidSignature(model))
addAll(checkAfterMethodsHaveValidSignature(model))
}
}
/**
* checkBeforeMethodsHaveValidSignature ensures that all methods annotated with [Before] have a valid signature
*
* @param model the model of the [GroupFixture] to validate
* @return a list of strings describing all validation errors
*/
private fun checkBeforeMethodsHaveValidSignature(model: GroupFixtureModel): List<String> {
val errors = mutableListOf<String>()
model.beforeMethods.apply {
errors.addAll(checkThatMethodsHaveNoParameters(this, Before::class.java))
errors.addAll(checkThatMethodsAreStatic(this, Before::class.java))
}
return errors
}
/**
* checkAfterMethodsHaveValidSignature ensures that all methods annotated with [Before] have a valid signature
*
* @param model the model of the [GroupFixture] to validate
* @return a list of strings describing all validation errors
*/
private fun checkAfterMethodsHaveValidSignature(model: GroupFixtureModel): List<String> {
val errors = mutableListOf<String>()
model.afterMethods.apply {
errors.addAll(checkThatMethodsHaveNoParameters(this, After::class.java))
errors.addAll(checkThatMethodsAreStatic(this, After::class.java))
}
return errors
}
}
| livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/groups/GroupFixtureChecker.kt | 1859699448 |
package com.example.blog
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| android/app/src/main/kotlin/com/example/blog/MainActivity.kt | 4169196552 |
package ch.rmy.android.http_shortcuts.data.enums
enum class ResponseDisplayAction(val key: String) {
RERUN("rerun"),
SHARE("share"),
COPY("copy"),
SAVE("save");
companion object {
fun parse(key: String) =
values().firstOrNull { it.key == key }
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/enums/ResponseDisplayAction.kt | 25484524 |
package xyz.nulldev.ts.api.v2.java.impl.util
class ProxyList<T, V>(private val orig: List<T>,
private val proxy: (T) -> V): AbstractList<V>() {
override val size = orig.size
override fun get(index: Int) = proxy(orig[index])
} | TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/util/ProxyList.kt | 3114424866 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework.propertyBased
import com.intellij.lang.Language
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater
import com.intellij.openapi.util.Conditions
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.impl.source.PostprocessReformattingAspect
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.util.FileContentUtilCore
import org.jetbrains.jetCheck.Generator
/**
* @author peter
*/
object PsiIndexConsistencyTester {
val commonRefs: List<RefKind> = listOf(RefKind.PsiFileRef, RefKind.DocumentRef, RefKind.DirRef,
RefKind.AstRef(null),
RefKind.StubRef(null), RefKind.GreenStubRef(null))
fun commonActions(refs: List<RefKind>): Generator<Action> = Generator.frequency(
1, Generator.constant(Action.Gc),
15, Generator.sampledFrom(Action.Commit,
Action.ReparseFile,
Action.FilePropertiesChanged,
Action.ReloadFromDisk,
Action.Reformat,
Action.PostponedFormatting,
Action.RenamePsiFile,
Action.RenameVirtualFile,
Action.Save),
20, Generator.sampledFrom(refs).flatMap { Generator.sampledFrom(Action.LoadRef(it), Action.ClearRef(it)) })
fun runActions(model: Model, vararg actions: Action) {
WriteCommandAction.runWriteCommandAction(model.project) {
try {
actions.forEach { it.performAction(model) }
}
finally {
try {
Action.Save.performAction(model)
model.vFile.delete(this)
}
catch (e: Throwable) {
e.printStackTrace()
}
}
}
}
open class Model(val vFile: VirtualFile, val fixture: CodeInsightTestFixture) {
val refs = hashMapOf<RefKind, Any?>()
val project = fixture.project!!
fun findPsiFile(language: Language? = null) = findViewProvider().let { vp -> vp.getPsi(language ?: vp.baseLanguage) }!!
private fun findViewProvider() = PsiManager.getInstance(project).findViewProvider(vFile)!!
fun getDocument() = FileDocumentManager.getInstance().getDocument(vFile)!!
fun isCommitted(): Boolean {
val document = FileDocumentManager.getInstance().getCachedDocument(vFile)
return document == null || PsiDocumentManager.getInstance(project).isCommitted(document)
}
open fun onCommit() {}
open fun onReload() {}
open fun onSave() {}
}
interface Action {
fun performAction(model: Model)
abstract class SimpleAction: Action {
override fun toString(): String = javaClass.simpleName
}
object Gc: SimpleAction() {
override fun performAction(model: Model) = PlatformTestUtil.tryGcSoftlyReachableObjects()
}
object Commit: SimpleAction() {
override fun performAction(model: Model) {
PsiDocumentManager.getInstance(model.project).commitAllDocuments()
model.onCommit()
}
}
object Save: SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
FileDocumentManager.getInstance().saveAllDocuments()
model.onSave()
}
}
object PostponedFormatting: SimpleAction() {
override fun performAction(model: Model) =
PostprocessReformattingAspect.getInstance(model.project).doPostponedFormatting()
}
object ReparseFile : SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
FileContentUtilCore.reparseFiles(model.vFile)
model.onSave()
}
}
object FilePropertiesChanged : SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
PushedFilePropertiesUpdater.getInstance(model.project).filePropertiesChanged(model.vFile, Conditions.alwaysTrue())
}
}
object ReloadFromDisk : SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
PsiManager.getInstance(model.project).reloadFromDisk(model.findPsiFile())
model.onReload()
if (model.isCommitted()) {
model.onCommit()
}
}
}
object RenameVirtualFile: SimpleAction() {
override fun performAction(model: Model) {
model.vFile.rename(this, model.vFile.nameWithoutExtension + "1." + model.vFile.extension)
}
}
object RenamePsiFile: SimpleAction() {
override fun performAction(model: Model) {
val newName = model.vFile.nameWithoutExtension + "1." + model.vFile.extension
model.findPsiFile().name = newName
assert(model.findPsiFile().name == newName)
assert(model.vFile.name == newName)
}
}
object Reformat: SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
Commit.performAction(model)
CodeStyleManager.getInstance(model.project).reformat(model.findPsiFile())
}
}
data class LoadRef(val kind: RefKind): Action {
override fun performAction(model: Model) {
model.refs[kind] = kind.loadRef(model)
}
}
data class ClearRef(val kind: RefKind): Action {
override fun performAction(model: Model) {
model.refs.remove(kind)
}
}
}
abstract class RefKind {
abstract fun loadRef(model: Model): Any?
object PsiFileRef : RefKind() {
override fun loadRef(model: Model): Any? = model.findPsiFile()
}
object DocumentRef : RefKind() {
override fun loadRef(model: Model): Any? = model.getDocument()
}
object DirRef : RefKind() {
override fun loadRef(model: Model): Any? = model.findPsiFile().containingDirectory
}
data class AstRef(val language: Language?) : RefKind() {
override fun loadRef(model: Model): Any? = model.findPsiFile(language).node
}
data class StubRef(val language: Language?) : RefKind() {
override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).stubTree
}
data class GreenStubRef(val language: Language?) : RefKind() {
override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).greenStubTree
}
}
} | platform/testFramework/testSrc/com/intellij/testFramework/propertyBased/PsiIndexConsistencyTester.kt | 2437214764 |
package org.maxur.mserv.frame
/**
* Holder for Locator.
*/
interface LocatorHolder {
/**
* Returns a Locator.
* @return the Locator.
*/
fun get(): LocatorImpl
/**
* Put the Locator to holder.
* @param value The Locator.
*/
fun put(value: LocatorImpl)
/**
* Remove The Locator from Holder by it's name.
* @param name The name of the Locator.
*/
fun remove(name: String)
}
internal class SingleHolder : LocatorHolder {
private var locator: LocatorImpl = NullLocator
override fun get() = locator
override fun put(value: LocatorImpl) {
locator = if (locator is NullLocator)
value
else
throw IllegalStateException("You can have only one service locator per microservice")
}
override fun remove(name: String) {
locator = if (locator.name == name)
NullLocator
else
throw IllegalArgumentException("Locator '$name' is not found")
}
}
| maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/LocatorHolder.kt | 1778113871 |
package org.andreych.workcalendar.service
import org.andreych.workcalendar.storage.CalendarStorage
class CalendarService(private val calendarStorage: CalendarStorage) {
suspend fun getCalendarBytes(): ByteArray? {
return calendarStorage.getBytes()
}
} | src/main/kotlin/org/andreych/workcalendar/service/CalendarService.kt | 1762970313 |
/*
* Copyright 2019 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.fragments.verification
import android.os.Bundle
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import butterknife.BindView
import butterknife.OnClick
import im.vector.R
import im.vector.fragments.VectorBaseFragment
import org.matrix.androidsdk.crypto.rest.model.crypto.KeyVerificationStart
import org.matrix.androidsdk.crypto.verification.IncomingSASVerificationTransaction
import org.matrix.androidsdk.crypto.verification.OutgoingSASVerificationRequest
class SASVerificationShortCodeFragment : VectorBaseFragment() {
private lateinit var viewModel: SasVerificationViewModel
companion object {
fun newInstance() = SASVerificationShortCodeFragment()
}
@BindView(R.id.sas_decimal_code)
lateinit var decimalTextView: TextView
@BindView(R.id.sas_emoji_description)
lateinit var descriptionTextView: TextView
@BindView(R.id.sas_emoji_grid)
lateinit var emojiGrid: ViewGroup
@BindView(R.id.emoji0)
lateinit var emoji0View: ViewGroup
@BindView(R.id.emoji1)
lateinit var emoji1View: ViewGroup
@BindView(R.id.emoji2)
lateinit var emoji2View: ViewGroup
@BindView(R.id.emoji3)
lateinit var emoji3View: ViewGroup
@BindView(R.id.emoji4)
lateinit var emoji4View: ViewGroup
@BindView(R.id.emoji5)
lateinit var emoji5View: ViewGroup
@BindView(R.id.emoji6)
lateinit var emoji6View: ViewGroup
override fun getLayoutResId() = R.layout.fragment_sas_verification_display_code
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = activity?.run {
ViewModelProviders.of(this).get(SasVerificationViewModel::class.java)
} ?: throw Exception("Invalid Activity")
viewModel.transaction?.let {
if (it.supportsEmoji()) {
val emojicodes = it.getEmojiCodeRepresentation(it.shortCodeBytes!!)
emojicodes.forEachIndexed { index, emojiRepresentation ->
when (index) {
0 -> {
emoji0View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji0View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
1 -> {
emoji1View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji1View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
2 -> {
emoji2View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji2View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
3 -> {
emoji3View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji3View.findViewById<TextView>(R.id.item_emoji_name_tv)?.setText(emojiRepresentation.nameResId)
}
4 -> {
emoji4View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji4View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
5 -> {
emoji5View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji5View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
6 -> {
emoji6View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji
emoji6View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId)
}
}
}
}
//decimal is at least supported
decimalTextView.text = it.getShortCodeRepresentation(KeyVerificationStart.SAS_MODE_DECIMAL)
if (it.supportsEmoji()) {
descriptionTextView.text = getString(R.string.sas_emoji_description)
decimalTextView.isVisible = false
emojiGrid.isVisible = true
} else {
descriptionTextView.text = getString(R.string.sas_decimal_description)
decimalTextView.isVisible = true
emojiGrid.isInvisible = true
}
}
viewModel.transactionState.observe(this, Observer {
if (viewModel.transaction is IncomingSASVerificationTransaction) {
val uxState = (viewModel.transaction as IncomingSASVerificationTransaction).uxState
when (uxState) {
IncomingSASVerificationTransaction.State.SHOW_SAS -> {
viewModel.loadingLiveEvent.value = null
}
IncomingSASVerificationTransaction.State.VERIFIED -> {
viewModel.loadingLiveEvent.value = null
viewModel.deviceIsVerified()
}
IncomingSASVerificationTransaction.State.CANCELLED_BY_ME,
IncomingSASVerificationTransaction.State.CANCELLED_BY_OTHER -> {
viewModel.loadingLiveEvent.value = null
viewModel.navigateCancel()
}
else -> {
viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner
}
}
} else if (viewModel.transaction is OutgoingSASVerificationRequest) {
val uxState = (viewModel.transaction as OutgoingSASVerificationRequest).uxState
when (uxState) {
OutgoingSASVerificationRequest.State.SHOW_SAS -> {
viewModel.loadingLiveEvent.value = null
}
OutgoingSASVerificationRequest.State.VERIFIED -> {
viewModel.loadingLiveEvent.value = null
viewModel.deviceIsVerified()
}
OutgoingSASVerificationRequest.State.CANCELLED_BY_ME,
OutgoingSASVerificationRequest.State.CANCELLED_BY_OTHER -> {
viewModel.loadingLiveEvent.value = null
viewModel.navigateCancel()
}
else -> {
viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner
}
}
}
})
}
@OnClick(R.id.sas_request_continue_button)
fun didAccept() {
viewModel.confirmEmojiSame()
}
@OnClick(R.id.sas_request_cancel_button)
fun didCancel() {
viewModel.cancelTransaction()
}
} | vector/src/main/java/im/vector/fragments/verification/SASVerificationShortCodeFragment.kt | 224999776 |
package io.kotest.engine.launcher
import io.kotest.engine.cli.parseArgs
data class LauncherArgs(
// A path to the test to execute. Nested tests will also be executed
val testpath: String?,
// restricts tests to the package or subpackages
val packageName: String?,
// the fully qualified name of the spec class which contains the test to execute
val spec: String?,
// true to force true colour on the terminal; auto to have autodefault
val termcolor: String?,
// the fully qualified name of a reporter implementation
val reporter: String?,
// Tag expression to control which tests are executed
val tagExpression: String?,
// true to output the configuration values when the Engine is created
val dumpconfig: Boolean?
)
fun parseLauncherArgs(args: List<String>): LauncherArgs {
val a = parseArgs(args)
return LauncherArgs(
testpath = a["testpath"],
packageName = a["package"],
spec = a["spec"],
termcolor = a["termcolor"],
// writer is for backwards compatibility
reporter = a["reporter"] ?: a["writer"],
tagExpression = a["tags"],
dumpconfig = a["dumpconfig"]?.toBoolean(),
)
}
| kotest-framework/kotest-framework-engine/src/jvmMain/kotlin/io/kotest/engine/launcher/parseLauncherArgs.kt | 3960607554 |
/*
* Copyright 2019 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.fragments.discovery
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import butterknife.BindView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.google.android.material.textfield.TextInputLayout
import im.vector.R
import im.vector.ui.epoxy.BaseEpoxyHolder
import im.vector.ui.util.setTextOrHide
@EpoxyModelClass(layout = R.layout.item_settings_edit_text)
abstract class SettingsItemText : EpoxyModelWithHolder<SettingsItemText.Holder>() {
@EpoxyAttribute var descriptionText: String? = null
@EpoxyAttribute var errorText: String? = null
@EpoxyAttribute
var interactionListener: Listener? = null
override fun bind(holder: Holder) {
super.bind(holder)
holder.textView.setTextOrHide(descriptionText)
holder.validateButton.setOnClickListener {
val code = holder.editText.text.toString()
holder.editText.text.clear()
interactionListener?.onValidate(code)
}
if (errorText.isNullOrBlank()) {
holder.textInputLayout.error = null
} else {
holder.textInputLayout.error = errorText
}
holder.editText.setOnEditorActionListener { tv, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
val code = tv.text.toString()
interactionListener?.onValidate(code)
holder.editText.text.clear()
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
}
class Holder : BaseEpoxyHolder() {
@BindView(R.id.settings_item_description)
lateinit var textView: TextView
@BindView(R.id.settings_item_edittext)
lateinit var editText: EditText
@BindView(R.id.settings_item_enter_til)
lateinit var textInputLayout: TextInputLayout
@BindView(R.id.settings_item_enter_button)
lateinit var validateButton: Button
}
interface Listener {
fun onValidate(code: String)
}
} | vector/src/main/java/im/vector/fragments/discovery/SettingsItemText.kt | 3724437455 |
package com.github.parkee.messenger.model.response
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class Postback(
@JsonProperty("payload") val payload: Any?
) | src/main/kotlin/com/github/parkee/messenger/model/response/Postback.kt | 3659580440 |
package io.sentry.transport
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.check
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.ISerializer
import io.sentry.RequestDetails
import io.sentry.SentryEnvelope
import io.sentry.SentryEvent
import io.sentry.SentryOptions
import io.sentry.SentryOptions.Proxy
import io.sentry.Session
import io.sentry.protocol.User
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy.Type
import java.net.URL
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class HttpConnectionTest {
private class Fixture {
val serializer = mock<ISerializer>()
var proxy: Proxy? = null
val connection = mock<HttpsURLConnection>()
val currentDateProvider = mock<ICurrentDateProvider>()
val authenticatorWrapper = mock<AuthenticatorWrapper>()
val rateLimiter = mock<RateLimiter>()
var sslSocketFactory: SSLSocketFactory? = null
var hostnameVerifier: HostnameVerifier? = null
val requestDetails = mock<RequestDetails>()
init {
whenever(connection.outputStream).thenReturn(mock())
whenever(connection.inputStream).thenReturn(mock())
whenever(connection.setHostnameVerifier(any())).thenCallRealMethod()
whenever(connection.setSSLSocketFactory(any())).thenCallRealMethod()
whenever(requestDetails.headers).thenReturn(mapOf("header-name" to "header-value"))
val url = mock<URL>()
whenever(url.openConnection()).thenReturn(connection)
whenever(url.openConnection(any())).thenReturn(connection)
whenever(requestDetails.url).thenReturn(url)
}
fun getSUT(): HttpConnection {
val options = SentryOptions()
options.setSerializer(serializer)
options.proxy = proxy
options.sslSocketFactory = sslSocketFactory
options.hostnameVerifier = hostnameVerifier
return HttpConnection(options, requestDetails, authenticatorWrapper, rateLimiter)
}
}
private val fixture = Fixture()
@Test
fun `test serializes envelope`() {
val transport = fixture.getSUT()
whenever(fixture.connection.responseCode).thenReturn(200)
val envelope = SentryEnvelope.from(fixture.serializer, createSession(), null)
val result = transport.send(envelope)
verify(fixture.serializer).serialize(eq(envelope), any())
assertTrue(result.isSuccess)
}
@Test
fun `uses Retry-After header if X-Sentry-Rate-Limit is not set when sending an envelope`() {
val transport = fixture.getSUT()
throwOnEnvelopeSerialize()
whenever(fixture.connection.getHeaderField(eq("Retry-After"))).thenReturn("30")
whenever(fixture.connection.responseCode).thenReturn(429)
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0)
val envelope = SentryEnvelope.from(fixture.serializer, createSession(), null)
val result = transport.send(envelope)
verify(fixture.rateLimiter).updateRetryAfterLimits(null, "30", 429)
verify(fixture.serializer).serialize(eq(envelope), any())
assertFalse(result.isSuccess)
}
@Test
fun `passes on the response code on error when sending an envelope`() {
val transport = fixture.getSUT()
throwOnEnvelopeSerialize()
whenever(fixture.connection.responseCode).thenReturn(1234)
val envelope = SentryEnvelope.from(fixture.serializer, createSession(), null)
val result = transport.send(envelope)
verify(fixture.serializer).serialize(eq(envelope), any())
assertFalse(result.isSuccess)
assertEquals(1234, result.responseCode)
}
@Test
fun `uses the default retry interval if there is no Retry-After header when sending an envelope`() {
val transport = fixture.getSUT()
throwOnEnvelopeSerialize()
whenever(fixture.connection.responseCode).thenReturn(429)
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0)
val envelope = SentryEnvelope.from(fixture.serializer, createSession(), null)
val result = transport.send(envelope)
verify(fixture.serializer).serialize(eq(envelope), any())
verify(fixture.rateLimiter).updateRetryAfterLimits(null, null, 429)
assertFalse(result.isSuccess)
}
@Test
fun `failure to get response code doesn't break sending an envelope`() {
val transport = fixture.getSUT()
throwOnEnvelopeSerialize()
whenever(fixture.connection.responseCode).thenThrow(IOException())
val session = Session("123", User(), "env", "release")
val envelope = SentryEnvelope.from(fixture.serializer, session, null)
val result = transport.send(envelope)
verify(fixture.serializer).serialize(eq(envelope), any())
assertFalse(result.isSuccess)
assertEquals(-1, result.responseCode)
}
@Test
fun `When SSLSocketFactory is given, set to connection`() {
val factory = mock<SSLSocketFactory>()
fixture.sslSocketFactory = factory
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.connection).sslSocketFactory = eq(factory)
}
@Test
fun `When SSLSocketFactory is not given, do not set to connection`() {
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.connection, never()).sslSocketFactory = any()
}
@Test
fun `When HostnameVerifier is given, set to connection`() {
val hostname = mock<HostnameVerifier>()
fixture.hostnameVerifier = hostname
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.connection).hostnameVerifier = eq(hostname)
}
@Test
fun `When HostnameVerifier is not given, do not set to connection`() {
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.connection, never()).hostnameVerifier = any()
}
@Test
fun `When Proxy host and port are given, set to connection`() {
fixture.proxy = Proxy("proxy.example.com", "8090")
val transport = fixture.getSUT()
transport.send(createEnvelope())
assertEquals(java.net.Proxy(Type.HTTP, InetSocketAddress("proxy.example.com", 8090)), transport.proxy)
}
@Test
fun `When Proxy username and password are given, set to connection`() {
fixture.proxy = Proxy("proxy.example.com", "8090", "some-user", "some-password")
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.authenticatorWrapper).setDefault(check<ProxyAuthenticator> {
assertEquals("some-user", it.user)
assertEquals("some-password", it.password)
})
}
@Test
fun `When Proxy port has invalid format, proxy is not set to connection`() {
fixture.proxy = Proxy("proxy.example.com", "xxx")
val transport = fixture.getSUT()
transport.send(createEnvelope())
assertNull(transport.proxy)
verifyZeroInteractions(fixture.authenticatorWrapper)
}
@Test
fun `sets common headers and on http connection`() {
val transport = fixture.getSUT()
transport.send(createEnvelope())
verify(fixture.connection).setRequestProperty("header-name", "header-value")
verify(fixture.requestDetails.url).openConnection()
}
private fun createSession(): Session {
return Session("123", User(), "env", "release")
}
// TODO: make inline fun <reified T : Any>, so we can throwOnSerialize<SentryEvent>()
private fun throwOnEventSerialize() {
whenever(fixture.serializer.serialize(any<SentryEvent>(), any())).thenThrow(IOException())
}
private fun throwOnEnvelopeSerialize() {
whenever(fixture.serializer.serialize(any<SentryEnvelope>(), any())).thenThrow(IOException())
}
private fun createEnvelope(event: SentryEvent = SentryEvent()): SentryEnvelope {
return SentryEnvelope.from(fixture.serializer, event, null)
}
}
| sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt | 2194505618 |
package com.qfleng.um.audio
class LrcRow {
//保存当前时间
var currentTime: Long = 0
//保存内容
var content: String? = null
var tag: Object? = null
} | UnrealMedia/app/src/main/java/com/qfleng/um/audio/LrcRow.kt | 3883371899 |
/*************************************************************************/
/* StorageScope.kt */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.io
import android.content.Context
import android.os.Build
import android.os.Environment
import java.io.File
/**
* Represents the different storage scopes.
*/
internal enum class StorageScope {
/**
* Covers internal and external directories accessible to the app without restrictions.
*/
APP,
/**
* Covers shared directories (from Android 10 and higher).
*/
SHARED,
/**
* Everything else..
*/
UNKNOWN;
class Identifier(context: Context) {
private val internalAppDir: String? = context.filesDir.canonicalPath
private val internalCacheDir: String? = context.cacheDir.canonicalPath
private val externalAppDir: String? = context.getExternalFilesDir(null)?.canonicalPath
private val sharedDir : String? = Environment.getExternalStorageDirectory().canonicalPath
private val downloadsSharedDir: String? = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).canonicalPath
private val documentsSharedDir: String? = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).canonicalPath
/**
* Determines which [StorageScope] the given path falls under.
*/
fun identifyStorageScope(path: String?): StorageScope {
if (path == null) {
return UNKNOWN
}
val pathFile = File(path)
if (!pathFile.isAbsolute) {
return UNKNOWN
}
val canonicalPathFile = pathFile.canonicalPath
if (internalAppDir != null && canonicalPathFile.startsWith(internalAppDir)) {
return APP
}
if (internalCacheDir != null && canonicalPathFile.startsWith(internalCacheDir)) {
return APP
}
if (externalAppDir != null && canonicalPathFile.startsWith(externalAppDir)) {
return APP
}
if (sharedDir != null && canonicalPathFile.startsWith(sharedDir)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
// Before R, apps had access to shared storage so long as they have the right
// permissions (and flag on Q).
return APP
}
// Post R, access is limited based on the target destination
// 'Downloads' and 'Documents' are still accessible
if ((downloadsSharedDir != null && canonicalPathFile.startsWith(downloadsSharedDir))
|| (documentsSharedDir != null && canonicalPathFile.startsWith(documentsSharedDir))) {
return APP
}
return SHARED
}
return UNKNOWN
}
}
}
| platform/android/java/lib/src/org/godotengine/godot/io/StorageScope.kt | 920953558 |
/*
* 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.players.bukkit.event.profile
import com.rpkit.core.event.RPKEvent
import com.rpkit.players.bukkit.profile.RPKThinProfile
interface RPKThinProfileEvent: RPKEvent {
val profile: RPKThinProfile
} | bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/event/profile/RPKThinProfileEvent.kt | 80000463 |
/*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.main.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import pl.org.seva.navigator.contact.Contact
@Database(
entities = [Contact.Entity::class],
version = ContactsDatabase.ADDED_DEBUG_DATABASE_VERSION, )
abstract class NavigatorDbAbstract : RoomDatabase() {
abstract fun contactDao(): ContactDao
}
| navigator/src/main/kotlin/pl/org/seva/navigator/main/data/db/NavigatorDbAbstract.kt | 3679656848 |
// Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.completion
import com.intellij.codeInsight.completion.CompletionResultSet
class IdentifierCompletionResultSet(private val resultSet: CompletionResultSet) {
private val added = mutableSetOf<String>()
fun addIdentifier(id: CompletionIdentifier) {
if (!added.contains(id.identifierName)) {
added.add(id.identifierName)
id.addToResult(resultSet)
}
}
}
| src/main/java/com/google/idea/gn/completion/IdentifierCompletionResultSet.kt | 808580518 |
/*
* 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.moderation.bukkit.command.warn
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.warning.RPKWarningProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import java.time.format.DateTimeFormatter
class WarningListCommand(private val plugin: RPKModerationBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.warning.list")) {
sender.sendMessage(plugin.messages["no-permission-warning-list"])
return true
}
var player: Player? = null
if (sender is Player) {
player = sender
}
if (args.isNotEmpty()) {
val argPlayer = plugin.server.getPlayer(args[0])
if (argPlayer != null) {
player = argPlayer
}
}
if (player == null) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val warningProvider = plugin.core.serviceManager.getServiceProvider(RPKWarningProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(player)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val profile = minecraftProfile.profile
if (profile !is RPKProfile) {
sender.sendMessage(plugin.messages["no-profile"])
return true
}
val warnings = warningProvider.getWarnings(profile)
sender.sendMessage(plugin.messages["warning-list-title"])
for ((index, warning) in warnings.withIndex()) {
sender.sendMessage(plugin.messages["warning-list-item", mapOf(
Pair("issuer", warning.issuer.name),
Pair("profile", warning.profile.name),
Pair("index", (index + 1).toString()),
Pair("reason", warning.reason),
Pair("time", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(warning.time))
)])
}
return true
}
}
| bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/warn/WarningListCommand.kt | 2716450524 |
package org.evomaster.core.problem.web.service
import com.google.inject.AbstractModule
/**
* Class defining all the beans needed to enable EM to
* handle Web Applications
*
* TODO See equivalent RestModule
*/
class WebModule: AbstractModule() {
override fun configure() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | core/src/main/kotlin/org/evomaster/core/problem/web/service/WebModule.kt | 1770819853 |
package org.evomaster.core.problem.graphql.service
import com.google.inject.Inject
import org.evomaster.core.Lazy
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.problem.enterprise.EnterpriseActionGroup
import org.evomaster.core.problem.graphql.GraphQLAction
import org.evomaster.core.problem.graphql.GraphQLIndividual
import org.evomaster.core.problem.api.service.ApiWsStructureMutator
import org.evomaster.core.problem.rest.SampleType
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.Individual
import org.evomaster.core.search.service.mutator.MutatedGeneSpecification
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/*
TODO: here there is quite bit of code that is similar to REST.
Once this is stable, should refactoring to avoid duplication
*/
class GraphQLStructureMutator : ApiWsStructureMutator() {
companion object{
private val log: Logger = LoggerFactory.getLogger(GraphQLStructureMutator::class.java)
}
@Inject
private lateinit var sampler: GraphQLSampler
override fun mutateStructure(individual: Individual, evaluatedIndividual: EvaluatedIndividual<*>, mutatedGenes: MutatedGeneSpecification?, targets: Set<Int>) {
if (individual !is GraphQLIndividual) {
throw IllegalArgumentException("Invalid individual type")
}
if (!individual.canMutateStructure()) {
return // nothing to do
}
when (individual.sampleType) {
SampleType.RANDOM -> mutateForRandomType(individual, mutatedGenes)
//TODO other kinds
//this would be a bug
else -> throw IllegalStateException("Cannot handle sample type ${individual.sampleType}")
}
if (config.trackingEnabled()) tag(individual, time.evaluatedIndividuals)
}
override fun addInitializingActions(individual: EvaluatedIndividual<*>, mutatedGenes: MutatedGeneSpecification?) {
addInitializingActions(individual, mutatedGenes, sampler)
}
private fun mutateForRandomType(ind: GraphQLIndividual, mutatedGenes: MutatedGeneSpecification?) {
val main = ind.seeMainActionComponents() as List<EnterpriseActionGroup>
if (main.size == 1) {
val sampledAction = sampler.sampleRandomAction(0.05) as GraphQLAction
ind.addGQLAction(action= sampledAction)
Lazy.assert {
sampledAction.hasLocalId()
}
//save mutated genes
mutatedGenes?.addRemovedOrAddedByAction(sampledAction, ind.seeAllActions().size, localId = sampledAction.getLocalId(), false, ind.seeAllActions().size)
return
}
if (randomness.nextBoolean() || main.size == config.maxTestSize) {
//delete one at random
log.trace("Deleting action from test")
val chosen = randomness.choose(main.indices)
//save mutated genes
val removedActions = main[chosen].flatten()
for(a in removedActions) {
/*
FIXME: how does position work when adding/removing a subtree?
*/
mutatedGenes?.addRemovedOrAddedByAction(a, chosen, localId = main[chosen].getLocalId(),true, chosen)
}
ind.removeGQLActionAt(chosen)
} else {
//add one at random
log.trace("Adding action to test")
val sampledAction = sampler.sampleRandomAction(0.05) as GraphQLAction
val chosen = randomness.choose(main.indices)
ind.addGQLAction(chosen, sampledAction)
Lazy.assert {
sampledAction.hasLocalId()
}
//save mutated genes
mutatedGenes?.addRemovedOrAddedByAction(sampledAction, chosen, localId = sampledAction.getLocalId(), false, chosen)
}
}
override fun getSqlInsertBuilder(): SqlInsertBuilder? {
return sampler.sqlInsertBuilder
}
} | core/src/main/kotlin/org/evomaster/core/problem/graphql/service/GraphQLStructureMutator.kt | 1944128673 |
package org.evomaster.core.database.extract.mysql
import org.evomaster.client.java.controller.internal.db.SchemaExtractor
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.search.gene.collection.EnumGene
import org.evomaster.core.search.gene.optional.NullableGene
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class CreateTableEnumTest : ExtractTestBaseMySQL() {
override fun getSchemaLocation(): String = "/sql_schema/mysql_create_enum.sql"
@Test
fun testCreateAndExtract() {
val schema = SchemaExtractor.extract(connection)
assertNotNull(schema)
val tableDto = schema.tables.find { it.name.equals("shirts", ignoreCase = true) }
assertNotNull(tableDto)
assertEquals(2, tableDto!!.columns.size)
assertEquals(1, tableDto.tableCheckExpressions.size)
tableDto.columns.apply {
val size = find { it.name.equals("size",ignoreCase = true) }
assertNotNull(size)
assertEquals("ENUM", size!!.type)
}
assertEquals("size enum('x-small','small','medium','large','x-large')",tableDto.tableCheckExpressions[0].sqlCheckExpression.toLowerCase())
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction("shirts", setOf("name", "size"))
val sizeGene = actions[0].seeTopGenes().find { it.name == "size" }
assertTrue(sizeGene is NullableGene)
(sizeGene as NullableGene).apply {
assertTrue(gene is EnumGene<*>)
assertEquals(5, (gene as EnumGene<*>).values.size)
assertTrue((gene as EnumGene<*>).values.containsAll(listOf("x-small","small","medium","large","x-large")))
}
}
} | core/src/test/kotlin/org/evomaster/core/database/extract/mysql/CreateTableEnumTest.kt | 3104114687 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.util.InheritanceUtil.isInheritor
import org.jetbrains.plugins.groovy.extensions.GroovyApplicabilityProvider
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.ApplicabilityResult
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.ApplicabilityResult.applicable
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.ApplicabilityResult.inapplicable
open class ConstructorMapApplicabilityProvider : GroovyApplicabilityProvider() {
open fun isConstructor(method: PsiMethod): Boolean {
return method.isConstructor
}
override fun isApplicable(argumentTypes: Array<out PsiType>,
method: PsiMethod,
substitutor: PsiSubstitutor?,
place: PsiElement?,
eraseParameterTypes: Boolean): ApplicabilityResult? {
if (!isConstructor(method)) return null
val parameters = method.parameterList.parameters
if (parameters.isEmpty() && argumentTypes.size == 1) {
return if (isInheritor(argumentTypes[0], CommonClassNames.JAVA_UTIL_MAP)) applicable else inapplicable
}
return null
}
} | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ConstructorMapApplicabilityProvider.kt | 207288347 |
package chat.rocket.android.server.infrastructure
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.Operation
import chat.rocket.android.db.model.MessagesSync
import chat.rocket.android.server.domain.MessagesRepository
import chat.rocket.android.util.retryDB
import chat.rocket.core.model.Message
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class DatabaseMessagesRepository(
private val dbManager: DatabaseManager,
private val mapper: DatabaseMessageMapper
) : MessagesRepository {
override suspend fun getById(id: String): Message? = withContext(Dispatchers.IO) {
retryDB("getMessageById($id)") {
dbManager.messageDao().getMessageById(id)?.let { message -> mapper.map(message) }
}
}
override suspend fun getByRoomId(roomId: String): List<Message> = withContext(Dispatchers.IO) {
// FIXME - investigate how to avoid this distinctBy here, since DAO is returning a lot of
// duplicate rows (something related to our JOINS and relations on Room)
retryDB("getMessagesByRoomId($roomId)") {
dbManager.messageDao().getMessagesByRoomId(roomId)
.distinctBy { it.message.message.id }
.let { messages ->
mapper.map(messages)
}
}
}
override suspend fun getRecentMessages(roomId: String, count: Long): List<Message> =
withContext(Dispatchers.IO) {
retryDB("getRecentMessagesByRoomId($roomId, $count)") {
dbManager.messageDao().getRecentMessagesByRoomId(roomId, count)
.distinctBy { it.message.message.id }
.let { messages ->
mapper.map(messages)
}
}
}
override suspend fun save(message: Message) {
dbManager.processMessagesBatch(listOf(message)).join()
}
override suspend fun saveAll(newMessages: List<Message>) {
dbManager.processMessagesBatch(newMessages).join()
}
override suspend fun removeById(id: String) {
withContext(Dispatchers.IO) {
retryDB("delete($id)") { dbManager.messageDao().delete(id) }
}
}
override suspend fun removeByRoomId(roomId: String) {
withContext(Dispatchers.IO) {
retryDB("deleteByRoomId($roomId)") {
dbManager.messageDao().deleteByRoomId(roomId)
}
}
}
override suspend fun getAllUnsent(): List<Message> = withContext(Dispatchers.IO) {
retryDB("getUnsentMessages") {
dbManager.messageDao().getUnsentMessages()
.distinctBy { it.message.message.id }
.let { mapper.map(it) }
}
}
override suspend fun saveLastSyncDate(roomId: String, timeMillis: Long) {
dbManager.sendOperation(Operation.SaveLastSync(MessagesSync(roomId, timeMillis)))
}
override suspend fun getLastSyncDate(roomId: String): Long? = withContext(Dispatchers.IO) {
retryDB("getLastSync($roomId)") {
dbManager.messageDao().getLastSync(roomId)?.timestamp
}
}
} | app/src/main/java/chat/rocket/android/server/infrastructure/DatabaseMessagesRepository.kt | 1275038311 |
package com.peacock.fantafone.pages
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.peacock.fantafone.MainActivity.context
import com.peacock.fantafone.R
/**
* Created by fabrizio on 21/04/17.
*/
class Tab3Stats : Fragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.lm3_stats, container, false)
setHasOptionsMenu(true)
val mViewPager = view.findViewById(R.id.viewPager) as ViewPager
mViewPager.adapter = MyAdapter(childFragmentManager)
val tabLayout = view.findViewById(R.id.tabs) as TabLayout
tabLayout.setupWithViewPager(mViewPager)
return view
}
private class MyAdapter internal constructor(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount(): Int {
return 2
}
override fun getItem(position: Int): Fragment? {
when (position) {
0 -> return Stats0Drivers()
1 -> return Stats1Members()
}
return null
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return context.getString(R.string.drivers)
1 -> return context.getString(R.string.members)
}
return null
}
}
} | app/src/main/java/com/peacock/fantafone/pages/Tab3Stats.kt | 1465290341 |
package io.sweers.palettehelper.util
import com.mixpanel.android.mpmetrics.MixpanelAPI
import org.json.JSONObject
val ANALYTICS_NAV_SOURCE = "Navigation Source"
val ANALYTICS_NAV_ENTER = "Navigation Enter Event"
val ANALYTICS_NAV_DESTINATION = "Navigation Destination"
val ANALYTICS_NAV_MAIN = "Main Activity"
val ANALYTICS_NAV_DETAIL = "Detail Activity"
val ANALYTICS_NAV_SHARE = "External Share"
val ANALYTICS_NAV_INTERNAL = "Internal storage"
val ANALYTICS_NAV_CAMERA = "Camera"
val ANALYTICS_NAV_URL = "Image URL"
val ANALYTICS_KEY_NUMCOLORS = "Number of colors"
val ANALYTICS_KEY_PLAY_REFERRER = "Google Play install referrer"
public fun MixpanelAPI.trackNav(src: String, dest: String) {
val props: JSONObject = JSONObject()
.put(ANALYTICS_NAV_SOURCE, src)
.put(ANALYTICS_NAV_DESTINATION, dest)
track("Navigation", props)
}
public fun MixpanelAPI.trackMisc(key: String, value: String) {
track("Misc", JSONObject().put(key, value))
}
| palettehelper/src/main/java/io/sweers/palettehelper/util/Analytics.kt | 2255547215 |
package com.natpryce.hamkrest
import com.natpryce.hamkrest.assertion.assert
import com.natpryce.hamkrest.assertion.that
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class LogicalConnectives {
@Test
fun negation() {
val m: Matcher<Int> = !equalTo(20)
assertEquals("is not equal to 20", m.description)
assertEquals("is equal to 20", (!m).description)
assertMismatchWithDescription("is equal to 20", m(20))
}
@Test
fun negation_of_negation_is_identity() {
val m: Matcher<Int> = equalTo(20)
assertTrue {!(!m) === m}
}
@Test
fun disjunction() {
val m = equalTo(10) or equalTo(20)
assertMatch(m(10))
assertMatch(m(20))
assertMismatchWithDescription("was: 11", m(11))
assert.that(m.description, equalTo("is equal to 10 or is equal to 20"))
}
@Test
fun anyOf() {
val m = anyOf(equalTo(10), equalTo(20))
assertMatch(m(10))
assertMatch(m(20))
assertMismatchWithDescription("was: 11", m(11))
assert.that(m.description, equalTo("is equal to 10 or is equal to 20"))
assertMatch(anyOf(equalTo(10))(10))
assertMismatchWithDescription("was: 11", allOf(equalTo(10))(11))
assertMatch(anyOf<Int>()(999))
assert.that(anyOf<Int>().description, equalTo("anything"))
}
@Test
fun conjunction() {
val m = greaterThan(10) and lessThan(20)
assertMatch(m(11))
assertMatch(m(19))
assertMismatchWithDescription("was: 10", m(10))
assertMismatchWithDescription("was: 20", m(20))
assert.that(m.description, equalTo("is greater than 10 and is less than 20"))
}
@Test
fun allOf() {
val m = allOf(greaterThan(10), lessThan(20))
assertMatch(m(11))
assertMatch(m(19))
assertMismatchWithDescription("was: 10", m(10))
assertMismatchWithDescription("was: 20", m(20))
assert.that(m.description, equalTo("is greater than 10 and is less than 20"))
assertMatch(allOf(greaterThan(10))(11))
assertMismatchWithDescription("was: 9", allOf(greaterThan(10))(9))
assertMatch(allOf<Int>()(999))
assert.that(allOf<Int>().description, equalTo("anything"))
}
}
class FunctionToMatcher {
@Test
fun create_matcher_from_named_function_reference() {
val isBlank = Matcher(String::isBlank)
assertEquals("is blank", isBlank.description)
assertMatch(isBlank(""))
assertMatch(isBlank(" "))
assertMismatchWithDescription("was: \"wrong\"", isBlank("wrong"))
}
@Test
fun create_matcher_from_binary_function_reference_and_second_parameter() {
fun String.hasLength(n: Int): Boolean = this.length == n
val hasLength4 = Matcher(String::hasLength, 4)
assertEquals("has length 4", hasLength4.description)
assertMatch(hasLength4("yeah"))
assertMatch(hasLength4("nope"))
assertMismatchWithDescription("was: \"wrong\"", hasLength4("wrong"))
}
@Test
fun create_matcher_factory_from_binary_function_reference() {
fun String.hasLength(n: Int): Boolean = this.length == n
val hasLength = Matcher(String::hasLength)
assertEquals("has length 4", hasLength(4).description)
assertEquals("has length 6", hasLength(6).description)
assertMatch(hasLength(3)("yes"))
assertMatch(hasLength(4)("yeah"))
}
@Test
fun can_pass_function_references_to_assert_that() {
assert.that(" ", String::isBlank)
}
}
open class Fruit(val ripeness: Double)
class Apple(ripeness: Double, val forCooking: Boolean) : Fruit(ripeness)
class Orange(ripeness: Double, val segmentCount: Int) : Fruit(ripeness)
fun isRipe(f: Fruit): Boolean = f.ripeness >= 0.5
fun canBeShared(o: Orange): Boolean = o.segmentCount % 2 == 0
fun isCookingApple(a: Apple): Boolean = a.forCooking
class Subtyping {
@Test
fun the_kotlin_type_system_makes_an_old_java_programmer_very_happy() {
val mA: Matcher<Apple> = ::isRipe and ::isCookingApple
val mO: Matcher<Orange> = ::isRipe and ::canBeShared
assertMatch(mA(Apple(ripeness = 1.0, forCooking = true)))
assertMatch(mO(Orange(ripeness = 1.0, segmentCount = 4)))
}
}
class Projections {
@Test
fun can_match_projection_by_property() {
val isLongEnough = has(String::length, greaterThan(4))
assert.that("12345", isLongEnough)
assert.that("1234", !isLongEnough)
assert.that(isLongEnough.description, equalTo("has length that is greater than 4"))
}
@Test
fun can_match_projection_by_function() {
assert.that("12345", has(::toInt, equalTo(12345)))
assert.that("1234", !has(::toInt, equalTo(12345)))
}
@Test
fun description_of_projection_is_human_readableified() {
assert.that(has(::toInt, equalTo(12345)).description, equalTo(
"has to int that is equal to 12345"))
}
}
fun toInt(s: String) : Int = s.toInt() | src/test/kotlin/com/natpryce/hamkrest/matching_tests.kt | 1911907191 |
package com.todoist.pojo
open class User<T : TzInfo, F : Features>(
id: String,
email: String,
fullName: String,
imageId: String?,
open var apiToken: String?,
open var tzInfo: T?,
open var isPremium: Boolean,
open var premiumUntil: Long?,
open var freeTrialExpires: Long?,
open var startPage: String?,
open var startDay: Int?,
open var weekendStartDay: Int?,
open var nextWeek: Int?,
open var teamInboxId: String?,
open var shareLimit: Int?,
open var karma: Long?,
open var karmaTrend: String?,
open var isKarmaDisabled: Boolean,
open var isKarmaVacation: Boolean,
open var autoReminder: Int?,
open var themeId: String?,
open var features: F?,
open var businessAccountId: String?,
open var dailyGoal: Int?,
open var weeklyGoal: Int?,
open var daysOff: IntArray?,
open var uniquePrefix: Long?,
open var hasPassword: Boolean,
open var verificationStatus: VerificationStatus,
open var multiFactorAuthEnabled: Boolean,
) : Person(id, email, fullName, imageId, false) {
enum class VerificationStatus(private val key: String) {
VERIFIED("verified"),
VERIFIED_BY_THIRD_PARTY("verified_by_third_party"),
UNVERIFIED("unverified"),
LEGACY("legacy"),
BLOCKED("blocked");
override fun toString() = key
companion object {
fun get(statusKey: String): VerificationStatus = values().first { it.key == statusKey }
}
}
}
| src/main/java/com/todoist/pojo/User.kt | 1665749302 |
package com.github.davinkevin.podcastserver.update.updaters.rss
import com.github.davinkevin.podcastserver.service.image.ImageServiceConfig
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.web.reactive.function.client.WebClient
import reactor.netty.http.client.HttpClient
import com.github.davinkevin.podcastserver.service.image.ImageService
/**
* Created by kevin on 01/09/2019
*/
@Configuration
@Import(ImageServiceConfig::class)
class RSSUpdaterConfig {
@Bean
fun rssUpdater(imageService: ImageService, wcb: WebClient.Builder): RSSUpdater {
val builder = wcb
.clone()
.clientConnector(ReactorClientHttpConnector(HttpClient.create().followRedirect(true)))
return RSSUpdater(imageService, builder)
}
}
| backend/src/main/kotlin/com/github/davinkevin/podcastserver/update/updaters/rss/RSSUpdaterConfig.kt | 2523748756 |
package com.binlly.fastpeak.service.remoteconfig
import com.binlly.fastpeak.base.model.IModel
/**
* Created by yy on 2017/10/10.
*/
data class RemoteMockModel(val router: Map<String, Int>): IModel | app/src/main/java/com/binlly/fastpeak/service/remoteconfig/RemoteMockModel.kt | 2976273072 |
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutManager
import android.graphics.BitmapFactory
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.TaskStackBuilder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.util.SparseArray
import android.view.MenuItem
import android.widget.Toast
import com.github.shadowsocks.App.Companion.app
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.database.ProfileManager
import com.github.shadowsocks.utils.resolveResourceId
import com.google.android.gms.samples.vision.barcodereader.BarcodeCapture
import com.google.android.gms.samples.vision.barcodereader.BarcodeGraphic
import com.google.android.gms.vision.Frame
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import xyz.belvi.mobilevisionbarcodescanner.BarcodeRetriever
class ScannerActivity : AppCompatActivity(), Toolbar.OnMenuItemClickListener, BarcodeRetriever {
companion object {
private const val TAG = "ScannerActivity"
private const val REQUEST_IMPORT = 2
private const val REQUEST_IMPORT_OR_FINISH = 3
}
private fun navigateUp() {
val intent = parentActivityIntent
if (shouldUpRecreateTask(intent) || isTaskRoot)
TaskStackBuilder.create(this).addNextIntentWithParentStack(intent).startActivities()
else finish()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= 25) getSystemService(ShortcutManager::class.java).reportShortcutUsed("scan")
if (try {
(getSystemService(Context.CAMERA_SERVICE) as CameraManager).cameraIdList.isEmpty()
} catch (_: CameraAccessException) {
true
}) {
startImport()
return
}
setContentView(R.layout.layout_scanner)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar.title = title
toolbar.setNavigationIcon(theme.resolveResourceId(R.attr.homeAsUpIndicator))
toolbar.setNavigationOnClickListener { navigateUp() }
toolbar.inflateMenu(R.menu.scanner_menu)
toolbar.setOnMenuItemClickListener(this)
(supportFragmentManager.findFragmentById(R.id.barcode) as BarcodeCapture).setRetrieval(this)
}
override fun onRetrieved(barcode: Barcode) = runOnUiThread {
Profile.findAll(barcode.rawValue).forEach { ProfileManager.createProfile(it) }
navigateUp()
}
override fun onRetrievedMultiple(closetToClick: Barcode?, barcode: MutableList<BarcodeGraphic>?) = check(false)
override fun onBitmapScanned(sparseArray: SparseArray<Barcode>?) { }
override fun onRetrievedFailed(reason: String?) {
Log.w(TAG, reason)
}
override fun onPermissionRequestDenied() {
Toast.makeText(this, R.string.add_profile_scanner_permission_required, Toast.LENGTH_SHORT).show()
startImport()
}
override fun onMenuItemClick(item: MenuItem) = when (item.itemId) {
R.id.action_import -> {
startImport(true)
true
}
else -> false
}
private fun startImport(manual: Boolean = false) = startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType("image/*")
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true), if (manual) REQUEST_IMPORT else REQUEST_IMPORT_OR_FINISH)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_IMPORT, REQUEST_IMPORT_OR_FINISH -> if (resultCode == Activity.RESULT_OK) {
var success = false
val detector = BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build()
if (detector.isOperational) {
var list = listOfNotNull(data?.data)
val clipData = data?.clipData
if (clipData != null) list += (0 until clipData.itemCount).map { clipData.getItemAt(it).uri }
val resolver = contentResolver
for (uri in list) try {
val barcodes = detector.detect(Frame.Builder()
.setBitmap(BitmapFactory.decodeStream(resolver.openInputStream(uri))).build())
for (i in 0 until barcodes.size()) Profile.findAll(barcodes.valueAt(i).rawValue).forEach {
ProfileManager.createProfile(it)
success = true
}
} catch (e: Exception) {
app.track(e)
}
} else Log.w(TAG, "Google vision isn't operational.")
Toast.makeText(this, if (success) R.string.action_import_msg else R.string.action_import_err,
Toast.LENGTH_SHORT).show()
navigateUp()
} else if (requestCode == REQUEST_IMPORT_OR_FINISH) navigateUp()
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
}
| mobile/src/main/java/com/github/shadowsocks/ScannerActivity.kt | 3738063286 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.rally.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import com.example.compose.rally.R
import java.text.DecimalFormat
/**
* A row representing the basic information of an Account.
*/
@Composable
fun AccountRow(
modifier: Modifier = Modifier,
name: String,
number: Int,
amount: Float,
color: Color
) {
BaseRow(
modifier = modifier,
color = color,
title = name,
subtitle = stringResource(R.string.account_redacted) + AccountDecimalFormat.format(number),
amount = amount,
negative = false
)
}
/**
* A row representing the basic information of a Bill.
*/
@Composable
fun BillRow(name: String, due: String, amount: Float, color: Color) {
BaseRow(
color = color,
title = name,
subtitle = "Due $due",
amount = amount,
negative = true
)
}
@Composable
private fun BaseRow(
modifier: Modifier = Modifier,
color: Color,
title: String,
subtitle: String,
amount: Float,
negative: Boolean
) {
val dollarSign = if (negative) "–$ " else "$ "
val formattedAmount = formatAmount(amount)
Row(
modifier = modifier
.height(68.dp)
.clearAndSetSemantics {
contentDescription =
"$title account ending in ${subtitle.takeLast(4)}, current balance $dollarSign$formattedAmount"
},
verticalAlignment = Alignment.CenterVertically
) {
val typography = MaterialTheme.typography
AccountIndicator(
color = color,
modifier = Modifier
)
Spacer(Modifier.width(12.dp))
Column(Modifier) {
Text(text = title, style = typography.body1)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(text = subtitle, style = typography.subtitle1)
}
}
Spacer(Modifier.weight(1f))
Row(
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = dollarSign,
style = typography.h6,
modifier = Modifier.align(Alignment.CenterVertically)
)
Text(
text = formattedAmount,
style = typography.h6,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
Spacer(Modifier.width(16.dp))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Icon(
imageVector = Icons.Filled.ChevronRight,
contentDescription = null,
modifier = Modifier
.padding(end = 12.dp)
.size(24.dp)
)
}
}
RallyDivider()
}
/**
* A vertical colored line that is used in a [BaseRow] to differentiate accounts.
*/
@Composable
private fun AccountIndicator(color: Color, modifier: Modifier = Modifier) {
Spacer(
modifier
.size(4.dp, 36.dp)
.background(color = color)
)
}
@Composable
fun RallyDivider(modifier: Modifier = Modifier) {
Divider(color = MaterialTheme.colors.background, thickness = 1.dp, modifier = modifier)
}
fun formatAmount(amount: Float): String {
return AmountDecimalFormat.format(amount)
}
private val AccountDecimalFormat = DecimalFormat("####")
private val AmountDecimalFormat = DecimalFormat("#,###.##")
/**
* Used with accounts and bills to create the animated circle.
*/
fun <E> List<E>.extractProportions(selector: (E) -> Float): List<Float> {
val total = this.sumOf { selector(it).toDouble() }
return this.map { (selector(it) / total).toFloat() }
}
| NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/components/CommonUi.kt | 1488443073 |
package com.floor13.game.actors
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.graphics.g2d.Batch
import com.floor13.game.FloorMinus13
import com.floor13.game.core.map.Map
import com.floor13.game.core.map.Door
import com.floor13.game.util.SidedTextureResolver
import com.floor13.game.texture
import com.floor13.game.TILE_SIZE
class MapActor(val map: Map): BaseActor() {
// TODO: pick atlas basing on theme (bunker (1-4 lvl), lab (5-8) etc.)
val textureResolver =
SidedTextureResolver(
FloorMinus13.getAtlas("graphics/terrain/level1/atlas.atlas"),
map)
val fogOfWarResolver =
SidedTextureResolver(
FloorMinus13.getAtlas("graphics/fow/atlas.atlas"),
map.width,
map.height,
{ x1, y1, x2, y2 ->
map.isExplored(x1, y1) == map.isExplored(x2, y2)
// TODO: handle also invisibilty fog of war
}
)
init {
setBounds(
0f,
0f,
map.width * TILE_SIZE,
map.height * TILE_SIZE
)
}
override fun draw(batch: Batch, parentAlpha: Float) {
for (x in 0 until map.width) {
for (y in 0 until map.height) {
val tile = map[x, y]
batch.draw(
textureResolver.getTexture(tile.texture, x, y),
x * TILE_SIZE,
y * TILE_SIZE
)
if (!map.isExplored(x, y))
batch.draw(
fogOfWarResolver.getTexture(UNEXPLORED_TEXTURE_NAME, x, y),
x * TILE_SIZE,
y * TILE_SIZE
)
// TODO: handle also insibility fog of war
// TODO: drawing creature (if present)
// TODO: drawing items (if present)
}
}
}
companion object {
val UNEXPLORED_TEXTURE_NAME = "unexplored"
}
}
| core/src/com/floor13/game/actors/MapActor.kt | 457005973 |
package tech.summerly.quiet.extensions
import android.content.Context
import android.support.v7.widget.PopupMenu
import android.view.View
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import org.jetbrains.anko.alert
import org.jetbrains.anko.noButton
import org.jetbrains.anko.toast
import org.jetbrains.anko.yesButton
import tech.summerly.quiet.R
import tech.summerly.quiet.bean.Playlist
import tech.summerly.quiet.data.local.LocalMusicApi
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bean.MusicType
import tech.summerly.quiet.module.common.utils.inputDialog
import tech.summerly.quiet.module.playlistdetail.PlaylistDetailActivity
import tech.summerly.quiet.ui.widget.PlaylistSelectorBottomSheet
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/20
* desc :
*/
class PopupMenuHelper(private val context: Context) {
/**
* 获取音乐的弹出按钮
* TODO
*/
fun getMusicPopupMenu(target: View, music: Music): PopupMenu {
val popupMenu = PopupMenu(context, target)
popupMenu.inflate(R.menu.popup_menu_music)
val defaultMusicHandler = when (music.type) {
MusicType.LOCAL -> LocalMusicHandler(context, music)
MusicType.NETEASE -> TODO()
MusicType.NETEASE_FM -> TODO()
}
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_music_add_to_next -> {
//TODO
}
R.id.menu_music_add_to_tag -> defaultMusicHandler.addToPlaylist()
R.id.menu_music_to_album -> defaultMusicHandler.navToAlbum()
R.id.menu_music_delete -> {
context
.alert(string(R.string.alert_message_delete_music, music.title)) {
yesButton {
Single
.create<String> {
val delete = music.deleteAction
val isSuccess = delete?.invoke()
if (isSuccess == true) {
it.onSuccess(string(R.string.toast_delete_music_success, music.title))
} else {
it.onError(Exception(string(R.string.toast_delete_music_failed, music.title)))
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ message ->
context.toast(message)
}, { exception ->
exception.message?.let {
context.toast(it)
}
})
}
noButton {
//do nothing
}
}.show()
}
}
true
}
return popupMenu
}
fun getPlaylistItemPopupMenu(target: View, playlist: Playlist): PopupMenu {
val popupMenu = PopupMenu(context, target)
popupMenu.inflate(R.menu.popup_playlist_item)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.popup_playlist_remove -> {
context.alert {
title = ("删除歌单 ${playlist.name}")
yesButton {
launch {
LocalMusicApi.removePlaylist(playlist)
launch(UI) {
it.dismiss()
}
}
log { "删除 ---> ${playlist.id}" }
}
}.show()
}
R.id.popup_playlist_rename -> {
context
.inputDialog("重命名",
"名字", "命名",
"取消") { dialog, textInputLayout ->
val text = textInputLayout.editText?.text?.toString()?.trim()
if (text.isNullOrBlank()) {
textInputLayout.error = "不能为空"
} else {
launch {
LocalMusicApi.updatePlaylist(playlist.copy(name = text!!))
launch(UI) {
dialog.dismiss()
}
}
}
log { "text = $text" }
}
.show()
}
}
true
}
return popupMenu
}
interface MusicHandler {
val context: Context
val music: Music
fun addToPlaylist()
fun navToAlbum()
@Deprecated("")
fun delete()
}
class LocalMusicHandler(override val context: Context, override val music: Music) : MusicHandler {
override fun addToPlaylist() {
PlaylistSelectorBottomSheet(context) { selector, playlist ->
launch {
LocalMusicApi.addToPlaylist(music, playlist = playlist)
launch(UI) {
[email protected](string(R.string.toast_add_to_tag_success))
selector.dismiss()
}
}
}.show()
}
override fun navToAlbum() {
PlaylistDetailActivity.startForLocalAlbum(context, music.album.name)
}
override fun delete() {
context.alert(string(R.string.alert_message_delete_music, music.title)) {
yesButton {
log("正在删除本地音乐 : $music ")
if (music.delete()) {
context.toast(string(R.string.toast_delete_music_success, music.title))
} else {
context.toast(string(R.string.toast_delete_music_failed, music.title))
log("删除失败")
}
}
noButton {
//do nothing
}
}.show()
}
}
} | app/src/main/java/tech/summerly/quiet/extensions/PopupMenuHelper.kt | 1776804407 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.loop
import uk.co.nickthecoder.tickle.Game
import uk.co.nickthecoder.tickle.graphics.Window
import uk.co.nickthecoder.tickle.physics.TickleWorld
/**
* This is the default implementation of [GameLoop].
*
* Note. This implementation call tick on Producer, Director, all StageViews, and all Stage (and therefore all Roles)
* every frame. There is no attempt to keep a constant frame rate.
* Therefore under heavy load, the time between two ticks can vary, and there is no mechanism to even out these
* steps to prevent objects moving at different speeds depending on the load.
*
* If your games uses physics (JBox2d), then TickleWorld ensures that the time step is consistent.
* i.e. objects WILL move at a constant speed, regardless of load. (at the expense of potential stuttering).
*
* Runs as quickly as possible. It will be capped to the screen's refresh rate if using v-sync.
* See [Window.enableVSync].
*/
class FullSpeedGameLoop(game: Game) : AbstractGameLoop(game) {
override fun sceneStarted() {
resetStats()
game.scene.stages.values.forEach { stage ->
stage.world?.resetAccumulator()
}
}
override fun tick() {
tickCount++
with(game) {
producer.preTick()
director.preTick()
producer.tick()
director.tick()
if (!game.paused) {
game.scene.views.values.forEach { it.tick() }
game.scene.stages.values.forEach { it.tick() }
// Call tick on all TickleWorlds
// Each stage can have its own TickleWorld. However, in the most common case, there is only
// one tickle world shared by all stages. Given the way that TickleWorld keeps a constant
// time step, we COULD just call tick on every stage's TickleWorld without affecting the game.
// However, debugging information may be misleading, as the first stage will cause a step, and
// the subsequent stages will skip (because the accumulator is near zero).
// So, this code ticks all Stages' worlds, but doesn't bother doing it twice for the same world.
var world: TickleWorld? = null
game.scene.stages.values.forEach { stage ->
val stageWorld = stage.world
if (stageWorld != null) {
if (stageWorld != world) {
world = stageWorld
stageWorld.tick()
}
}
}
}
director.postTick()
producer.postTick()
mouseMoveTick()
processRunLater()
}
game.scene.draw(game.renderer)
game.window.swap()
}
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/loop/FullSpeedGameLoop.kt | 3986482877 |
/*
* Copyright 2016 Christian Broomfield
*
* 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.sbg.rpg.javafx
import com.sbg.rpg.javafx.model.AnnotatedSpriteSheet
import com.sbg.rpg.packing.common.SpriteCutter
import com.sbg.rpg.packing.common.SpriteDrawer
import com.sbg.rpg.packing.common.extensions.filenameWithoutExtension
import com.sbg.rpg.packing.common.extensions.pmap
import com.sbg.rpg.packing.common.extensions.readImage
import com.sbg.rpg.packing.unpacker.SpriteSheetUnpacker
import org.apache.logging.log4j.LogManager
import tornadofx.Controller
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
class SpriteSheetProcessorController : Controller() {
private val logger = LogManager.getLogger(SpriteSheetProcessorController::class.simpleName)
private val view: SpriteSheetProcessorView by inject()
private val spriteSheetUnpacker: SpriteSheetUnpacker = SpriteSheetUnpacker(SpriteCutter(SpriteDrawer()))
private var spriteSheetPaths: List<Path> = emptyList()
fun unpackSpriteSheets(spriteSheetFiles: List<File>): List<AnnotatedSpriteSheet> {
logger.debug("Loading files $spriteSheetFiles")
this.spriteSheetPaths = spriteSheetFiles.map { Paths.get(it.absolutePath) }
return spriteSheetPaths.pmap { spriteSheetPath ->
logger.debug("Unpacking ${spriteSheetPath.fileName}")
val spriteSheet = spriteSheetPath.readImage()
val spriteBoundsList = spriteSheetUnpacker.discoverSprites(spriteSheet)
AnnotatedSpriteSheet(
spriteSheet,
spriteBoundsList
)
}
}
fun saveSprites(directory: File) {
val spritesPerFile = spriteSheetPaths.pmap { spriteSheetPath ->
spriteSheetPath.fileName to spriteSheetUnpacker.unpack(spriteSheetPath.readImage())
}
logger.debug("Writing individual sprites to file.")
for ((fileName, sprites) in spritesPerFile) {
val fileNameWithoutExtension = fileName.filenameWithoutExtension()
sprites.forEachIndexed { idx, sprite ->
ImageIO.write(
sprite,
"png",
Paths.get(directory.absolutePath, "${fileNameWithoutExtension}_$idx.png").toFile())
}
}
logger.debug("Finished writing sprites to file.")
}
}
| src/main/java/com/sbg/rpg/javafx/SpriteSheetProcessorController.kt | 2371805558 |
package fr.geobert.efficio
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.preference.PreferenceFragment
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import fr.geobert.efficio.db.DbHelper
import fr.geobert.efficio.dialog.FileChooserDialog
import fr.geobert.efficio.dialog.FileChooserDialogListener
import fr.geobert.efficio.dialog.MessageDialog
import fr.geobert.efficio.misc.MY_PERM_REQUEST_WRITE_EXT_STORAGE
import fr.geobert.efficio.misc.OnRefreshReceiver
import kotlinx.android.synthetic.main.item_editor.*
import kotlinx.android.synthetic.main.settings_activity.*
class SettingsActivity : BaseActivity(), FileChooserDialogListener {
companion object {
fun callMe(ctx: Context) {
val i = Intent(ctx, SettingsActivity::class.java)
ctx.startActivity(i)
}
}
class SettingsFragment : PreferenceFragment(), FileChooserDialogListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.settings)
}
override fun onFileChosen(name: String) {
(activity as FileChooserDialogListener).onFileChosen(name)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
setSpinnerVisibility(View.GONE)
setTitle(R.string.settings)
setIcon(R.mipmap.ic_action_arrow_left)
setIconOnClick(View.OnClickListener { onBackPressed() })
if (savedInstanceState == null) {
fragmentManager.beginTransaction().replace(R.id.flContent, SettingsFragment(),
"settings").commit()
}
backup_db_btn.setOnClickListener {
askPermAndBackupDatabase()
}
restore_db_btn.setOnClickListener {
chooseFileToRestore()
}
}
private fun chooseFileToRestore() {
val f = FileChooserDialog.newInstance("/Efficio")
f.setTargetFragment(fragmentManager.findFragmentByTag("settings"), 0)
f.show(fragmentManager, "FileChooser")
}
override fun onFileChosen(name: String) {
val msg = if (DbHelper.restoreDatabase(this, name)) {
val i = Intent(OnRefreshReceiver.REFRESH_ACTION)
sendBroadcast(i)
R.string.restore_database_done
} else R.string.restore_database_fail
Snackbar.make(my_toolbar, msg, Snackbar.LENGTH_LONG).show()
}
private fun askPermAndBackupDatabase() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
MY_PERM_REQUEST_WRITE_EXT_STORAGE)
} else {
doBackup()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
MY_PERM_REQUEST_WRITE_EXT_STORAGE -> {
if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
doBackup()
} else {
MessageDialog.newInstance(R.string.permission_write_required, R.string.permission_required_title)
.show(fragmentManager, "PermAsk")
}
}
}
}
private fun doBackup() {
val name = DbHelper.backupDb()
val msg = if (name != null)
getString(R.string.backup_database_done).format(name)
else getString(R.string.backup_database_fail)
Snackbar.make(my_toolbar, msg,
Snackbar.LENGTH_LONG).show()
}
}
| app/src/main/kotlin/fr/geobert/efficio/SettingsActivity.kt | 2096227739 |
package net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda
import com.fasterxml.jackson.annotation.JsonIgnore
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.DiscordUser
import net.perfectdreams.loritta.morenitta.utils.ImageFormat
import net.perfectdreams.loritta.morenitta.utils.extensions.getEffectiveAvatarUrl
open class JDAUser(@JsonIgnore val handle: net.dv8tion.jda.api.entities.User) : DiscordUser {
override val id: Long
get() = handle.idLong
override val name: String
get() = handle.name
override val avatar: String?
get() = handle.avatarId
override val avatarUrl: String?
get() = handle.effectiveAvatarUrl
override val asMention: String
get() = handle.asMention
override val isBot: Boolean
get() = handle.isBot
/**
* Gets the effective avatar URL in the specified [format]
*
* @see getEffectiveAvatarUrl
*/
fun getEffectiveAvatarUrl(format: ImageFormat) = getEffectiveAvatarUrl(format, 128)
/**
* Gets the effective avatar URL in the specified [format] and [ímageSize]
*
* @see getEffectiveAvatarUrlInFormat
*/
fun getEffectiveAvatarUrl(format: ImageFormat, imageSize: Int): String {
val extension = format.extension
return if (avatar != null) {
"https://cdn.discordapp.com/avatars/$id/$avatar.${extension}?size=$imageSize"
} else {
val avatarId = id % 5
// This only exists in png AND doesn't have any other sizes
"https://cdn.discordapp.com/embed/avatars/$avatarId.png"
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/platform/discord/legacy/entities/jda/JDAUser.kt | 1823598696 |
package com.skypicker.reactnative.nativemodules.device
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
import java.util.*
class RNDeviceInfoPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
val modules = ArrayList<NativeModule>()
modules.add(RNDeviceInfoManager(reactContext))
return modules
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| android/react-native-native-modules/src/main/java/com/skypicker/reactnative/nativemodules/device/RNDeviceInfoPackage.kt | 533081941 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.compile
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.recorder.ScriptGenerator
import com.intellij.testGuiFramework.recorder.actions.PerformScriptAction
import java.io.File
import java.net.URL
import java.nio.file.Paths
object KotlinCompileUtil {
private val LOG by lazy { Logger.getInstance("#${KotlinCompileUtil::class.qualifiedName}") }
fun compile(codeString: String) {
LocalCompiler().compileOnPooledThread(ScriptGenerator.ScriptWrapper.wrapScript(codeString),
getAllUrls().map { Paths.get(it.toURI()).toFile().path })
}
fun compileAndRun(codeString: String) {
LocalCompiler().compileAndRunOnPooledThread(ScriptGenerator.ScriptWrapper.wrapScript(codeString),
getAllUrls().map { Paths.get(it.toURI()).toFile().path })
}
fun getAllUrls(): List<URL> {
if (ServiceManager::class.java.classLoader.javaClass.name.contains("Launcher\$AppClassLoader")) {
//lets substitute jars with a common lib dir to avoid Windows long path error
val urls = ServiceManager::class.java.classLoader.forcedUrls()
val libUrl = urls.filter { url ->
(url.file.endsWith("idea.jar") && File(url.path).parentFile.name == "lib")
}.firstOrNull()!!.getParentURL()
urls.filter { url -> !url.file.startsWith(libUrl.file) }.plus(libUrl).toSet()
//add git4idea urls to allow git configuration from local runner
// if (System.getenv("TEAMCITY_VERSION") != null) urls.plus(getGit4IdeaUrls())
if (!ApplicationManager.getApplication().isUnitTestMode)
urls.plus(ServiceManager::class.java.classLoader.forcedBaseUrls())
return urls.toList()
}
var list: List<URL> = (ServiceManager::class.java.classLoader.forcedUrls()
+ PerformScriptAction::class.java.classLoader.forcedUrls())
if (!ApplicationManager.getApplication().isUnitTestMode)
list += ServiceManager::class.java.classLoader.forcedBaseUrls()
return list
}
fun getGit4IdeaUrls(): List<URL> {
val git4IdeaPluginClassLoader = PluginManager.getPlugins().filter { pluginDescriptor -> pluginDescriptor.name.toLowerCase() == "git integration" }.firstOrNull()!!.pluginClassLoader
val urls = git4IdeaPluginClassLoader.forcedUrls()
val libUrl = urls.filter { url ->
(url.file.endsWith("git4idea.jar") && File(url.path).parentFile.name == "lib")
}.firstOrNull()!!.getParentURL()
urls.filter { url -> !url.file.startsWith(libUrl.file) }.plus(libUrl).toSet()
return urls
}
fun URL.getParentURL() = File(this.file).parentFile.toURI().toURL()
fun ClassLoader.forcedUrls(): List<URL> {
val METHOD_DEFAULT_NAME: String = "getUrls"
val METHOD_ALTERNATIVE_NAME: String = "getURLs"
var methodName: String = METHOD_DEFAULT_NAME
if (this.javaClass.methods.any { mtd -> mtd.name == METHOD_ALTERNATIVE_NAME }) methodName = METHOD_ALTERNATIVE_NAME
val method = this.javaClass.getMethod(methodName)
method.isAccessible
val methodResult = method.invoke(this)
val myList: List<*> = (methodResult as? Array<*>)?.asList() ?: methodResult as List<*>
return myList.filterIsInstance(URL::class.java)
}
fun ClassLoader.forcedBaseUrls(): List<URL> {
try {
return ((this.javaClass.getMethod("getBaseUrls").invoke(
this) as? List<*>)!!.filter { it is URL && it.protocol == "file" && !it.file.endsWith("jar!") }) as List<URL>
}
catch (e: NoSuchMethodException) {
return emptyList()
}
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/KotlinCompileUtil.kt | 3461872567 |
package eu.kanade.tachiyomi.ui.library
import android.view.View
import android.view.ViewGroup
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.util.inflate
import eu.kanade.tachiyomi.widget.RecyclerViewPagerAdapter
/**
* This adapter stores the categories from the library, used with a ViewPager.
*
* @constructor creates an instance of the adapter.
*/
class LibraryAdapter(private val controller: LibraryController) : RecyclerViewPagerAdapter() {
/**
* The categories to bind in the adapter.
*/
var categories: List<Category> = emptyList()
// This setter helps to not refresh the adapter if the reference to the list doesn't change.
set(value) {
if (field !== value) {
field = value
notifyDataSetChanged()
}
}
private var boundViews = arrayListOf<View>()
/**
* Creates a new view for this adapter.
*
* @return a new view.
*/
override fun createView(container: ViewGroup): View {
val view = container.inflate(R.layout.library_category) as LibraryCategoryView
view.onCreate(controller)
return view
}
/**
* Binds a view with a position.
*
* @param view the view to bind.
* @param position the position in the adapter.
*/
override fun bindView(view: View, position: Int) {
(view as LibraryCategoryView).onBind(categories[position])
boundViews.add(view)
}
/**
* Recycles a view.
*
* @param view the view to recycle.
* @param position the position in the adapter.
*/
override fun recycleView(view: View, position: Int) {
(view as LibraryCategoryView).onRecycle()
boundViews.remove(view)
}
/**
* Returns the number of categories.
*
* @return the number of categories or 0 if the list is null.
*/
override fun getCount(): Int {
return categories.size
}
/**
* Returns the title to display for a category.
*
* @param position the position of the element.
* @return the title to display.
*/
override fun getPageTitle(position: Int): CharSequence {
return categories[position].name
}
/**
* Returns the position of the view.
*/
override fun getItemPosition(obj: Any): Int {
val view = obj as? LibraryCategoryView ?: return POSITION_NONE
val index = categories.indexOfFirst { it.id == view.category.id }
return if (index == -1) POSITION_NONE else index
}
/**
* Called when the view of this adapter is being destroyed.
*/
fun onDestroy() {
for (view in boundViews) {
if (view is LibraryCategoryView) {
view.unsubscribe()
}
}
}
} | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt | 2512539246 |
package com.directdev.portal.di
import android.content.Context
import com.google.firebase.analytics.FirebaseAnalytics
import dagger.Module
import dagger.Provides
/**-------------------------------------------------------------------------------------------------
* Created by chris on 8/25/17.
*------------------------------------------------------------------------------------------------*/
@Module
class FirebaseAnalyticsModule {
@Provides
fun providesFirebaseAnalytics(ctx: Context): FirebaseAnalytics = FirebaseAnalytics.getInstance(ctx)
} | app/src/main/java/com/directdev/portal/di/FirebaseAnalyticsModule.kt | 1945629361 |
package com.doubley.customandroidtest.sampleapp
import android.app.Activity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
public class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.getItemId()
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| sampleapp/src/main/java/com/doubley/customandroidtest/sampleapp/MainActivity.kt | 2249444779 |
package uk.co.appsbystudio.geoshare.setup
interface InitialSetupPresenter {
fun addDeviceToken()
fun onPermissionsResult()
fun onError(error: String)
} | mobile/src/main/java/uk/co/appsbystudio/geoshare/setup/InitialSetupPresenter.kt | 324362325 |
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.gs.obevo.db.impl.platforms.mysql
import com.gs.obevo.api.appdata.PhysicalSchema
import com.gs.obevo.db.api.appdata.DbEnvironment
import com.gs.obevo.db.impl.core.envinfrasetup.AbstractEnvironmentInfraSetup
import com.gs.obevo.dbmetadata.api.DbMetadataManager
import com.gs.obevo.impl.ChangeTypeBehaviorRegistry
import com.gs.obevo.impl.DeployMetricsCollector
import java.sql.Connection
import javax.sql.DataSource
/**
* MySQL environment setup.
*/
internal class MySqlEnvironmentInfraSetup(env: DbEnvironment, ds: DataSource, deployMetricsCollector: DeployMetricsCollector, dbMetadataManager: DbMetadataManager, changeTypeBehaviorRegistry: ChangeTypeBehaviorRegistry) : AbstractEnvironmentInfraSetup(env, ds, deployMetricsCollector, dbMetadataManager, changeTypeBehaviorRegistry) {
override fun createSchema(conn: Connection, schema: PhysicalSchema) {
jdbc.update(conn, "CREATE SCHEMA " + schema.physicalName)
}
}
| obevo-db-impls/obevo-db-mysql/src/main/java/com/gs/obevo/db/impl/platforms/mysql/MySqlEnvironmentInfraSetup.kt | 741432800 |
package net.pterodactylus.sone.database.memory
import net.pterodactylus.sone.test.TestValue.from
import net.pterodactylus.sone.test.mock
import net.pterodactylus.sone.test.whenever
import net.pterodactylus.util.config.Configuration
import net.pterodactylus.util.config.Value
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.nullValue
import org.junit.Test
/**
* Unit test for [ConfigurationLoader].
*/
class ConfigurationLoaderTest {
private val configuration = mock<Configuration>()
private val configurationLoader = ConfigurationLoader(configuration)
private fun setupStringValue(attribute: String, value: String? = null): Value<String?> =
from(value).apply {
whenever(configuration.getStringValue(attribute)).thenReturn(this)
}
private fun setupLongValue(attribute: String, value: Long? = null): Value<Long?> =
from(value).apply {
whenever(configuration.getLongValue(attribute)).thenReturn(this)
}
@Test
fun `loader can load known posts`() {
setupStringValue("KnownPosts/0/ID", "Post2")
setupStringValue("KnownPosts/1/ID", "Post1")
setupStringValue("KnownPosts/2/ID")
val knownPosts = configurationLoader.loadKnownPosts()
assertThat(knownPosts, containsInAnyOrder("Post1", "Post2"))
}
@Test
fun `loader can load known post replies`() {
setupStringValue("KnownReplies/0/ID", "PostReply2")
setupStringValue("KnownReplies/1/ID", "PostReply1")
setupStringValue("KnownReplies/2/ID")
val knownPosts = configurationLoader.loadKnownPostReplies()
assertThat(knownPosts, containsInAnyOrder("PostReply1", "PostReply2"))
}
@Test
fun `loader can load bookmarked posts`() {
setupStringValue("Bookmarks/Post/0/ID", "Post2")
setupStringValue("Bookmarks/Post/1/ID", "Post1")
setupStringValue("Bookmarks/Post/2/ID")
val knownPosts = configurationLoader.loadBookmarkedPosts()
assertThat(knownPosts, containsInAnyOrder("Post1", "Post2"))
}
@Test
fun `loader can save bookmarked posts`() {
val post1 = setupStringValue("Bookmarks/Post/0/ID")
val post2 = setupStringValue("Bookmarks/Post/1/ID")
val post3 = setupStringValue("Bookmarks/Post/2/ID")
val originalPosts = setOf("Post1", "Post2")
configurationLoader.saveBookmarkedPosts(originalPosts)
val extractedPosts = setOf(post1.value, post2.value)
assertThat(extractedPosts, containsInAnyOrder("Post1", "Post2"))
assertThat(post3.value, nullValue())
}
@Test
fun `loader can load Sone following times`() {
setupStringValue("SoneFollowingTimes/0/Sone", "Sone1")
setupLongValue("SoneFollowingTimes/0/Time", 1000L)
setupStringValue("SoneFollowingTimes/1/Sone", "Sone2")
setupLongValue("SoneFollowingTimes/1/Time", 2000L)
setupStringValue("SoneFollowingTimes/2/Sone")
assertThat(configurationLoader.getSoneFollowingTime("Sone1"), equalTo(1000L))
assertThat(configurationLoader.getSoneFollowingTime("Sone2"), equalTo(2000L))
assertThat(configurationLoader.getSoneFollowingTime("Sone3"), nullValue())
}
@Test
fun `loader can overwrite existing Sone following time`() {
val sone1Id = setupStringValue("SoneFollowingTimes/0/Sone", "Sone1")
val sone1Time = setupLongValue("SoneFollowingTimes/0/Time", 1000L)
val sone2Id = setupStringValue("SoneFollowingTimes/1/Sone", "Sone2")
val sone2Time = setupLongValue("SoneFollowingTimes/1/Time", 2000L)
setupStringValue("SoneFollowingTimes/2/Sone")
configurationLoader.setSoneFollowingTime("Sone1", 3000L)
assertThat(listOf(sone1Id.value to sone1Time.value, sone2Id.value to sone2Time.value), containsInAnyOrder<Pair<String?, Long?>>(
"Sone1" to 3000L,
"Sone2" to 2000L
))
}
@Test
fun `loader can remove Sone following time`() {
val sone1Id = setupStringValue("SoneFollowingTimes/0/Sone", "Sone1")
val sone1Time = setupLongValue("SoneFollowingTimes/0/Time", 1000L)
val sone2Id = setupStringValue("SoneFollowingTimes/1/Sone", "Sone2")
val sone2Time = setupLongValue("SoneFollowingTimes/1/Time", 2000L)
setupStringValue("SoneFollowingTimes/2/Sone")
configurationLoader.removeSoneFollowingTime("Sone1")
assertThat(sone1Id.value, equalTo("Sone2"))
assertThat(sone1Time.value, equalTo(2000L))
assertThat(sone2Id.value, nullValue())
}
@Test
fun `sone with missing following time is not loaded`() {
setupStringValue("SoneFollowingTimes/0/Sone", "Sone1")
setupLongValue("SoneFollowingTimes/0/Time", 1000L)
setupStringValue("SoneFollowingTimes/1/Sone", "Sone2")
setupLongValue("SoneFollowingTimes/1/Time")
setupStringValue("SoneFollowingTimes/2/Sone")
assertThat(configurationLoader.getSoneFollowingTime("Sone1"), equalTo(1000L))
assertThat(configurationLoader.getSoneFollowingTime("Sone2"), nullValue())
assertThat(configurationLoader.getSoneFollowingTime("Sone3"), nullValue())
}
}
| src/test/kotlin/net/pterodactylus/sone/database/memory/ConfigurationLoaderTest.kt | 1533395872 |
package com.wangjie.androidkotlinbucket.library
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.app.Fragment
import android.view.View
import android.widget.Toast
/**
* Author: wangjie
* Email: [email protected]
* Date: 11/9/15.
*/
/** Activity **/
// 从Activity中注入View
public fun <T : View> Activity._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { findViewById(resId) as T }
//// 绑定点击事件
//public fun Activity._click(onClick: ((View) -> Unit)?, vararg resId: Int): Activity {
// __click({ findViewById(it) }, onClick, resId)
// return this
//}
/** Fragment **/
// 从Fragment中注入View
public fun <T : View> Fragment._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { view!!.findViewById(resId) as T }
//// 绑定点击事件
//public fun Fragment._click(onClick: ((View) -> Unit)?, vararg resId: Int): Fragment {
// __click({ view.findViewById(it) }, onClick, resId)
// return this
//}
/** View **/
// 从View中注入View
public fun <T : View> View._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { findViewById(resId) as T }
//// 绑定点击事件
//public fun View._click(onClick: ((View) -> Unit)?, vararg resId: Int): View {
// __click({ findViewById(it) }, onClick, resId)
// return this
//}
/** Common **/
//public fun _abkClick(onClick: ((View) -> Unit)?, vararg view: View) {
// onClick?.let {
// view.forEach { it.setOnClickListener(onClick) }
// }
//}
//
//
//private inline fun __click(findView: (Int) -> View, noinline onClick: ((View) -> Unit)?, resId: IntArray) {
// onClick?.let {
// resId.forEach { findView(it).setOnClickListener(onClick) }
// }
//}
inline fun <reified T : Activity> Context.toActivity(f: (Intent) -> Unit) {
with(Intent(this, T::class.java)) {
f(this)
startActivity(this)
}
}
// toast
fun Activity.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, message, duration).show()
fun Fragment.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = context?.lets { Toast.makeText(this, message, duration).show() }
fun View.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = context?.lets { Toast.makeText(this, message, duration).show() }
| library/src/main/kotlin/com/wangjie/androidkotlinbucket/library/AKBViewExt.kt | 683341094 |
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util
import ink.abb.pogo.scraper.services.BotService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import java.math.BigInteger
import java.security.SecureRandom
import java.util.regex.Pattern
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Component
open class ApiAuthProvider : HandlerInterceptorAdapter() {
@Autowired
lateinit var service: BotService
val random: SecureRandom = SecureRandom()
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest,
response: HttpServletResponse, handler: Any): Boolean {
if (request.method.equals("OPTIONS"))
return true // Allow preflight calls
val pattern = Pattern.compile("\\/api/bot/([A-Za-z0-9\\-_]*)")
val matcher = pattern.matcher(request.requestURI)
if (matcher.find()) {
val token = service.getBotContext(matcher.group(1)).restApiToken
// If the token is invalid or isn't in the request, nothing will be done
return request.getHeader("X-PGB-ACCESS-TOKEN")!!.equals(token)
}
return false
}
fun generateRandomString(): String {
return BigInteger(130, random).toString(32)
}
fun generateAuthToken(botName: String) {
val token: String = this.generateRandomString()
service.getBotContext(botName).restApiToken = token
Log.cyan("REST API token for bot $botName : $token has been generated")
}
fun generateRestPassword(botName: String) {
val password: String = this.generateRandomString()
service.getBotContext(botName).restApiPassword = password
service.doWithBot(botName) {
it.settings.restApiPassword = password
}
Log.red("Generated restApiPassword: $password")
}
}
| src/main/kotlin/ink/abb/pogo/scraper/util/ApiAuthProvider.kt | 3162755172 |
package io.particle.mesh.setup.flow.setupsteps
import io.particle.mesh.common.android.livedata.nonNull
import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate
import io.particle.mesh.setup.flow.MeshSetupStep
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.context.SetupContexts
import io.particle.mesh.setup.flow.FlowUiDelegate
class StepCollectMeshNetworkToJoinSelection(private val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
if (ctxs.mesh.meshNetworkToJoinLD.value != null) {
return
}
flowUi.getMeshNetworkToJoin()
ctxs.mesh.meshNetworkToJoinLD
.nonNull(scopes)
.runBlockOnUiThreadAndAwaitUpdate(scopes) {
// no-op; we're just awaiting the update.
}
}
}
| mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepCollectMeshNetworkToJoinSelection.kt | 2037084203 |
/* 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 org.mozilla.focus.settings.privacy
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.content.res.AppCompatResources
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import mozilla.components.browser.icons.IconRequest
import mozilla.components.support.ktx.android.view.putCompoundDrawablesRelativeWithIntrinsicBounds
import org.mozilla.focus.R
import org.mozilla.focus.databinding.ConnectionDetailsBinding
import org.mozilla.focus.ext.components
@SuppressWarnings("LongParameterList")
class ConnectionDetailsPanel(
context: Context,
private val tabTitle: String,
private val tabUrl: String,
private val isConnectionSecure: Boolean,
private val goBack: () -> Unit,
) : BottomSheetDialog(context) {
private var binding: ConnectionDetailsBinding =
ConnectionDetailsBinding.inflate(layoutInflater, null, false)
init {
setContentView(binding.root)
expandBottomSheet()
updateSiteInfo()
updateConnectionState()
setListeners()
}
private fun expandBottomSheet() {
val bottomSheet =
findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout
BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_EXPANDED
}
private fun updateSiteInfo() {
binding.siteTitle.text = tabTitle
binding.siteFullUrl.text = tabUrl
context.components.icons.loadIntoView(
binding.siteFavicon,
IconRequest(tabUrl, isPrivate = true),
)
}
private fun updateConnectionState() {
binding.securityInfo.text = if (isConnectionSecure) {
context.getString(R.string.secure_connection)
} else {
context.getString(R.string.insecure_connection)
}
val securityIcon = if (isConnectionSecure) {
AppCompatResources.getDrawable(context, R.drawable.mozac_ic_lock)
} else {
AppCompatResources.getDrawable(context, R.drawable.mozac_ic_warning)
}
binding.securityInfo.putCompoundDrawablesRelativeWithIntrinsicBounds(
start = securityIcon,
end = null,
top = null,
bottom = null,
)
}
private fun setListeners() {
binding.detailsBack.setOnClickListener {
goBack.invoke()
dismiss()
}
}
}
| app/src/main/java/org/mozilla/focus/settings/privacy/ConnectionDetailsPanel.kt | 3716406773 |
/*
* Copyright 2000-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.
*/
package com.intellij.diff.comparison
public class SplitComparisonUtilTest : ComparisonUtilTestBase() {
public fun testSplitter() {
splitter {
("x" - "z")
default(mod(0, 0, 1, 1))
testAll()
}
splitter {
("x_y" - "a_b")
default(mod(0, 0, 2, 2))
testAll()
}
splitter {
("x_y" - "a_b y")
default(mod(0, 0, 1, 1), mod(1, 1, 1, 1))
testAll()
}
splitter {
("x y" - "x a_b y")
default(mod(0, 0, 1, 2))
testAll()
}
splitter {
("x_y" - "x a_y b")
default(mod(0, 0, 1, 1), mod(1, 1, 1, 1))
testAll()
}
splitter {
("x_" - "x a_...")
default(mod(0, 0, 2, 2))
testAll()
}
splitter {
("x_y_" - "a_b_")
default(mod(0, 0, 2, 2))
testAll()
}
splitter {
("x_y" - " x _ y ")
default(mod(0, 0, 2, 2))
testDefault()
}
splitter {
("x_y" - " x _ y.")
default(mod(0, 0, 1, 1), mod(1, 1, 1, 1))
testDefault()
}
splitter {
("a_x_b_" - " x_")
default(del(0, 0, 1), mod(1, 0, 1, 1), del(2, 1, 1))
testDefault()
}
splitter {
("a_x_b_" - "!x_")
default(del(0, 0, 1), mod(1, 0, 1, 1), del(2, 1, 1))
testAll()
}
}
public fun testSquash() {
splitter(squash = true) {
("x" - "z")
default(mod(0, 0, 1, 1))
testAll()
}
splitter(squash = true) {
("x_y" - "a_b")
default(mod(0, 0, 2, 2))
testAll()
}
splitter(squash = true) {
("x_y" - "a_b y")
default(mod(0, 0, 2, 2))
testAll()
}
splitter(squash = true) {
("a_x_b_" - " x_")
default(mod(0, 0, 3, 1))
testDefault()
}
splitter(squash = true) {
("a_x_b_" - "!x_")
default(mod(0, 0, 3, 1))
testAll()
}
}
public fun testTrim() {
splitter(trim = true) {
("_" - " _ ")
default(mod(0, 0, 2, 2))
trim()
testAll()
}
splitter(trim = true) {
("" - " _ ")
default(mod(0, 0, 1, 2))
trim(ins(1, 1, 1))
ignore()
testAll()
}
splitter(trim = true) {
(" _ " - "")
default(mod(0, 0, 2, 1))
trim(del(1, 1, 1))
ignore()
testAll()
}
splitter(trim = true) {
("x_y" - "z_ ")
default(mod(0, 0, 2, 2))
testAll()
}
splitter(trim = true) {
("z" - "z_ ")
default(ins(1, 1, 1))
ignore()
testAll()
}
splitter(trim = true) {
("z_ x" - "z_ w")
default(mod(1, 1, 1, 1))
testAll()
}
splitter(trim = true) {
("__z__" - "z")
default(del(0, 0, 2), del(3, 1, 2))
ignore()
testAll()
}
}
}
| platform/diff-impl/tests/com/intellij/diff/comparison/SplitComparisonUtilTest.kt | 848866641 |
package screenswitchersample.espressotestingbootstrap.application
import android.app.Application
import android.content.Context
import com.squareup.rx2.idler.Rx2Idler
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import io.reactivex.plugins.RxJavaPlugins
import leakcanary.AppWatcher
import screenswitchersample.core.activity.ActivityComponentFactory
import screenswitchersample.core.application.ApplicationInitializationAction
import screenswitchersample.core.leak.LeakWatcher
import screenswitchersample.espressotestingbootstrap.activity.TestActivityComponentFactory
import timber.log.Timber
import javax.inject.Singleton
@Module
internal class TestApplicationModule(
private val application: Application
) {
@Provides @Singleton fun provideApplicationContext(): Context {
return application
}
@Module
companion object {
@Provides @Singleton @JvmStatic fun provideLeakWatcher(): LeakWatcher {
return object : LeakWatcher {
override fun <T> watch(t: T, description: String) {
AppWatcher.objectWatcher.watch(t as Any, description)
}
}
}
@Provides @JvmStatic
fun provideScreenSwitcherActivityComponentFactory(): ActivityComponentFactory {
return TestActivityComponentFactory
}
@Provides @IntoSet @JvmStatic
fun provideTimberInitializationAction(): ApplicationInitializationAction {
return ApplicationInitializationAction {
Timber.plant(Timber.DebugTree())
}
}
@Provides @IntoSet @JvmStatic
fun provideUnlockScreenInitializationAction(): ApplicationInitializationAction {
return ApplicationInitializationAction { application ->
application.registerActivityLifecycleCallbacks(UnlockScreenActivityLifecycleCallbacks)
}
}
@Provides @IntoSet @JvmStatic
fun provideRxJavaIdlingResourceInitializationAction(): ApplicationInitializationAction {
return ApplicationInitializationAction {
RxJavaPlugins.setInitComputationSchedulerHandler(Rx2Idler.create("RxJava 2.x Computation Scheduler"))
RxJavaPlugins.setInitIoSchedulerHandler(Rx2Idler.create("RxJava 2.x IO Scheduler"))
}
}
}
}
| espresso-testing-bootstrap/src/main/java/screenswitchersample/espressotestingbootstrap/application/TestApplicationModule.kt | 1962104165 |
package leakcanary.internal
import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import leakcanary.ProcessInfo
import leakcanary.internal.friendly.mainHandler
import leakcanary.internal.friendly.noOpDelegate
/**
* Tracks whether the app is in background, based on the app's importance.
*/
internal class BackgroundListener(
private val processInfo: ProcessInfo,
private val callback: (Boolean) -> Unit
) : ActivityLifecycleCallbacks by noOpDelegate() {
private val checkAppInBackground: Runnable = object : Runnable {
override fun run() {
val appInBackgroundNow = processInfo.isImportanceBackground
updateBackgroundState(appInBackgroundNow)
if (!appInBackgroundNow) {
mainHandler.removeCallbacks(this)
mainHandler.postDelayed(this, BACKGROUND_REPEAT_DELAY_MS)
}
}
}
private fun updateBackgroundState(appInBackgroundNow: Boolean) {
if (appInBackground != appInBackgroundNow) {
appInBackground = appInBackgroundNow
callback.invoke(appInBackgroundNow)
}
}
private var appInBackground = false
fun install(application: Application) {
application.registerActivityLifecycleCallbacks(this)
updateBackgroundState(appInBackgroundNow = false)
checkAppInBackground.run()
}
fun uninstall(application: Application) {
application.unregisterActivityLifecycleCallbacks(this)
updateBackgroundState(appInBackgroundNow = false)
mainHandler.removeCallbacks(checkAppInBackground)
}
override fun onActivityPaused(activity: Activity) {
mainHandler.removeCallbacks(checkAppInBackground)
mainHandler.postDelayed(checkAppInBackground, BACKGROUND_DELAY_MS)
}
override fun onActivityResumed(activity: Activity) {
updateBackgroundState(appInBackgroundNow = false)
mainHandler.removeCallbacks(checkAppInBackground)
}
companion object {
private const val BACKGROUND_DELAY_MS = 1000L
private const val BACKGROUND_REPEAT_DELAY_MS = 5000L
}
}
| leakcanary-android-release/src/main/java/leakcanary/internal/BackgroundListener.kt | 864819977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.