content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// "Create annotation 'foo'" "false" // ACTION: Create function 'foo' // ACTION: Rename reference // ERROR: Unresolved reference: foo fun test() = <caret>foo(1, "2")
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/annotationEntry/notAnnotation.kt
2305446120
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.refactoring.suggested import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.tree.IElementType import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.elementType import com.intellij.refactoring.suggested.SuggestedRefactoringState import com.intellij.refactoring.suggested.SuggestedRefactoringStateChanges import com.intellij.refactoring.suggested.SuggestedRefactoringSupport import com.intellij.refactoring.suggested.range import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.ParamHelper internal class PySuggestedRefactoringStateChanges(support: PySuggestedRefactoringSupport) : SuggestedRefactoringStateChanges(support) { override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? { return findStateChanges(declaration).signature(declaration, prevState) } override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> { return findStateChanges(declaration).parameterMarkerRanges(declaration) } override fun updateState(state: SuggestedRefactoringState, declaration: PsiElement): SuggestedRefactoringState { return findStateChanges(declaration).updateNewState(state, declaration, super.updateState(state, declaration)) } override fun guessParameterIdByMarkers(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? { return super.guessParameterIdByMarkers(markerRange, prevState) ?: // findStateChanges(prevState.declaration) can't be used here since !prevState.declaration.isValid sequenceOf(ChangeSignatureStateChanges(this), RenameStateChanges) .mapNotNull { it.guessParameterIdByMarker(markerRange, prevState) } .firstOrNull() } private fun findStateChanges(declaration: PsiElement): StateChangesInternal { return sequenceOf(ChangeSignatureStateChanges(this), RenameStateChanges).first { it.isApplicable(declaration) } } private interface StateChangesInternal { fun isApplicable(declaration: PsiElement): Boolean fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> fun updateNewState(prevState: SuggestedRefactoringState, declaration: PsiElement, newState: SuggestedRefactoringState): SuggestedRefactoringState = newState fun guessParameterIdByMarker(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? = null } private class ChangeSignatureStateChanges(private val mainStateChanges: PySuggestedRefactoringStateChanges) : StateChangesInternal { companion object { private val DISAPPEARED_RANGES = Key.create<Map<RangeMarker, Any>>("PySuggestedRefactoringStateChanges.ChangeSignature.DISAPPEARED_RANGES") } override fun isApplicable(declaration: PsiElement): Boolean = PySuggestedRefactoringSupport.isAvailableForChangeSignature(declaration) override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? { val signature = createSignatureData(declaration as PyFunction) ?: return null return if (prevState == null) signature else mainStateChanges.matchParametersWithPrevState(signature, declaration, prevState) } override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> { return (declaration as PyFunction).parameterList.parameters.map(this::getParameterMarker) } override fun updateNewState(prevState: SuggestedRefactoringState, declaration: PsiElement, newState: SuggestedRefactoringState): SuggestedRefactoringState { val initialSignature = prevState.oldSignature val prevSignature = prevState.newSignature val newSignature = newState.newSignature val idsPresent = newSignature.parameters.map { it.id }.toSet() val disappearedRanges = (prevState.additionalData[DISAPPEARED_RANGES] ?: emptyMap()) .filter { it.key.isValid && it.value !in idsPresent } .toMutableMap() prevSignature.parameters .asSequence() .map { it.id } .filter { id -> id !in idsPresent && initialSignature.parameterById(id) != null } .mapNotNull { id -> prevState.parameterMarkers.firstOrNull { it.parameterId == id } } .filter { it.rangeMarker.isValid } .associateByTo(disappearedRanges, { it.rangeMarker }, { it.parameterId }) return newState.withAdditionalData(DISAPPEARED_RANGES, disappearedRanges) } override fun guessParameterIdByMarker(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? { val disappearedRanges = prevState.additionalData[DISAPPEARED_RANGES] ?: return null return disappearedRanges.entries.firstOrNull { it.key.isValid && it.key.range == markerRange }?.value } private fun createSignatureData(function: PyFunction): SuggestedRefactoringSupport.Signature? { val name = function.name ?: return null val parametersData = function.parameterList.parameters.map { createParameterData(it) ?: return null } return SuggestedRefactoringSupport.Signature.create(name, PyTypingTypeProvider.ANY, parametersData, null) } private fun getParameterMarker(parameter: PyParameter): TextRange? { val asNamed = parameter.asNamed if (asNamed != null) { if (asNamed.isPositionalContainer) return getChildRange(parameter, PyTokenTypes.MULT) if (asNamed.isKeywordContainer) return getChildRange(parameter, PyTokenTypes.EXP) } return PsiTreeUtil.skipWhitespacesForward(parameter) ?.takeIf { it.elementType == PyTokenTypes.COMMA || it.elementType == PyTokenTypes.RPAR } ?.textRange } private fun getChildRange(element: PsiElement, type: IElementType): TextRange? = element.node.findChildByType(type)?.textRange private fun createParameterData(parameter: PyParameter): SuggestedRefactoringSupport.Parameter? { val name = when (parameter) { is PySlashParameter -> PySlashParameter.TEXT is PySingleStarParameter -> PySingleStarParameter.TEXT is PyNamedParameter -> ParamHelper.getNameInSignature(parameter) else -> return null } return SuggestedRefactoringSupport.Parameter( Any(), name, PyTypingTypeProvider.ANY, PySuggestedRefactoringSupport.ParameterData(parameter.defaultValueText) ) } } private object RenameStateChanges : StateChangesInternal { override fun isApplicable(declaration: PsiElement): Boolean = PySuggestedRefactoringSupport.isAvailableForRename(declaration) override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? { val name = (declaration as PsiNameIdentifierOwner).name ?: return null return SuggestedRefactoringSupport.Signature.create(name, null, emptyList(), null) } override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> = emptyList() } }
python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringStateChanges.kt
3817549565
// 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.index.stubs import com.google.common.hash.HashCode import com.intellij.openapi.Disposable import com.intellij.openapi.application.ReadAction import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.impl.DebugUtil import com.intellij.psi.stubs.* import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.TestApplicationManager import com.intellij.util.indexing.* import com.intellij.util.io.PersistentHashMap import com.intellij.util.io.write import junit.framework.TestCase import org.jetbrains.index.IndexGenerator import java.io.File import java.nio.file.Paths import java.util.* import kotlin.system.exitProcess open class StubsGenerator(private val stubsVersion: String, private val stubsStorageFilePath: String) : IndexGenerator<SerializedStubTree>(stubsStorageFilePath) { private val serializationManager = SerializationManagerImpl(File("$stubsStorageFilePath.names").toPath(), false) fun buildStubsForRoots(roots: Collection<VirtualFile>) { // ensure indexes initialized ReadAction.run<Throwable> { FileBasedIndex.getInstance().ensureUpToDate(ID.create<Any, Any>("Stubs"), null, null) } try { buildIndexForRoots(roots) } finally { Disposer.dispose(serializationManager) writeStubsVersionFile(stubsStorageFilePath, stubsVersion) } } override fun getIndexValue(fileContent: FileContentImpl): SerializedStubTree? { val stub = buildStubForFile(fileContent, serializationManager) if (stub == null) { return null } return SerializedStubTree.serializeStub(stub, serializationManager, StubForwardIndexExternalizer.createFileLocalExternalizer()) } override fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, SerializedStubTree> { return PersistentHashMap(File("$stubsStorageFilePath.input").toPath(), HashCodeDescriptor.instance, GeneratingFullStubExternalizer()) } open fun buildStubForFile(fileContent: FileContent, serializationManager: SerializationManagerImpl): Stub? { return ReadAction.compute<Stub, Throwable> { StubTreeBuilder.buildStubTree(fileContent) } } } private fun writeStubsVersionFile(stubsStorageFilePath: String, stubsVersion: String) { val stubSerializationVersion = FileBasedIndexExtension.EXTENSION_POINT_NAME.findExtensionOrFail(StubUpdatingIndex::class.java).version Paths.get("$stubsStorageFilePath.version").write("$stubSerializationVersion\n$stubsVersion") } fun mergeStubs(paths: List<String>, stubsFilePath: String, stubsFileName: String, projectPath: String, stubsVersion: String) { TestApplicationManager.getInstance() PlatformTestUtil.loadAndOpenProject(Paths.get(projectPath), Disposable { }) // we don't need a project here, but I didn't find a better way to wait until indices and components are initialized val stubExternalizer = GeneratingFullStubExternalizer() val storageFile = File(stubsFilePath, "$stubsFileName.input") if (storageFile.exists()) { storageFile.delete() } val storage = PersistentHashMap(storageFile.toPath(), HashCodeDescriptor.instance, stubExternalizer) val stringEnumeratorFile = File(stubsFilePath, "$stubsFileName.names") if (stringEnumeratorFile.exists()) { stringEnumeratorFile.delete() } val newSerializationManager = SerializationManagerImpl(stringEnumeratorFile.toPath(), false) val map = HashMap<HashCode, Int>() println("Writing results to ${storageFile.absolutePath}") for (path in paths) { println("Reading stubs from $path") var count = 0 val fromStorageFile = File(path, "$stubsFileName.input") val fromStorage = PersistentHashMap(fromStorageFile, HashCodeDescriptor.instance, stubExternalizer) val serializationManager = SerializationManagerImpl(File(path, "$stubsFileName.names").toPath(), true) try { fromStorage.processKeysWithExistingMapping { key -> count++ val value = fromStorage.get(key) // re-serialize stub tree to correctly enumerate strings in the new string enumerator val newForwardIndexSerializer = StubForwardIndexExternalizer.createFileLocalExternalizer() val newStubTree = value.reSerialize(newSerializationManager, newForwardIndexSerializer) if (storage.containsMapping(key)) { if (newStubTree != storage.get(key)) { // TODO: why are they slightly different??? storage.get(key).stub val stub = value.stub val newStubTree2 = SerializedStubTree.serializeStub(stub, newSerializationManager, newForwardIndexSerializer) TestCase.assertTrue(newStubTree == newStubTree2) // wtf!!! why are they equal now??? } map[key] = map[key]!! + 1 } else { storage.put(key, newStubTree) map[key] = 1 } true } } finally { fromStorage.close() Disposer.dispose(serializationManager) } println("Items in ${fromStorageFile.absolutePath}: $count") } storage.close() Disposer.dispose(newSerializationManager) val total = map.size println("Total items in storage: $total") writeStubsVersionFile(stringEnumeratorFile.nameWithoutExtension, stubsVersion) for (i in 2..paths.size) { val count = map.entries.stream().filter { e -> e.value == i }.count() println("Intersection between $i: ${"%.2f".format(if (total > 0) 100.0 * count / total else 0.0)}%") } exitProcess(0) } /** * Generates stubs for file content for different language levels returned by languageLevelIterator * and checks that they are all equal. */ abstract class LanguageLevelAwareStubsGenerator<T>(stubsVersion: String, stubsStorageFilePath: String) : StubsGenerator(stubsVersion, stubsStorageFilePath) { companion object { val FAIL_ON_ERRORS: Boolean = System.getenv("STUB_GENERATOR_FAIL_ON_ERRORS")?.toBoolean() ?: false } abstract fun languageLevelIterator(): Iterator<T> abstract fun applyLanguageLevel(level: T) abstract fun defaultLanguageLevel(): T override fun buildStubForFile(fileContent: FileContent, serializationManager: SerializationManagerImpl): Stub? { var prevLanguageLevel: T? = null var prevStub: Stub? = null val iter = languageLevelIterator() try { for (languageLevel in iter) { applyLanguageLevel(languageLevel) // create new FileContentImpl, because it caches stub in user data val content = FileContentImpl.createByContent(fileContent.file, fileContent.content) val stub = super.buildStubForFile(content, serializationManager) if (stub != null) { val bytes = BufferExposingByteArrayOutputStream() serializationManager.serialize(stub, bytes) if (prevStub != null) { try { check(stub, prevStub) } catch (e: AssertionError) { val msg = "Stubs are different for ${content.file.path} between Python versions $prevLanguageLevel and $languageLevel.\n" // Debug info // TestCase.assertEquals(msg, DebugUtil.stubTreeToString(stub), DebugUtil.stubTreeToString(prevStub)) TestCase.assertTrue(msg, DebugUtil.stubTreeToString(stub)==DebugUtil.stubTreeToString(prevStub)) TestCase.fail(msg + "But DebugUtil.stubTreeToString values of stubs are unfortunately equal.") } } } prevLanguageLevel = languageLevel prevStub = stub } applyLanguageLevel(defaultLanguageLevel()) return prevStub!! } catch (e: AssertionError) { if (FAIL_ON_ERRORS) { throw e } println("Can't generate universal stub for ${fileContent.file.path}") // Debug info // e.printStackTrace() return null } } } private fun check(stub: Stub, stub2: Stub) { TestCase.assertEquals(stub.stubType, stub2.stubType) val stubs = stub.childrenStubs val stubs2 = stub2.childrenStubs TestCase.assertEquals(stubs.size, stubs2.size) var i = 0 val len = stubs.size while (i < len) { check(stubs[i], stubs2[i]) ++i } }
tools/index-tools/src/org/jetbrains/index/stubs/StubsGenerator.kt
3182048518
// WITH_STDLIB // IS_APPLICABLE: false class MyClass { fun foo1() = Unit fun foo2(a: MyClass) = Unit fun foo3() = Unit fun foo4(a: MyClass) { val a = MyClass() a.foo1() a.foo2(this) a.foo3()<caret> } }
plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToApply/thisParameter2.kt
3439042187
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.builtInWebServer import com.google.common.base.Function import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.intellij.ProjectTopics import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.SmartList import com.intellij.util.io.exists import java.nio.file.Paths import java.util.concurrent.TimeUnit import kotlin.streams.asSequence private const val cacheSize: Long = 4096 * 4 /** * Implement [WebServerRootsProvider] to add your provider */ class WebServerPathToFileManager(private val project: Project) { val pathToInfoCache: Cache<String, PathInfo> = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!! // time to expire should be greater than pathToFileCache private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>() internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!! /** * https://youtrack.jetbrains.com/issue/WEB-25900 * * Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search * (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir) */ internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>( CacheLoader.from(Function { path -> val suitableRoots = SmartList<SuitableRoot>() var moduleQualifier: String? = null val modules = runReadAction { ModuleManager.getInstance(project).modules } for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (root.findChild(path!!) != null) { if (moduleQualifier == null) { moduleQualifier = getModuleNameQualifier(project, module) } suitableRoots.add(SuitableRoot(root, moduleQualifier)) } } } } suitableRoots }))!! init { ApplicationManager.getApplication().messageBus.connect (project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { for (event in events) { if (event is VFileContentChangeEvent) { val file = event.file for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) { if (rootsProvider.isClearCacheOnFileContentChanged(file)) { clearCache() break } } } else { clearCache() break } } } }) project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { clearCache() } }) } companion object { @JvmStatic fun getInstance(project: Project) = project.service<WebServerPathToFileManager>() } private fun clearCache() { pathToInfoCache.invalidateAll() virtualFileToPathInfo.invalidateAll() pathToExistShortTermCache.invalidateAll() parentToSuitableRoot.invalidateAll() } @JvmOverloads fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? { return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile() } @JvmOverloads fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? { var pathInfo = pathToInfoCache.getIfPresent(path) if (pathInfo == null || !pathInfo.isValid) { if (pathToExistShortTermCache.getIfPresent(path) == false) { return null } pathInfo = doFindByRelativePath(path, pathQuery) if (cacheResult) { if (pathInfo != null && pathInfo.isValid) { pathToInfoCache.put(path, pathInfo) } else { pathToExistShortTermCache.put(path, false) } } } return pathInfo } fun getPath(file: VirtualFile): String? = getPathInfo(file)?.path fun getPathInfo(child: VirtualFile): PathInfo? { var result = virtualFileToPathInfo.getIfPresent(child) if (result == null) { result = WebServerRootsProvider.EP_NAME.extensions().asSequence().map { it.getPathInfo(child, project) }.find { it != null } if (result != null) { virtualFileToPathInfo.put(child, result) } } return result } internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? { val result = WebServerRootsProvider.EP_NAME.extensions().asSequence().map { it.resolve(path, project, pathQuery) }.find { it != null } ?: return null result.file?.let { virtualFileToPathInfo.put(it, result) } return result } fun getResolver(path: String): FileResolver = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER } interface FileResolver { fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo? } private val RELATIVE_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { // WEB-17691 built-in server doesn't serve files it doesn't have in the project tree // temp:// reports isInLocalFileSystem == true, but it is not true if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") { return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) } } val file = Paths.get(root.path, path) return if (file.exists()) { PathInfo(file, null, root, moduleName, isLibrary) } else { null } } } private val EMPTY_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { val file = findIndexFile(root) ?: return null return PathInfo(null, file, root, moduleName, isLibrary) } } internal val defaultPathQuery = PathQuery()
platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt
2246347381
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.util import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiClass import com.intellij.psi.SmartPointerManager import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.util.ClassUtil import com.intellij.psi.xml.XmlTag import com.intellij.util.SmartList import com.intellij.util.xml.DomManager import org.jetbrains.idea.devkit.dom.Extension import org.jetbrains.idea.devkit.dom.ExtensionPoint import java.util.* fun locateExtensionsByPsiClass(psiClass: PsiClass): List<ExtensionCandidate> { return findExtensionsByClassName(psiClass.project, ClassUtil.getJVMClassName(psiClass) ?: return emptyList()) } fun locateExtensionsByExtensionPoint(extensionPoint: ExtensionPoint): List<ExtensionCandidate> { return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, null).findCandidates() } fun locateExtensionsByExtensionPointAndId(extensionPoint: ExtensionPoint, extensionId: String): ExtensionLocator { return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, extensionId) } internal fun processExtensionDeclarations(name: String, project: Project, strictMatch: Boolean = true, callback: (Extension, XmlTag) -> Boolean) { val scope = PluginRelatedLocatorsUtils.getCandidatesScope(project) PsiSearchHelper.getInstance(project).processElementsWithWord( { element, offsetInElement -> val elementAtOffset = (element as? XmlTag)?.findElementAt(offsetInElement) ?: return@processElementsWithWord true if (strictMatch) { if (!elementAtOffset.textMatches(name)) { return@processElementsWithWord true } } else if (!StringUtil.contains(elementAtOffset.text, name)) { return@processElementsWithWord true } val extension = DomManager.getDomManager(project).getDomElement(element) as? Extension ?: return@processElementsWithWord true callback(extension, element) }, scope, name, UsageSearchContext.IN_FOREIGN_LANGUAGES, /* case-sensitive = */ true) } private fun findExtensionsByClassName(project: Project, className: String): List<ExtensionCandidate> { val result = Collections.synchronizedList(SmartList<ExtensionCandidate>()) val smartPointerManager by lazy { SmartPointerManager.getInstance(project) } processExtensionsByClassName(project, className) { tag, _ -> result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(tag))) true } return result } internal inline fun processExtensionsByClassName(project: Project, className: String, crossinline processor: (XmlTag, ExtensionPoint) -> Boolean) { processExtensionDeclarations(className, project) { extension, tag -> extension.extensionPoint?.let { processor(tag, it) } ?: true } } internal class ExtensionByExtensionPointLocator(private val project: Project, extensionPoint: ExtensionPoint, private val extensionId: String?) : ExtensionLocator() { private val pointQualifiedName = extensionPoint.effectiveQualifiedName private fun processCandidates(processor: (XmlTag) -> Boolean) { // We must search for the last part of EP name, because for instance 'com.intellij.console.folding' extension // may be declared as <extensions defaultExtensionNs="com"><intellij.console.folding ... val epNameToSearch = StringUtil.substringAfterLast(pointQualifiedName, ".") ?: return processExtensionDeclarations(epNameToSearch, project, false /* not strict match */) { extension, tag -> val ep = extension.extensionPoint ?: return@processExtensionDeclarations true if (ep.effectiveQualifiedName == pointQualifiedName && (extensionId == null || extensionId == extension.id.stringValue)) { // stop after the first found candidate if ID is specified processor(tag) && extensionId == null } else { true } } } override fun findCandidates(): List<ExtensionCandidate> { val result = Collections.synchronizedList(SmartList<ExtensionCandidate>()) val smartPointerManager by lazy { SmartPointerManager.getInstance(project) } processCandidates { result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(it))) } return result } } sealed class ExtensionLocator { abstract fun findCandidates(): List<ExtensionCandidate> }
plugins/devkit/devkit-core/src/util/ExtensionLocator.kt
673614344
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent import com.intellij.ui.table.JBTable import com.intellij.util.ui.AbstractTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.components.ComboBoxTableCellEditorComponent import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeViewModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PopupMenuListItemCellRenderer import java.awt.Component import javax.swing.JTable internal object PackageScopeTableCellEditor : AbstractTableCellEditor() { private val comboBoxEditor = JBComboBoxTableCellEditorComponent() override fun getCellEditorValue(): Any? = comboBoxEditor.editorValue override fun getTableCellEditorComponent(table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int): Component = when (val scopeViewModel = value as ScopeViewModel<*>) { is ScopeViewModel.InstalledPackage -> { val availableScopes = scopeViewModel.packageModel.usageInfo .flatMap { it.availableScopes } val scopeViewModels = (availableScopes + scopeViewModel.installedScopes) .distinct() .sorted() .map { scopeViewModel.copy(selectedScope = it) } createComboBoxEditor(table, scopeViewModels, scopeViewModel.selectedScope) } is ScopeViewModel.InstallablePackage -> { val scopeViewModels = scopeViewModel.availableScopes .distinct() .sorted() .map { scopeViewModel.copy(selectedScope = it) } createComboBoxEditor(table, scopeViewModels, scopeViewModel.selectedScope) } }.apply { table.colors.applyTo(this, isSelected = true) setCell(row, column) } private fun createComboBoxEditor( table: JTable, scopeViewModels: List<ScopeViewModel<*>>, selectedScope: PackageScope ): ComboBoxTableCellEditorComponent<*> { require(table is JBTable) { "The packages list table is expected to be a JBTable, but was a ${table::class.qualifiedName}" } val selectedViewModel = scopeViewModels.find { it.selectedScope == selectedScope } val cellRenderer = PopupMenuListItemCellRenderer(selectedViewModel, table.colors) { it.selectedScope.displayName } return ComboBoxTableCellEditorComponent(table, cellRenderer).apply { options = scopeViewModels value = selectedViewModel isShowBelowCell = false isForcePopupMatchCellWidth = false } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/editors/PackageScopeTableCellEditor.kt
1057140699
package com.kingz.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import java.io.Serializable /** * author:ZekeWang * date:2021/5/11 * description:网络请求的Cookie表 * @since DataBase v3 */ @Entity(tableName = "http_cookie", primaryKeys = ["id"]) class CookiesEntity( @ColumnInfo(name = "id") var id: Int = 0, @ColumnInfo(name = "url", defaultValue = "") var url: String = "", @ColumnInfo(name = "cookies", defaultValue = "") var cookies: String = "" ) : Serializable { override fun toString(): String { return "CookiesEntity(id=$id, url='$url', cookies='$cookies')" } }
database/src/main/java/com/kingz/database/entity/CookiesEntity.kt
380820500
package com.twobbble.presenter import com.twobbble.biz.api.IBucketShotsBiz import com.twobbble.biz.impl.BucketShotsBiz import com.twobbble.entity.Shot import com.twobbble.tools.NetObserver import com.twobbble.tools.singleData import com.twobbble.view.api.IBucketShotsView import org.jetbrains.annotations.NotNull /** * Created by liuzipeng on 2017/3/12. */ class BucketShotsPresenter(val mBucketShotsView: IBucketShotsView) : BasePresenter() { private val mBucketShotBiz: IBucketShotsBiz by lazy { BucketShotsBiz() } fun getBucketShots(id: Long, access_token: String = singleData.token!!, page: Int?, isLoadMore: Boolean) { mBucketShotBiz.getBucketShots(id, access_token, page, NetObserver({ mDisposables.add(it) }, { mBucketShotsView.getShotSuccess(it, isLoadMore) }, { mBucketShotsView.getShotFailed(it, isLoadMore) }, mBucketShotsView)) } fun removeShotFromBucket(@NotNull access_token: String = singleData.token!!, @NotNull id: Long, @NotNull shot_id: Long?) { mBucketShotBiz.removeShotFromBucket(access_token, id, shot_id, NetObserver({ mBucketShotsView.showProgressDialog() mDisposables.add(it) }, { mBucketShotsView.hideProgressDialog() mBucketShotsView.removeShotSuccess() }, { mBucketShotsView.hideProgressDialog() mBucketShotsView.removeShotFailed(it) })) } }
app/src/main/java/com/twobbble/presenter/BucketShotsPresenter.kt
4001874807
package pl.ches.citybikes.presentation.common.base.scheduler import rx.Observable /** * A [Observable.Transformer] that is used to set the schedulers for an Observable that can * be subscribed by [MvpLceRxPresenter]. * * @author Hannes Dorfmann * * * @since 1.0.0 */ interface SchedulerTransformer<T> : Observable.Transformer<T, T>
app/src/main/kotlin/pl/ches/citybikes/presentation/common/base/scheduler/SchedulerTransformer.kt
2593903963
// API_VERSION: 1.3 // WITH_RUNTIME val x: Pair<String, Int> = listOf("a" to 1, "c" to 3, "b" to 2).<caret>sortedByDescending { it.second }.first()
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedByDescendingFirst.kt
1291386843
package com.github.bjansen.intellij.pebble.editor import com.github.bjansen.intellij.pebble.lang.PebbleFileViewProvider import com.github.bjansen.intellij.pebble.psi.PebbleFile import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens import com.github.bjansen.pebble.parser.PebbleLexer import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil.insertStringAtCaret import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.TokenType import java.util.regex.Pattern /** * Automatically close delimiters. */ // TODO This doesn't support custom delimiters class PebbleTypedHandler : TypedHandlerDelegate() { private val tagNamePattern: Pattern = Pattern.compile("\\{%\\s+(\\w+).*") private val tagsThatCanBeClosed = mapOf( "autoescape" to "endautoescape", "block" to "endblock", "cache" to "endcache", "filter" to "endfilter", "for" to "endfor", "if" to "endif", "macro" to "endmacro", "parallel" to "endparallel" ) override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result { if (file.viewProvider !is PebbleFileViewProvider) { return TypedHandlerDelegate.Result.CONTINUE } if (c != '}' && c != '#' && c != '{') { return TypedHandlerDelegate.Result.CONTINUE } val offset = editor.caretModel.offset val charBefore = getCharAt(editor.document, offset - 1) val charAfter = getCharAt(editor.document, offset) val buf = StringBuilder() var caretShift = 2 if (charBefore == '{' && (c == '#' || c == '{')) { // autoclose the comment buf.append(c).append(" ") if (needsClosingDelimiter(editor, offset, c)) { buf.append(" ").append(if (c == '#') c else '}') if (charAfter != '}') { buf.append('}') } } } if (charBefore == '%' && c == '}') { val closingTag = tagsThatCanBeClosed[findOpeningTagName(editor)] if (closingTag != null) { buf.append("}{% ").append(closingTag).append(" %}") } caretShift = 1 } if (buf.isEmpty()) { return TypedHandlerDelegate.Result.CONTINUE } insertStringAtCaret(editor, buf.toString(), true, caretShift) val documentManager = PsiDocumentManager.getInstance(project) documentManager.commitDocument(editor.document) return TypedHandlerDelegate.Result.STOP } private fun findOpeningTagName(editor: Editor): String? { var offset = editor.caretModel.offset while (offset > 0) { if (getCharAt(editor.document, offset) == '%' && getCharAt(editor.document, offset - 1) == '{') { val tag = editor.document.text.substring(offset-1 until editor.caretModel.offset) val matcher = tagNamePattern.matcher(tag) if (matcher.matches()) { return matcher.group(1) } } offset-- } return null } private fun needsClosingDelimiter(editor: Editor, afterOffset: Int, openingChar: Char): Boolean { val closingChar = if (openingChar == '{') '}' else openingChar val docCharSequence = editor.document.charsSequence for (offset in afterOffset until docCharSequence.length) { val nextChar = if (offset + 1 < docCharSequence.length) docCharSequence[offset + 1] else '\u0000' val currChar = docCharSequence[offset] if (currChar == '{' && nextChar == openingChar) { return true } if (currChar != closingChar || nextChar != '}') { continue } return false } return true } private fun getCharAt(document: Document, offset: Int): Char { if (offset >= document.textLength || offset < 0) { return '\u0000' } return document.charsSequence[offset] } } class PebbleEnterBetweenTagsHandler : EnterHandlerDelegateAdapter() { override fun preprocessEnter(file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>, dataContext: DataContext, originalHandler: EditorActionHandler?): EnterHandlerDelegate.Result { if (file is PebbleFile && betweenMatchingTags(editor, caretOffset.get())) { editor.document.insertString(caretOffset.get(), "\n") } return EnterHandlerDelegate.Result.Continue } private fun betweenMatchingTags(editor: Editor, offset: Int): Boolean { if (offset < 2) { return false } val chars = editor.document.charsSequence if (chars[offset - 1] != '}' || chars[offset - 2] != '%') { return false } val highlighter = (editor as EditorEx).highlighter val iterator = highlighter.createIterator(offset - 1) if (iterator.tokenType !== tokens[PebbleLexer.TAG_CLOSE]) { return false } iterator.advance() if (!iterator.atEnd() && iterator.tokenType === tokens[PebbleLexer.TAG_OPEN]) { // see if it's an "endXXX" tag do { iterator.advance() } while (!iterator.atEnd() && iterator.tokenType === TokenType.WHITE_SPACE) return !iterator.atEnd() && iterator.tokenType === tokens[PebbleLexer.ID_NAME] && chars.substring(iterator.start..iterator.end).startsWith("end") } return false } }
src/main/kotlin/com/github/bjansen/intellij/pebble/editor/PebbleTypedHandler.kt
2463419729
package com.github.kerubistan.kerub.planner.steps.storage.fs.unallocate import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.model.io.VirtualDiskFormat import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testFsCapability import com.github.kerubistan.kerub.testHost import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.github.kerubistan.kroki.size.GB import org.apache.sshd.client.session.ClientSession import org.apache.sshd.client.subsystem.sftp.SftpClient import org.junit.Test import java.math.BigInteger class UnAllocateFsExecutorTest { @Test fun execute() { val hostExecutor = mock<HostCommandExecutor>() val session = mock<ClientSession>() val sftpClient = mock<SftpClient>() whenever(session.createSftpClient()).thenReturn(sftpClient) whenever(hostExecutor.execute(eq(testHost), any<(ClientSession) -> BigInteger>())).then { (it.arguments[1] as (ClientSession) -> Unit).invoke(session) } val vssDynDao = mock<VirtualStorageDeviceDynamicDao>() UnAllocateFsExecutor(hostExecutor, vssDynDao).execute( UnAllocateFs( vstorage = testDisk, allocation = VirtualStorageFsAllocation( hostId = testHost.id, actualSize = 10.GB, mountPoint = "/kerub", fileName = "/kerub/${testDisk.id}.qcow2", type = VirtualDiskFormat.qcow2, capabilityId = testFsCapability.id ), host = testHost ) ) verify(sftpClient).remove(eq("/kerub/${testDisk.id}.qcow2")) } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/unallocate/UnAllocateFsExecutorTest.kt
3942462223
package io.multifunctions import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad internal class MultiMapIndexedNotNullSpec : WordSpec() { init { "mapIndexedNotNull" should { "produce a correct mapping from Pair" { val testData = listOf(Pair("one", "two")) testData mapIndexedNotNull { index, one, two -> index shouldBe 0 one shouldBe "one" two shouldBe "two" Pair(one, two) } shouldBe testData } "produce a correct mapping from Triple" { val testData = listOf(Triple("one", "two", "three")) testData mapIndexedNotNull { index, one, two, three -> index shouldBe 0 one shouldBe "one" two shouldBe "two" three shouldBe "three" Triple(one, two, three) } shouldBe testData } "produce a correct mapping from Quad" { val testData = listOf(Quad("one", "two", "three", "four")) testData mapIndexedNotNull { index, one, two, three, four -> index shouldBe 0 one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" Quad(one, two, three, four) } shouldBe testData } "produce a correct mapping from Penta" { val testData = listOf(Penta("one", "two", "three", "four", "five")) testData mapIndexedNotNull { index, one, two, three, four, five -> index shouldBe 0 one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" Penta(one, two, three, four, five) } shouldBe testData } "produce a correct mapping from Hexa" { val testData = listOf(Hexa("one", "two", "three", "four", "five", "six")) testData mapIndexedNotNull { index, one, two, three, four, five, six -> index shouldBe 0 one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" Hexa(one, two, three, four, five, six) } shouldBe testData } "produce a correct mapping from Hepta" { val testData = listOf(Hepta("one", "two", "three", "four", "five", "six", "seven")) testData mapIndexedNotNull { index, one, two, three, four, five, six, seven -> index shouldBe 0 one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" seven shouldBe "seven" Hepta(one, two, three, four, five, six, seven) } shouldBe testData } "handle null values" { val actual = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair(null, null), Pair("ten", "eleven") ) val expected = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair("ten", "eleven") ) actual mapIndexedNotNull { _, one, two -> Pair(one, two) } shouldBe expected } } } }
multi-functions/src/test/kotlin/io/multifunctions/MultiMapIndexedNotNullSpec.kt
1607778388
/* * 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.privacysandbox.tools.core.generator.poet import androidx.privacysandbox.tools.core.model.Type @JvmDefaultWithCompatibility /** Describes the contents of an AIDL file. */ internal interface AidlFileSpec { val type: Type val typesToImport: Set<Type> val innerContent: String fun getFileContent(): String = buildList { add("package ${type.packageName};") if (typesToImport.isNotEmpty()) { add(typesToImport.map { "import ${it.qualifiedName};" }.sorted().joinToString(separator = "\n")) } add(innerContent) }.joinToString(separator = "\n\n") }
privacysandbox/tools/tools-core/src/main/java/androidx/privacysandbox/tools/core/generator/poet/AidlFileSpec.kt
397171144
/* * Copyright 2018 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.navigation import androidx.annotation.IdRes /** * A host is a single context or container for navigation via a [NavController]. * * It is strongly recommended to construct the nav controller by instantiating a * [NavHostController], which offers additional APIs specifically for a NavHost. * The NavHostController should still only be externally accessible as a [NavController], * rather than directly exposing it as a [NavHostController]. * * Navigation hosts must: * * * Handle [saving][NavController.saveState] and * [restoring][NavController.restoreState] their controller's state * * Call [Navigation.setViewNavController] on their root view * * Route system Back button events to the NavController either by manually calling * [NavController.popBackStack] or by calling * [NavHostController.setOnBackPressedDispatcher] * when constructing the NavController. * * Optionally, a navigation host should consider calling: * * * Call [NavHostController.setLifecycleOwner] to associate the * NavController with a specific Lifecycle. * * Call [NavHostController.setViewModelStore] to enable usage of * [NavController.getViewModelStoreOwner] and navigation graph scoped ViewModels. */ public interface NavHost { /** * The [navigation controller][NavController] for this navigation host. */ public val navController: NavController } /** * Construct a new [NavGraph] */ @Suppress("Deprecation") @Deprecated( "Use routes to create your NavGraph instead", ReplaceWith( "createGraph(startDestination = startDestination.toString(), route = id.toString()) " + "{ builder.invoke() }" ) ) public inline fun NavHost.createGraph( @IdRes id: Int = 0, @IdRes startDestination: Int, builder: NavGraphBuilder.() -> Unit ): NavGraph = navController.createGraph(id, startDestination, builder) /** * Construct a new [NavGraph] */ public inline fun NavHost.createGraph( startDestination: String, route: String? = null, builder: NavGraphBuilder.() -> Unit ): NavGraph = navController.createGraph(startDestination, route, builder)
navigation/navigation-runtime/src/main/java/androidx/navigation/NavHost.kt
1394191168
package gg.obsidian.modtools import org.bukkit.entity.Player import java.util.* object MsgHistory { val history = HashMap<UUID, UUID>() fun getTo(player: Player): UUID? { if (history.containsKey(player.uniqueId)) { return history[player.uniqueId] } return null } fun reportMessage(from: Player, to: Player) { history.put(from.uniqueId, to.uniqueId) history.put(to.uniqueId, from.uniqueId) } }
src/main/kotlin/gg/obsidian/modtools/MsgHistory.kt
2874173395
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.conventionNameCalls import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.inspections.KotlinEqualsBetweenInconvertibleTypesInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.conventionNameCalls.isAnyEquals import org.jetbrains.kotlin.idea.intentions.isOperatorOrCompatible import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getLastParentOfTypeInRow import org.jetbrains.kotlin.resolve.calls.util.getFirstArgumentExpression import org.jetbrains.kotlin.resolve.calls.util.getReceiverExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeWithPossibleSmartCastToFP import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.isNullabilityFlexible import org.jetbrains.kotlin.types.typeUtil.* import org.jetbrains.kotlin.util.OperatorNameConventions class ReplaceCallWithBinaryOperatorInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java ) { private fun IElementType.inverted(): KtSingleValueToken? = when (this) { KtTokens.LT -> KtTokens.GT KtTokens.GT -> KtTokens.LT KtTokens.GTEQ -> KtTokens.LTEQ KtTokens.LTEQ -> KtTokens.GTEQ else -> null } override fun isApplicable(element: KtDotQualifiedExpression): Boolean { val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression ?: return false if (operation(calleeExpression) == null) return false val context = element.analyze(BodyResolveMode.PARTIAL) val resolvedCall = element.callExpression?.getResolvedCall(context) ?: return false if (!resolvedCall.isReallySuccess()) return false if (resolvedCall.call.typeArgumentList != null) return false val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return false if ((resolvedCall.getArgumentMapping(argument) as ArgumentMatch).valueParameter.index != 0) return false if (!element.isReceiverExpressionWithValue()) return false val (expressionToBeReplaced, newExpression) = getReplacementExpression(element) ?: return false val newContext = newExpression.analyzeAsReplacement(expressionToBeReplaced, context) return newContext.diagnostics.noSuppression().forElement(newExpression).isEmpty() } override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis() override fun inspectionHighlightType(element: KtDotQualifiedExpression): ProblemHighlightType { val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression val identifier = calleeExpression?.getReferencedNameAsName() if (identifier == OperatorNameConventions.EQUALS) { val context = element.analyze(BodyResolveMode.PARTIAL) if (element.receiverExpression.getType(context)?.isNullabilityFlexible() == true) { return ProblemHighlightType.INFORMATION } } val isFloatingPointNumberEquals = calleeExpression?.isFloatingPointNumberEquals() ?: false return if (isFloatingPointNumberEquals) { ProblemHighlightType.INFORMATION } else if (identifier == OperatorNameConventions.EQUALS || identifier == OperatorNameConventions.COMPARE_TO) { ProblemHighlightType.GENERIC_ERROR_OR_WARNING } else { ProblemHighlightType.INFORMATION } } override fun inspectionText(element: KtDotQualifiedExpression) = KotlinBundle.message("call.replaceable.with.binary.operator") override val defaultFixText: String get() = KotlinBundle.message("replace.with.binary.operator") override fun fixText(element: KtDotQualifiedExpression): String { val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression ?: return defaultFixText if (calleeExpression.isFloatingPointNumberEquals()) { return KotlinBundle.message("replace.total.order.equality.with.ieee.754.equality") } val operation = operation(calleeExpression) ?: return defaultFixText return KotlinBundle.message("replace.with.0", operation.value) } override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val (expressionToBeReplaced, newExpression) = getReplacementExpression(element) ?: return expressionToBeReplaced.replace(newExpression) } private fun getReplacementExpression(element: KtDotQualifiedExpression): Pair<KtExpression, KtExpression>? { val callExpression = element.callExpression ?: return null val calleeExpression = callExpression.calleeExpression as? KtSimpleNameExpression ?: return null val operation = operation(calleeExpression) ?: return null val argument = callExpression.valueArguments.single().getArgumentExpression() ?: return null val receiver = element.receiverExpression val factory = KtPsiFactory(element) return when (operation) { KtTokens.EXCLEQ -> { val prefixExpression = element.getWrappingPrefixExpressionIfAny() ?: return null val newExpression = factory.createExpressionByPattern("$0 != $1", receiver, argument, reformat = false) prefixExpression to newExpression } in OperatorConventions.COMPARISON_OPERATIONS -> { val binaryParent = element.parent as? KtBinaryExpression ?: return null val newExpression = factory.createExpressionByPattern("$0 ${operation.value} $1", receiver, argument, reformat = false) binaryParent to newExpression } else -> { val newExpression = factory.createExpressionByPattern("$0 ${operation.value} $1", receiver, argument, reformat = false) element to newExpression } } } private fun PsiElement.getWrappingPrefixExpressionIfAny() = (getLastParentOfTypeInRow<KtParenthesizedExpression>() ?: this).parent as? KtPrefixExpression private fun operation(calleeExpression: KtSimpleNameExpression): KtSingleValueToken? { val identifier = calleeExpression.getReferencedNameAsName() val dotQualified = calleeExpression.parent.parent as? KtDotQualifiedExpression ?: return null val isOperatorOrCompatible by lazy { (calleeExpression.resolveToCall()?.resultingDescriptor as? FunctionDescriptor)?.isOperatorOrCompatible == true } return when (identifier) { OperatorNameConventions.EQUALS -> { if (!dotQualified.isAnyEquals()) return null with(KotlinEqualsBetweenInconvertibleTypesInspection) { val receiver = dotQualified.receiverExpression val argument = dotQualified.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression() if (dotQualified.analyze(BodyResolveMode.PARTIAL).isInconvertibleTypes(receiver, argument)) return null } val prefixExpression = dotQualified.getWrappingPrefixExpressionIfAny() if (prefixExpression != null && prefixExpression.operationToken == KtTokens.EXCL) KtTokens.EXCLEQ else KtTokens.EQEQ } OperatorNameConventions.COMPARE_TO -> { if (!isOperatorOrCompatible) return null // callee -> call -> DotQualified -> Binary val binaryParent = dotQualified.parent as? KtBinaryExpression ?: return null val notZero = when { binaryParent.right?.text == "0" -> binaryParent.left binaryParent.left?.text == "0" -> binaryParent.right else -> return null } if (notZero != dotQualified) return null val token = binaryParent.operationToken as? KtSingleValueToken ?: return null if (token in OperatorConventions.COMPARISON_OPERATIONS) { if (notZero == binaryParent.left) token else token.inverted() } else { null } } else -> { if (!isOperatorOrCompatible) return null OperatorConventions.BINARY_OPERATION_NAMES.inverse()[identifier] } } } private fun KtDotQualifiedExpression.isFloatingPointNumberEquals(): Boolean { val resolvedCall = resolveToCall() ?: return false val resolutionFacade = getResolutionFacade() val context = analyze(resolutionFacade, BodyResolveMode.PARTIAL) val declarationDescriptor = containingDeclarationForPseudocode?.resolveToDescriptorIfAny() val dataFlowValueFactory = resolutionFacade.dataFlowValueFactory val defaultType: (KotlinType, Set<KotlinType>) -> KotlinType = { givenType, stableTypes -> stableTypes.firstOrNull() ?: givenType } val receiverType = resolvedCall.getReceiverExpression()?.getKotlinTypeWithPossibleSmartCastToFP( context, declarationDescriptor, languageVersionSettings, dataFlowValueFactory, defaultType ) ?: return false val argumentType = resolvedCall.getFirstArgumentExpression()?.getKotlinTypeWithPossibleSmartCastToFP( context, declarationDescriptor, languageVersionSettings, dataFlowValueFactory, defaultType ) ?: return false return receiverType.isFpType() && argumentType.isNumericType() || argumentType.isFpType() && receiverType.isNumericType() } private fun KtSimpleNameExpression.isFloatingPointNumberEquals(): Boolean { val dotQualified = parent.parent as? KtDotQualifiedExpression ?: return false return dotQualified.isFloatingPointNumberEquals() } private fun KotlinType.isFpType(): Boolean { return isFloat() || isDouble() } private fun KotlinType.isNumericType(): Boolean { return isFpType() || isByte() || isShort() || isInt() || isLong() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/conventionNameCalls/ReplaceCallWithBinaryOperatorInspection.kt
2576081884
// WITH_STDLIB fun test(list: List<Int>) { val toSortedSet = list.<caret>filter { it > 1 }.toSortedSet() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/toSortedSet.kt
1142489461
val a = 12
plugins/kotlin/idea/tests/testData/formatter/PropertyWithInference.after.kt
1914600209
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.codegen.inline.isInlineOrInsideInline import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType internal fun KtElement.containingFunction(): KtNamedFunction? { val containingDeclaration = containingDeclarationForPseudocode return if (containingDeclaration is KtFunctionLiteral) { val call = containingDeclaration.getStrictParentOfType<KtCallExpression>() if (call?.resolveToCall()?.resultingDescriptor?.isInlineOrInsideInline() == true) { containingDeclaration.containingFunction() } else { null } } else { containingDeclaration as? KtNamedFunction } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/quickFixUtils.kt
168104604
// 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.codeInsight.daemon.impl.quickfix import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase /** * @author Pavel.Dolgov */ class DeleteUnreachableTest : LightQuickFixParameterizedTestCase() { override fun getBasePath() = "/codeInsight/daemonCodeAnalyzer/quickFix/deleteUnreachable" }
java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/quickfix/DeleteUnreachableTest.kt
3510045659
val a = """ | blah blah {<caret>} """.trimMargin() //----- val a = """ | blah blah { | <caret> | } """.trimMargin()
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs2/enterInsideBraces.kt
1346997924
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runToolbar import com.intellij.execution.runToolbar.data.RWSlotManagerState import com.intellij.execution.runToolbar.data.RWStateListener import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.IdeFrame import java.awt.event.ContainerEvent import java.awt.event.ContainerListener import javax.swing.SwingUtilities class RunToolbarMainWidgetComponent(val presentation: Presentation, place: String, group: ActionGroup) : FixWidthSegmentedActionToolbarComponent(place, group) { companion object { private val LOG = Logger.getInstance(RunToolbarMainWidgetComponent::class.java) private var counter: MutableMap<Project, Int> = mutableMapOf() } override fun logNeeded(): Boolean = RunToolbarProcess.logNeeded private var project: Project? = null set(value) { if(field == value) return field?.let { remove(it) } field = value field?.let { add(it) } } private var popupController: RunToolbarPopupController? = null private val componentListener = object : ContainerListener { override fun componentAdded(e: ContainerEvent) { rebuildPopupControllerComponent() } override fun componentRemoved(e: ContainerEvent) { rebuildPopupControllerComponent() } } private val managerStateListener = object : RWStateListener { override fun stateChanged(state: RWSlotManagerState) { updateState() } } private var state: RunToolbarMainSlotState? = null private fun updateState() { state = project?.let { val slotManager = RunToolbarSlotManager.getInstance(it) val value = when (slotManager.getState()) { RWSlotManagerState.SINGLE_MAIN -> { RunToolbarMainSlotState.PROCESS } RWSlotManagerState.SINGLE_PLAIN, RWSlotManagerState.MULTIPLE -> { if(isOpened) RunToolbarMainSlotState.CONFIGURATION else RunToolbarMainSlotState.INFO } RWSlotManagerState.INACTIVE -> { RunToolbarMainSlotState.CONFIGURATION } RWSlotManagerState.MULTIPLE_WITH_MAIN -> { if(isOpened) RunToolbarMainSlotState.PROCESS else RunToolbarMainSlotState.INFO } } value } if(RunToolbarProcess.logNeeded) LOG.info("MAIN SLOT state updated: $state RunToolbar") } override fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) { if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT state: ${state} new filtered: ${filteredIds}} visible: $ides RunToolbar") } internal var isOpened = false set(value) { if(field == value) return field = value if(RunToolbarProcess.logNeeded) LOG.info("MAIN SLOT isOpened: $isOpened RunToolbar") updateState() if (RunToolbarProcess.isExperimentalUpdatingEnabled) { forceUpdate() } } override fun isSuitableAction(action: AnAction): Boolean { return state?.let { if(action is RTBarAction) { action.checkMainSlotVisibility(it) } else true } ?: true } override fun addNotify() { super.addNotify() (SwingUtilities.getWindowAncestor(this) as? IdeFrame)?.project?.let { project = it RUN_CONFIG_WIDTH = RunToolbarSettings.getInstance(it).getRunConfigWidth() } } override fun updateWidthHandler() { super.updateWidthHandler() project?.let { RunToolbarSettings.getInstance(it).setRunConfigWidth(RUN_CONFIG_WIDTH) } } private fun rebuildPopupControllerComponent() { popupController?.let { it.updateControllerComponents(components.filter{it is PopupControllerComponent}.toMutableList()) } } override fun removeNotify() { project = null super.removeNotify() } private fun add(project: Project) { popupController = RunToolbarPopupController(project, this) val value = counter.getOrDefault(project, 0) + 1 counter[project] = value val slotManager = RunToolbarSlotManager.getInstance(project) DataManager.registerDataProvider(component, DataProvider { key -> when { RunToolbarData.RUN_TOOLBAR_DATA_KEY.`is`(key) -> { slotManager.mainSlotData } RunToolbarData.RUN_TOOLBAR_POPUP_STATE_KEY.`is`(key) -> { isOpened } RunToolbarData.RUN_TOOLBAR_MAIN_STATE.`is`(key) -> { state } else -> null } }) if (value == 1) { slotManager.stateListeners.addListener(managerStateListener) slotManager.active = true } rebuildPopupControllerComponent() addContainerListener(componentListener) } private fun remove(project: Project) { RunToolbarSlotManager.getInstance(project).stateListeners.removeListener(managerStateListener) counter[project]?.let { val value = maxOf(it - 1, 0) counter[project] = value if (value == 0) { RunToolbarSlotManager.getInstance(project).active = false counter.remove(project) } } removeContainerListener(componentListener) popupController?.let { if(!Disposer.isDisposed(it)) { Disposer.dispose(it) } } popupController = null state = null } }
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarMainWidgetComponent.kt
412894241
/* * 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. */ class B(val a: Int) fun B.foo() = this.a
backend.native/tests/codegen/function/extension.kt
2099254123
// 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.toolWindow import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.impl.AbstractDroppableStripe import com.intellij.openapi.wm.impl.LayoutData import com.intellij.openapi.wm.impl.SquareStripeButton import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Point import java.awt.Rectangle import javax.swing.JComponent import javax.swing.JPanel internal class ToolWindowLeftToolbar : ToolWindowToolbar() { private class StripeV2(private val toolBar: ToolWindowLeftToolbar, override val anchor: ToolWindowAnchor) : AbstractDroppableStripe(VerticalFlowLayout(0, 0)) { override val isNewStripes: Boolean get() = true override fun getButtonFor(toolWindowId: String) = toolBar.getButtonFor(toolWindowId) override fun getToolWindowFor(component: JComponent) = (component as SquareStripeButton).toolWindow override fun tryDroppingOnGap(data: LayoutData, gap: Int, insertOrder: Int) { toolBar.tryDroppingOnGap(data, gap, dropRectangle) { layoutDragButton(data, gap) } } override fun toString() = "StripeNewUi(anchor=$anchor)" } private val topPane = StripeV2(this, ToolWindowAnchor.LEFT) private val bottomPane = StripeV2(this, ToolWindowAnchor.BOTTOM) val moreButton = MoreSquareStripeButton(this) init { border = JBUI.Borders.customLine(JBUI.CurrentTheme.ToolWindow.borderColor(), 1, 0, 0, 1) topPane.background = JBUI.CurrentTheme.ToolWindow.background() bottomPane.background = JBUI.CurrentTheme.ToolWindow.background() val topWrapper = JPanel(BorderLayout()) topWrapper.add(topPane, BorderLayout.NORTH) add(topWrapper, BorderLayout.NORTH) add(bottomPane, BorderLayout.SOUTH) } override fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe { return when (anchor) { ToolWindowAnchor.LEFT -> topPane ToolWindowAnchor.BOTTOM -> bottomPane ToolWindowAnchor.TOP -> bottomPane else -> throw IllegalArgumentException("Wrong anchor $anchor") } } fun initMoreButton() { topPane.parent?.add(moreButton, BorderLayout.CENTER) } override fun getStripeFor(screenPoint: Point): AbstractDroppableStripe? { if (!isVisible || !moreButton.isVisible) { return null } val moreButtonRect = Rectangle(moreButton.locationOnScreen, moreButton.size) if (Rectangle(topPane.locationOnScreen, topPane.size).contains(screenPoint) || topPane.getButtons().isEmpty() && moreButtonRect.contains(screenPoint)) { return topPane } else if (!moreButtonRect.contains(screenPoint) && Rectangle(locationOnScreen, size).also { JBInsets.removeFrom(it, insets) }.contains(screenPoint)) { return bottomPane } else { return null } } override fun reset() { topPane.reset() bottomPane.reset() } override fun getButtonFor(toolWindowId: String): StripeButtonManager? { return topPane.getButtons().find { it.id == toolWindowId } ?: bottomPane.getButtons().find { it.id == toolWindowId } } }
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowLeftToolbar.kt
2114852449
package alraune import pieces100.* import vgrechka.* abstract class Kate<Fields : BunchOfFields>( val modalTitle: String, val submitButtonTitle: String = AlText.ok, val submitButtonLevel: AlButtonStyle = AlButtonStyle.Primary, val cancelButtonTitle: String = AlText.changedMind) : Dancer<ShitWithContext<ModalShit, Context1>> { abstract fun setInitialFields(fs: Fields) abstract fun makeFields(): Fields abstract fun serveGivenValidFields(fs: Fields) abstract fun ooModalBody(fs: Fields) open fun serveOkButtonForScrewedState() {imf("Hey little bitch, override me")} open fun decorateModal(it: ComposeModalContent) {it.blueLeftMargin()} var modalContentDomid by notNull<String>() override fun dance() : ShitWithContext<ModalShit, Context1> { val fields = useFields(makeFields(), FieldSource.Initial()) setInitialFields(fields) return _modalWithScripts(fields) } class Problems( val errors: Boolean = false, val midAirComparisonPageHref: String? = null, val shitRemoved: Boolean = false) fun _modalWithScripts(fieldsToRender: Fields, problems: Problems = Problems()): ShitWithContext<ModalShit, Context1> { modalContentDomid = uuid_insideIgnoreWhenCheckingForStaleness() return composeModalWithScripts { it.modalDialogDomid = modalContentDomid it.title = modalTitle decorateModal(it) if (problems.shitRemoved) { it.body = div().with { oo(composeRedTriangleBanner("Эту хрень уже удалили. Поздно укакался")) oo(div("У тебя теперь остается тупо один вариант...")) } it.footer = !ButtonBarWithTicker() .tickerLocation(Rightness.Left) .addSubmitFormButton(MinimalButtonShit(t("TOTE", "Я обламываюсь"), AlButtonStyle.Primary, freakingServant {serveOkButtonForScrewedState()})) } else { it.body = div().with { if (problems.errors) oo(composeFixErrorsBelowBanner()) problems.midAirComparisonPageHref?.let { oo(composeMidAirCollisionBanner( toTheRightOfMessage = ComposeChevronLink(t("TOTE", "Сравнить"), it).WithLeftMargin().newTab())) } ooModalBody(fieldsToRender) } it.footer = !ButtonBarWithTicker() .tickerLocation(Rightness.Left) .addSubmitFormButton(when { problems.midAirComparisonPageHref != null -> MinimalButtonShit(t("TOTE", "Затереть и сохранить мое"), AlButtonStyle.Danger, freakingServant { rctx0.al.forceOverwriteStale = true serve() }) else -> MinimalButtonShit(submitButtonTitle, submitButtonLevel, freakingServant {serve()}) }) .addCloseModalButton(cancelButtonTitle) } } } fun serve() { val fs = useFields(makeFields(), FieldSource.Post()) fun notFuckingOk(problems: Problems) { val currentModalContentDomid = modalContentDomid val newMWS = _modalWithScripts(fs, problems) btfEval(jsReplaceElement(currentModalContentDomid, newMWS.shit.modalContent, newMWS.context.onDomReadyPlusOnShown())) btfEval(jsScrollModalToTop()) } if (anyFieldErrors(fs)) { notFuckingOk(Problems(errors = true)) } else { try { serveGivenValidFields(fs) } catch (mac: MidAirCollision) { if (mac.midAirComparisonPageHref != null) notFuckingOk(Problems(midAirComparisonPageHref = mac.midAirComparisonPageHref)) else throw mac } catch (e: ShitRemovedCollision) { notFuckingOk(Problems(shitRemoved = true)) } } } }
alraune/alraune/src/main/java/alraune/Kate.kt
511620103
// 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 training.learn.lesson.general.assistance import com.intellij.codeInsight.documentation.QuickDocUtil import com.intellij.codeInsight.hint.ImplementationViewComponent import org.assertj.swing.timing.Timeout import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LessonsBundle import training.learn.course.KLesson import training.ui.LearningUiUtil import java.util.concurrent.TimeUnit class QuickPopupsLesson(private val sample: LessonSample) : KLesson("CodeAssistance.QuickPopups", LessonsBundle.message("quick.popups.lesson.name")) { override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) task("QuickJavaDoc") { text(LessonsBundle.message("quick.popups.show.documentation", action(it))) triggerOnQuickDocumentationPopup() restoreIfModifiedOrMoved(sample) test { actions(it) } } task { text(LessonsBundle.message("quick.popups.press.escape", action("EditorEscape"))) stateCheck { previous.ui?.isShowing != true } restoreIfModifiedOrMoved() test { invokeActionViaShortcut("ESCAPE") } } task("QuickImplementations") { text(LessonsBundle.message("quick.popups.show.implementation", action(it))) triggerUI().component { _: ImplementationViewComponent -> true } restoreIfModifiedOrMoved() test { actions(it) val delay = Timeout.timeout(3, TimeUnit.SECONDS) LearningUiUtil.findShowingComponentWithTimeout(project, ImplementationViewComponent::class.java, delay) Thread.sleep(500) invokeActionViaShortcut("ESCAPE") } } } private fun TaskRuntimeContext.checkDocComponentClosed(): Boolean { val activeDocComponent = QuickDocUtil.getActiveDocComponent(project) return activeDocComponent == null || !activeDocComponent.isShowing } override val suitableTips = listOf("CtrlShiftIForLookup", "CtrlShiftI", "QuickJavaDoc") override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("quick.popups.help.link"), LessonUtil.getHelpLink("using-code-editor.html#quick_popups")), ) }
plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/QuickPopupsLesson.kt
1972168023
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.ring fun fibonacci(): Sequence<Int> { var a = 0 var b = 1 fun next(): Int { val res = a + b a = b b = res return res } return generateSequence { next() } } fun Any.isPalindrome() = toString() == toString().reversed() inline fun IntRange.sum(predicate: (Int) -> Boolean): Int { var sum = 0 for (i in this) if (predicate(i)) sum += i return sum } inline fun Sequence<Int>.sum(predicate: (Int) -> Boolean): Int { var sum = 0 for (i in this) if (predicate(i)) sum += i return sum } /** * A class tests decisions of various Euler problems * * NB: all tests here work slower than Java, probably because of all these functional wrappers */ open class EulerBenchmark { //Benchmark fun problem1bySequence() = (1..BENCHMARK_SIZE).asSequence().sum( { it % 3 == 0 || it % 5 == 0} ) //Benchmark fun problem1() = (1..BENCHMARK_SIZE).sum( { it % 3 == 0 || it % 5 == 0} ) //Benchmark fun problem2() = fibonacci().takeWhile { it < BENCHMARK_SIZE }.sum { it % 2 == 0 } //Benchmark fun problem4(): Long { val s: Long = BENCHMARK_SIZE.toLong() val maxLimit = (s-1)*(s-1) val minLimit = (s/10)*(s/10) val maxDiv = BENCHMARK_SIZE-1 val minDiv = BENCHMARK_SIZE/10 for (i in maxLimit downTo minLimit) { if (!i.isPalindrome()) continue; for (j in minDiv..maxDiv) { if (i % j == 0L) { val res = i / j if (res in minDiv.toLong()..maxDiv.toLong()) { return i } } } } return -1 } private val veryLongNumber = """ 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 """ //Benchmark fun problem8(): Long { val productSize = when(BENCHMARK_SIZE) { in 1..10 -> 4 in 11..1000 -> 8 else -> 13 } val digits: MutableList<Int> = ArrayList() for (digit in veryLongNumber) { if (digit in '0'..'9') { digits.add(digit.toInt() - '0'.toInt()) } } var largest = 0L for (i in 0..digits.size -productSize-1) { var product = 1L for (j in 0..productSize-1) { product *= digits[i+j] } if (product > largest) largest = product } return largest } //Benchmark fun problem9(): Long { val BENCHMARK_SIZE = BENCHMARK_SIZE // Looks awful but removes all implicit getSize() calls for (c in BENCHMARK_SIZE/3..BENCHMARK_SIZE-3) { val c2 = c.toLong() * c.toLong() for (b in (BENCHMARK_SIZE-c)/2..c-1) { if (b+c >= BENCHMARK_SIZE) break val a = BENCHMARK_SIZE - b - c if (a >= b) continue val b2 = b.toLong() * b.toLong() val a2 = a.toLong() * a.toLong() if (c2 == b2 + a2) { return a.toLong() * b.toLong() * c.toLong() } } } return -1L } data class Children(val left: Int, val right: Int) //Benchmark fun problem14(): List<Int> { // Simplified problem is solved here: it's not allowed to leave the interval [0..BENCHMARK_SIZE) inside a number chain val BENCHMARK_SIZE = BENCHMARK_SIZE // Build a tree // index is produced from first & second val tree = Array(BENCHMARK_SIZE, { i -> Children(i*2, if (i>4 && (i+2) % 6 == 0) (i-1)/3 else 0)}) // Find longest chain by DFS fun dfs(begin: Int): List<Int> { if (begin == 0 || begin >= BENCHMARK_SIZE) return listOf() val left = dfs(tree[begin].left) val right = dfs(tree[begin].right) return listOf(begin) + if (left.size > right.size) left else right } return dfs(1) } data class Way(val length: Int, val next: Int) //Benchmark fun problem14full(): List<Int> { val BENCHMARK_SIZE = BENCHMARK_SIZE // Previous achievements: map (number) -> (length, next) val map: MutableMap<Int, Way> = HashMap() // Starting point map.put(1, Way(0, 0)) // Check all other numbers var bestNum = 0 var bestLen = 0 fun go(begin: Int): Way { val res = map[begin] if (res != null) return res val next = if (begin % 2 == 0) begin/2 else 3*begin+1 val childRes = go(next) val myRes = Way(childRes.length + 1, next) map[begin] = myRes return myRes } for (i in 2..BENCHMARK_SIZE-1) { val res = go(i) if (res.length > bestLen) { bestLen = res.length bestNum = i } } fun unroll(begin: Int): List<Int> { if (begin == 0) return listOf() val next = map[begin]?.next ?: 0 return listOf(begin) + unroll(next) } return unroll(bestNum) } }
performance/ring/src/main/kotlin/org/jetbrains/ring/EulerBenchmark.kt
845457575
// "Delete redundant extension property" "false" // ACTION: Convert property to function // ACTION: Do not show return expression hints // ACTION: Move to companion object // ACTION: Remove explicit type specification class C : Thread() { val Thread.<caret>priority: Int get() = [email protected]() }
plugins/kotlin/idea/tests/testData/quickfix/migration/conflictingExtension/wrongExplicitThis.kt
2771544526
// 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 com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ArtifactsOrderEntityImpl(val dataSource: ArtifactsOrderEntityData) : ArtifactsOrderEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val orderOfArtifacts: List<String> get() = dataSource.orderOfArtifacts override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ArtifactsOrderEntityData?) : ModifiableWorkspaceEntityBase<ArtifactsOrderEntity, ArtifactsOrderEntityData>( result), ArtifactsOrderEntity.Builder { constructor() : this(ArtifactsOrderEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ArtifactsOrderEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isOrderOfArtifactsInitialized()) { error("Field ArtifactsOrderEntity#orderOfArtifacts should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_orderOfArtifacts = getEntityData().orderOfArtifacts if (collection_orderOfArtifacts is MutableWorkspaceList<*>) { collection_orderOfArtifacts.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ArtifactsOrderEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.orderOfArtifacts != dataSource.orderOfArtifacts) this.orderOfArtifacts = dataSource.orderOfArtifacts.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } private val orderOfArtifactsUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("orderOfArtifacts") } override var orderOfArtifacts: MutableList<String> get() { val collection_orderOfArtifacts = getEntityData().orderOfArtifacts if (collection_orderOfArtifacts !is MutableWorkspaceList) return collection_orderOfArtifacts if (diff == null || modifiable.get()) { collection_orderOfArtifacts.setModificationUpdateAction(orderOfArtifactsUpdater) } else { collection_orderOfArtifacts.cleanModificationUpdateAction() } return collection_orderOfArtifacts } set(value) { checkModificationAllowed() getEntityData(true).orderOfArtifacts = value orderOfArtifactsUpdater.invoke(value) } override fun getEntityClass(): Class<ArtifactsOrderEntity> = ArtifactsOrderEntity::class.java } } class ArtifactsOrderEntityData : WorkspaceEntityData<ArtifactsOrderEntity>() { lateinit var orderOfArtifacts: MutableList<String> fun isOrderOfArtifactsInitialized(): Boolean = ::orderOfArtifacts.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ArtifactsOrderEntity> { val modifiable = ArtifactsOrderEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ArtifactsOrderEntity { return getCached(snapshot) { val entity = ArtifactsOrderEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): ArtifactsOrderEntityData { val clonedEntity = super.clone() clonedEntity as ArtifactsOrderEntityData clonedEntity.orderOfArtifacts = clonedEntity.orderOfArtifacts.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ArtifactsOrderEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ArtifactsOrderEntity(orderOfArtifacts, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ArtifactsOrderEntityData if (this.entitySource != other.entitySource) return false if (this.orderOfArtifacts != other.orderOfArtifacts) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ArtifactsOrderEntityData if (this.orderOfArtifacts != other.orderOfArtifacts) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + orderOfArtifacts.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + orderOfArtifacts.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.orderOfArtifacts?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ArtifactsOrderEntityImpl.kt
1271339614
package io.github.sdsstudios.ScoreKeeper.ViewHolders import android.content.Context import io.github.sdsstudios.ScoreKeeper.R import ir.coderz.ghostadapter.BindItem /** * Created by sethsch1 on 06/11/17. */ @BindItem(layout = R.layout.view_holder_notes, holder = EditTextHolder::class) class NotesItem(ctx: Context, hintId: Int ) : StringEditTextItem(ctx, hintId) { override var error = false }
app/src/main/java/io/github/sdsstudios/ScoreKeeper/ViewHolders/NotesItem.kt
3183391012
// 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.project.test.base.jvm.utils import java.lang.management.ManagementFactory object JvmRuntimeUtils { fun getGCTime(): Long { var result: Long = 0 for (garbageCollectorMXBean in ManagementFactory.getGarbageCollectorMXBeans()) { result += garbageCollectorMXBean.collectionTime } return result } fun getJitTime(): Long { return ManagementFactory.getCompilationMXBean().totalCompilationTime } }
plugins/kotlin/project-tests/project-tests-base/test/org/jetbrains/kotlin/idea/project/test/base/jvm/utils/JvmRuntimeUtils.kt
62873861
// 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.newProject.steps import com.intellij.execution.ExecutionException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathMappingSettings import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.UIUtil import com.jetbrains.python.PyBundle import com.jetbrains.python.PySdkBundle import com.jetbrains.python.Result import com.jetbrains.python.remote.PyProjectSynchronizer import com.jetbrains.python.remote.PyProjectSynchronizerProvider import com.jetbrains.python.remote.PythonSshInterpreterManager import com.jetbrains.python.sdk.PythonSdkUtil import com.jetbrains.python.sdk.add.PyAddSdkPanel import com.jetbrains.python.sdk.associatedModulePath import com.jetbrains.python.sdk.sdkSeemsValid import java.awt.BorderLayout import java.awt.Component import javax.swing.JComboBox import javax.swing.JComponent /** * @author vlan */ class PyAddExistingSdkPanel(project: Project?, module: Module?, existingSdks: List<Sdk>, newProjectPath: String?, preferredSdk: Sdk?) : PyAddSdkPanel() { override val panelName: String get() = PyBundle.message("python.add.sdk.panel.name.previously.configured.interpreter") /** * Path mappings of current synchronizer. * Once set, [remotePathField] will be updated on any change of local path passed through mappings */ private var defaultMappings: List<PathMappingSettings.PathMapping>? = null override val sdk: Sdk? get() = sdkComboBox.selectedItem as? Sdk /** * Either a [ComboBox] with "Add Interpreter" link component for targets-based UI or a combobox of the legacy [PythonSdkChooserCombo]. * * The rollback to the latter option is possible by switching off *python.use.targets.api* registry key. */ private val sdkComboBox: JComboBox<*> private val addSdkChangedListener: (Runnable) -> Unit val remotePath: String? get() = if (remotePathField.mainPanel.isVisible) remotePathField.textField.text else null override var newProjectPath: String? = newProjectPath set(value) { field = value updateRemotePathIfNeeded() } private val remotePathField = PyRemotePathField().apply { addActionListener { val currentSdk = sdk ?: return@addActionListener if (!PythonSdkUtil.isRemote(currentSdk)) return@addActionListener textField.text = currentSdk.chooseRemotePath(parent) ?: return@addActionListener } } init { layout = BorderLayout() val sdksForNewProject = existingSdks.filter { it.associatedModulePath == null } val interpreterComponent: JComponent if (Registry.`is`("python.use.targets.api")) { val preselectedSdk = sdksForNewProject.firstOrNull { it == preferredSdk } val pythonSdkComboBox = createPythonSdkComboBox(sdksForNewProject, preselectedSdk) pythonSdkComboBox.addActionListener { update() } interpreterComponent = pythonSdkComboBox.withAddInterpreterLink(project, module) sdkComboBox = pythonSdkComboBox addSdkChangedListener = { runnable -> sdkComboBox.addActionListener { runnable.run() } } } else { val legacySdkChooser = PythonSdkChooserCombo(project, module, sdksForNewProject) { it != null && it == preferredSdk }.apply { if (SystemInfo.isMac && !UIUtil.isUnderDarcula()) { putClientProperty("JButton.buttonType", null) } addChangedListener { update() } } interpreterComponent = legacySdkChooser sdkComboBox = legacySdkChooser.comboBox addSdkChangedListener = { runnable -> legacySdkChooser.addChangedListener { runnable.run() } } } val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent(PySdkBundle.message("python.interpreter.label"), interpreterComponent) .addComponent(remotePathField.mainPanel) .panel add(formPanel, BorderLayout.NORTH) update() } override fun validateAll(): List<ValidationInfo> = listOf(validateSdkChooserField(), validateRemotePathField()) .filterNotNull() override fun addChangeListener(listener: Runnable) { addSdkChangedListener(listener) remotePathField.addTextChangeListener { listener.run() } } private fun validateSdkChooserField(): ValidationInfo? { val selectedSdk = sdk val message = when { selectedSdk == null -> PyBundle.message("python.sdk.no.interpreter.selection") ! selectedSdk.sdkSeemsValid -> PyBundle.message("python.sdk.choose.valid.interpreter") else -> return null } return ValidationInfo(message, sdkComboBox) } private fun validateRemotePathField(): ValidationInfo? { val path = remotePath return when { path != null && path.isBlank() -> ValidationInfo(PyBundle.message("python.new.project.remote.path.not.provided")) else -> null } } private fun update() { val synchronizer = sdk?.projectSynchronizer remotePathField.mainPanel.isVisible = synchronizer != null if (synchronizer != null) { val defaultRemotePath = synchronizer.getDefaultRemotePath() synchronizer.getAutoMappings()?.let { when (it) { is Result.Success -> defaultMappings = it.result is Result.Failure -> { remotePathField.textField.text = it.error remotePathField.setReadOnly(true) return } } } assert(defaultRemotePath == null || defaultMappings == null) { "Can't have both: default mappings and default value" } assert(!(defaultRemotePath?.isEmpty() ?: false)) { "Mappings are empty" } val textField = remotePathField.textField if (defaultRemotePath != null && StringUtil.isEmpty(textField.text)) { textField.text = defaultRemotePath } } // DefaultMappings revokes user ability to change mapping by her self, so field is readonly remotePathField.setReadOnly(defaultMappings != null) updateRemotePathIfNeeded() } /** * Remote path should be updated automatically if [defaultMappings] are set. * See [PyProjectSynchronizer.getAutoMappings]. */ private fun updateRemotePathIfNeeded() { val path = newProjectPath ?: return val mappings = defaultMappings ?: return remotePathField.textField.text = mappings.find { it.canReplaceLocal(path) }?.mapToRemote(path) ?: "?" } companion object { private val Sdk.projectSynchronizer: PyProjectSynchronizer? get() = PyProjectSynchronizerProvider.getSynchronizer(this) private fun Sdk.chooseRemotePath(owner: Component): String? { val remoteManager = PythonSshInterpreterManager.Factory.getInstance() ?: return null val (supplier, panel) = try { remoteManager.createServerBrowserForm(this) ?: return null } catch (e: Exception) { when (e) { is ExecutionException, is InterruptedException -> { Logger.getInstance(PyAddExistingSdkPanel::class.java).warn("Failed to create server browse button", e) JBPopupFactory.getInstance() .createMessage(PyBundle.message("remote.interpreter.remote.server.permissions")) .show(owner) return null } else -> throw e } } panel.isVisible = true val wrapper = object : DialogWrapper(true) { init { init() } override fun createCenterPanel() = panel } return if (wrapper.showAndGet()) supplier.get() else null } } }
python/src/com/jetbrains/python/newProject/steps/PyAddExistingSdkPanel.kt
1283707887
// 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.findUsages import com.intellij.psi.PsiElement import com.intellij.testFramework.assertEqualsToFile import org.jetbrains.kotlin.idea.findUsages.similarity.KotlinUsageSimilarityFeaturesProvider import java.io.File abstract class AbstractKotlinGroupUsagesBySimilarityFeaturesTest : AbstractFindUsagesTest() { override fun <T : PsiElement> doTest(path: String) { myFixture.configureByFile(getTestName(true) + ".kt") val elementAtCaret = myFixture.getReferenceAtCaretPosition()!!.element val features = KotlinUsageSimilarityFeaturesProvider().getFeatures(elementAtCaret) val file = File(testDataDirectory, getTestName(true) + ".features.txt") assertEqualsToFile("", file, features.bag.map { """${it.key} => ${it.value}""" }.joinToString(separator = ",\n")) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/AbstractKotlinGroupUsagesBySimilarityFeaturesTest.kt
3853570870
// 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.nj2k.types import com.intellij.psi.* import com.intellij.psi.impl.compiled.ClsMethodImpl import com.intellij.psi.impl.source.PsiAnnotationMethodImpl import org.jetbrains.kotlin.builtins.PrimitiveType import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.base.utils.fqname.fqName import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.util.getParameterDescriptor import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.j2k.ast.Nullability.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.JKSymbolProvider import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol import org.jetbrains.kotlin.nj2k.symbols.JKMethodSymbol import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKVarianceTypeParameterType.Variance import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* fun JKType.asTypeElement(annotationList: JKAnnotationList = JKAnnotationList()) = JKTypeElement(this, annotationList) fun JKClassSymbol.asType(nullability: Nullability = Default): JKClassType = JKClassType(this, emptyList(), nullability) val PsiType.isKotlinFunctionalType: Boolean get() { val fqName = safeAs<PsiClassType>()?.resolve()?.kotlinFqName ?: return false return functionalTypeRegex.matches(fqName.asString()) } fun PsiParameter.typeFqName(): FqName? = this.getParameterDescriptor()?.type?.fqName fun KtParameter.typeFqName(): FqName? = this.descriptor?.type?.fqName private val functionalTypeRegex = """(kotlin\.jvm\.functions|kotlin)\.Function[\d+]""".toRegex() fun KtTypeReference.toJK(typeFactory: JKTypeFactory): JKType? = analyze(BodyResolveMode.PARTIAL) .get(BindingContext.TYPE, this) ?.let { typeFactory.fromKotlinType(it) } infix fun JKJavaPrimitiveType.isStrongerThan(other: JKJavaPrimitiveType) = jvmPrimitiveTypesPriority.getValue(this.jvmPrimitiveType.primitiveType) > jvmPrimitiveTypesPriority.getValue(other.jvmPrimitiveType.primitiveType) private val jvmPrimitiveTypesPriority = mapOf( PrimitiveType.BOOLEAN to -1, PrimitiveType.CHAR to 0, PrimitiveType.BYTE to 1, PrimitiveType.SHORT to 2, PrimitiveType.INT to 3, PrimitiveType.LONG to 4, PrimitiveType.FLOAT to 5, PrimitiveType.DOUBLE to 6 ) fun JKType.applyRecursive(transform: (JKType) -> JKType?): JKType = transform(this) ?: when (this) { is JKTypeParameterType -> this is JKClassType -> JKClassType( classReference, parameters.map { it.applyRecursive(transform) }, nullability ) is JKNoType -> this is JKJavaVoidType -> this is JKJavaPrimitiveType -> this is JKJavaArrayType -> JKJavaArrayType(type.applyRecursive(transform), nullability) is JKContextType -> JKContextType is JKJavaDisjunctionType -> JKJavaDisjunctionType(disjunctions.map { it.applyRecursive(transform) }, nullability) is JKStarProjectionType -> this else -> this } inline fun <reified T : JKType> T.updateNullability(newNullability: Nullability): T = if (nullability == newNullability) this else when (this) { is JKTypeParameterType -> JKTypeParameterType(identifier, newNullability) is JKClassType -> JKClassType(classReference, parameters, newNullability) is JKNoType -> this is JKJavaVoidType -> this is JKJavaPrimitiveType -> this is JKJavaArrayType -> JKJavaArrayType(type, newNullability) is JKContextType -> JKContextType is JKJavaDisjunctionType -> this else -> this } as T @Suppress("UNCHECKED_CAST") fun <T : JKType> T.updateNullabilityRecursively(newNullability: Nullability): T = applyRecursive { type -> when (type) { is JKTypeParameterType -> JKTypeParameterType(type.identifier, newNullability) is JKClassType -> JKClassType( type.classReference, type.parameters.map { it.updateNullabilityRecursively(newNullability) }, newNullability ) is JKJavaArrayType -> JKJavaArrayType(type.type.updateNullabilityRecursively(newNullability), newNullability) else -> null } } as T fun JKType.isStringType(): Boolean = (this as? JKClassType)?.classReference?.isStringType() == true fun JKClassSymbol.isStringType(): Boolean = fqName == CommonClassNames.JAVA_LANG_STRING || fqName == StandardNames.FqNames.string.asString() fun JKJavaPrimitiveType.toLiteralType(): JKLiteralExpression.LiteralType? = when (this) { JKJavaPrimitiveType.CHAR -> JKLiteralExpression.LiteralType.CHAR JKJavaPrimitiveType.BOOLEAN -> JKLiteralExpression.LiteralType.BOOLEAN JKJavaPrimitiveType.INT -> JKLiteralExpression.LiteralType.INT JKJavaPrimitiveType.LONG -> JKLiteralExpression.LiteralType.LONG JKJavaPrimitiveType.DOUBLE -> JKLiteralExpression.LiteralType.DOUBLE JKJavaPrimitiveType.FLOAT -> JKLiteralExpression.LiteralType.FLOAT else -> null } fun JKType.asPrimitiveType(): JKJavaPrimitiveType? = if (this is JKJavaPrimitiveType) this else when (fqName) { StandardNames.FqNames._char.asString(), CommonClassNames.JAVA_LANG_CHARACTER -> JKJavaPrimitiveType.CHAR StandardNames.FqNames._boolean.asString(), CommonClassNames.JAVA_LANG_BOOLEAN -> JKJavaPrimitiveType.BOOLEAN StandardNames.FqNames._int.asString(), CommonClassNames.JAVA_LANG_INTEGER -> JKJavaPrimitiveType.INT StandardNames.FqNames._long.asString(), CommonClassNames.JAVA_LANG_LONG -> JKJavaPrimitiveType.LONG StandardNames.FqNames._float.asString(), CommonClassNames.JAVA_LANG_FLOAT -> JKJavaPrimitiveType.FLOAT StandardNames.FqNames._double.asString(), CommonClassNames.JAVA_LANG_DOUBLE -> JKJavaPrimitiveType.DOUBLE StandardNames.FqNames._byte.asString(), CommonClassNames.JAVA_LANG_BYTE -> JKJavaPrimitiveType.BYTE StandardNames.FqNames._short.asString(), CommonClassNames.JAVA_LANG_SHORT -> JKJavaPrimitiveType.SHORT else -> null } fun JKJavaPrimitiveType.isNumberType() = this == JKJavaPrimitiveType.INT || this == JKJavaPrimitiveType.LONG || this == JKJavaPrimitiveType.FLOAT || this == JKJavaPrimitiveType.DOUBLE fun JKJavaPrimitiveType.kotlinName() = jvmPrimitiveType.javaKeywordName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.US) else it.toString() } val primitiveTypes = listOf( JvmPrimitiveType.BOOLEAN, JvmPrimitiveType.CHAR, JvmPrimitiveType.BYTE, JvmPrimitiveType.SHORT, JvmPrimitiveType.INT, JvmPrimitiveType.FLOAT, JvmPrimitiveType.LONG, JvmPrimitiveType.DOUBLE ) fun JKType.arrayFqName(): String = if (this is JKJavaPrimitiveType) PrimitiveType.valueOf(jvmPrimitiveType.name).arrayTypeFqName.asString() else StandardNames.FqNames.array.asString() fun JKClassSymbol.isArrayType(): Boolean = fqName in arrayFqNames private val arrayFqNames = buildList { JKJavaPrimitiveType.ALL.mapTo(this) { PrimitiveType.valueOf(it.jvmPrimitiveType.name).arrayTypeFqName.asString() } add(StandardNames.FqNames.array.asString()) } fun JKType.isArrayType() = when (this) { is JKClassType -> classReference.isArrayType() is JKJavaArrayType -> true else -> false } fun JKType.isUnit(): Boolean = fqName == StandardNames.FqNames.unit.asString() val JKType.isCollectionType: Boolean get() = fqName in collectionFqNames val JKType.fqName: String? get() = safeAs<JKClassType>()?.classReference?.fqName private val collectionFqNames = setOf( StandardNames.FqNames.mutableIterator.asString(), StandardNames.FqNames.mutableList.asString(), StandardNames.FqNames.mutableCollection.asString(), StandardNames.FqNames.mutableSet.asString(), StandardNames.FqNames.mutableMap.asString(), StandardNames.FqNames.mutableMapEntry.asString(), StandardNames.FqNames.mutableListIterator.asString() ) fun JKType.arrayInnerType(): JKType? = when (this) { is JKJavaArrayType -> type is JKClassType -> if (this.classReference.isArrayType()) this.parameters.singleOrNull() else null else -> null } fun JKMethodSymbol.isAnnotationMethod(): Boolean = when (val target = target) { is JKJavaAnnotationMethod, is PsiAnnotationMethodImpl -> true is ClsMethodImpl -> target.containingClass?.isAnnotationType == true else -> false } fun JKClassSymbol.isInterface(): Boolean { return when (val target = target) { is PsiClass -> target.isInterface is KtClass -> target.isInterface() is JKClass -> target.classKind == JKClass.ClassKind.INTERFACE else -> false } } fun JKType.isInterface(): Boolean = (this as? JKClassType)?.classReference?.isInterface() ?: false fun JKType.replaceJavaClassWithKotlinClassType(symbolProvider: JKSymbolProvider): JKType = applyRecursive { type -> if (type is JKClassType && type.classReference.fqName == "java.lang.Class") { JKClassType( symbolProvider.provideClassSymbol(StandardNames.FqNames.kClass.toSafe()), type.parameters.map { it.replaceJavaClassWithKotlinClassType(symbolProvider) }, NotNull ) } else null } fun JKLiteralExpression.isNull(): Boolean = this.type == JKLiteralExpression.LiteralType.NULL fun JKParameter.determineType(symbolProvider: JKSymbolProvider): JKType = if (isVarArgs) { val typeParameters = if (type.type is JKJavaPrimitiveType) emptyList() else listOf(JKVarianceTypeParameterType(Variance.OUT, type.type)) JKClassType(symbolProvider.provideClassSymbol(type.type.arrayFqName()), typeParameters, NotNull) } else type.type
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/types/typesUtils.kt
1833147791
// PROBLEM: none package my.simple.name import my.simple.name.Bar.Foo.Companion.CheckClass class Bar { class Foo { companion object { class CheckClass } } } class F { fun foo(a: Bar<caret>.Foo.Companion.CheckClass) {} companion object { class CheckClass } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantQualifierName/notApplicableCompanionType.kt
2142910718
package notExcludedPackage class SomeOtherClass
plugins/kotlin/completion/tests/testData/basic/multifile/ClassInExcludedPackage/ClassInExcludedPackage.dependency2.kt
4123411111
// API_VERSION: 1.4 // WITH_STDLIB val x = listOf("a" to 1, "c" to 3, "b" to 2).<caret>sortedByDescending { it.second }.firstOrNull()
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedByDescendingFirstOrNull2.kt
2570175845
/* * 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.ui.theme import androidx.compose.ui.unit.dp val Keyline1 = 24.dp
Jetcaster/app/src/main/java/com/example/jetcaster/ui/theme/Keylines.kt
2536066083
// 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.ide.konan.gradle import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradleImportingTestCase import java.io.File abstract class TestCaseWithFakeKotlinNative : KotlinGradleImportingTestCase() { protected fun configureProject() { configureByFiles() // include data dir with fake Kotlin/Native libraries val testSuiteDataDir = testDataDirectory().parentFile val kotlinNativeHome = testSuiteDataDir.resolve(FAKE_KOTLIN_NATIVE_HOME_RELATIVE_PATH) kotlinNativeHome.walkTopDown() .filter { it.isFile } .forEach { pathInTestSuite -> // need to put copied file one directory upper than the project root, so adding ".." to the beginning of relative path // reason: distribution KLIBs should not be appear in IDEA indexes, so they should be located outside of the project root val relativePathInProject = DOUBLE_DOT_PATH.resolve(pathInTestSuite.relativeTo(testSuiteDataDir)) createProjectSubFile(relativePathInProject.toString(), pathInTestSuite.readText()) } } } internal val FAKE_KOTLIN_NATIVE_HOME_RELATIVE_PATH = File("kotlin-native-data-dir", "kotlin-native-PLATFORM-VERSION") internal val DOUBLE_DOT_PATH = File("..")
plugins/kotlin/gradle/gradle-native/tests/test/org/jetbrains/kotlin/ide/konan/gradle/TestCaseWithFakeKotlinNative.kt
2229697018
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.daemon.quickFix import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix import com.intellij.codeInsight.daemon.impl.quickfix.AddUsesDirectiveFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.openapi.command.WriteCommandAction import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiJavaModule class AddModuleDirectiveTest : LightJava9ModulesCodeInsightFixtureTestCase() { fun testNewRequires() = doRequiresTest( "module M { }", "module M {\n" + " requires M2;\n" + "}") fun testRequiresAfterOther() = doRequiresTest( "module M {\n" + " requires other;\n" + "}", "module M {\n" + " requires other;\n" + " requires M2;\n" + "}") fun testNoDuplicateRequires() = doRequiresTest( "module M { requires M2; }", "module M { requires M2; }") fun testRequiresInIncompleteModule() = doRequiresTest( "module M {", "module M {\n" + " requires M2;") fun testNewExports() = doExportsTest( "module M { }", "module M {\n" + " exports pkg.m;\n" + "}") fun testExportsAfterOther() = doExportsTest( "module M {\n" + " exports pkg.other;\n" + "}", "module M {\n" + " exports pkg.other;\n" + " exports pkg.m;\n" + "}") fun testNoNarrowingExports() = doExportsTest( "module M { exports pkg.m; }", "module M { exports pkg.m; }") fun testNoDuplicateExports() = doExportsTest( "module M { exports pkg.m to M1, M2; }", "module M { exports pkg.m to M1, M2; }") fun testNoExportsToUnnamed() = doExportsTest( "module M { exports pkg.m to M1; }", "module M { exports pkg.m to M1; }", target = "") fun testExportsExtendsOther() = doExportsTest( "module M {\n" + " exports pkg.m to M1;\n" + "}", "module M {\n" + " exports pkg.m to M1, M2;\n" + "}") fun testExportsExtendsIncompleteOther() = doExportsTest( "module M {\n" + " exports pkg.m to M1\n" + "}", "module M {\n" + " exports pkg.m to M1, M2\n" + "}") fun testNewUses() = doUsesTest( "module M { }", "module M {\n" + " uses pkg.m.C;\n" + "}") fun testUsesAfterOther() = doUsesTest( "module M {\n" + " uses pkg.m.B;\n" + "}", "module M {\n" + " uses pkg.m.B;\n" + " uses pkg.m.C;\n" + "}") fun testNoDuplicateUses() = doUsesTest( "module M { uses pkg.m.C; }", "module M { uses pkg.m.C; }") private fun doRequiresTest(text: String, expected: String) = doTest(text, { AddRequiresDirectiveFix(it, "M2") }, expected) private fun doExportsTest(text: String, expected: String, target: String = "M2") = doTest(text, { AddExportsDirectiveFix(it, "pkg.m", target) }, expected) private fun doUsesTest(text: String, expected: String) = doTest(text, { AddUsesDirectiveFix(it, "pkg.m.C") }, expected) private fun doTest(text: String, fix: (PsiJavaModule) -> IntentionAction, expected: String) { val file = myFixture.configureByText("module-info.java", text) as PsiJavaFile val action = fix(file.moduleDeclaration!!) WriteCommandAction.writeCommandAction(file).run<RuntimeException> { action.invoke(project, editor, file) } assertEquals(expected, file.text) } }
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/AddModuleDirectiveTest.kt
1153874096
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui.browser import com.intellij.diff.DiffContentFactory import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.trimExpandText import com.intellij.diff.lang.DiffIgnoredRangeProvider import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ByteBackedContentRevision import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ui.ChangesComparator import com.intellij.util.ModalityUiUtil import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NotNull class ChangesFilterer(val project: Project?, val listener: Listener) : Disposable { companion object { @JvmField val DATA_KEY: DataKey<ChangesFilterer> = DataKey.create("com.intellij.openapi.vcs.changes.ui.browser.ChangesFilterer") } private val LOCK = Any() private val updateQueue = MergingUpdateQueue("ChangesFilterer", 300, true, MergingUpdateQueue.ANY_COMPONENT, this) private var progressIndicator: ProgressIndicator = EmptyProgressIndicator() private var rawChanges: List<Change>? = null private var activeFilter: Filter? = null private var processedChanges: List<Change>? = null private var pendingChanges: List<Change>? = null private var filteredOutChanges: List<Change>? = null override fun dispose() { resetFilter() } @RequiresEdt fun setChanges(changes: List<Change>?) { val oldChanges = rawChanges if (oldChanges == null && changes == null) return if (oldChanges != null && changes != null && ContainerUtil.equalsIdentity(oldChanges, changes)) return rawChanges = changes?.toList() if (activeFilter != null) { restartLoading() } } @RequiresEdt fun getFilteredChanges(): FilteredState { synchronized(LOCK) { val processed = processedChanges val pending = pendingChanges val filteredOut = filteredOutChanges return when { processed != null && pending != null && filteredOut != null -> FilteredState.create(processed, pending, filteredOut) else -> FilteredState.create(rawChanges ?: emptyList()) } } } @RequiresEdt fun getProgress(): Float { val pendingCount = synchronized(LOCK) { pendingChanges?.size } val totalCount = rawChanges?.size if (pendingCount == null || totalCount == null || totalCount == 0) return 1.0f return (1.0f - pendingCount.toFloat() / totalCount).coerceAtLeast(0.0f) } @NotNull fun hasActiveFilter(): Boolean = activeFilter != null fun clearFilter() = setFilter(null) private fun setFilter(filter: Filter?) { activeFilter = filter restartLoading() } private fun restartLoading() { val indicator = resetFilter() val filter = activeFilter val changesToFilter = rawChanges if (filter == null || changesToFilter == null) { updatePresentation() return } val changes = changesToFilter.sortedWith(ChangesComparator.getInstance(false)) // Work around expensive removeAt(0) with double reversion val pending = changes.asReversed().asSequence().map { Change(it.beforeRevision, it.afterRevision, FileStatus.OBSOLETE) } .toMutableList().asReversed() val processed = mutableListOf<Change>() val filteredOut = mutableListOf<Change>() synchronized(LOCK) { processedChanges = processed pendingChanges = pending filteredOutChanges = filteredOut } updatePresentation() ApplicationManager.getApplication().executeOnPooledThread { ProgressManager.getInstance().runProcess( { filterChanges(changes, filter, pending, processed, filteredOut) }, indicator) } } private fun filterChanges(changes: List<Change>, filter: Filter, pending: MutableList<Change>, processed: MutableList<Change>, filteredOut: MutableList<Change>) { queueUpdatePresentation() val filteredChanges = filter.acceptBulk(this, changes) if (filteredChanges != null) { synchronized(LOCK) { ProgressManager.checkCanceled() pending.clear() processed.addAll(filteredChanges) val filteredOutSet = changes.toMutableSet() filteredOutSet.removeAll(filteredChanges) filteredOut.addAll(filteredOutSet) } updatePresentation() return } for (change in changes) { ProgressManager.checkCanceled() val accept = filter.accept(this, change) synchronized(LOCK) { ProgressManager.checkCanceled() pending.removeAt(0) if (accept) { processed.add(change) } else { filteredOut.add(change) } } queueUpdatePresentation() } updatePresentation() } private fun queueUpdatePresentation() { updateQueue.queue(DisposableUpdate.createDisposable(updateQueue, "update") { updatePresentation() }) } private fun updatePresentation() { ModalityUiUtil.invokeLaterIfNeeded( ModalityState.any()) { updateQueue.cancelAllUpdates() listener.updateChanges() } } private fun resetFilter(): ProgressIndicator { synchronized(LOCK) { processedChanges = null pendingChanges = null filteredOutChanges = null progressIndicator.cancel() progressIndicator = EmptyProgressIndicator() return progressIndicator } } private interface Filter { fun isAvailable(filterer: ChangesFilterer): Boolean = true fun accept(filterer: ChangesFilterer, change: Change): Boolean fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? = null @Nls fun getText(): String @Nls fun getDescription(): String? = null } private object MovesOnlyFilter : Filter { override fun getText(): String = VcsBundle.message("action.filter.moved.files.text") override fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? { for (epFilter in BulkMovesOnlyChangesFilter.EP_NAME.extensionList) { val filteredChanges = epFilter.filter(filterer.project, changes) if (filteredChanges != null) { return filteredChanges } } return null } override fun accept(filterer: ChangesFilterer, change: Change): Boolean { val bRev = change.beforeRevision ?: return true val aRev = change.afterRevision ?: return true if (bRev.file == aRev.file) return true if (bRev is ByteBackedContentRevision && aRev is ByteBackedContentRevision) { val bytes1 = bRev.contentAsBytes ?: return true val bytes2 = aRev.contentAsBytes ?: return true return !bytes1.contentEquals(bytes2) } else { val content1 = bRev.content ?: return true val content2 = aRev.content ?: return true return content1 != content2 } } } private object NonImportantFilter : Filter { override fun getText(): String = VcsBundle.message("action.filter.non.important.files.text") override fun isAvailable(filterer: ChangesFilterer): Boolean = filterer.project != null override fun accept(filterer: ChangesFilterer, change: Change): Boolean { val project = filterer.project val bRev = change.beforeRevision ?: return true val aRev = change.afterRevision ?: return true val content1 = bRev.content ?: return true val content2 = aRev.content ?: return true val diffContent1 = DiffContentFactory.getInstance().create(project, content1, bRev.file) val diffContent2 = DiffContentFactory.getInstance().create(project, content2, aRev.file) val provider = DiffIgnoredRangeProvider.EP_NAME.extensions.find { it.accepts(project, diffContent1) && it.accepts(project, diffContent2) } if (provider == null) return content1 != content2 val ignoredRanges1 = provider.getIgnoredRanges(project, content1, diffContent1) val ignoredRanges2 = provider.getIgnoredRanges(project, content2, diffContent2) val ignored1 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges1) val ignored2 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges2) val range = trimExpandText(content1, content2, 0, 0, content1.length, content2.length, ignored1, ignored2) return !range.isEmpty } } interface Listener { fun updateChanges() } class FilteredState private constructor(val changes: List<Change>, val pending: List<Change>, val filteredOut: List<Change>) { companion object { @JvmStatic fun create(changes: List<Change>): FilteredState = create(changes, emptyList(), emptyList()) fun create(changes: List<Change>, pending: List<Change>, filteredOut: List<Change>): FilteredState = FilteredState(changes.toList(), pending.toList(), filteredOut.toList()) } } class FilterGroup : DefaultActionGroup(), Toggleable, DumbAware { init { isPopup = true templatePresentation.text = VcsBundle.message("action.filter.filter.by.text") templatePresentation.icon = AllIcons.General.Filter } override fun update(e: AnActionEvent) { val filterer = e.getData(DATA_KEY) if (filterer == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = filterer.rawChanges != null Toggleable.setSelected(e.presentation, filterer.activeFilter != null) } override fun getChildren(e: AnActionEvent?): Array<AnAction> { val filterer = e?.getData(DATA_KEY) ?: return AnAction.EMPTY_ARRAY return listOf(MovesOnlyFilter, NonImportantFilter) .filter { it.isAvailable(filterer) } .map { ToggleFilterAction(filterer, it) } .toTypedArray() } override fun disableIfNoVisibleChildren(): Boolean = false } private class ToggleFilterAction(val filterer: ChangesFilterer, val filter: Filter) : ToggleAction(filter.getText(), filter.getDescription(), null), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = filterer.activeFilter == filter override fun setSelected(e: AnActionEvent, state: Boolean) { filterer.setFilter(if (state) filter else null) } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/browser/ChangesFilterer.kt
2463334061
fun foo(p: String) { if (x()) return println(p.<caret>isNotEmpty()) }
plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/IfReturn.kt
2293143145
package p2 interface Some fun receiveSomeCtor(ctor: () -> Some) { }
plugins/kotlin/idea/tests/testData/quickfix/autoImports/noImportInterfaceRefAsConstructor.before.Dependency.kt
1780194036
package dependency typealias A = () -> Unit fun foo(a: A) { a.invoke() } class SomeClass
plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/TypeAliases/Dependency.kt
2684789276
package ch.rmy.android.framework.extensions import androidx.annotation.IntRange import ch.rmy.android.framework.utils.localization.StaticLocalizable fun String.truncate(@IntRange(from = 1) maxLength: Int) = if (length > maxLength) substring(0, maxLength - 1) + "…" else this fun String.replacePrefix(oldPrefix: String, newPrefix: String) = runIf(startsWith(oldPrefix)) { "$newPrefix${removePrefix(oldPrefix)}" } fun <T : CharSequence> T.takeUnlessEmpty(): T? = takeUnless { it.isEmpty() } fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) } fun String.toLocalizable() = StaticLocalizable(this)
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/StringExtensions.kt
1626800575
package pt.joaomneto.titancompanion import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Test import org.junit.runner.RunWith import pt.joaomneto.titancompanion.TCBaseTest import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook.STARSHIP_TRAVELLER @LargeTest @RunWith(AndroidJUnit4::class) open class TestST : TCBaseTest() { override val gamebook = STARSHIP_TRAVELLER @Test fun testSuccessfulCreation() { performStartAdventure() performFillSavegameName() performVitalStatisticsRoll() performSaveAdventureFromCreationScreen() assertAdventureLoaded() testVitalStatisticsFragment() } }
src/androidTest/java/pt/joaomneto/titancompanion/TestST.kt
1010711488
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.interactivesliceprovider.slicebuilders import android.content.Context import android.net.Uri import androidx.core.graphics.drawable.IconCompat import androidx.slice.builders.ListBuilder import androidx.slice.builders.SliceAction import androidx.slice.builders.cell import androidx.slice.builders.gridRow import androidx.slice.builders.header import androidx.slice.builders.list import com.example.android.interactivesliceprovider.InteractiveSliceProvider import com.example.android.interactivesliceprovider.R.drawable import com.example.android.interactivesliceprovider.SliceActionsBroadcastReceiver import com.example.android.interactivesliceprovider.SliceBuilder import com.example.android.interactivesliceprovider.data.DataRepository class GridSliceBuilder( val context: Context, sliceUri: Uri, val repo: DataRepository ) : SliceBuilder(sliceUri) { override fun buildSlice() = list(context, sliceUri, ListBuilder.INFINITY) { val data = repo.getGridData() header { // Second argument for title/subtitle informs system we are waiting for data to load. setTitle(data.title, data.title.isEmpty()) setSubtitle(data.subtitle, data.subtitle.isEmpty()) primaryAction = SliceAction.create( SliceActionsBroadcastReceiver.getIntent( context, InteractiveSliceProvider.ACTION_TOAST, "Primary Action for Grid Slice" ), IconCompat.createWithResource(context, drawable.ic_home), ListBuilder.ICON_IMAGE, "Primary" ) } gridRow { cell { addImage( IconCompat.createWithResource(context, drawable.ic_home), ListBuilder.ICON_IMAGE ) addTitleText("Home") addText(data.home, data.home.isEmpty()) } cell { addImage( IconCompat.createWithResource(context, drawable.ic_work), ListBuilder.ICON_IMAGE ) addTitleText("Work") addText(data.work, data.work.isEmpty()) } cell { addImage( IconCompat.createWithResource(context, drawable.ic_school), ListBuilder.ICON_IMAGE ) addTitleText("School") addText(data.school, data.school.isEmpty()) } } } companion object { const val TAG = "GridSliceBuilder" } }
app/src/main/java/com/example/android/interactivesliceprovider/slicebuilders/GridSliceBuilder.kt
71868767
package com.alexstyl.specialdates import org.joda.time.LocalTime data class TimeOfDay(private val dateTime: LocalTime) { constructor(hour: Int, minute: Int) : this(LocalTime(hour, minute)) val hours: Int get() = dateTime.hourOfDay val minutes: Int get() = dateTime.minuteOfHour override fun toString(): String { val hour = hours val str = StringBuilder() if (isOneDigit(hour)) { str.append(ZERO) } str.append(hour) .append(SEPARATOR) val minute = minutes if (isOneDigit(minute)) { str.append(ZERO) } str.append(minute) return str.toString() } private fun isOneDigit(value: Int): Boolean { return value < 10 } fun toMillis(): Long { return dateTime.millisOfDay.toLong() } fun isAfter(timeOfDay: TimeOfDay): Boolean { return dateTime.isAfter(timeOfDay.dateTime) } companion object { private const val ZERO = "0" private const val SEPARATOR = ":" fun now(): TimeOfDay { return TimeOfDay(LocalTime.now()) } } }
memento/src/main/java/com/alexstyl/specialdates/TimeOfDay.kt
4059343514
package com.camerakit.api import android.graphics.SurfaceTexture import com.camerakit.type.CameraFacing import com.camerakit.type.CameraFlash import com.camerakit.type.CameraSize interface CameraActions { fun open(facing: CameraFacing) fun release() fun setPreviewOrientation(degrees: Int) fun setPreviewSize(size: CameraSize) fun startPreview(surfaceTexture: SurfaceTexture) fun stopPreview() fun setFlash(flash: CameraFlash) fun setPhotoSize(size: CameraSize) fun capturePhoto(callback: (jpeg: ByteArray) -> Unit) }
camerakit/src/main/java/com/camerakit/api/CameraActions.kt
737707126
package ds.meterscanner.scheduler import com.evernote.android.job.Job import com.evernote.android.job.JobCreator class SnapshotJobCreator : JobCreator { override fun create(tag: String): Job? = Class.forName(tag).newInstance() as Job? }
app/src/main/java/ds/meterscanner/scheduler/SnapshotJobCreator.kt
3084250101
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 12/3/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.importwallet import android.os.Bundle import android.view.inputmethod.EditorInfo import com.breadwallet.databinding.ControllerImportPasswordBinding import com.breadwallet.ui.BaseMobiusController import com.breadwallet.ui.changehandlers.DialogChangeHandler import com.breadwallet.ui.flowbind.clicks import com.breadwallet.ui.flowbind.editorActions import com.breadwallet.ui.flowbind.textChanges import com.breadwallet.ui.importwallet.PasswordController.E import com.breadwallet.ui.importwallet.PasswordController.F import com.breadwallet.ui.importwallet.PasswordController.M import com.spotify.mobius.Next.dispatch import com.spotify.mobius.Next.next import com.spotify.mobius.Update import drewcarlson.mobius.flow.subtypeEffectHandler import dev.zacsweers.redacted.annotations.Redacted import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge class PasswordController( args: Bundle? = null ) : BaseMobiusController<M, E, F>(args) { init { overridePopHandler(DialogChangeHandler()) overridePushHandler(DialogChangeHandler()) } override val defaultModel = M.DEFAULT override val update = Update<M, E, F> { model, event -> when (event) { is E.OnPasswordChanged -> next(model.copy(password = event.password)) E.OnConfirmClicked -> dispatch(setOf(F.Confirm(model.password))) E.OnCancelClicked -> dispatch(setOf(F.Cancel)) } } override val flowEffectHandler get() = subtypeEffectHandler<F, E> { addConsumerSync(Main, ::handleConfirm) addActionSync<F.Cancel>(Main, ::handleCancel) } private val binding by viewBinding(ControllerImportPasswordBinding::inflate) override fun bindView(modelFlow: Flow<M>): Flow<E> { return with(binding) { merge( inputPassword.editorActions() .filter { it == EditorInfo.IME_ACTION_DONE } .map { E.OnConfirmClicked }, inputPassword.textChanges().map { E.OnPasswordChanged(it) }, buttonConfirm.clicks().map { E.OnConfirmClicked }, buttonCancel.clicks().map { E.OnCancelClicked } ) } } private fun handleConfirm(effect: F.Confirm) { findListener<Listener>()?.onPasswordConfirmed(effect.password) router.popController(this) } private fun handleCancel() { findListener<Listener>()?.onPasswordCancelled() router.popController(this) } interface Listener { fun onPasswordConfirmed(password: String) fun onPasswordCancelled() } data class M(@Redacted val password: String = "") { companion object { val DEFAULT = M() } } sealed class E { data class OnPasswordChanged( @Redacted val password: String ) : E() object OnConfirmClicked : E() object OnCancelClicked : E() } sealed class F { data class Confirm( @Redacted val password: String ) : F() object Cancel : F() } }
app/src/main/java/com/breadwallet/ui/importwallet/PasswordController.kt
174200984
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.ui.app import android.content.Context import android.content.SharedPreferences internal object PrefPool { private var pref: SharedPreferences? = null private const val PREFERENCE_NAME = "main_preference" fun getSharedPref(context: Context): SharedPreferences { if (pref == null) { pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) } return pref!! } }
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/app/PrefPool.kt
638586725
package com.rpkit.essentials.bukkit.command import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import org.bukkit.Material import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class JumpCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender.hasPermission("rpkit.essentials.command.jump")) { if (sender is Player) { val transparent: Set<Material>? = null val block = sender.getTargetBlock(transparent, 64) if (block != null) { sender.teleport(block.location) sender.sendMessage(plugin.messages["jump-valid"]) } else { sender.sendMessage(plugin.messages["jump-invalid-block"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-jump"]) } return true } }
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/JumpCommand.kt
1488761766
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.reactor import com.mongodb.ReadPreference import com.mongodb.client.model.Filters import org.bson.types.ObjectId import org.junit.Test import org.litote.kmongo.MongoOperator.oid import org.litote.kmongo.json import org.litote.kmongo.model.Friend import kotlin.test.assertEquals import kotlin.test.assertNull /** * */ class FindOneTest : KMongoReactorBaseTest<Friend>() { @Test fun canFindOne() { col.insertOne(Friend("John", "22 Wall Street Avenue")).blockLast() val friend = col.findOne("{name:'John'}").block() ?: throw AssertionError("Value must not null!") assertEquals("John", friend.name) } @Test fun canFindOneBson() { col.insertOne(Friend("John", "22 Wall Street Avenue")).blockLast() val friend = col.findOne(Filters.eq("name", "John")).block() ?: throw AssertionError("Value must not null!") assertEquals("John", friend.name) } @Test fun canFindOneWithEmptyQuery() { col.insertOne(Friend("John", "22 Wall Street Avenue")).blockLast() val friend = col.findOne().block() ?: throw AssertionError("Value must not null!") assertEquals("John", friend.name) } @Test fun canFindOneWithObjectId() { val john = Friend(ObjectId(), "John") col.insertOne(john).blockLast() val friend = col.findOneById(john._id ?: Any()).block() ?: throw AssertionError("Value must not null!") assertEquals(john._id, friend._id) } @Test fun canFindOneWithObjectIdInQuery() { val id = ObjectId() val john = Friend(id, "John") col.insertOne(john).blockLast() val friend = col.findOne("{_id:${id.json}}").block() ?: throw AssertionError("Value must not null!") assertEquals(id, friend._id) } @Test fun canFindOneWithObjectIdAsString() { val id = ObjectId() val john = Friend(id, "John") col.insertOne(john).blockLast() val friend = col.findOne("{_id:{$oid:'$id'}}").block() ?: throw AssertionError("Value must not null!") assertEquals(id, friend._id) } @Test fun whenNoResultShouldReturnNull() { val friend = col.findOne("{_id:'invalid-id'}").block() assertNull(friend) } @Test fun canFindOneWithReadPreference() { col.insertOne(Friend("John", "22 Wall Street Avenue")).blockLast() val friend = col.withReadPreference(ReadPreference.primaryPreferred()).findOne("{name:'John'}").block() ?: throw AssertionError("Value must not null!") assertEquals("John", friend.name) } }
kmongo-reactor-core-tests/src/main/kotlin/org/litote/kmongo/reactor/FindOneTest.kt
165640157
package de.maxdobler.systemicconsensus import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("de.maxdobler.systemicconsensus", appContext.packageName) } }
app/src/androidTest/java/de/maxdobler/systemicconsensus/ExampleInstrumentedTest.kt
3132165745
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.coroutine import kotlinx.coroutines.runBlocking import org.bson.types.ObjectId import org.junit.Test import org.litote.kmongo.MongoOperator import org.litote.kmongo.model.Friend import kotlin.test.assertEquals /** * */ class ReactiveStreamsDeleteTest : KMongoReactiveStreamsCoroutineBaseTest<Friend>() { @Test fun canDeleteASpecificDocument() = runBlocking { col.insertMany(listOf(Friend("John"), Friend("Peter"))) col.deleteOne("{name:'John'}") val list = col.find().toList() assertEquals(1, list.size) assertEquals("Peter", list.first().name) } @Test fun `can delete one in ClientSession`() = runBlocking { col.insertMany(listOf(Friend("John"), Friend("Peter"))) mongoClient.startSession().use { col.deleteOne(it, "{name:'John'}") val list = col.find(it).toList() assertEquals(1, list.size) assertEquals("Peter", list.first().name) } } @Test fun canDeleteByObjectId() = runBlocking { col.insertOne("{ _id:{${MongoOperator.oid}:'47cc67093475061e3d95369d'}, name:'John'}") col.deleteOneById(ObjectId("47cc67093475061e3d95369d")) val count = col.countDocuments() assertEquals(0, count) } @Test fun canDeleteWithSessionByObjectId() = runBlocking { mongoClient.startSession().use { col.insertOne(it, "{ _id:{${MongoOperator.oid}:'47cc67093475061e3d95369d'}, name:'John'}") col.deleteOneById(it, ObjectId("47cc67093475061e3d95369d")) val count = col.countDocuments(it) assertEquals(0, count) } } @Test fun canRemoveAll() = runBlocking { col.insertMany(listOf(Friend("John"), Friend("Peter"))) col.deleteMany("{}") val count = col.countDocuments() assertEquals(0, count) } @Test fun `can remove all in ClientSession`() = runBlocking { col.insertMany(listOf(Friend("John"), Friend("Peter"))) mongoClient.startSession().use { col.deleteMany(it, "{}") val count = col.countDocuments(it) assertEquals(0, count) } } }
kmongo-coroutine-core-tests/src/main/kotlin/org/litote/kmongo/coroutine/ReactiveStreamsDeleteTest.kt
1712889951
package com.foo.rest.examples.spring.openapi.v3.wiremock.jsonarray class WmJsonCycleDto { var y : Int? = null var referToSelf : WmJsonCycleDto? = null }
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/jsonarray/WmJsonCycleDto.kt
1707460773
package cx.ring.plugins.RecyclerPicker import android.content.Context import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView.Recycler class RecyclerPickerLayoutManager( context: Context?, orientation: Int, reverseLayout: Boolean, private val listener: ItemSelectedListener ) : LinearLayoutManager(context, orientation, reverseLayout) { private var recyclerView: RecyclerView? = null override fun onAttachedToWindow(view: RecyclerView) { super.onAttachedToWindow(view) recyclerView = view // Smart snapping val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(recyclerView) } override fun onLayoutCompleted(state: RecyclerView.State) { super.onLayoutCompleted(state) scaleDownView() } override fun scrollHorizontallyBy( dx: Int, recycler: Recycler, state: RecyclerView.State ): Int { val scrolled = super.scrollHorizontallyBy(dx, recycler, state) return if (orientation == VERTICAL) { 0 } else { scaleDownView() scrolled } } override fun onScrollStateChanged(state: Int) { super.onScrollStateChanged(state) // When scroll stops we notify on the selected item if (state == RecyclerView.SCROLL_STATE_IDLE) { // Find the closest child to the recyclerView center --> this is the selected item. val recyclerViewCenterX = recyclerViewCenterX var minDistance = recyclerView!!.width var position = -1 for (i in 0 until recyclerView!!.childCount) { val child = recyclerView!!.getChildAt(i) val childCenterX = getDecoratedLeft(child) + (getDecoratedRight(child) - getDecoratedLeft(child)) / 2 val newDistance = Math.abs(childCenterX - recyclerViewCenterX) if (newDistance < minDistance) { minDistance = newDistance position = recyclerView!!.getChildLayoutPosition(child) } } listener.onItemSelected(position) } } private val recyclerViewCenterX: Int private get() = recyclerView!!.width / 2 + recyclerView!!.left private fun scaleDownView() { val mid = width / 2.0f for (i in 0 until childCount) { // Calculating the distance of the child from the center val child = getChildAt(i) val childMid = (getDecoratedLeft(child!!) + getDecoratedRight(child)) / 2.0f val distanceFromCenter = Math.abs(mid - childMid) // The scaling formula var k = Math.sqrt((distanceFromCenter / width).toDouble()).toFloat() k *= 1.5f val scale = 1 - k * 0.66f // Set scale to view child.scaleX = scale child.scaleY = scale } } interface ItemSelectedListener { fun onItemSelected(position: Int) fun onItemClicked(position: Int) } }
ring-android/app/src/main/java/cx/ring/plugins/RecyclerPicker/RecyclerPickerLayoutManager.kt
3039629270
package com.gmail.blueboxware.libgdxplugin.json import com.gmail.blueboxware.libgdxplugin.LibGDXCodeInsightFixtureTestCase import com.gmail.blueboxware.libgdxplugin.filetypes.json.LibGDXJsonFileType import com.intellij.testFramework.LightPlatformCodeInsightTestCase /* * Copyright 2021 Blue Box Ware * * 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. */ class TestQuoteHandling : LibGDXCodeInsightFixtureTestCase() { fun testDoubleQuote1() = doTest( "<caret>", "\"\"" ) fun testDoubleQuote2() = doTest( "\"<caret>\"", "\"\"" ) fun testDoubleQuoteAtEndOfUnquotedString() = doTest( "[foo<caret>]", "[foo\"]" ) fun testSingleQuote() = doTest( "<caret>", "'", '\'' ) fun testBackSpaceInQuotes() = doTest( "\"<caret>\"", "", '\b' ) fun testBackSpaceInQuotesInUnquotedString() = doTest( "foo\"<caret>\"bar", "foo\"bar", '\b' ) fun testDoubleQuoteInUnquotedString() = doTest( "foo<caret>bar", "foo\"bar" ) fun doTest(source: String, expected: String, char: Char = '\"') { myFixture.configureByText(LibGDXJsonFileType.INSTANCE, source) if (char == '\b') { LightPlatformCodeInsightTestCase.backspace(editor, project) } else { myFixture.type(char) } myFixture.checkResult(expected) } }
src/test/kotlin/com/gmail/blueboxware/libgdxplugin/json/TestQuoteHandling.kt
554180643
import com.badlogic.gdx.scenes.scene2d.ui.TextButton import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets @GDXAssets(atlasFiles = arrayOf(""), skinFiles = ["src\\findUsages/findUsagesWithTags2.skin"]) val s: Skin = Skin() object O { @GDXAssets(atlasFiles = arrayOf(""), skinFiles = arrayOf("src\\findUsages\\findUsagesWithTags1.skin", "src/findUsages/findUsagesWithTags2.skin")) val skin: Skin = Skin() } fun f() { val c = s.get("toggle", TextButton.TextButtonStyle::class.java) val d = O.skin.has("toggle", TextButton.TextButtonStyle::class.java) }
src/test/testdata/assetsInCode/findUsages/FindUsagesWithTags2.kt
4283018640
import org.junit.Test import org.junit.Ignore import org.junit.Rule import org.junit.rules.ExpectedException import kotlin.test.assertEquals class HammingTest { @Rule @JvmField var expectedException: ExpectedException = ExpectedException.none() @Test fun `empty strands`() { assertEquals(0, Hamming.compute("", "")) } @Test fun `single letter identical strands`() { assertEquals(0, Hamming.compute("A", "A")) } @Test fun `single letter different strands`() { assertEquals(1, Hamming.compute("G", "T")) } @Test fun `long identical strands`() { assertEquals(0, Hamming.compute("GGACTGAAATCTG", "GGACTGAAATCTG")) } @Test fun `long different strands`() { assertEquals(9, Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT")) } @Test fun `disallow first strand longer`() { expectedException.expect(IllegalArgumentException::class.java) expectedException.expectMessage("left and right strands must be of equal length") Hamming.compute("AATG", "AAA") } @Test fun `disallow second strand longer`() { expectedException.expect(IllegalArgumentException::class.java) expectedException.expectMessage("left and right strands must be of equal length") Hamming.compute("ATA", "AGTG") } }
exercism/kotlin/hamming/src/test/kotlin/HammingTest.kt
3910765642
package com.example.data.datasources.dtos.responses data class ImageResponse (val path: String, val extension: String)
data/src/main/java/com/example/data/datasources/dtos/responses/ImageResponse.kt
3203549900
package com.androidessence.cashcaretaker.core.di import com.androidessence.cashcaretaker.ui.accountlist.AccountListViewModel import com.androidessence.cashcaretaker.ui.addaccount.AddAccountViewModel import com.androidessence.cashcaretaker.ui.addtransaction.AddTransactionViewModel import com.androidessence.cashcaretaker.ui.transactionlist.TransactionListViewModel import com.androidessence.cashcaretaker.ui.transfer.AddTransferViewModel import org.koin.android.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { AccountListViewModel( repository = get(), analyticsTracker = get() ) } viewModel { AddTransactionViewModel( repository = get(), analyticsTracker = get() ) } viewModel { AddTransferViewModel( repository = get(), analyticsTracker = get() ) } viewModel { AddAccountViewModel( repository = get(), analyticsTracker = get() ) } viewModel { (accountName: String) -> TransactionListViewModel( accountName = accountName, repository = get(), analyticsTracker = get() ) } }
app/src/main/java/com/androidessence/cashcaretaker/core/di/KoinViewModelModule.kt
3088260642
package com.jjl.accounttest.domain.model import com.google.gson.Gson import com.jjl.accounttest.domain.entity.AccountsResponse import org.junit.Assert import org.junit.Test /** * Created by jjimeno on 22/10/17. */ class AccountTest { @Test fun `parsing account ok`() { val string = provideElementsAsString() val parsedObj = Gson().fromJson(string, AccountsResponse::class.java) Assert.assertNotNull(parsedObj) Assert.assertEquals(3,parsedObj.accounts.size) val account = parsedObj.accounts.first() Assert.assertEquals(985000, account.accountBalanceInCents) Assert.assertEquals(AccountCurrency.EUR, account.accountCurrency) Assert.assertEquals(748757694, account.accountId) Assert.assertEquals("Hr P L G N StellingTD", account.accountName) Assert.assertEquals(748757694, account.accountNumber.toLong()) Assert.assertEquals(AccountType.PAYMENT, account.accountType) Assert.assertEquals("", account.alias) Assert.assertEquals(true, account.isVisible) Assert.assertEquals("NL23INGB0748757694", account.iban) } private fun provideElementsAsString(): String { return "{\n" + "\t\"accounts\": [{\n" + "\t\t\"accountBalanceInCents\": 985000,\n" + "\t\t\"accountCurrency\": \"EUR\",\n" + "\t\t\"accountId\": 748757694,\n" + "\t\t\"accountName\": \"Hr P L G N StellingTD\",\n" + "\t\t\"accountNumber\": 748757694,\n" + "\t\t\"accountType\": \"PAYMENT\",\n" + "\t\t\"alias\": \"\",\n" + "\t\t\"isVisible\": true,\n" + "\t\t\"iban\": \"NL23INGB0748757694\"\n" + "\t}, {\n" + "\t\t\"accountBalanceInCents\": 1000000,\n" + "\t\t\"accountCurrency\": \"EUR\",\n" + "\t\t\"accountId\": 700000027559,\n" + "\t\t\"accountName\": \",\",\n" + "\t\t\"accountNumber\": 748757732,\n" + "\t\t\"accountType\": \"PAYMENT\",\n" + "\t\t\"alias\": \"\",\n" + "\t\t\"isVisible\": false,\n" + "\t\t\"iban\": \"NL88INGB0748757732\"\n" + "\t}, {\n" + "\t\t\"accountBalanceInCents\": 15000,\n" + "\t\t\"accountCurrency\": \"EUR\",\n" + "\t\t\"accountId\": 700000027559,\n" + "\t\t\"accountName\": \"\",\n" + "\t\t\"accountNumber\": \"H 177-27066\",\n" + "\t\t\"accountType\": \"SAVING\",\n" + "\t\t\"alias\": \"SAVINGS\",\n" + "\t\t\"iban\": \"\",\n" + "\t\t\"isVisible\": true,\n" + "\t\t\"linkedAccountId\": 748757694,\n" + "\t\t\"productName\": \"Oranje Spaarrekening\",\n" + "\t\t\"productType\": 1000,\n" + "\t\t\"savingsTargetReached\": 1,\n" + "\t\t\"targetAmountInCents\": 2000\n" + "\t}],\n" + "\t\"failedAccountTypes\": \"CREDITCARDS\",\n" + "\t\"returnCode\": \"OK\"\n" + "}\n" } }
domain/src/test/java/com/jjl/accounttest/domain/model/AccountTest.kt
2362364348
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.welcomemessages.rules import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.endpoints.WelcomeMessageRules import jp.nephy.penicillin.models.WelcomeMessageRule /** * Returns a Welcome Message Rule by the given id. * * [Twitter API reference](https://developer.twitter.com/en/docs/direct-messages/welcome-messages/api-reference/get-welcome-message-rule) * * @param id The id of the Welcome Message Rule that should be returned. * @param options Optional. Custom parameters of this request. * @receiver [WelcomeMessageRules] endpoint instance. * @return [JsonObjectApiAction] for [WelcomeMessageRule.Single] model. */ fun WelcomeMessageRules.show( id: Long, vararg options: Option ) = client.session.get("/1.1/direct_messages/welcome_messages/rules/show.json") { parameters( "id" to id, *options ) }.jsonObject<WelcomeMessageRule.Single>()
src/main/kotlin/jp/nephy/penicillin/endpoints/welcomemessages/rules/Show.kt
2486475351
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.remote /** Encapsulates information about a client of the ChronicleService. */ data class ClientDetails( /** The linux User ID for the client of ChronicleService. */ val userId: Int, /** Whether or not the client of the ChronicleService is an isolated process. */ val isolationType: IsolationType = IsolationType.UNKNOWN, /** Any associated packages for APKs under the ownership of the user with [userId]. */ val associatedPackages: List<String> = emptyList() ) { /** Type of isolation the client is under. */ enum class IsolationType { UNKNOWN, ISOLATED_PROCESS, DEFAULT_PROCESS, } }
java/com/google/android/libraries/pcc/chronicle/remote/ClientDetails.kt
1689729774
/* * Copyright 2013-2017 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.server import jetbrains.buildServer.requirements.Requirement import jetbrains.buildServer.requirements.RequirementType import jetbrains.buildServer.serverSide.PropertiesProcessor import com.jonnyzzz.teamcity.plugins.node.common.BowerBean import com.jonnyzzz.teamcity.plugins.node.common.NodeBean import com.jonnyzzz.teamcity.plugins.node.common.BowerExecutionMode /* * Copyright 2000-2013 Eugene Petrenko * * 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. */ /** * Created by Victor Mosin ([email protected]) * Date: 01.02.17 9:15 */ class BowerRunType : RunTypeBase() { private val bean = BowerBean() override fun getType(): String = bean.runTypeName override fun getDisplayName(): String = "Bower" override fun getDescription(): String = "Executes Bower tasks" override fun getEditJsp(): String = "bower.edit.jsp" override fun getViewJsp(): String = "bower.view.jsp" override fun getRunnerPropertiesProcessor(): PropertiesProcessor = PropertiesProcessor { arrayListOf() } override fun describeParameters(parameters: Map<String, String>): String = "Run targets: ${bean.parseCommands(parameters[bean.targets]).joinToString(", ")}" override fun getDefaultRunnerProperties(): MutableMap<String, String> = hashMapOf(bean.bowerMode to bean.bowerModeDefault.value) override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> { val result = arrayListOf<Requirement>() result.addAll(super.getRunnerSpecificRequirements(runParameters)) result.add(Requirement(NodeBean().nodeJSConfigurationParameter, null, RequirementType.EXISTS)) if (bean.parseMode(runParameters[bean.bowerMode]) == BowerExecutionMode.GLOBAL) { result.add(Requirement(bean.bowerConfigurationParameter, null, RequirementType.EXISTS)) } return result } }
server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/BowerRunType.kt
213638563
package io.github.manamiproject.manami.app.lists.watchlist import io.github.manamiproject.manami.app.state.InternalState import io.github.manamiproject.manami.app.state.State import io.github.manamiproject.manami.app.commands.Command internal class CmdRemoveWatchListEntry( val state: State = InternalState, val watchListEntry: WatchListEntry, ) : Command { override fun execute(): Boolean { if (state.watchList().map { it.link }.none { it == watchListEntry.link }) { return false } state.removeWatchListEntry(watchListEntry) return true } }
manami-app/src/main/kotlin/io/github/manamiproject/manami/app/lists/watchlist/CmdRemoveWatchListEntry.kt
3239440531
/*- * ========================LICENSE_START================================= * ids-webconsole * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.webconsole.api import de.fhg.aisec.ids.api.Constants import de.fhg.aisec.ids.api.conm.ConnectionManager import de.fhg.aisec.ids.api.endpointconfig.EndpointConfigManager import de.fhg.aisec.ids.api.router.RouteManager import de.fhg.aisec.ids.api.settings.ConnectionSettings import de.fhg.aisec.ids.api.settings.ConnectorConfig import de.fhg.aisec.ids.api.settings.Settings import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import io.swagger.annotations.Authorization import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.util.TreeMap import java.util.function.Consumer import java.util.regex.Pattern import java.util.stream.Collectors import javax.ws.rs.BadRequestException import javax.ws.rs.Consumes import javax.ws.rs.GET import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * REST API interface for configurations in the connector. * * * The API will be available at http://localhost:8181/cxf/api/v1/config/<method>. * * @author Julian Schuette ([email protected]) * @author Gerd Brost ([email protected]) * @author Michael Lux ([email protected]) </method> */ @Component @Path("/config") @Api(value = "Connector Configuration", authorizations = [Authorization(value = "oauth2")]) class ConfigApi { @Autowired private lateinit var settings: Settings @Autowired private lateinit var routeManager: RouteManager @Autowired(required = false) private var connectionManager: ConnectionManager? = null @Autowired(required = false) private var endpointConfigManager: EndpointConfigManager? = null @GET @ApiOperation(value = "Retrieves the current configuration", response = ConnectorConfig::class) @Path("/connectorConfig") @Produces( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun get(): ConnectorConfig { return settings.connectorConfig } @POST // @OPTIONS @Path("/connectorConfig") @ApiOperation(value = "Sets the overall configuration of the connector") @ApiResponses( ApiResponse( code = 500, message = "_No valid preferences received_: If incorrect configuration parameter is provided" ) ) @Consumes( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun set(config: ConnectorConfig?): String { if (config == null) { throw BadRequestException("No valid preferences received!") } settings.connectorConfig = config return "OK" } /** * Save connection configuration of a particular connection. * * @param connection The name of the connection * @param conSettings The connection configuration of the connection */ @POST @Path("/connectionConfigs/{con}") @ApiOperation(value = "Save connection configuration of a particular connection") @ApiResponses( ApiResponse( code = 500, message = "_No valid connection settings received!_: If incorrect connection settings parameter is provided" ) ) @Consumes( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun setConnectionConfigurations( @PathParam("con") connection: String, conSettings: ConnectionSettings? ): Response { return conSettings?.let { // connection has format "<route_id> - host:port" // store only "host:port" in database to make connection available in other parts of the application // where rout_id is not available val m = CONNECTION_CONFIG_PATTERN.matcher(connection) if (!m.matches()) { // GENERAL_CONFIG has changed settings.setConnectionSettings(connection, it) } else { // specific endpoint config has changed settings.setConnectionSettings(m.group(1), it) // notify EndpointConfigurationListeners that some endpointConfig has changed endpointConfigManager?.notify(m.group(1)) } Response.ok().build() } ?: Response.serverError().entity("No valid connection settings received!").build() } /** * Sends configuration of a connection * * @param connection Connection identifier * @return The connection configuration of the requested connection */ @GET @Path("/connectionConfigs/{con}") @ApiOperation(value = "Sends configuration of a connection", response = ConnectionSettings::class) @Produces( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun getConnectionConfigurations(@PathParam("con") connection: String): ConnectionSettings { return settings.getConnectionSettings(connection) } // add endpoint configurations// For every currently available endpoint, go through all preferences and check // if the id is already there. If not, create empty config. // create missing endpoint configurations // add route id before host identifier for web console view // Set of all connection configurations, properly ordered // Load all existing entries // Assert global configuration entry // add all available endpoints /** * Sends configurations of all connections * * @return Map of connection names/configurations */ @get:AuthorizationRequired @get:Produces(MediaType.APPLICATION_JSON) @get:ApiResponses( ApiResponse( code = 200, message = "Map of connections and configurations", response = ConnectionSettings::class, responseContainer = "Map" ) ) @get:ApiOperation(value = "Retrieves configurations of all connections") @get:Path("/connectionConfigs") @get:GET val allConnectionConfigurations: Map<String, ConnectionSettings> get() { val connectionManager = connectionManager ?: return emptyMap() // Set of all connection configurations, properly ordered val allSettings: MutableMap<String, ConnectionSettings> = TreeMap( Comparator { o1: String, o2: String -> when (Constants.GENERAL_CONFIG) { o1 -> { return@Comparator -1 } o2 -> { return@Comparator 1 } else -> { return@Comparator o1.compareTo(o2) } } } ) // Load all existing entries allSettings.putAll(settings.allConnectionSettings) // Assert global configuration entry allSettings.putIfAbsent(Constants.GENERAL_CONFIG, ConnectionSettings()) val routeInputs = routeManager .routes .mapNotNull { it.id } .associateWith { routeManager.getRouteInputUris(it) } // add all available endpoints for (endpoint in connectionManager.listAvailableEndpoints()) { // For every currently available endpoint, go through all preferences and check // if the id is already there. If not, create empty config. val hostIdentifier = endpoint.host + ":" + endpoint.port // create missing endpoint configurations if (allSettings.keys.stream().noneMatch { anObject: String? -> hostIdentifier == anObject }) { allSettings[hostIdentifier] = ConnectionSettings() } } // add route id before host identifier for web console view val retAllSettings: MutableMap<String, ConnectionSettings> = HashMap() for ((key, value) in allSettings) { if (key == Constants.GENERAL_CONFIG) { retAllSettings[key] = value } else { var endpointIdentifiers = routeInputs .entries .stream() .filter { (_, value1) -> value1.stream().anyMatch { u: String -> u.startsWith("idsserver://$key") } } .map { (key1) -> "$key1 - $key" } .collect(Collectors.toList()) if (endpointIdentifiers.isEmpty()) { endpointIdentifiers = listOf("<no route found> - $key") } // add endpoint configurations endpointIdentifiers.forEach( Consumer { endpointIdentifier: String -> if (retAllSettings.keys.stream() .noneMatch { anObject: String? -> endpointIdentifier == anObject } ) { retAllSettings[endpointIdentifier] = value } } ) } } return retAllSettings } companion object { private val CONNECTION_CONFIG_PATTERN = Pattern.compile(".* - ([^ ]+)$") } }
ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt
3691168841
package ht.pq.khanh.task.reminder import android.support.v7.app.AppCompatActivity import android.os.Bundle import ht.pq.khanh.multitask.R class ReminderActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reminder) } }
app/src/main/java/ht/pq/khanh/task/reminder/ReminderActivity.kt
339265619
package cn.yiiguxing.plugin.translate.ui import cn.yiiguxing.plugin.translate.util.Hyperlinks import com.intellij.ui.BrowserHyperlinkListener import javax.swing.event.HyperlinkEvent open class DefaultHyperlinkListener : BrowserHyperlinkListener() { override fun hyperlinkActivated(hyperlinkEvent: HyperlinkEvent) { if (!Hyperlinks.handleDefaultHyperlinkActivated(hyperlinkEvent)) { super.hyperlinkActivated(hyperlinkEvent) } } companion object : DefaultHyperlinkListener() }
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/DefaultHyperlinkListener.kt
932566122
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.maps.android.rx import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.PointOfInterest import com.google.maps.android.rx.shared.MainThreadObservable import io.reactivex.rxjava3.android.MainThreadDisposable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Observer /** * Creates an [Observable] that emits whenever a point of interest is clicked. * * The created [Observable] uses [GoogleMap.setOnPoiClickListener] to listen to poi click events. * Since only one listener at a time is allowed, only one Observable at a time can be used. */ public fun GoogleMap.poiClickEvents(): Observable<PointOfInterest> = GoogleMapPoiClickObservable(this) private class GoogleMapPoiClickObservable( private val googleMap: GoogleMap ) : MainThreadObservable<PointOfInterest>() { override fun subscribeMainThread(observer: Observer<in PointOfInterest>) { val listener = PoiClickListener(googleMap, observer) observer.onSubscribe(listener) googleMap.setOnPoiClickListener(listener) } private class PoiClickListener( private val googleMap: GoogleMap, private val observer: Observer<in PointOfInterest> ) : MainThreadDisposable(), GoogleMap.OnPoiClickListener { override fun onDispose() { googleMap.setOnPoiClickListener(null) } override fun onPoiClick(poi: PointOfInterest) { if (!isDisposed) { observer.onNext(poi) } } } }
maps-rx/src/main/java/com/google/maps/android/rx/GoogleMapPoiClickObservable.kt
965684903
package ru.maxlord.kotlinandroidapp.base import android.content.SharedPreferences import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.trello.rxlifecycle.components.RxFragment import ru.maxlord.kotlinandroidapp.activity.base.BaseActivity import ru.maxlord.kotlinandroidapp.activity.base.BaseNoActionBarActivity import ru.maxlord.kotlinandroidapp.activity.splash.Splash import ru.maxlord.kotlinandroidapp.annotation.ConfigPrefs import javax.inject.Inject /** * * @author Lord (Kuleshov M.V.) * @since 11.01.16 */ abstract class BaseFragment: RxFragment() { // @Bind(R.id.toolbar) protected var toolbar: Toolbar? = null lateinit var prefs: SharedPreferences @Inject fun setSharedPreferences(@ConfigPrefs prefs: SharedPreferences) { this.prefs = prefs } private var component: FragmentSubComponent? = null fun getComponent(): FragmentSubComponent { return component!! } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(getLayoutRes(), container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (activity is BaseActivity) { val activity = activity as BaseActivity this.component = activity.getComponent().plus(FragmentModule(this)) inject() } else if (activity is BaseNoActionBarActivity) { val activity = activity as BaseNoActionBarActivity this.component = activity.getComponent().plus(FragmentModule(this)) inject() } else if (activity is Splash) { val activity = activity as Splash this.component = activity.getComponent().plus(FragmentModule(this)) inject() } if (toolbar != null) { toolbar!!.title = activity.title } loadData() } /** * @return */ @LayoutRes protected abstract fun getLayoutRes(): Int protected abstract fun inject() override fun onViewCreated(v: View?, savedInstanceState: Bundle?) { super.onViewCreated(v, savedInstanceState) initControls(v) onRestoreInstanceState(savedInstanceState) } protected open fun onRestoreInstanceState(savedInstanceState: Bundle?) { } protected open fun initControls(v: View?) { } open fun loadData() { } protected fun releaseDatabaseHelper() { // OpenHelperManager.releaseHelper() } }
app/src/main/kotlin/ru/maxlord/kotlinandroidapp/base/BaseFragment.kt
1378354067
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustMethodCallExprElement import org.rust.lang.core.psi.impl.RustExprElementImpl import org.rust.lang.core.resolve.ref.RustMethodCallReferenceImpl import org.rust.lang.core.resolve.ref.RustReference abstract class RustMethodCallExprImplMixin(node: ASTNode?) : RustExprElementImpl(node), RustMethodCallExprElement { override val referenceNameElement: PsiElement get() = identifier override fun getReference(): RustReference = RustMethodCallReferenceImpl(this) }
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustMethodCallExprImplMixin.kt
479902902
package net.perfectdreams.loritta.morenitta.listeners import com.github.benmanes.caffeine.cache.Caffeine import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.MuteCommand import net.perfectdreams.loritta.morenitta.dao.Mute import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.morenitta.modules.AutoroleModule import net.perfectdreams.loritta.morenitta.modules.InviteLinkModule import net.perfectdreams.loritta.morenitta.modules.WelcomeModule import net.perfectdreams.loritta.morenitta.tables.DonationKeys import net.perfectdreams.loritta.morenitta.tables.GuildProfiles import net.perfectdreams.loritta.morenitta.tables.Mutes import net.perfectdreams.loritta.morenitta.utils.debug.DebugLog import net.perfectdreams.loritta.morenitta.utils.extensions.await import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mu.KotlinLogging import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.channel.concrete.TextChannel import net.dv8tion.jda.api.events.guild.GuildJoinEvent import net.dv8tion.jda.api.events.guild.GuildLeaveEvent import net.dv8tion.jda.api.events.guild.GuildReadyEvent import net.dv8tion.jda.api.events.guild.invite.GuildInviteCreateEvent import net.dv8tion.jda.api.events.guild.invite.GuildInviteDeleteEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent import net.dv8tion.jda.api.events.http.HttpRequestEvent import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import net.perfectdreams.loritta.morenitta.dao.servers.Giveaway import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.AutoroleConfig import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.MemberCounterChannelConfig import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.WelcomerConfig import net.perfectdreams.loritta.morenitta.tables.servers.CustomGuildCommands import net.perfectdreams.loritta.morenitta.tables.servers.Giveaways import net.perfectdreams.loritta.morenitta.tables.servers.ServerRolePermissions import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.MemberCounterChannelConfigs import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.ModerationPunishmentMessagesConfig import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.WarnActions import net.perfectdreams.loritta.common.utils.ServerPremiumPlans import net.perfectdreams.loritta.morenitta.utils.giveaway.GiveawayManager import okio.Buffer import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.update import org.slf4j.LoggerFactory import java.util.concurrent.TimeUnit import kotlin.collections.set class DiscordListener(internal val loritta: LorittaBot) : ListenerAdapter() { companion object { // You can update a channel 2 times every 10 minutes // https://cdn.discordapp.com/attachments/681830234168754226/716341063912128636/unknown.png private const val MEMBER_COUNTER_COOLDOWN = 300_000L // 5 minutes in ms val memberCounterLastUpdate = Caffeine.newBuilder() .expireAfterWrite(15L, TimeUnit.MINUTES) .build<Long, Long>() .asMap() /** * Stores the member counter executing update mutexes, used when a topic update is being executed. */ val memberCounterExecutingUpdatesMutexes = Caffeine.newBuilder() .expireAfterWrite(15L, TimeUnit.MINUTES) .build<Long, Mutex>() .asMap() private val logger = KotlinLogging.logger {} private val requestLogger = LoggerFactory.getLogger("requests") suspend fun queueTextChannelTopicUpdates(loritta: LorittaBot, guild: Guild, serverConfig: ServerConfig) { val activeDonationValues = loritta.getOrCreateServerConfig(guild.idLong).getActiveDonationKeysValue(loritta) logger.debug { "Creating text channel topic updates in $guild for ${guild.textChannels.size} channels! Donation key value is $activeDonationValues" } val memberCountConfigs = loritta.newSuspendedTransaction { MemberCounterChannelConfig.find { MemberCounterChannelConfigs.channelId inList guild.channels.map { it.idLong } }.toList() } val validChannels = guild.textChannels.filter { channel -> val memberCounterConfig = memberCountConfigs.firstOrNull { it.channelId == channel.idLong } memberCounterConfig != null && guild.selfMember.hasPermission(channel, Permission.MANAGE_CHANNEL) && memberCounterConfig.topic.contains("{counter}") } val channelsThatWillBeChecked = validChannels.take(ServerPremiumPlans.getPlanFromValue(activeDonationValues).memberCounterCount) for (textChannel in channelsThatWillBeChecked) GlobalScope.launch(loritta.coroutineDispatcher) { queueTextChannelTopicUpdate(loritta, guild, serverConfig, textChannel) } } private suspend fun queueTextChannelTopicUpdate(loritta: LorittaBot, guild: Guild, serverConfig: ServerConfig, textChannel: TextChannel) { if (!guild.selfMember.hasPermission(textChannel, Permission.MANAGE_CHANNEL)) return val memberCountConfig = loritta.newSuspendedTransaction { MemberCounterChannelConfig.find { MemberCounterChannelConfigs.channelId eq textChannel.idLong }.firstOrNull() } ?: return val memberCounterPendingForUpdateMutex = memberCounterExecutingUpdatesMutexes.getOrPut(textChannel.idLong) { Mutex() } val memberCounterExecutingUpdateMutex = memberCounterExecutingUpdatesMutexes.getOrPut(textChannel.idLong) { Mutex() } if (memberCounterPendingForUpdateMutex.isLocked) { // If the "memberCounterPendingForUpdateMutex" is locked, then it means that we already have a job waiting for the counter to be updated! // So we are going to return, the counter will be updated later when the mutex is unlocked so... whatever. logger.info { "Text channel $textChannel topic already has a pending update for guild $guild, cancelling..." } return } val diff = System.currentTimeMillis() - (memberCounterLastUpdate[textChannel.idLong] ?: 0) if (memberCounterExecutingUpdateMutex.isLocked) { // If the "memberCounterExecutingUpdateMutex" is locked, then it means that the counter is still updating! // We will wait until it is finished and then continue. logger.info { "Text channel $textChannel topic already has a pending execute for guild $guild, waiting until the update is executed to continue..." } // Double locc time memberCounterPendingForUpdateMutex.withLock { memberCounterExecutingUpdateMutex.withLock { delayForTextChannelUpdateCooldown(textChannel, diff) updateTextChannelTopic(loritta, guild, serverConfig, textChannel, memberCountConfig) } } return } memberCounterExecutingUpdateMutex.withLock { delayForTextChannelUpdateCooldown(textChannel, diff) updateTextChannelTopic(loritta, guild, serverConfig, textChannel, memberCountConfig) } } private suspend fun delayForTextChannelUpdateCooldown(textChannel: TextChannel, diff: Long) { if (MEMBER_COUNTER_COOLDOWN > diff) { // We are also going to offset the update for about ~5m, since we can only update a channel every 5m! logger.info { "Waiting ${diff}ms until the next $textChannel topic update..." } delay(MEMBER_COUNTER_COOLDOWN - diff) } } private suspend fun updateTextChannelTopic(loritta: LorittaBot, guild: Guild, serverConfig: ServerConfig, textChannel: TextChannel, memberCounterConfig: MemberCounterChannelConfig) { val formattedTopic = memberCounterConfig.getFormattedTopic(guild) val locale = loritta.localeManager.getLocaleById(serverConfig.localeId) logger.info { "Updating text channel $textChannel topic in $guild!" } logger.trace { "Member Counter Theme = ${memberCounterConfig.theme}"} logger.trace { "Member Counter Padding = ${memberCounterConfig.padding}"} logger.trace { "Formatted Topic = $formattedTopic" } // The reason we use ".await()" is so we can track when the request is successfully sent! // And, if the request is rate limited, it will take more time to be processed, which is perfect for us! textChannel.manager.setTopic(formattedTopic).reason(locale["loritta.modules.counter.auditLogReason"]).await() memberCounterLastUpdate[textChannel.idLong] = System.currentTimeMillis() } } override fun onHttpRequest(event: HttpRequestEvent) { val copy = event.requestRaw?.newBuilder()?.build() val body = copy?.body val originalMediaType = body?.contentType() val mediaType = "${originalMediaType?.type}/${originalMediaType?.subtype}" if (mediaType == "application/json") { // We will only write the content if the input is "application/json" // // Because if we write every body, this also includes images... And that causes Humongous Allocations (a lot of memory used)! And that's bad!! val buffer = Buffer() copy?.body?.writeTo(buffer) val input = buffer.readUtf8() val length = body?.contentLength() requestLogger.info("${event.route.method.name} ${event.route.compiledRoute} Media Type: $mediaType; Content Length: $length; -> ${event.response?.code}\n$input") } else if (originalMediaType != null) { requestLogger.info("${event.route.method.name} ${event.route.compiledRoute} Media Type: $mediaType; -> ${event.response?.code}") } else { requestLogger.info("${event.route.method.name} ${event.route.compiledRoute} -> ${event.response?.code}") } } override fun onGuildInviteCreate(event: GuildInviteCreateEvent) { InviteLinkModule.cachedInviteLinks.remove(event.guild.idLong) } override fun onGuildInviteDelete(event: GuildInviteDeleteEvent) { InviteLinkModule.cachedInviteLinks.remove(event.guild.idLong) } override fun onGenericMessageReaction(e: GenericMessageReactionEvent) { val user = e.user ?: return if (user.isBot) // Se uma mensagem de um bot, ignore a mensagem! return if (DebugLog.cancelAllEvents) return if (loritta.rateLimitChecker.checkIfRequestShouldBeIgnored()) return if (loritta.messageInteractionCache.containsKey(e.messageIdLong)) { val functions = loritta.messageInteractionCache[e.messageIdLong]!! if (e is MessageReactionAddEvent) { if (functions.onReactionAdd != null) { GlobalScope.launch(loritta.coroutineDispatcher) { try { functions.onReactionAdd!!.invoke(e) } catch (e: Exception) { logger.error("Erro ao tentar processar onReactionAdd", e) } } } if (user.idLong == functions.originalAuthor && (functions.onReactionAddByAuthor != null || functions.onReactionByAuthor != null)) { GlobalScope.launch(loritta.coroutineDispatcher) { try { functions.onReactionByAuthor?.invoke(e) functions.onReactionAddByAuthor?.invoke(e) } catch (e: Exception) { logger.error("Erro ao tentar processar onReactionAddByAuthor", e) } } } } if (e is MessageReactionRemoveEvent) { if (functions.onReactionRemove != null) { GlobalScope.launch(loritta.coroutineDispatcher) { try { functions.onReactionRemove!!.invoke(e) } catch (e: Exception) { logger.error("Erro ao tentar processar onReactionRemove", e) } } } if (user.idLong == functions.originalAuthor && (functions.onReactionRemoveByAuthor != null || functions.onReactionByAuthor != null)) { GlobalScope.launch(loritta.coroutineDispatcher) { try { functions.onReactionByAuthor?.invoke(e) functions.onReactionRemoveByAuthor?.invoke(e) } catch (e: Exception) { logger.error("Erro ao tentar processar onReactionRemoveByAuthor", e) } } } } } } override fun onGuildLeave(e: GuildLeaveEvent) { logger.info { "Someone removed me @ ${e.guild}! :(" } loritta.cachedServerConfigs.invalidate(e.guild.idLong) // Remover threads de role removal caso a Loritta tenha saido do servidor val toRemove = mutableListOf<String>() MuteCommand.roleRemovalJobs.forEach { key, value -> if (key.startsWith(e.guild.id)) { logger.debug { "Stopping mute job $value @ ${e.guild} because they removed me!" } value.cancel() toRemove.add(key) } } toRemove.forEach { MuteCommand.roleRemovalJobs.remove(it) } logger.debug { "Deleting all ${e.guild} related stuff..." } GlobalScope.launch(loritta.coroutineDispatcher) { loritta.newSuspendedTransaction { logger.trace { "Deleting all ${e.guild} profiles..."} // Deletar todos os perfis do servidor GuildProfiles.deleteWhere { GuildProfiles.guildId eq e.guild.idLong } // Deletar configurações logger.trace { "Deleting all ${e.guild} configurations..." } val serverConfig = ServerConfig.findById(e.guild.idLong) logger.trace { "Removing all donation keys references about ${e.guild}..." } if (serverConfig != null) { DonationKeys.update({ DonationKeys.activeIn eq serverConfig.id }) { it[activeIn] = null } logger.trace { "Deleting all ${e.guild} role perms..." } ServerRolePermissions.deleteWhere { ServerRolePermissions.guild eq serverConfig.id } logger.trace { "Deleting all ${e.guild} custom commands..." } CustomGuildCommands.deleteWhere { CustomGuildCommands.guild eq serverConfig.id } val moderationConfig = serverConfig?.moderationConfig logger.trace { "Deleting all ${e.guild} warn actions..." } if (moderationConfig != null) WarnActions.deleteWhere { WarnActions.config eq moderationConfig.id } logger.trace { "Deleting all ${e.guild} member counters..." } MemberCounterChannelConfigs.deleteWhere { MemberCounterChannelConfigs.guild eq serverConfig.id } logger.trace { "Deleting all ${e.guild} moderation messages counters..." } ModerationPunishmentMessagesConfig.deleteWhere { ModerationPunishmentMessagesConfig.guild eq serverConfig.id } } logger.trace { "Deleting ${e.guild} config..." } serverConfig?.delete() logger.trace { "Deleting all ${e.guild}'s giveaways..." } val allGiveaways = Giveaway.find { Giveaways.guildId eq e.guild.idLong } logger.trace { "${e.guild} has ${allGiveaways.count()} giveaways that will be cancelled and deleted!" } allGiveaways.forEach { loritta.giveawayManager.cancelGiveaway(it, true, true) } Mutes.deleteWhere { Mutes.guildId eq e.guild.idLong } logger.trace { "Done! Everything related to ${e.guild} was deleted!" } } } } override fun onGuildJoin(event: GuildJoinEvent) { logger.info { "Someone added me @ ${event.guild}! :)" } } override fun onGuildMemberJoin(event: GuildMemberJoinEvent) { // Remove because maybe it is present in the set MuteCommand.notInTheServerUserIds.remove(event.user.idLong) if (DebugLog.cancelAllEvents) return if (loritta.rateLimitChecker.checkIfRequestShouldBeIgnored()) return logger.debug { "${event.member} joined server ${event.guild}" } GlobalScope.launch(loritta.coroutineDispatcher) { try { val serverConfig = loritta.getOrCreateServerConfig(event.guild.idLong, true) val profile = serverConfig.getUserDataIfExistsAsync(loritta, event.guild.idLong) if (profile != null) { loritta.newSuspendedTransaction { profile.isInGuild = true } } val autoroleConfig = serverConfig.getCachedOrRetreiveFromDatabase<AutoroleConfig?>(loritta, ServerConfig::autoroleConfig) val welcomerConfig = serverConfig.getCachedOrRetreiveFromDatabase<WelcomerConfig?>(loritta, ServerConfig::welcomerConfig) queueTextChannelTopicUpdates(loritta, event.guild, serverConfig) if (autoroleConfig != null && autoroleConfig.enabled && !autoroleConfig.giveOnlyAfterMessageWasSent && event.guild.selfMember.hasPermission(Permission.MANAGE_ROLES)) // Está ativado? AutoroleModule.giveRoles(event.member, autoroleConfig) if (welcomerConfig != null) // Está ativado? loritta.welcomeModule.handleJoin(event, serverConfig, welcomerConfig) val mute = loritta.newSuspendedTransaction { Mute.find { (Mutes.guildId eq event.guild.idLong) and (Mutes.userId eq event.member.user.idLong) }.firstOrNull() } logger.trace { "Does ${event.member} in guild ${event.guild} has a mute status? $mute" } if (mute != null) { logger.debug { "${event.member} in guild ${event.guild} has a mute! Readding roles and recreating role removal task!" } val locale = loritta.localeManager.getLocaleById(serverConfig.localeId) val muteRole = MuteCommand.getMutedRole(loritta, event.guild, loritta.localeManager.getLocaleById(serverConfig.localeId)) ?: return@launch event.guild.addRoleToMember(event.member, muteRole).await() if (mute.isTemporary) MuteCommand.spawnRoleRemovalThread(loritta, event.guild, locale, event.user, mute.expiresAt!!) } } catch (e: Exception) { logger.error("[${event.guild.name}] Ao entrar no servidor ${event.user.name}", e) } } } override fun onGuildMemberRemove(event: GuildMemberRemoveEvent) { if (DebugLog.cancelAllEvents) return if (loritta.rateLimitChecker.checkIfRequestShouldBeIgnored()) return val member = event.member val user = event.user logger.debug { "$user ($member) left server ${event.guild}" } // Remover thread de role removal caso o usuário tenha saido do servidor val job = MuteCommand.roleRemovalJobs[event.guild.id + "#" + user.id] logger.debug { "Stopping mute job $job due to member guild quit" } job?.cancel() MuteCommand.roleRemovalJobs.remove(event.guild.id + "#" + user.id) GlobalScope.launch(loritta.coroutineDispatcher) { try { if (event.user.id == loritta.config.loritta.discord.applicationId.toString()) return@launch val serverConfig = loritta.getOrCreateServerConfig(event.guild.idLong, true) val profile = serverConfig.getUserDataIfExistsAsync(loritta, event.user.idLong) if (profile != null) { loritta.newSuspendedTransaction { profile.isInGuild = false } } queueTextChannelTopicUpdates(loritta, event.guild, serverConfig) val welcomerConfig = serverConfig.getCachedOrRetreiveFromDatabase<WelcomerConfig?>(loritta, ServerConfig::welcomerConfig) if (welcomerConfig != null) loritta.welcomeModule.handleLeave(event, serverConfig, welcomerConfig) } catch (e: Exception) { logger.error("[${event.guild.name}] Ao sair do servidor ${event.user.name}", e) } } } override fun onGuildReady(event: GuildReadyEvent) { GlobalScope.launch(loritta.coroutineDispatcher) { loritta.guildSetupQueue.addToSetupQueue(event.guild) } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/listeners/DiscordListener.kt
3870205814
package net.perfectdreams.loritta.morenitta.commands.vanilla.utils import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.escapeMentions import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.translate.GoogleTranslateUtils import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.LorittaBot class TranslateCommand(loritta: LorittaBot) : AbstractCommand(loritta, "traduzir", listOf("translate"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) { override fun getDescriptionKey() = LocaleKeyData("commands.command.translate.description") override fun getExamplesKey() = LocaleKeyData("commands.command.translate.examples") // TODO: Fix Usage override suspend fun run(context: CommandContext, locale: BaseLocale) { if (context.args.size >= 2) { val strLang = context.args[0] context.args[0] = "" // Super workaround val text = context.args.joinToString(" ") try { val translatedText = GoogleTranslateUtils.translate(text, "auto", strLang) context.reply( LorittaReply( translatedText!!.escapeMentions(), "\uD83D\uDDFA" ) ) } catch (e: Exception) { logger.warn(e) { "Error while translating $text to $strLang!" } } } else { context.explain() } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/TranslateCommand.kt
88038880
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC 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.myflightbook.android import android.app.Activity import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.SparseArray import android.view.* import android.widget.BaseExpandableListAdapter import android.widget.EditText import android.widget.TextView import androidx.lifecycle.lifecycleScope import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.myflightbook.android.webservices.AuthToken import com.myflightbook.android.webservices.CustomPropertyTypesSvc import com.myflightbook.android.webservices.CustomPropertyTypesSvc.Companion.cachedPropertyTypes import com.myflightbook.android.webservices.FlightPropertiesSvc import kotlinx.coroutines.launch import model.CustomPropertyType import model.DBCache import model.DecimalEdit import model.DecimalEdit.CrossFillDelegate import model.FlightProperty import model.FlightProperty.Companion.crossProduct import model.FlightProperty.Companion.distillList import model.FlightProperty.Companion.fromDB import model.FlightProperty.Companion.refreshPropCache import model.FlightProperty.Companion.rewritePropertiesForFlight import java.util.* class ActViewProperties : FixedExpandableListActivity(), PropertyEdit.PropertyListener, CrossFillDelegate { private var mrgfpIn = arrayOf<FlightProperty>() private var mRgfpall: Array<FlightProperty>? = null private var mRgcpt: Array<CustomPropertyType>? = null private var mRgexpandedgroups: BooleanArray? = null private var mIdflight: Long = -1 private var mIdexistingid = 0 private var mXfillvalue = 0.0 private var mXfilltachstart = 0.0 private fun refreshPropertyTypes(fAllowCache : Boolean = true) { val act = this as Activity lifecycleScope.launch { ActMFBForm.doAsync<CustomPropertyTypesSvc, Array<CustomPropertyType>?>(act, CustomPropertyTypesSvc(), getString(R.string.prgCPT), { s -> s.getCustomPropertyTypes(AuthToken.m_szAuthToken, fAllowCache, act) }, { _, result -> if (result != null && result.isNotEmpty()) { mRgcpt = result // Refresh the CPT's for each item in the full array if (mRgfpall != null) { refreshPropCache() for (fp in mRgfpall!!) fp.refreshPropType() } populateList() } } ) } } private fun deleteProperty(fp : FlightProperty, idExisting: Int) { val act = this as Activity lifecycleScope.launch { ActMFBForm.doAsync<FlightPropertiesSvc, Any?>( act, FlightPropertiesSvc(), getString(R.string.prgDeleteProp), { s-> s.deletePropertyForFlight(AuthToken.m_szAuthToken, idExisting, fp.idProp, act) }, { _, _ -> val alNew = ArrayList<FlightProperty>() for (fp2 in mrgfpIn) if (fp2.idProp != fp.idProp) alNew.add(fp) mrgfpIn = alNew.toTypedArray() } ) } } private inner class ExpandablePropertyListAdapter( val mContext: Context?, val mGroups: ArrayList<String>?, val mChildren: ArrayList<ArrayList<FlightProperty>?>? ) : BaseExpandableListAdapter() { private val mCachedviews: SparseArray<View> = SparseArray() override fun getGroupCount(): Int { assert(mGroups != null) return mGroups!!.size } override fun getChildrenCount(groupPos: Int): Int { assert(mChildren != null) return mChildren!![groupPos]!!.size } override fun getGroup(i: Int): Any { assert(mGroups != null) return mGroups!![i] } override fun getChild(groupPos: Int, childPos: Int): Any { assert(mChildren != null) return mChildren!![groupPos]!![childPos] } override fun getGroupId(groupPos: Int): Long { return groupPos.toLong() } override fun getChildId(groupPos: Int, childPos: Int): Long { assert(mChildren != null) // return childPos; return mChildren!![groupPos]!![childPos].idPropType.toLong() } override fun hasStableIds(): Boolean { return false } override fun getGroupView( groupPosition: Int, isExpanded: Boolean, convertViewIn: View?, parent: ViewGroup ): View { assert(mGroups != null) var convertView = convertViewIn if (convertView == null) { assert(mContext != null) val infalInflater = (mContext!!.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater) convertView = infalInflater.inflate(R.layout.grouprow, parent, false) } val tv = convertView?.findViewById<TextView>(R.id.propertyGroup) tv?.text = mGroups!![groupPosition] return convertView!! } override fun getChildView( groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertViewIn: View?, parent: ViewGroup ): View { val fp = getChild(groupPosition, childPosition) as FlightProperty // ignore passed-in value of convert view; keep these all around all the time. var convertView = mCachedviews[fp.getCustomPropertyType()!!.idPropType] if (convertView == null) { assert(mContext != null) val infalInflater = (mContext!!.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater) convertView = infalInflater.inflate(R.layout.cptitem, parent, false) mCachedviews.put(fp.getCustomPropertyType()!!.idPropType, convertView) } val pe: PropertyEdit = convertView.findViewById(R.id.propEdit) // only init if it's not already set up - this avoids focus back-and-forth with edittext val fpExisting = pe.flightProperty if (fpExisting == null || fpExisting.idPropType != fp.idPropType) pe.initForProperty( fp, fp.idPropType, this@ActViewProperties, if (fp.idPropType == CustomPropertyType.idPropTypeTachStart) ( object: CrossFillDelegate { override fun crossFillRequested(sender: DecimalEdit?) { if (mXfilltachstart > 0 && sender != null) sender.doubleValue = mXfilltachstart } }) else this@ActViewProperties) return convertView } override fun isChildSelectable(i: Int, i1: Int): Boolean { return false } override fun onGroupExpanded(groupPosition: Int) { super.onGroupExpanded(groupPosition) if (mRgexpandedgroups != null) mRgexpandedgroups!![groupPosition] = true } override fun onGroupCollapsed(groupPosition: Int) { super.onGroupCollapsed(groupPosition) if (mRgexpandedgroups != null) mRgexpandedgroups!![groupPosition] = false } } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.expandablelist) val tvSearch = findViewById<TextView>(R.id.txtSearchProp) tvSearch.setHint(R.string.hintSearchProperties) tvSearch.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { populateList() } override fun afterTextChanged(editable: Editable) {} }) val i = intent mIdflight = i.getLongExtra(ActNewFlight.PROPSFORFLIGHTID, -1) if (mIdflight >= 0) { // initialize the flightprops from the db mrgfpIn = fromDB(mIdflight) } mIdexistingid = i.getIntExtra(ActNewFlight.PROPSFORFLIGHTEXISTINGID, 0) mXfillvalue = i.getDoubleExtra(ActNewFlight.PROPSFORFLIGHTCROSSFILLVALUE, 0.0) mXfilltachstart = i.getDoubleExtra(ActNewFlight.TACHFORCROSSFILLVALUE, 0.0) val cptSvc = CustomPropertyTypesSvc() if (cptSvc.getCacheStatus() === DBCache.DBCacheStatus.VALID) { mRgcpt = cachedPropertyTypes populateList() } else refreshPropertyTypes() val srl = findViewById<SwipeRefreshLayout>(R.id.swiperefresh) srl?.setOnRefreshListener { srl.isRefreshing = false refreshProps() } } public override fun onPause() { super.onPause() if (currentFocus != null) currentFocus!!.clearFocus() // force any in-progress edit to commit, particularly for properties. updateProps() } private fun updateProps() { val rgfpUpdated = distillList(mRgfpall) rewritePropertiesForFlight(mIdflight, rgfpUpdated) } private fun containsWords(szTargetIn: String, rgTerms: Array<String>): Boolean { var szTarget = szTargetIn szTarget = szTarget.uppercase(Locale.getDefault()) for (s in rgTerms) { if (s.isNotEmpty() && !szTarget.contains(s)) return false } return true } private fun populateList() { // get the cross product of property types with existing properties if (mRgcpt == null) mRgcpt = cachedPropertyTypes // try to avoid passing null if (mRgfpall == null) mRgfpall = crossProduct(mrgfpIn, mRgcpt) // This maps the headers to the individual sub-lists. val headers = HashMap<String, String>() val childrenMaps = HashMap<String, ArrayList<FlightProperty>?>() // Keep a list of the keys in order val alKeys = ArrayList<String>() var szKeyLast: String? = "" val szRestrict = (findViewById<View>(R.id.txtSearchProp) as EditText).text.toString().uppercase( Locale.getDefault() ) val rgTerms = szRestrict.split("\\s+".toRegex()).toTypedArray() // slice and dice into headers/first names for (fp in mRgfpall!!) { if (!containsWords(fp.labelString(), rgTerms)) continue // get the section for this property val szKey = if (fp.getCustomPropertyType()!!.isFavorite) getString(R.string.lblPreviouslyUsed) else fp.labelString() .substring(0, 1).uppercase( Locale.getDefault() ) if (szKey.compareTo(szKeyLast!!) != 0) { alKeys.add(szKey) szKeyLast = szKey } if (!headers.containsKey(szKey)) headers[szKey] = szKey // Get the array-list for that key, creating it if necessary val alProps: ArrayList<FlightProperty>? = if (childrenMaps.containsKey(szKey)) childrenMaps[szKey] else ArrayList() assert(alProps != null) alProps!!.add(fp) childrenMaps[szKey] = alProps } // put the above into arrayLists, but in the order that the keys were encountered. .values() is an undefined order. val headerList = ArrayList<String>() val childrenList = ArrayList<ArrayList<FlightProperty>?>() for (s in alKeys) { headerList.add(headers[s]!!) childrenList.add(childrenMaps[s]) } if (mRgexpandedgroups == null) mRgexpandedgroups = BooleanArray(alKeys.size) else if (mRgexpandedgroups!!.size != alKeys.size) { mRgexpandedgroups = BooleanArray(alKeys.size) if (mRgexpandedgroups!!.size <= 5) // autoexpand if fewer than 5 groups. Arrays.fill(mRgexpandedgroups!!, true) } val mAdapter = ExpandablePropertyListAdapter(this, headerList, childrenList) setListAdapter(mAdapter) for (i in mRgexpandedgroups!!.indices) if (mRgexpandedgroups!![i]) this.expandableListView!!.expandGroup(i) } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.propertylistmenu, menu) return true } private fun refreshProps() { updateProps() // preserve current user edits refreshPropertyTypes(false) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuBackToFlight -> { updateProps() finish() } R.id.menuRefreshProperties -> refreshProps() else -> return super.onOptionsItemSelected( item ) } return true } private fun deleteDefaultedProperty(fp: FlightProperty) { for (f in mrgfpIn) if (f.idPropType == fp.idPropType && f.idProp > 0) deleteProperty(fp, mIdexistingid) } //region Property update delegates override fun updateProperty(id: Int, fp: FlightProperty) { if (mIdexistingid > 0 && fp.isDefaultValue()) deleteDefaultedProperty(fp) } override fun dateOfFlightShouldReset(dt: Date) {} //region DecimalEdit cross-fill override fun crossFillRequested(sender: DecimalEdit?) { sender!!.doubleValue = mXfillvalue } //endregion }
app/src/main/java/com/myflightbook/android/ActViewProperties.kt
3931697055
package org.rocfish import org.boot.XSpringContext import io.vertx.kotlin.redis.RedisOptions import io.vertx.redis.RedisClient import org.rocfish.managers.MinioManager import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import io.vertx.ext.mongo.MongoClient import io.vertx.kotlin.core.json.JsonObject import org.rocfish.domain.* import org.rocfish.domain.views.DefaultViewPortFactory import org.rocfish.dao.DefaultSearcherFactory import org.rocfish.dao.OptionTargetFactory import org.rocfish.dao.SearcherFactory import org.rocfish.dao.impl.* import org.springframework.context.annotation.Scope @Configuration open class BeanConfig { @Value("\${redis.host}") open lateinit var redisHost:String @Value("\${redis.port}") open var redisPort:Int = 6379 @Value("\${redis.password}") open lateinit var redisPassword:String @Value("\${asyncMongo.host}") open lateinit var mongoHost:String @Value("\${asyncMongo.port}") open var mongoPort:Int = 27017 @Value("\${asyncMongo.db_name}") open lateinit var mongoDB:String @Value("\${asyncMongo.username}") open lateinit var mongoUserName:String @Value("\${asyncMongo.password}") open lateinit var mongoPassword:String @Value("\${asyncMongo.authMechanism}") open lateinit var mongoAuthMechanism:String @Value("\${asyncMongo.keepAlive}") open var mongoKeepAlive:Boolean = true @Bean(name = ["io.vertx.redis.RedisClient"]) open fun redisClient(): RedisClient { var config = RedisOptions(host = this.redisHost, port = this.redisPort, auth = this.redisPassword) return RedisClient.create(XSpringContext.vertx, config) } @Bean(name = ["org.rocfish.managers.MinioManager"]) open fun minioClient(): MinioManager = MinioManager() @Bean(name = ["io.vertx.ext.mongo.MongoClient"]) open fun asyncMongo():MongoClient = MongoClient.createShared(XSpringContext.vertx, JsonObject( "host" to this.mongoHost, "port" to this.mongoPort, "db_name" to this.mongoDB, "username" to this.mongoUserName, "password" to this.mongoPassword, "authMechanism" to this.mongoAuthMechanism, "keepAlive" to this.mongoKeepAlive)) //searcher相关配置,每个searcher都为非单例型:prototype @Bean(name = ["org.rocfish.dao.impl.collectors.mongo.QueryOptionTarget"]) @Scope("prototype") open fun mongoOptionTargetBean(): MongoOptionTargetFactoryBean { return MongoOptionTargetFactoryBean() } @Bean(name = ["org.rocfish.dao.OptionTargetFactory"]) open fun optionTargetFactory(): OptionTargetFactory { return SpringOptionTargetFactory() } @Bean(name = ["org.rocfish.domain.ViewPortFactory"]) open fun viewportFactory():ViewPortFactory { return DefaultViewPortFactory() } @Bean(name = ["org.rocfish.dao.SearcherFactory"]) open fun searcherFactory():SearcherFactory { return DefaultSearcherFactory() } }
src/main/kotlin/org/rocfish/BeanConfig.kt
795724685
package com.directdev.portal.repositories import android.content.Context import com.crashlytics.android.Crashlytics import com.directdev.portal.R import com.directdev.portal.utils.savePref import org.json.JSONException import org.json.JSONObject import javax.inject.Inject /**------------------------------------------------------------------------------------------------- * Created by chris on 8/26/17. *------------------------------------------------------------------------------------------------*/ class ProfileRepository @Inject constructor(val ctx: Context) { fun save(profile: JSONObject) { try { ctx.savePref(R.string.major, profile.getString("ACAD_PROG_DESCR")) ctx.savePref(R.string.degree, profile.getString("ACAD_CAREER_DESCR")) ctx.savePref(R.string.birthday, profile.getString("BIRTHDATE")) ctx.savePref(R.string.name, profile.getString("NAMA")) ctx.savePref(R.string.nim, profile.getString("NIM")) } catch (err: JSONException) { Crashlytics.log(profile.toString()) Crashlytics.logException(err) throw err } } }
app/src/main/java/com/directdev/portal/repositories/ProfileRepository.kt
2719564219
package com.github.christophpickl.kpotpourri.github.internal import com.github.christophpickl.kpotpourri.github.AssetUpload import com.github.christophpickl.kpotpourri.github.CreateReleaseRequest import com.github.christophpickl.kpotpourri.github.CreateReleaseResponse import com.github.christophpickl.kpotpourri.github.Github4kException import com.github.christophpickl.kpotpourri.github.GithubApi import com.github.christophpickl.kpotpourri.github.Issue import com.github.christophpickl.kpotpourri.github.Milestone import com.github.christophpickl.kpotpourri.github.RepositoryConfig import com.github.christophpickl.kpotpourri.github.State import com.github.christophpickl.kpotpourri.github.Tag import com.github.christophpickl.kpotpourri.http4k.BaseUrlConfig import com.github.christophpickl.kpotpourri.http4k.ServerConfig import com.github.christophpickl.kpotpourri.http4k.StatusFamily import com.github.christophpickl.kpotpourri.http4k.buildHttp4k import com.github.christophpickl.kpotpourri.http4k.get import com.github.christophpickl.kpotpourri.http4k.patch import com.github.christophpickl.kpotpourri.http4k.post import mu.KotlinLogging.logger @Suppress("KDocMissingDocumentation") internal class GithubApiImpl( private val config: RepositoryConfig, connection: ServerConfig ) : GithubApi { companion object { private val GITHUB_MIMETYPE = "application/vnd.github.v3+json" } private val log = logger {} private fun ServerConfig.toBaseUrlConfig() = BaseUrlConfig( protocol = protocol, hostName = hostName, port = port, path = "/repos/${config.repositoryOwner}/${config.repositoryName}" ) private val http4k = buildHttp4k { baseUrlBy(connection.toBaseUrlConfig()) basicAuth(config.username, config.password) addHeader("Accept" to GITHUB_MIMETYPE) enforceStatusFamily(StatusFamily.Success_2) } override fun listOpenMilestones(): List<Milestone> { log.debug("listOpenMilestones()") // state defaults to "open" return http4k.get<Array<MilestoneJson>>("/milestones") .map { it.toMilestone() } .sortedBy { it.version } } override fun listIssues(milestone: Milestone): List<Issue> { log.debug("listIssues(milestone={})", milestone) return http4k.get<Array<IssueJson>>("/issues") { addQueryParam("state" to "all") addQueryParam("milestone" to milestone.number) } .map { it.toIssue() } .sortedBy { it.number } } override fun listTags() = http4k.get<Array<Tag>>("/tags") .toList() .sortedBy(Tag::name) override fun close(milestone: Milestone) { if (milestone.state == State.Closed) { throw Github4kException("Milestone already closed: $milestone") } val response = http4k.patch<UpdateMilestoneResponseJson>("/milestones/${milestone.number}") { requestBody(UpdateMilestoneRequestJson(state = State.Closed.jsonValue)) } if (response.state != State.Closed.jsonValue) { throw Github4kException("Failed to close milestone: $milestone") } } override fun createNewRelease(createRequest: CreateReleaseRequest) = http4k.post<CreateReleaseResponse>("/releases") { requestBody(createRequest) } override fun listReleases(): List<CreateReleaseResponse> = http4k.get<Array<CreateReleaseResponse>>("/releases") .toList() .sortedBy { it.name } override fun uploadReleaseAsset(upload: AssetUpload) { // "upload_url": "https://uploads.github.com/repos/christophpickl/gadsu_release_playground/releases/5934443/assets{?name,label}", val uploadUrl = http4k.get<SingleReleaseJson>("/releases/${upload.releaseId}").upload_url.removeSuffix("{?name,label}") log.debug { "Upload URL for github assets: $uploadUrl" } // "https://uploads.github.com/repos/christophpickl/gadsu_release_playground/releases/5934443/assets{?name,label}" val response = http4k.post<AssetUploadResponse>(uploadUrl) { addHeader("Content-Type" to upload.contentType) addQueryParam("name" to upload.fileName) requestBytesBody(upload.bytes, upload.contentType) disableBaseUrl() } log.debug { "Uploaded asset: $response" } if (response.state != "uploaded") { throw Github4kException("Upload failed for ${upload.fileName}! ($upload, $response)") } } override fun toString() = "${this.javaClass.simpleName}[config=$config]" } @JsonData internal data class SingleReleaseJson( val upload_url: String )
github4k/src/main/kotlin/com/github/christophpickl/kpotpourri/github/internal/GithubApiImpl.kt
3554924240
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class SmartScopesTest { @Test fun test_SmartScopes_isAncestorsSet() { assertFalse(SmartScopes.Companion.isAncestorsSet(SmartScopes.SELF.flags)) assertTrue(SmartScopes.Companion.isAncestorsSet(SmartScopes.PARENT.flags)) assertTrue(SmartScopes.Companion.isAncestorsSet(SmartScopes.ANCESTORS.flags)) assertFalse(SmartScopes.Companion.isAncestorsSet(SmartScopes.CHILDREN.flags)) assertFalse(SmartScopes.Companion.isAncestorsSet(SmartScopes.DESCENDANTS.flags)) assertFalse(SmartScopes.Companion.isAncestorsSet(SmartScopes.INDICES.flags)) assertTrue(SmartScopes.Companion.isAncestorsSet(setOf(SmartScopes.PARENT, SmartScopes.ANCESTORS))) assertTrue(SmartScopes.Companion.isAncestorsSet(setOf(SmartScopes.PARENT, SmartScopes.ANCESTORS, SmartScopes.SELF))) } @Test fun test_SmartScopes_isDescendantsSet() { assertFalse(SmartScopes.Companion.isDescendantSet(SmartScopes.SELF.flags)) assertFalse(SmartScopes.Companion.isDescendantSet(SmartScopes.PARENT.flags)) assertFalse(SmartScopes.Companion.isDescendantSet(SmartScopes.ANCESTORS.flags)) assertTrue(SmartScopes.Companion.isDescendantSet(SmartScopes.CHILDREN.flags)) assertTrue(SmartScopes.Companion.isDescendantSet(SmartScopes.DESCENDANTS.flags)) assertFalse(SmartScopes.Companion.isDescendantSet(SmartScopes.INDICES.flags)) assertTrue(SmartScopes.Companion.isDescendantSet(setOf(SmartScopes.CHILDREN, SmartScopes.DESCENDANTS))) assertTrue(SmartScopes.Companion.isDescendantSet(setOf(SmartScopes.CHILDREN, SmartScopes.DESCENDANTS, SmartScopes.SELF))) } @Test fun test_SmartScopes_isValidSet() { assertTrue(SmartScopes.Companion.isValidSet(SmartScopes.SELF.flags)) assertTrue(SmartScopes.Companion.isValidSet(SmartScopes.PARENT.flags)) assertTrue(SmartScopes.Companion.isValidSet(SmartScopes.ANCESTORS.flags)) assertTrue(SmartScopes.Companion.isValidSet(SmartScopes.CHILDREN.flags)) assertTrue(SmartScopes.Companion.isValidSet(SmartScopes.DESCENDANTS.flags)) assertFalse(SmartScopes.Companion.isValidSet(SmartScopes.INDICES.flags)) assertTrue(SmartScopes.Companion.isValidSet(setOf(SmartScopes.PARENT, SmartScopes.ANCESTORS))) assertTrue(SmartScopes.Companion.isValidSet(setOf(SmartScopes.PARENT, SmartScopes.ANCESTORS, SmartScopes.SELF))) assertTrue(SmartScopes.Companion.isValidSet(setOf(SmartScopes.CHILDREN, SmartScopes.DESCENDANTS))) assertTrue(SmartScopes.Companion.isValidSet(setOf(SmartScopes.CHILDREN, SmartScopes.DESCENDANTS, SmartScopes.SELF))) assertFalse(SmartScopes.Companion.isValidSet(setOf(SmartScopes.CHILDREN, SmartScopes.PARENT, SmartScopes.ANCESTORS, SmartScopes.SELF))) assertFalse(SmartScopes.Companion.isValidSet(setOf(SmartScopes.DESCENDANTS, SmartScopes.PARENT, SmartScopes.ANCESTORS, SmartScopes.SELF))) assertFalse(SmartScopes.Companion.isValidSet(setOf(SmartScopes.PARENT, SmartScopes.CHILDREN, SmartScopes.DESCENDANTS, SmartScopes.SELF))) assertFalse(SmartScopes.Companion.isValidSet(setOf(SmartScopes.ANCESTORS, SmartScopes.CHILDREN, SmartScopes.DESCENDANTS, SmartScopes.SELF))) } }
test/src/com/vladsch/smart/SmartScopesTest.kt
1716174462
package org.paradise.ipaq.integration import com.jayway.restassured.RestAssured import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc import org.apache.commons.io.IOUtils import org.junit.After import org.junit.AfterClass import org.junit.Before import org.junit.BeforeClass import org.junit.runner.RunWith import org.mockserver.client.server.MockServerClient import org.mockserver.integration.ClientAndServer import org.mockserver.model.JsonBody import org.paradise.ipaq.ColtApplication import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT import org.springframework.core.io.Resource import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.web.context.WebApplicationContext import java.io.IOException import java.nio.charset.Charset /** * @author terrence */ @RunWith(SpringRunner::class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = arrayOf(ColtApplication::class, IntegrationConfig::class)) @TestPropertySource("/test.properties") abstract class AbstractIntegrationTest { @Autowired protected var webApplicationContext: WebApplicationContext? = null protected var mock: MockMvc? = null // Spring Boot dynamic random port injected during runtime @Value("\${local.server.port}") protected val port: Int = 0 @Before fun setup() { mock = MockMvcBuilders.webAppContextSetup(webApplicationContext!!).build() RestAssured.port = port RestAssuredMockMvc.mockMvc(mock) } @After fun tearDown() { mockServerClient!!.reset() } protected fun <T> getBean(id: String, classOfBean: Class<T>): T { return webApplicationContext!!.getBean(id, classOfBean) } protected fun <T> getBean(classOfBean: Class<T>): T { return webApplicationContext!!.getBean(classOfBean) } companion object { // Same localhost and port defined in "test.properties" val MOCK_SERVER_PORT = 8000 var mockServerClient: MockServerClient? = null @BeforeClass @JvmStatic fun beforeClass() { mockServerClient = ClientAndServer.startClientAndServer(MOCK_SERVER_PORT) } @AfterClass @JvmStatic fun afterClass() { mockServerClient!!.stop() } fun toJsonBody(resource: Resource): JsonBody { try { return JsonBody(IOUtils.toString(resource.inputStream, Charset.defaultCharset())) } catch (e: IOException) { throw RuntimeException(e) } } protected fun asJson(endpoint: String): String { return endpoint + ".json" } protected fun asXml(endpoint: String): String { return endpoint + ".xml" } protected fun sizeOf(path: String): String { return path + ".size()" } } }
src/test/kotlin/org/paradise/ipaq/integration/AbstractIntegrationTest.kt
173218961
import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec import pokur.calculate.HandProcessor import pokur.generate.CardGenerator /** * Created by jiaweizhang on 6/19/2017. */ class HandValueCorrectnessTests : StringSpec() { fun printHandValue(handValue: Int) { fun generateHandValue(handValue: Int): String { return """1: ${handValue shr 20} |2: ${handValue shr 16 and 0b1111} |3: ${handValue shr 12 and 0b1111} |4: ${handValue shr 8 and 0b1111} |5: ${handValue shr 4 and 0b1111} |6: ${handValue and 0b1111}""".trimMargin() } println(generateHandValue(handValue)) } init { val hp = HandProcessor() val cg = CardGenerator() "Compare 7 using different methods" { for (i in 1..10000) { val sevenCards = cg.generateCardsByShuffle(7) val complex = hp.findHandValue7Complex(sevenCards) val using5 = hp.findHandValue7Using5(sevenCards) if (complex != using5) { for (card in sevenCards) { print("${card.toString()} ") } println() printHandValue(complex) println() printHandValue(using5) println() complex shouldBe using5 } } } } }
src/test/kotlin/HandValueCorrectnessTests.kt
2389148066
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.websocket import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer import org.jitsi.utils.logging2.createLogger import org.jitsi.videobridge.Videobridge import org.jitsi.videobridge.relay.RelayConfig import org.jitsi.videobridge.websocket.config.WebsocketServiceConfig.Companion.config class ColibriWebSocketService( webserverIsTls: Boolean ) { private val baseUrl: String? private val relayUrl: String? init { // We default to matching the protocol used by the local jetty // instance, but we allow for the configuration via properties // to override it since certain use-cases require it. if (config.enabled) { val useTls = config.useTls ?: webserverIsTls val protocol = if (useTls) "wss" else "ws" baseUrl = "$protocol://${config.domain}/$COLIBRI_WS_ENDPOINT/${config.serverId}" relayUrl = if (RelayConfig.config.enabled) { "$protocol://${config.domain}/$COLIBRI_RELAY_WS_ENDPOINT/${config.serverId}" } else { null } logger.info("Base URL: $baseUrl Relay URL: $relayUrl") } else { logger.info("WebSockets are not enabled") baseUrl = null relayUrl = null } } /** * Return a String representing the URL for an endpoint with ID [endpointId] in a conference with * ID [conferenceId] to use to connect to the websocket with password [pwd] or null if the * [ColibriWebSocketService] is not enabled. */ fun getColibriWebSocketUrl(conferenceId: String, endpointId: String, pwd: String): String? { if (!config.enabled) { return null } // "wss://example.com/colibri-ws/server-id/conf-id/endpoint-id?pwd=123 return "$baseUrl/$conferenceId/$endpointId?pwd=$pwd" } /** * Return a String representing the URL for a relay with ID [relayId] in a conference with * ID [conferenceId] to use to connect to the websocket with password [pwd] or null if the * [ColibriWebSocketService] is not enabled. */ fun getColibriRelayWebSocketUrl(conferenceId: String, relayId: String, pwd: String): String? { if (!config.enabled) { return null } // "wss://example.com/colibri-relay-ws/server-id/conf-id/relay-id?pwd=123 return "$relayUrl/$conferenceId/$relayId?pwd=$pwd" } fun registerServlet( servletContextHandler: ServletContextHandler, videobridge: Videobridge ) { if (config.enabled) { logger.info("Registering servlet with baseUrl = $baseUrl, relayUrl = $relayUrl") val holder = ServletHolder().apply { servlet = ColibriWebSocketServlet(config.serverId, videobridge) } servletContextHandler.addServlet(holder, "/$COLIBRI_WS_ENDPOINT/*") servletContextHandler.addServlet(holder, "/$COLIBRI_RELAY_WS_ENDPOINT/*") /* TODO, if you want to register additional Websocket servlets elsewhere: factor this out, it should only be called once. */ JettyWebSocketServletContainerInitializer.configure(servletContextHandler, null) } else { logger.info("Disabled, not registering servlet") } } companion object { private val logger = createLogger() /** * The root path of the HTTP endpoint for COLIBRI WebSockets. */ private const val COLIBRI_WS_ENDPOINT = "colibri-ws" /** * The root path of the HTTP endpoint for COLIBRI Relay-to-Relay (Octo) WebSockets. */ private const val COLIBRI_RELAY_WS_ENDPOINT = "colibri-relay-ws" /** * Code elsewhere needs the value with the leading and trailing slashes, but when * building URLs above, it's more readable to have the slashes be part of the String * being built, so the separation is obvious. */ const val COLIBRI_WS_PATH = "/$COLIBRI_WS_ENDPOINT/" /** * Similarly for relay */ const val COLIBRI_RELAY_WS_PATH = "/$COLIBRI_RELAY_WS_ENDPOINT/" } }
jvb/src/main/kotlin/org/jitsi/videobridge/websocket/ColibriWebSocketService.kt
3605197215
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package pl.touk.android.bubble.coordinates import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorManager class CoordinatesCalculator { companion object { private val PITCH_POSITION = 1 private val ROLL_POSITION = 2 private val SENSOR_RESULTS_SIZE = 3 private val ORIENTATION_COORDINATES_RESULT_SIZE = 3 private val ROTATION_MATRIX_SIZE = 9 } private val magneticSensorValues: FloatArray = FloatArray(SENSOR_RESULTS_SIZE) private val accelerometerSensorValues: FloatArray = FloatArray(SENSOR_RESULTS_SIZE) private val rotationMatrix: FloatArray = FloatArray(ROTATION_MATRIX_SIZE) private val orientationCoordinates: FloatArray = FloatArray(ORIENTATION_COORDINATES_RESULT_SIZE) public fun calculate(sensorEvent: SensorEvent): Coordinates { cacheEventData(sensorEvent) SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerSensorValues, magneticSensorValues); SensorManager.getOrientation(rotationMatrix, orientationCoordinates); val pitch = orientationCoordinates[PITCH_POSITION] val roll = orientationCoordinates[ROLL_POSITION] return Coordinates(pitch, roll) } private fun cacheEventData(sensorEvent: SensorEvent) { if (sensorEvent.sensor.type == Sensor.TYPE_ACCELEROMETER) { System.arraycopy(sensorEvent.values, 0, accelerometerSensorValues, 0, SENSOR_RESULTS_SIZE); } else if (sensorEvent.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) { System.arraycopy(sensorEvent.values, 0, magneticSensorValues, 0, SENSOR_RESULTS_SIZE); } } internal fun calculateAverage(coordinates: List<Coordinates>): Coordinates { var averagePitch = 0f var averageRoll = 0f val size = coordinates.size().toFloat() coordinates.forEach { averagePitch += it.pitch averageRoll += it.roll } return Coordinates(averagePitch / size, averageRoll / size) } }
bubble/src/main/java/pl/touk/android/bubble/coordinates/CoordinatesCalculator.kt
1419776706
package com.github.shynixn.petblocks.core.logic.persistence.entity import com.github.shynixn.petblocks.api.business.annotation.YamlSerialize import com.github.shynixn.petblocks.api.persistence.entity.AIFlyRiding /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class AIFlyRidingEntity : AIBaseEntity(), AIFlyRiding { /** * Name of the type. */ override var type: String = "fly-riding" /** * Riding speed. */ @YamlSerialize(value = "speed", orderNumber = 1) override var ridingSpeed: Double = 1.0 /** * Riding offset from ground. */ @YamlSerialize(value = "offset-y", orderNumber = 2) override var ridingYOffSet: Double = 1.0 }
petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/persistence/entity/AIFlyRidingEntity.kt
3359950848
package com.cout970.magneticraft.features.automatic_machines import com.cout970.magneticraft.api.conveyorbelt.IConveyorBelt import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBoxStorage import com.cout970.magneticraft.api.pneumatic.PneumaticBox import com.cout970.magneticraft.misc.RegisterRenderer import com.cout970.magneticraft.misc.inventory.get import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.vector.* import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.tilerenderers.* import com.cout970.modelloader.api.* import com.cout970.modelloader.api.animation.AnimatedModel import com.cout970.modelloader.api.formats.gltf.GltfAnimationBuilder import com.cout970.modelloader.api.util.TRSTransformation import net.minecraft.client.Minecraft import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.block.model.ItemCameraTransforms import net.minecraft.client.renderer.texture.TextureMap import net.minecraft.item.ItemSkull import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.ResourceLocation import net.minecraft.util.math.Vec3d import net.minecraftforge.client.ForgeHooksClient /** * Created by cout970 on 2017/08/10. */ @RegisterRenderer(TileFeedingTrough::class) object TileRendererFeedingTrough : BaseTileRenderer<TileFeedingTrough>() { override fun init() { createModel(Blocks.feedingTrough) } override fun render(te: TileFeedingTrough) { val item = te.invModule.inventory[0] val level = when { item.count > 32 -> 4 item.count > 16 -> 3 item.count > 8 -> 2 item.count > 0 -> 1 else -> 0 } Utilities.rotateFromCenter(te.facing, 90f) renderModel("default") if (level > 0) { Utilities.rotateFromCenter(EnumFacing.NORTH, 90f) stackMatrix { renderSide(level, item) rotate(180f, 0.0f, 1.0f, 0.0f) translate(-1.0, 0.0, -2.0) renderSide(level, item) } } } private fun renderSide(level: Int, item: ItemStack) { if (level >= 1) { pushMatrix() transform(Vec3d(2.0, 1.1, 6.0), Vec3d(90.0, 0.0, 0.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(7.5, 1.5, 7.0), Vec3d(90.0, 30.0, 0.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() } if (level >= 2) { pushMatrix() transform(Vec3d(0.0, 2.0, 12.0), Vec3d(90.0, -30.0, 0.0), Vec3d(16.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(16.5, 2.5, 12.5), Vec3d(90.0, -30.0, 0.0), Vec3d(16.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() } if (level >= 3) { pushMatrix() transform(Vec3d(1.0, 1.0, 7.0), Vec3d(-10.0, 22.0, 4.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(0.0, 1.0, 15.0), Vec3d(10.0, -22.0, -4.0), Vec3d(16.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(-2.5, -2.0, -4.0), Vec3d(20.0, -90.0, 5.0), Vec3d(0.0, 0.0, 8.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() } if (level >= 4) { pushMatrix() transform(Vec3d(5.0, 0.0, 4.5), Vec3d(-10.0, 0.0, 0.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(7.0, 0.0, 11.0), Vec3d(14.0, 0.0, 0.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() pushMatrix() transform(Vec3d(12.0, 0.0, 10.0), Vec3d(14.0, 0.0, 0.0), Vec3d(0.0, 0.0, 0.0), Vec3d(1.0, 1.0, 1.0)) renderItem(item) popMatrix() } } private fun transform(pos: Vec3d, rot: Vec3d, rotPos: Vec3d, scale: Vec3d) { translate(PIXEL * 16, 0.0, 0.0) rotate(0, -90, 0) translate(pos.xd * PIXEL, pos.yd * PIXEL, pos.zd * PIXEL) translate(rotPos.xd * PIXEL, rotPos.yd * PIXEL, rotPos.zd * PIXEL) rotate(rot.xd, rot.yd, rot.zd) translate(-rotPos.xd * PIXEL, -rotPos.yd * PIXEL, -rotPos.zd * PIXEL) translate(PIXEL * 4, 0.0, 0.0) GlStateManager.scale(scale.xd, scale.yd, scale.zd) } private fun rotate(x: Number, y: Number, z: Number) { rotate(z, 0f, 0f, 1f) rotate(y, 0f, 1f, 0f) rotate(x, 1f, 0f, 0f) } private fun renderItem(stack: ItemStack) { Minecraft.getMinecraft().renderItem.renderItem(stack, ItemCameraTransforms.TransformType.GROUND) } } @RegisterRenderer(TileInserter::class) object TileRendererInserter : BaseTileRenderer<TileInserter>() { override fun init() { val item = FilterNotString("item") createModel(Blocks.inserter, ModelSelector("animation0", item, FilterRegex("animation0", FilterTarget.ANIMATION)), ModelSelector("animation1", item, FilterRegex("animation1", FilterTarget.ANIMATION)), ModelSelector("animation2", item, FilterRegex("animation2", FilterTarget.ANIMATION)), ModelSelector("animation3", item, FilterRegex("animation3", FilterTarget.ANIMATION)), ModelSelector("animation4", item, FilterRegex("animation4", FilterTarget.ANIMATION)), ModelSelector("animation5", item, FilterRegex("animation5", FilterTarget.ANIMATION)), ModelSelector("animation6", item, FilterRegex("animation6", FilterTarget.ANIMATION)), ModelSelector("animation7", item, FilterRegex("animation7", FilterTarget.ANIMATION)), ModelSelector("animation8", item, FilterRegex("animation8", FilterTarget.ANIMATION)), ModelSelector("animation9", item, FilterRegex("animation9", FilterTarget.ANIMATION)) ) } override fun render(te: TileInserter) { Utilities.rotateFromCenter(te.facing, 180f) val mod = te.inserterModule val transition = mod.transition val extra = if (mod.moving) ticks else 0f time = ((mod.animationTime + extra) / mod.maxAnimationTime).coerceAtMost(1f).toDouble() * 20 * 0.33 renderModel(transition.animation) val item = te.inventory[0] if (item.isEmpty) return // animation0 is used to get the articulated node because Transition.ROTATING discards the // info about translation/rotation of the inner nodes val cache0 = getModel("animation0") as? AnimationRenderCache ?: return val cache1 = getModel(transition.animation) as? AnimationRenderCache ?: return val node = cache0.model.rootNodes.firstOrNull() ?: return val anim = cache1.model val localTime = ((time / 20.0) % cache1.model.length.toDouble()).toFloat() val trs = getGlobalTransform(item, anim, node, localTime) pushMatrix() ForgeHooksClient.multiplyCurrentGlMatrix(trs.matrix.apply { transpose() }) translate(0.0, (-7.5).px, 0.0) if (!Minecraft.getMinecraft().renderItem.shouldRenderItemIn3D(item) || item.item is ItemSkull) { // 2D item scale(0.75) } else { // 3D block rotate(180f, 0f, 1f, 0f) translate(0.0, (-1.9).px, 0.0) scale(0.9) } Minecraft.getMinecraft().renderItem.renderItem(item, ItemCameraTransforms.TransformType.GROUND) popMatrix() } fun getGlobalTransform(item: ItemStack, anim: AnimatedModel, node: AnimatedModel.Node, localTime: Float): TRSTransformation { val trs = anim.getTransform(node, localTime) if (node.children.isEmpty()) return trs return trs * getGlobalTransform(item, anim, node.children[0], localTime) } } @RegisterRenderer(TileConveyorBelt::class) object TileRendererConveyorBelt : BaseTileRenderer<TileConveyorBelt>() { var belt: IRenderCache? = null var beltUp: IRenderCache? = null var beltDown: IRenderCache? = null var cornerBelt: IRenderCache? = null override fun init() { createModel(Blocks.conveyorBelt, listOf( ModelSelector("back_legs", FilterRegex("back_leg.*")), ModelSelector("front_legs", FilterRegex("front_leg.*")), ModelSelector("lateral_left", FilterRegex("lateral_left")), ModelSelector("lateral_right", FilterRegex("lateral_right")), ModelSelector("panel_left", FilterRegex("panel_left")), ModelSelector("panel_right", FilterRegex("panel_right")) ), "base") createModel(Blocks.conveyorBelt, listOf( ModelSelector("corner", FilterNotRegex("support.*")), ModelSelector("corner_supports", FilterRegex("support.*")) ), "corner_base") createModel(Blocks.conveyorBelt, listOf( ModelSelector("up", FilterNotRegex("support.*")), ModelSelector("up_supports", FilterRegex("support.*")) ), "up_base", false) createModel(Blocks.conveyorBelt, listOf( ModelSelector("down", FilterNotRegex("support.*")), ModelSelector("down_supports", FilterRegex("support.*")) ), "down_base", false) val anim = modelOf(Blocks.conveyorBelt, "anim") val cornerAnim = modelOf(Blocks.conveyorBelt, "corner_anim") val upAnim = modelOf(Blocks.conveyorBelt, "up_anim") val downAnim = modelOf(Blocks.conveyorBelt, "down_anim") //cleaning cornerBelt?.close() belt?.close() beltUp?.close() beltDown?.close() val beltModel = ModelLoaderApi.getModelEntry(anim) ?: return val cornerBeltModel = ModelLoaderApi.getModelEntry(cornerAnim) ?: return val beltUpModel = ModelLoaderApi.getModelEntry(upAnim) ?: return val beltDownModel = ModelLoaderApi.getModelEntry(downAnim) ?: return val texture = resource("blocks/machines/conveyor_belt_anim") belt = updateTexture(beltModel, texture) cornerBelt = updateTexture(cornerBeltModel, texture) beltUp = updateTexture(beltUpModel, texture) beltDown = updateTexture(beltDownModel, texture) } override fun render(te: TileConveyorBelt) { Utilities.rotateFromCenter(te.facing) renderStaticParts(te) val limit = Config.conveyorBeltItemRenderLimit if (Minecraft.getMinecraft().player.getDistanceSq(te.pos) <= limit * limit) { renderDynamicParts(te.conveyorModule, ticks) } // translate(0f, 12.5 * PIXEL, 0f) //debug hitboxes // renderHitboxes(te) } // debug fun renderHitboxes(te: TileConveyorBelt) { te.conveyorModule.boxes.forEach { Utilities.renderBox(it.getHitBox()) } } // debug bitmaps fun renderBitmap(te: TileConveyorBelt, x: Double, y: Double, z: Double) { stackMatrix { translate(x, y + 1f, z) Utilities.rotateFromCenter(te.facing) Utilities.renderBox((vec3Of(1, 0, 0) * PIXEL).createAABBUsing(vec3Of(2, 1, 1) * PIXEL), vec3Of(0, 1, 0)) Utilities.renderBox((vec3Of(0, 0, 1) * PIXEL).createAABBUsing(vec3Of(1, 1, 2) * PIXEL), vec3Of(0, 0, 1)) val bitmap2 = te.conveyorModule.generateGlobalBitMap() for (i in 0 until 16) { for (j in 0 until 16) { val color = if (!bitmap2[i, j]) vec3Of(1, 1, 1) else vec3Of(0, 0, 1) val h = if (bitmap2[i, j]) 1 else 0 Utilities.renderBox( vec3Of(i, h, j) * PIXEL createAABBUsing vec3Of(i + 1, h, j + 1) * PIXEL, color) } } } } fun renderDynamicParts(mod: IConveyorBelt, partialTicks: Float) { bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE) mod.boxes.forEach { box -> stackMatrix { val boxPos = box.position + if (box.locked) 0f else partialTicks val pos = box.getPos(partialTicks) val y = when (mod.level) { 1 -> boxPos / 16.0 -1 -> 1.0 - boxPos / 16.0 else -> 0.0 } translate(pos.xd, 13.5 * PIXEL + y, pos.zd) Utilities.renderItem(box.item, mod.facing) } } } fun renderStaticParts(te: TileConveyorBelt) { val mod = te.conveyorModule if (mod.isUp) { stackMatrix { Utilities.rotateFromCenter(EnumFacing.NORTH, 180f) beltUp?.render() renderModel("up") if (mod.hasBlockDown()) { renderModel("up_supports") } } } else if (mod.isDown) { beltDown?.render() renderModel("down") if (mod.hasBlockDown()) { renderModel("down_supports") } } else if (mod.isCorner) { stackMatrix { if (mod.hasRight()) { rotate(90f, 0f, 1f, 0f) scale(-1f, 1f, 1f) GlStateManager.cullFace(GlStateManager.CullFace.FRONT) cornerBelt?.render() renderModel("corner") if (mod.hasBlockDown()) { renderModel("corner_supports") } GlStateManager.cullFace(GlStateManager.CullFace.BACK) } else { translate(1f, 0f, 0f) rotate(-90f, 0f, 1f, 0f) cornerBelt?.render() renderModel("corner") if (mod.hasBlockDown()) { renderModel("corner_supports") } } } } else { belt?.render() renderModel("default") if (mod.hasLeft()) { renderModel("lateral_left") } else { renderModel("panel_left") } if (mod.hasRight()) { renderModel("lateral_right") } else { renderModel("panel_right") } if (!mod.hasBlockDown()) return if (mod.hasBack()) { stackMatrix { translate(0f, 0f, PIXEL) renderModel("back_legs") } } else { renderModel("back_legs") } if (!mod.hasFront()) { renderModel("front_legs") } } } private fun updateTexture(model: ModelEntry, texture: ResourceLocation): IRenderCache { val raw = model.raw val textureMap = Minecraft.getMinecraft().textureMapBlocks val animTexture = textureMap.getAtlasSprite(texture.toString()) return when (raw) { is Model.Mcx -> { val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture) TextureModelCache(TextureMap.LOCATION_BLOCKS_TEXTURE, ModelCache { ModelUtilities.renderModel(finalModel) }) } is Model.Gltf -> { val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture) val anim = GltfAnimationBuilder().buildPlain(finalModel) AnimationRenderCache(anim) { 0.0 } } else -> error("Invalid type: $raw, ${raw::class.java}") } } } @RegisterRenderer(TilePneumaticTube::class) object TileRendererPneumaticTube : BaseTileRenderer<TilePneumaticTube>() { override fun init() { createModel(Blocks.pneumaticTube, listOf( ModelSelector("center_full", FilterString("center_full")), ModelSelector("north", FilterString("north")), ModelSelector("south", FilterString("south")), ModelSelector("east", FilterString("east")), ModelSelector("west", FilterString("west")), ModelSelector("up", FilterString("up")), ModelSelector("down", FilterString("down")), ModelSelector("center_north_h", FilterString("center_north_h")), ModelSelector("center_south_h", FilterString("center_south_h")), ModelSelector("center_east_h", FilterString("center_east_h")), ModelSelector("center_west_h", FilterString("center_west_h")), ModelSelector("center_up_h", FilterString("center_up_h")), ModelSelector("center_down_h", FilterString("center_down_h")), ModelSelector("center_north_v", FilterString("center_north_v")), ModelSelector("center_south_v", FilterString("center_south_v")), ModelSelector("center_east_v", FilterString("center_east_v")), ModelSelector("center_west_v", FilterString("center_west_v")), ModelSelector("center_up_v", FilterString("center_up_v")), ModelSelector("center_down_v", FilterString("center_down_v")) )) } override fun render(te: TilePneumaticTube) { val d = te.down() val u = te.up() val n = te.north() val s = te.south() val w = te.west() val e = te.east() GlStateManager.disableCull() when { n && s && !e && !w && !u && !d -> { renderModel("center_east_h") renderModel("center_west_h") renderModel("center_up_h") renderModel("center_down_h") } !n && !s && e && w && !u && !d -> { renderModel("center_north_h") renderModel("center_south_h") renderModel("center_up_v") renderModel("center_down_v") } !n && !s && !e && !w && u && d -> { renderModel("center_north_v") renderModel("center_south_v") renderModel("center_east_v") renderModel("center_west_v") } else -> renderModel("center_full") } if (n) renderModel("north") if (s) renderModel("south") if (e) renderModel("east") if (w) renderModel("west") if (u) renderModel("up") if (d) renderModel("down") GlStateManager.enableCull() renderItems(te.flow) } fun renderItems(flow: PneumaticBoxStorage) { flow.getItems().forEach { box -> val percent = if (!box.isOutput) { 1 - ((box.progress.toFloat() + ticks * 16) / PneumaticBox.MAX_PROGRESS) } else { (box.progress.toFloat() + ticks * 16) / PneumaticBox.MAX_PROGRESS } val offset = vec3Of(8.px, 7.px, 8.px) + box.side.toVector3() * 0.5 * percent stackMatrix { translate(offset) Utilities.renderTubeItem(box.item) } } } } @RegisterRenderer(TilePneumaticRestrictionTube::class) object TileRendererPneumaticRestrictionTube : BaseTileRenderer<TilePneumaticRestrictionTube>() { override fun init() { createModel(Blocks.pneumaticRestrictionTube, listOf( ModelSelector("center_full", FilterString("center_full")), ModelSelector("north", FilterString("north")), ModelSelector("south", FilterString("south")), ModelSelector("east", FilterString("east")), ModelSelector("west", FilterString("west")), ModelSelector("up", FilterString("up")), ModelSelector("down", FilterString("down")), ModelSelector("center_north_h", FilterString("center_north_h")), ModelSelector("center_south_h", FilterString("center_south_h")), ModelSelector("center_east_h", FilterString("center_east_h")), ModelSelector("center_west_h", FilterString("center_west_h")), ModelSelector("center_up_h", FilterString("center_up_h")), ModelSelector("center_down_h", FilterString("center_down_h")), ModelSelector("center_north_v", FilterString("center_north_v")), ModelSelector("center_south_v", FilterString("center_south_v")), ModelSelector("center_east_v", FilterString("center_east_v")), ModelSelector("center_west_v", FilterString("center_west_v")), ModelSelector("center_up_v", FilterString("center_up_v")), ModelSelector("center_down_v", FilterString("center_down_v")) )) } override fun render(te: TilePneumaticRestrictionTube) { val d = te.down() val u = te.up() val n = te.north() val s = te.south() val w = te.west() val e = te.east() GlStateManager.disableCull() when { n && s && !e && !w && !u && !d -> { renderModel("center_east_h") renderModel("center_west_h") renderModel("center_up_h") renderModel("center_down_h") } !n && !s && e && w && !u && !d -> { renderModel("center_north_h") renderModel("center_south_h") renderModel("center_up_v") renderModel("center_down_v") } !n && !s && !e && !w && u && d -> { renderModel("center_north_v") renderModel("center_south_v") renderModel("center_east_v") renderModel("center_west_v") } else -> renderModel("center_full") } if (n) renderModel("north") if (s) renderModel("south") if (e) renderModel("east") if (w) renderModel("west") if (u) renderModel("up") if (d) renderModel("down") GlStateManager.enableCull() TileRendererPneumaticTube.renderItems(te.flow) } }
src/main/kotlin/com/cout970/magneticraft/features/automatic_machines/TileRenders.kt
1116472050
package net.upgaming.pbrengine.models import net.upgaming.pbrengine.util.toFloatBuffer import org.joml.Vector2f import org.joml.Vector3f import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.* import org.lwjgl.opengl.GL30.* import java.io.File import java.nio.file.Files class Model(val vao: Int, val vertexCount: Int) { object Loader { private val vaos = arrayListOf<Int>() private val vbos = arrayListOf<Int>() fun load(data: Data): Model { val vao = createVAO() glBindVertexArray(vao) storeDataInAttributeArray(0, 3, data.vertices) storeDataInAttributeArray(1, 3, data.normals) storeDataInAttributeArray(2, 2, data.texCoords) glBindVertexArray(0) return Model(vao, data.vertices.size / 3) } fun loadVerticesOnly(vertices: FloatArray): Model { val vao = createVAO() glBindVertexArray(vao) storeDataInAttributeArray(0, 3, vertices) glBindVertexArray(0) return Model(vao, vertices.size / 3) } private fun storeDataInAttributeArray(index: Int, size: Int, data: FloatArray) { val buffer = data.toFloatBuffer() val vbo = createVBO() glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW) glVertexAttribPointer(index, size, GL_FLOAT, false, 0, 0) glEnableVertexAttribArray(index) glBindBuffer(GL_ARRAY_BUFFER, 0) } private fun createVAO(): Int { val vao = glGenVertexArrays() vaos.add(vao) return vao } private fun createVBO(): Int { val vbo = glGenBuffers() vbos.add(vbo) return vbo } fun cleanUp() { vbos.forEach(::glDeleteBuffers) vaos.forEach(::glDeleteVertexArrays) } } object OBJLoader { val vertices = arrayListOf<Vector3f>() val normals = arrayListOf<Vector3f>() val texCoords = arrayListOf<Vector2f>() val ordVertices = arrayListOf<Vector3f>() val ordNormals = arrayListOf<Vector3f>() val ordTexCoords = arrayListOf<Vector2f>() fun load(name: String): Model { clear() val path = "res/models/$name.obj" File(path).forEachLine { val parts = it.split(" ") when { it.startsWith("v ") -> { vertices.add(Vector3f( parts[1].toFloat(), parts[2].toFloat(), parts[3].toFloat() )) } it.startsWith("vn ") -> { normals.add(Vector3f( parts[1].toFloat(), parts[2].toFloat(), parts[3].toFloat() )) } it.startsWith("vt ") -> { texCoords.add(Vector2f( parts[1].toFloat(), parts[2].toFloat() )) } it.startsWith("f ") -> { for(i in 1..3) { val ind = parts[i].split("/") ordVertices.add(vertices[ind[0].toInt() - 1]) ordNormals.add(normals[ind[2].toInt() - 1]) ordTexCoords.add(texCoords[ind[1].toInt() - 1]) } } } } val verticesArray = FloatArray(ordVertices.size * 3) val normalsArray = FloatArray(ordNormals.size * 3) val texCoordsArray = FloatArray(ordTexCoords.size * 2) var count = 0 ordVertices.forEach { verticesArray[count++] = it.x verticesArray[count++] = it.y verticesArray[count++] = it.z } count = 0 ordNormals.forEach { normalsArray[count++] = it.x normalsArray[count++] = it.y normalsArray[count++] = it.z } count = 0 ordTexCoords.forEach { texCoordsArray[count++] = it.x texCoordsArray[count++] = it.y } return Model.Loader.load(Data(verticesArray, normalsArray, texCoordsArray)) } private fun clear() { vertices.clear() normals.clear() ordVertices.clear() ordNormals.clear() } } class Data(val vertices: FloatArray, val normals: FloatArray, val texCoords: FloatArray) }
src/main/kotlin/net/upgaming/pbrengine/models/Model.kt
2735973320
package com.example.android.eyebody.management.gallery import android.content.Intent import android.os.Bundle import android.os.Environment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import java.io.File import android.support.v7.widget.RecyclerView import android.widget.Toast import com.example.android.eyebody.R import com.example.android.eyebody.gallery.Photo import com.example.android.eyebody.gallery.PhotoFrameActivity import com.example.android.eyebody.management.BasePageFragment /** * Created by YOON on 2017-11-11 * Modified by Yeji on 2017-12-24 */ class GalleryManagementFragment : BasePageFragment() { var photoList = ArrayList<Photo>() lateinit var galleryView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { pageNumber = arguments.getInt(ARG_PAGE_NUMBER) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { var view = inflater!!.inflate(R.layout.fragment_management_gallery, container, false) galleryView = view.findViewById(R.id.galleryView) //photoList에 값 채워넣기(이미지 불러오기) LoadPhotos() //RecyclerView galleryView.hasFixedSize() galleryView.adapter = GalleryManagementAdapter(activity, this, photoList) return view } companion object { private val ARG_PAGE_NUMBER = "param1" fun newInstance(pn : Int) : GalleryManagementFragment { val fragment = GalleryManagementFragment() val args = Bundle() args.putInt(ARG_PAGE_NUMBER, pn) fragment.arguments = args return fragment } } fun LoadPhotos(){ var state: String = Environment.getExternalStorageState() //외부저장소(SD카드)가 마운트되었는지 확인 if (Environment.MEDIA_MOUNTED.equals(state)) { //디렉토리 생성 var filedir: String = activity.getExternalFilesDir(null).toString() + "/gallery_body" //Android/data/com.example.android.eyebody/files/gallery_body var file: File = File(filedir) if (!file.exists()) { if (!file.mkdirs()) { //EXCEPTION 디렉토리가 만들어지지 않음 } } for (f in file.listFiles()) { //TODO 이미지 파일이 아닌경우 예외처리 //TODO 이미지를 암호화해서 저장해놓고 불러올 때만 복호화 하기 photoList.add(Photo(f)) } } else{ //TODO EXCEPTION 외부저장소가 마운트되지 않아서 파일을 읽고 쓸 수 없음 } } fun itemViewClicked(itemView: View, pos: Int){ var intent = Intent(activity, PhotoFrameActivity::class.java) intent.putExtra("photoList", photoList) intent.putExtra("pos", pos); startActivity(intent) } fun itemViewLongClicked(itemView: View, pos: Int): Boolean{ return true } }
EyeBody2/app/src/main/java/com/example/android/eyebody/management/gallery/GalleryManagementFragment.kt
3681417695
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.networks.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.wear.compose.foundation.CurvedTextStyle import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.TimeText import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi import com.google.android.horologist.networks.data.DataUsageReport import com.google.android.horologist.networks.data.NetworkType import com.google.android.horologist.networks.data.Networks @ExperimentalHorologistNetworksApi @Composable public fun DataUsageTimeText( showData: Boolean, networkStatus: Networks, networkUsage: DataUsageReport?, modifier: Modifier = Modifier, pinnedNetworks: Set<NetworkType> = setOf() ) { val style = CurvedTextStyle(MaterialTheme.typography.caption1) val context = LocalContext.current if (showData) { TimeText( modifier = modifier, startCurvedContent = { curveDataUsage( networkStatus = networkStatus, networkUsage = networkUsage, style = style, context = context, pinnedNetworks = pinnedNetworks ) }, startLinearContent = { LinearDataUsage( networkStatus = networkStatus, networkUsage = networkUsage, style = MaterialTheme.typography.caption1, context = context ) } ) } else { TimeText(modifier = modifier) } }
network-awareness/src/main/java/com/google/android/horologist/networks/ui/DataUsageTimeText.kt
464901312
package com.elpassion.android.commons.rxjava2.test import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import io.reactivex.Completable import io.reactivex.observers.TestObserver import org.junit.Test class StubbingCompletableExtensionTest { @Test fun shouldReturnCompletableNeverWhenThenNeverIsUsed() { val mock = mock<Function0<Completable>>() whenever(mock.invoke()).thenNever() mock.invoke().test().assertCompletableNever() } @Test fun shouldReturnCompletableNeverWhenDoReturnNeverIsUsed() { val mock = mock<Function0<Completable>>() whenever(mock.invoke()).doReturnNever() mock.invoke().test().assertCompletableNever() } @Test fun shouldReturnCompletableJustWhenThenJustIsUsed() { val mock = mock<Function0<Completable>>() whenever(mock.invoke()).thenComplete() mock.invoke().test().assertCompletableComplete() } @Test fun shouldReturnCompletableJustWhenThenDoReturnJustIsUsed() { val mock = mock<Function0<Completable>>() whenever(mock.invoke()).doReturnComplete() mock.invoke().test().assertCompletableComplete() } @Test fun shouldReturnCompletableErrorWhenThenErrorIsUsed() { val mock = mock<Function0<Completable>>() val expectedError = RuntimeException() whenever(mock.invoke()).thenError(expectedError) mock.invoke().test().assertCompletableError(expectedError) } @Test fun shouldReturnCompletableErrorWhenDoReturnErrorIsUsed() { val mock = mock<Function0<Completable>>() val expectedError = RuntimeException() whenever(mock.invoke()).doReturnError(expectedError) mock.invoke().test().assertCompletableError(expectedError) } private fun <T> TestObserver<T>.assertCompletableError(expectedError: RuntimeException) { assertNoValues() assertError(expectedError) assertNotComplete() assertTerminated() } private fun <T> TestObserver<T>.assertCompletableNever() { assertNoValues() assertNoErrors() assertNotComplete() } private fun <T> TestObserver<T>.assertCompletableComplete() { assertNoValues() assertNoErrors() assertComplete() } }
rxjava2-test/src/test/java/com/elpassion/android/commons/rxjava2/test/StubbingCompletableExtensionTest.kt
2553299495
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.networks @RequiresOptIn( message = "Horologist Network Awareness is experimental. The API may be changed in the future." ) @Retention(AnnotationRetention.BINARY) public annotation class ExperimentalHorologistNetworksApi
network-awareness/src/main/java/com/google/android/horologist/networks/ExperimentalHorologistNetworksApi.kt
2797577307
package com.github.shanehd.utilities.kotlin import java.util.ArrayList import com.github.shanehd.utilities.StringUtils import com.github.shanehd.utilities.FileUtils import com.github.shanehd.utilities.i.NewLineIterator /** * @author https://www.github.com/ShaneHD */ /** * Surround a {@link String} with quotation marks */ val Any.quote: String get() = "\"$this\"" /** * Split a {@link String} by its {@link String#length()} */ fun String.splitByLength(maxLength: Int) : ArrayList<String> { return StringUtils.splitByLength(this, maxLength) } /** * Replace the last occurrence of something in a {@link String} */ fun String.replaceLast(from: String, to: String) : String { return StringUtils.replaceLast(this, from, to) } /** * Clean HTML tags from a {@link String}<br> * Only replaces < and > for now<br> * TODO improve */ val String.noHTML: String get() = StringUtils.cleanHTML(this) /** * Makes the first character upper case */ val String.firstUpper: String get() = StringUtils.format_FirstLetterUpper(this) /** * Iterate over all lines (\n) */ fun String.iterateLines(iterator: NewLineIterator) { FileUtils.iterateLines(this, iterator) }
Global Utilities/src/com/github/shanehd/utilities/kotlin/Ext_String.kt
3596067751
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.core.scope import org.koin.core.Koin import org.koin.core.component.KoinApiExtension import org.koin.core.definition.BeanDefinition import org.koin.core.definition.indexKey import org.koin.core.error.ClosedScopeException import org.koin.core.error.MissingPropertyException import org.koin.core.error.NoBeanDefFoundException import org.koin.core.logger.Level import org.koin.core.parameter.DefinitionParameters import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import org.koin.core.registry.InstanceRegistry import org.koin.core.time.measureDurationForResult import org.koin.ext.getFullName import kotlin.reflect.KClass data class Scope( val id: ScopeID, @KoinApiExtension val _scopeDefinition: ScopeDefinition, private val _koin: Koin ) { @PublishedApi internal val _linkedScope: ArrayList<Scope> = arrayListOf() @PublishedApi internal val _instanceRegistry = InstanceRegistry(_koin, this) @PublishedApi internal var _source: Any? = null val closed: Boolean get() = _closed private val _callbacks = arrayListOf<ScopeCallback>() private var _closed: Boolean = false private var _parameters: DefinitionParameters? = null val logger = _koin.logger internal fun create(links: List<Scope>) { _instanceRegistry.create(_scopeDefinition.definitions) _linkedScope.addAll(links) } inline fun <reified T : Any> getSource(): T = _source as? T ?: error( "Can't use Scope source for ${T::class.getFullName()} - source is:$_source") @KoinApiExtension fun setSource(t: Any?) { _source = t } /** * Add parent Scopes to allow instance resolution * i.e: linkTo(scopeC) - allow to resolve instance to current scope and scopeC * * @param scopes - Scopes to link with */ fun linkTo(vararg scopes: Scope) { if (!_scopeDefinition.isRoot) { _linkedScope.addAll(scopes) } else { error("Can't add scope link to a root scope") } } /** * Remove linked scope */ fun unlink(vararg scopes: Scope) { if (!_scopeDefinition.isRoot) { _linkedScope.removeAll(scopes) } else { error("Can't remove scope link to a root scope") } } /** * Lazy inject a Koin instance * @param qualifier * @param scope * @param parameters * * @return Lazy instance of type T */ @JvmOverloads inline fun <reified T : Any> inject( qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) { get<T>(qualifier, parameters) } /** * Lazy inject a Koin instance if available * @param qualifier * @param scope * @param parameters * * @return Lazy instance of type T or null */ @JvmOverloads inline fun <reified T : Any> injectOrNull( qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T?> = lazy(LazyThreadSafetyMode.NONE) { getOrNull<T>(qualifier, parameters) } /** * Get a Koin instance * @param qualifier * @param scope * @param parameters */ @JvmOverloads inline fun <reified T : Any> get( qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): T { return get(T::class, qualifier, parameters) } /** * Get a Koin instance if available * @param qualifier * @param scope * @param parameters * * @return instance of type T or null */ @JvmOverloads inline fun <reified T : Any> getOrNull( qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): T? { return getOrNull(T::class, qualifier, parameters) } /** * Get a Koin instance if available * @param qualifier * @param scope * @param parameters * * @return instance of type T or null */ @JvmOverloads fun <T : Any> getOrNull( clazz: KClass<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T? { return try { get(clazz, qualifier, parameters) } catch (e: ClosedScopeException) { _koin._logger.debug("Koin.getOrNull - scope closed - no instance found for ${clazz.getFullName()} on scope ${toString()}") null } catch (e: NoBeanDefFoundException) { _koin._logger.debug("Koin.getOrNull - no instance found for ${clazz.getFullName()} on scope ${toString()}") null } } /** * Get a Koin instance * @param clazz * @param qualifier * @param parameters * * @return instance of type T */ fun <T : Any> get( clazz: KClass<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { return if (_koin._logger.isAt(Level.DEBUG)) { val qualifierString = qualifier?.let { " with qualifier '$qualifier'" } ?: "" _koin._logger.debug("+- '${clazz.getFullName()}'$qualifierString") val (instance: T, duration: Double) = measureDurationForResult { resolveInstance<T>(qualifier, clazz, parameters) } _koin._logger.debug("|- '${clazz.getFullName()}' in $duration ms") return instance } else { resolveInstance(qualifier, clazz, parameters) } } /** * Get a Koin instance * @param java class * @param qualifier * @param parameters * * @return instance of type T */ @JvmOverloads fun <T : Any> get( clazz: Class<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { val kClass = clazz.kotlin return get(kClass, qualifier, parameters) } @Suppress("UNCHECKED_CAST") private fun <T : Any> resolveInstance( qualifier: Qualifier?, clazz: KClass<T>, parameters: ParametersDefinition? ): T { if (_closed) { throw ClosedScopeException("Scope '$id' is closed") } val indexKey = indexKey(clazz, qualifier) return _instanceRegistry.resolveInstance(indexKey, parameters) ?: run { _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope") getFromSource(clazz) } ?: run { _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope's source") _parameters?.getOrNull<T>(clazz) } ?: run { _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in injected parameters") findInOtherScope<T>(clazz, qualifier, parameters) } ?: run { _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in linked scopes") throwDefinitionNotFound(qualifier, clazz) } } @Suppress("UNCHECKED_CAST") private fun <T> getFromSource(clazz: KClass<*>): T? { return if (clazz.isInstance(_source)) _source as? T else null } private fun <T : Any> findInOtherScope( clazz: KClass<T>, qualifier: Qualifier?, parameters: ParametersDefinition? ): T? { var instance: T? = null for (scope in _linkedScope) { instance = scope.getOrNull<T>( clazz, qualifier, parameters ) if (instance != null) break } return instance } private fun throwDefinitionNotFound( qualifier: Qualifier?, clazz: KClass<*> ): Nothing { val qualifierString = qualifier?.let { " & qualifier:'$qualifier'" } ?: "" throw NoBeanDefFoundException( "No definition found for class:'${clazz.getFullName()}'$qualifierString. Check your definitions!") } internal fun createEagerInstances() { if (_scopeDefinition.isRoot) { _instanceRegistry.createEagerInstances() } } /** * Declare a component definition from the given instance * This result of declaring a scoped/single definition of type T, returning the given instance * (single definition of the current scope is root) * * @param instance The instance you're declaring. * @param qualifier Qualifier for this declaration * @param secondaryTypes List of secondary bound types * @param override Allows to override a previous declaration of the same type (default to false). */ inline fun <reified T : Any> declare( instance: T, qualifier: Qualifier? = null, secondaryTypes: List<KClass<*>>? = null, override: Boolean = false ) = synchronized(this) { val definition = _scopeDefinition.saveNewDefinition(instance, qualifier, secondaryTypes, override) _instanceRegistry.saveDefinition(definition, override = true) } /** * Get current Koin instance */ fun getKoin() = _koin /** * Get Scope * @param scopeID */ fun getScope(scopeID: ScopeID) = getKoin().getScope(scopeID) /** * Register a callback for this Scope Instance */ fun registerCallback(callback: ScopeCallback) { _callbacks += callback } /** * Get a all instance for given inferred class (in primary or secondary type) * * @return list of instances of type T */ inline fun <reified T : Any> getAll(): List<T> = getAll(T::class) /** * Get a all instance for given class (in primary or secondary type) * @param clazz T * * @return list of instances of type T */ fun <T : Any> getAll(clazz: KClass<*>): List<T> = _instanceRegistry.getAll(clazz) /** * Get instance of primary type P and secondary type S * (not for scoped instances) * * @return instance of type S */ inline fun <reified S, reified P> bind(noinline parameters: ParametersDefinition? = null): S { val secondaryType = S::class val primaryType = P::class return bind(primaryType, secondaryType, parameters) } /** * Get instance of primary type P and secondary type S * (not for scoped instances) * * @return instance of type S */ fun <S> bind( primaryType: KClass<*>, secondaryType: KClass<*>, parameters: ParametersDefinition? ): S { return _instanceRegistry.bind(primaryType, secondaryType, parameters) ?: throw NoBeanDefFoundException( "No definition found to bind class:'${primaryType.getFullName()}' & secondary type:'${secondaryType.getFullName()}'. Check your definitions!") } /** * Retrieve a property * @param key * @param defaultValue */ fun getProperty(key: String, defaultValue: String): String = _koin.getProperty(key, defaultValue) /** * Retrieve a property * @param key */ fun getPropertyOrNull(key: String): String? = _koin.getProperty(key) /** * Retrieve a property * @param key */ fun getProperty(key: String): String = _koin.getProperty(key) ?: throw MissingPropertyException("Property '$key' not found") /** * Close all instances from this scope */ fun close() = synchronized(this) { clear() _koin._scopeRegistry.deleteScope(this) } internal fun clear() { _closed = true _source = null if (_koin._logger.isAt(Level.DEBUG)) { _koin._logger.info("closing scope:'$id'") } // call on close from callbacks _callbacks.forEach { it.onScopeClose(this) } _callbacks.clear() _instanceRegistry.close() } override fun toString(): String { return "['$id']" } fun dropInstance(beanDefinition: BeanDefinition<*>) { _instanceRegistry.dropDefinition(beanDefinition) } fun loadDefinition(beanDefinition: BeanDefinition<*>) { _instanceRegistry.createDefinition(beanDefinition) } fun addParameters(parameters: DefinitionParameters) { _parameters = parameters } fun clearParameters() { _parameters = null } } typealias ScopeID = String
koin-projects/koin-core/src/main/kotlin/org/koin/core/scope/Scope.kt
1462174870
package com.mmartin.ghibliapi.person /** * Created by mmartin on 2/3/18. */ class PersonDetailPresenter { }
app/src/main/java/com/mmartin/ghibliapi/person/PersonDetailPresenter.kt
165488605
package com.garpr.android.data.models import com.garpr.android.test.BaseTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Test class SmashCompetitorTest : BaseTest() { companion object { private val SMASH_COMPETITOR_1 = SmashCompetitor( id = "1", name = "Charles", tag = "Charlezard" ) private val SMASH_COMPETITOR_2 = SmashCompetitor( id = "2", name = "Declan", tag = "Imyt", mains = listOf(SmashCharacter.SHEIK, SmashCharacter.FALCO, SmashCharacter.FOX) ) private val SMASH_COMPETITOR_3 = SmashCompetitor( id = "3", name = "Ivan", tag = "gaR", mains = emptyList() ) private val SMASH_COMPETITOR_4 = SmashCompetitor( id = "4", name = "Justin", tag = "mikkuz", mains = listOf(SmashCharacter.FOX, SmashCharacter.FOX, SmashCharacter.CPTN_FALCON, null) ) } @Test fun testFilteredMains1() { assertNull(SMASH_COMPETITOR_1.filteredMains) } @Test fun testFilteredMains2() { val filteredMains = SMASH_COMPETITOR_2.filteredMains assertEquals(3, filteredMains?.size) assertEquals(true, filteredMains?.contains(SmashCharacter.SHEIK)) assertEquals(true, filteredMains?.contains(SmashCharacter.FALCO)) assertEquals(true, filteredMains?.contains(SmashCharacter.FOX)) } @Test fun testFilteredMains3() { assertNull(SMASH_COMPETITOR_3.filteredMains) } @Test fun testFilteredMains4() { val filteredMains = SMASH_COMPETITOR_4.filteredMains assertEquals(2, filteredMains?.size) assertEquals(true, filteredMains?.contains(SmashCharacter.FOX)) assertEquals(true, filteredMains?.contains(SmashCharacter.CPTN_FALCON)) } @Test fun testEquals() { assertEquals(SMASH_COMPETITOR_1, SMASH_COMPETITOR_1) assertEquals(SMASH_COMPETITOR_2, SMASH_COMPETITOR_2) assertEquals(SMASH_COMPETITOR_3, SMASH_COMPETITOR_3) assertEquals(SMASH_COMPETITOR_4, SMASH_COMPETITOR_4) assertNotEquals(SMASH_COMPETITOR_1, SMASH_COMPETITOR_2) assertNotEquals(SMASH_COMPETITOR_2, SMASH_COMPETITOR_3) assertNotEquals(SMASH_COMPETITOR_3, SMASH_COMPETITOR_4) assertNotEquals(SMASH_COMPETITOR_4, SMASH_COMPETITOR_1) } @Test fun testHashCode() { assertEquals(SMASH_COMPETITOR_1.id.hashCode(), SMASH_COMPETITOR_1.hashCode()) assertEquals(SMASH_COMPETITOR_2.id.hashCode(), SMASH_COMPETITOR_2.hashCode()) assertEquals(SMASH_COMPETITOR_3.id.hashCode(), SMASH_COMPETITOR_3.hashCode()) assertEquals(SMASH_COMPETITOR_4.id.hashCode(), SMASH_COMPETITOR_4.hashCode()) assertNotEquals(SMASH_COMPETITOR_1.hashCode(), SMASH_COMPETITOR_2.hashCode()) assertNotEquals(SMASH_COMPETITOR_2.hashCode(), SMASH_COMPETITOR_3.hashCode()) assertNotEquals(SMASH_COMPETITOR_3.hashCode(), SMASH_COMPETITOR_4.hashCode()) assertNotEquals(SMASH_COMPETITOR_4.hashCode(), SMASH_COMPETITOR_1.hashCode()) } }
smash-ranks-android/app/src/test/java/com/garpr/android/data/models/SmashCompetitorTest.kt
1111437245
package com.openlattice.edm.processors import com.openlattice.edm.type.PropertyType import com.openlattice.rhizome.hazelcast.entryprocessors.AbstractReadOnlyRhizomeEntryProcessor import org.apache.olingo.commons.api.edm.FullQualifiedName import java.util.* /** * @author Drew Bailey &lt;[email protected]&gt; */ class GetFqnFromPropertyTypeEntryProcessor: AbstractReadOnlyRhizomeEntryProcessor<UUID, PropertyType, FullQualifiedName>() { override fun process(entry: MutableMap.MutableEntry<UUID, PropertyType?>): FullQualifiedName? { val es = entry.value ?: return null return es.type } }
src/main/kotlin/com/openlattice/edm/processors/GetFqnFromPropertyTypeEntryProcessor.kt
3324290969
package com.kazucocoa.droidtesthelperlib import android.content.Intent import android.os.IBinder import android.util.Log import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.Arrays class HandleAnimations { private val DISABLE = 0.0f private val ENABLE = 1.0f private lateinit var setAnimationScalesMethod: Method private lateinit var getAnimationScalesMethod: Method private lateinit var windowManagerObject: Any private fun animationHandler() { try { val asInterface = Class.forName("android.view.IWindowManager\$Stub").getDeclaredMethod("asInterface", IBinder::class.java) val getService = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String::class.java) val windowManagerClazz = Class.forName("android.view.IWindowManager") setAnimationScalesMethod = Class.forName("android.view.IWindowManager").getDeclaredMethod("setAnimationScales", FloatArray::class.java) getAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales") windowManagerObject = asInterface.invoke(null, getService.invoke(null, "window") as IBinder) } catch (e: Exception) { throw RuntimeException("Failed to access animation methods", e) } } private fun disableAnimations() { try { setAnimationScaleWith(DISABLE) } catch (e: Exception) { Log.e(TAG, "Failed to disable animations", e) } } fun enableAnimations() { try { setAnimationScaleWith(ENABLE) } catch (e: Exception) { Log.e(TAG, "Failed to enable animations", e) } } @Throws(InvocationTargetException::class, IllegalAccessException::class) private fun setAnimationScaleWith(scaleFactor: Float) { (getAnimationScalesMethod.invoke(windowManagerObject) as FloatArray).let { Arrays.fill(it, scaleFactor) setAnimationScalesMethod.invoke(windowManagerObject, it) } } companion object { private val TAG = HandleAnimations::class.java.simpleName private const val animationExtra = "ANIMATION" fun hasExtraRegardingAnimation(intent: Intent): Boolean { return intent.hasExtra(animationExtra) } fun enableAnimationsWithIntent(intent: Intent) { val enableAnimation = intent.getBooleanExtra(animationExtra, false) val handleAnimations = HandleAnimations() handleAnimations.animationHandler() if (enableAnimation) { handleAnimations.enableAnimations() } else { handleAnimations.disableAnimations() } } } }
droidtesthelperlib/src/main/java/com/kazucocoa/droidtesthelperlib/HandleAnimations.kt
3342183722