repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
980f/droid
android/src/main/kotlin/pers/hal42/android/NumberEditor.kt
1
3339
package pers.hal42.android import android.content.Intent import android.os.Bundle import android.view.inputmethod.EditorInfo.IME_ACTION_DONE import android.widget.EditText val dbg = Logger("NumberEditor") /** edit the given property * until we can figure out how to get Kotlin to give us a property with reasonable syntax we pass the setter and getter. * As of this note the '::' operator only works on a native object, not an instance of a class * */ class NumberEditor() : EasyActivity(1) { class Connection(val legend: String, val desc: String, val asInteger: Boolean, val hasSign: Boolean, val getter: () -> Float, val setter: (Float) -> Unit) { companion object X { //todo: reflection const val resultKey = "result" const val descKey = "desc" const val legendKey = "legend" const val startingKey = "starting" const val asIntegerKey = "asInteger" const val hasSignKey = "hasSign" fun entry(image: String?): Intent { val intent = Intent("NumberEntryResult") intent.putExtra(resultKey, image) return intent } fun recreate(transport: Intent): Connection { val connection = Connection( transport.getStringExtra(legendKey), transport.getStringExtra(descKey), transport.getBooleanExtra(asIntegerKey, false), transport.getBooleanExtra(hasSignKey, true), { transport.getFloatExtra(startingKey, 0F) }, { Unit } ) return connection } } /** the container will map activity results to this EditorConnection via this code*/ fun uniqueID() = this.hashCode() fun sendParams(intent: Intent) { intent.putExtra(descKey, desc) intent.putExtra(legendKey, legend) intent.putExtra(asIntegerKey, asInteger) intent.putExtra(hasSignKey, hasSign) intent.putExtra(startingKey, getter()) } /** accepting text so that we can add SI units to user entry */ fun accept(data: Intent?) { data?.let { val image = data.getStringExtra(resultKey) image?.let { try { val result = image.toFloat() dbg.i("As string: %s, as number: %f", image, result) setter(result) } catch (ex: NumberFormatException) { //don't call anything. dbg.e("Bad Format: %s", image) } } } } } var editor: EditText? = null fun onEditorAction(actionId: Int) { if (actionId == IME_ACTION_DONE) { val text = editor?.text val result = text?.toString() setResult(RESULT_OK, Connection.X.entry(result)) finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val connection = Connection.X.recreate(intent) val starting = connection.getter() makeText(-1).format(connection.desc, starting) editor = gridManager.addNumberEntry(starting, connection.asInteger, connection.hasSign) editor!!.selectAll() //but touching the widget to bring up the keyboard only deletes one character (occasionally none) editor!!.setOnEditorActionListener { p0, p1, p2 -> onEditorAction(p1) true } editor!!.showSoftInputOnFocus = true //despite upping sdk level this does not do what it suggests it does. } }
mit
595e8b7975dd37e4b11f762d3072623e
32.059406
158
0.651692
4.253503
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/InputClassScope.kt
24
2922
package org.jetbrains.protocolModelGenerator import org.jetbrains.jsonProtocol.ItemDescriptor import org.jetbrains.jsonProtocol.ProtocolMetaModel import org.jetbrains.protocolReader.TextOutput internal class InputClassScope(generator: DomainGenerator, namePath: NamePath) : ClassScope(generator, namePath) { override val typeDirection = TypeData.Direction.INPUT fun generateDeclarationBody(out: TextOutput, list: List<ItemDescriptor.Named>) { for (i in 0 until list.size) { val named = list[i] if (named.description != null) { out.doc(named.description) } val name = named.getName() val declarationName = generateMethodNameSubstitute(name, out) if (classContextNamespace.lastComponent == "RemoteObjectValue" && name == "value") { // specification says it is string, but it can be map or any other JSON too, so set Any? type out.append("@org.jetbrains.jsonProtocol.JsonField(allowAnyPrimitiveValue=true)\n" + " @Optional\n" + " fun value(): Any?\n\n ") continue } val typeDescriptor = InputMemberScope(name).resolveType(named) writeMember(out, typeDescriptor, declarationName) if (i != (list.size - 1)) { out.newLine().newLine() } } } inner class InputMemberScope(memberName: String) : MemberScope(this@InputClassScope, memberName) { override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType { val objectName = capitalizeFirstChar(memberName) addMember { out -> out.newLine().newLine().doc(description) if (properties == null) { out.append("interface ").append(objectName).append(" : JsonObjectBased").openBlock() } else { out.append("@JsonType").newLine() out.append("interface ").append(objectName).openBlock() for (property in properties) { out.doc(property.description) val methodName = generateMethodNameSubstitute(property.getName(), out) val memberScope = InputMemberScope(property.getName()) val typeDescriptor = memberScope.resolveType(property) writeMember(out, typeDescriptor, methodName) } } out.closeBlock() } return subMessageType(NamePath(objectName, classContextNamespace)) } } private fun writeMember(out: TextOutput, typeDescriptor: TypeDescriptor, name: String) { typeDescriptor.writeAnnotations(out) val asProperty = typeDescriptor.isPrimitive || typeDescriptor.isNullableType out.append(if (asProperty) "val" else "fun") out.append(" ").appendEscapedName(name) out.append(if (asProperty) ": " else "(): ") out.append(typeDescriptor.type.getShortText(classContextNamespace)) if (typeDescriptor.isNullableType) { out.append('?') } } }
apache-2.0
a734382b85da58ab40160e5f223e22ca
39.041096
127
0.67488
4.645469
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/JavaToKotlinAction.kt
1
13797
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ex.MessagesEx import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor import org.jetbrains.kotlin.idea.statistics.ConversionType import org.jetbrains.kotlin.idea.statistics.J2KFusCollector import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.isRunningInCidrIde import org.jetbrains.kotlin.j2k.ConverterSettings import org.jetbrains.kotlin.j2k.FilesResult import org.jetbrains.kotlin.j2k.J2kConverterExtension import org.jetbrains.kotlin.j2k.OldJavaToKotlinConverter import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.UserDataProperty import java.io.IOException import kotlin.io.path.notExists import kotlin.system.measureTimeMillis var VirtualFile.pathBeforeJ2K: String? by UserDataProperty(Key.create("PATH_BEFORE_J2K_CONVERSION")) class JavaToKotlinAction : AnAction() { companion object { private fun uniqueKotlinFileName(javaFile: VirtualFile): String { val nioFile = javaFile.fileSystem.getNioPath(javaFile) var i = 0 while (true) { val fileName = javaFile.nameWithoutExtension + (if (i > 0) i else "") + ".kt" if (nioFile == null || nioFile.resolveSibling(fileName).notExists()) return fileName i++ } } val title = KotlinBundle.message("action.j2k.name") private fun saveResults(javaFiles: List<PsiJavaFile>, convertedTexts: List<String>): List<VirtualFile> { val result = ArrayList<VirtualFile>() for ((psiFile, text) in javaFiles.zip(convertedTexts)) { try { val document = PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile) val errorMessage = when { document == null -> KotlinBundle.message("action.j2k.error.cant.find.document", psiFile.name) !document.isWritable -> KotlinBundle.message("action.j2k.error.read.only", psiFile.name) else -> null } if (errorMessage != null) { val message = KotlinBundle.message("action.j2k.error.cant.save.result", errorMessage) MessagesEx.error(psiFile.project, message).showLater() continue } document!!.replaceString(0, document.textLength, text) FileDocumentManager.getInstance().saveDocument(document) val virtualFile = psiFile.virtualFile if (ScratchRootType.getInstance().containsFile(virtualFile)) { val mapping = ScratchFileService.getInstance().scratchesMapping mapping.setMapping(virtualFile, KotlinFileType.INSTANCE.language) } else { val fileName = uniqueKotlinFileName(virtualFile) virtualFile.pathBeforeJ2K = virtualFile.path virtualFile.rename(this, fileName) } result += virtualFile } catch (e: IOException) { MessagesEx.error(psiFile.project, e.message ?: "").showLater() } } return result } fun convertFiles( files: List<PsiJavaFile>, project: Project, module: Module, enableExternalCodeProcessing: Boolean = true, askExternalCodeProcessing: Boolean = true, forceUsingOldJ2k: Boolean = false ): List<KtFile> { val javaFiles = files.filter { it.virtualFile.isWritable }.ifEmpty { return emptyList() } var converterResult: FilesResult? = null fun convert() { val converter = if (forceUsingOldJ2k) OldJavaToKotlinConverter( project, ConverterSettings.defaultSettings, IdeaJavaToKotlinServices ) else J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled).createJavaToKotlinConverter( project, module, ConverterSettings.defaultSettings, IdeaJavaToKotlinServices ) converterResult = converter.filesToKotlin( javaFiles, if (forceUsingOldJ2k) J2kPostProcessor(formatCode = true) else J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled) .createPostProcessor(formatCode = true), progress = ProgressManager.getInstance().progressIndicator!! ) } fun convertWithStatistics() { val conversionTime = measureTimeMillis { convert() } val linesCount = runReadAction { javaFiles.sumBy { StringUtil.getLineBreakCount(it.text) } } J2KFusCollector.log( ConversionType.FILES, ExperimentalFeatures.NewJ2k.isEnabled, conversionTime, linesCount, javaFiles.size ) } if (!ProgressManager.getInstance().runProcessWithProgressSynchronously( ::convertWithStatistics, title, true, project ) ) return emptyList() var externalCodeUpdate: ((List<KtFile>) -> Unit)? = null val result = converterResult ?: return emptyList() val externalCodeProcessing = result.externalCodeProcessing if (enableExternalCodeProcessing && externalCodeProcessing != null) { val question = KotlinBundle.message("action.j2k.correction.required") if (!askExternalCodeProcessing || (Messages.showYesNoDialog( project, question, title, Messages.getQuestionIcon() ) == Messages.YES) ) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { runReadAction { externalCodeUpdate = externalCodeProcessing.prepareWriteOperation( ProgressManager.getInstance().progressIndicator!! ) } }, title, true, project ) } } return project.executeWriteCommand(KotlinBundle.message("action.j2k.task.name"), null) { CommandProcessor.getInstance().markCurrentCommandAsGlobal(project) val newFiles = saveResults(javaFiles, result.results) .map { it.toPsiFile(project) as KtFile } .onEach { it.commitAndUnblockDocument() } externalCodeUpdate?.invoke(newFiles) PsiDocumentManager.getInstance(project).commitAllDocuments() newFiles.singleOrNull()?.let { FileEditorManager.getInstance(project).openFile(it.virtualFile, true) } newFiles } } } override fun actionPerformed(e: AnActionEvent) { val javaFiles = selectedJavaFiles(e).filter { it.isWritable }.toList() val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return if (javaFiles.isEmpty()) { val statusBar = WindowManager.getInstance().getStatusBar(project) JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(KotlinBundle.message("action.j2k.errornothing.to.convert"), MessageType.ERROR, null) .createBalloon() .showInCenterOf(statusBar.component) } if (!J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled) .doCheckBeforeConversion(project, module) ) return val firstSyntaxError = javaFiles.asSequence().map { PsiTreeUtil.findChildOfType(it, PsiErrorElement::class.java) }.firstOrNull() if (firstSyntaxError != null) { val count = javaFiles.filter { PsiTreeUtil.hasErrorElements(it) }.count() assert(count > 0) val firstFileName = firstSyntaxError.containingFile.name val question = when (count) { 1 -> KotlinBundle.message("action.j2k.correction.errors.single", firstFileName) else -> KotlinBundle.message("action.j2k.correction.errors.multiple", firstFileName, count - 1) } val okText = KotlinBundle.message("action.j2k.correction.investigate") val cancelText = KotlinBundle.message("action.j2k.correction.proceed") if (Messages.showOkCancelDialog( project, question, title, okText, cancelText, Messages.getWarningIcon() ) == Messages.OK ) { NavigationUtil.activateFileWithPsiElement(firstSyntaxError.navigationElement) return } } convertFiles(javaFiles, project, module) } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isEnabled(e) } private fun isEnabled(e: AnActionEvent): Boolean { if (isRunningInCidrIde) return false val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return false val project = e.project ?: return false e.getData(PlatformCoreDataKeys.MODULE) ?: return false return isAnyJavaFileSelected(project, virtualFiles) } private fun isAnyJavaFileSelected(project: Project, files: Array<VirtualFile>): Boolean { if (files.any { it.isSuitableDirectory() }) return true // Giving up on directories val manager = PsiManager.getInstance(project) return files.any { it.extension == JavaFileType.DEFAULT_EXTENSION && manager.findFile(it) is PsiJavaFile && it.isWritable } } private fun VirtualFile.isSuitableDirectory(): Boolean = isDirectory && fileType !is ArchiveFileType && isWritable private fun selectedJavaFiles(e: AnActionEvent): Sequence<PsiJavaFile> { val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf() val project = e.project ?: return sequenceOf() return allJavaFiles(virtualFiles, project) } private fun allJavaFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<PsiJavaFile> { val manager = PsiManager.getInstance(project) return allFiles(filesOrDirs) .asSequence() .mapNotNull { manager.findFile(it) as? PsiJavaFile } } private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { val result = ArrayList<VirtualFile>() for (file in filesOrDirs) { VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() { override fun visitFile(file: VirtualFile): Boolean { result.add(file) return true } }) } return result } }
apache-2.0
240ae700833d90c5c1c7b35e0739bf87
43.944625
158
0.622889
5.376851
false
false
false
false
LouisCAD/Splitties
modules/preferences/src/watchosX86Main/kotlin/splitties/preferences/NSUserDefaultsExtensions.kt
4
705
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import platform.Foundation.NSNumber import platform.Foundation.NSUserDefaults internal actual fun NSUserDefaults.setLong(value: Long, forKey: String) { setObject(value = NSNumber(longLong = value), forKey = forKey) } internal actual fun NSUserDefaults.setInt(value: Int, forKey: String) { setInteger(value = value, forKey = forKey) } internal actual fun NSUserDefaults.longForKey(key: String): Long { return (objectForKey(key) as NSNumber).longLongValue } internal actual fun NSUserDefaults.intForKey(key: String): Int = integerForKey(key)
apache-2.0
1dad51d7cda46547cdca3d2b5c1c7509
31.045455
109
0.771631
3.895028
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/pkg/PackageWrapper.kt
1
1632
package com.cognifide.gradle.aem.common.pkg import com.cognifide.gradle.aem.AemExtension import com.cognifide.gradle.aem.common.bundle.BundleFile import java.io.File class PackageWrapper(val aem: AemExtension) { val workDir = aem.obj.dir { convention(aem.obj.buildDir("package/wrapper")) } val bundlePath = aem.obj.string { convention("/apps/gap/wrapper/install") } fun definition(definition: PackageDefinition.(BundleFile) -> Unit) { this.definition = definition } private var definition: PackageDefinition.(BundleFile) -> Unit = {} fun wrap(file: File): File = when (file.extension) { "jar" -> wrapJar(file) "zip" -> file else -> throw PackageException("File '$file' must have '*.jar' or '*.zip' extension") } fun wrapJar(jar: File): File { val pkgName = jar.nameWithoutExtension val pkg = File(workDir.get().asFile, "$pkgName.zip") if (pkg.exists()) { aem.logger.info("CRX package wrapping OSGi bundle already exists: $pkg") return pkg } aem.logger.info("Wrapping OSGi bundle to CRX package: $jar") val bundle = BundleFile(jar) val bundlePath = "${bundlePath.get()}/${jar.name}" return aem.composePackage { this.archivePath.set(pkg) this.description.set(bundle.description) this.group.set(bundle.group) this.name.set(bundle.symbolicName) this.version.set(bundle.version) filter(bundlePath) content { copyJcrFile(jar, bundlePath) } definition(bundle) } } }
apache-2.0
5757ea605bff9f5c987bbe09cddf1fb2
31
93
0.627451
4.019704
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/DependentResolver.kt
1
2280
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.ResolveResult import com.intellij.psi.impl.source.resolve.ResolveCache import com.intellij.util.Consumer import com.intellij.util.SmartList abstract class DependentResolver<T : PsiPolyVariantReference> : ResolveCache.PolyVariantResolver<T> { companion object { /** * Given: resolve was called on a reference a.r1.r2...rN. * Its dependencies: a, a.r1, a.r1.r2, ... , a.r1.r2...rN-1. * We resolve dependencies in a loop. * Assume currently resolving dependency is a.r1.r2...rK, K < N. * By the time it is being processed all its dependencies are already resolved and the resolve results are stored in a list, * so we do not need to collect/resolve its dependencies again. * This field is needed to memoize currently resolving dependencies. */ private val resolvingDependencies = ThreadLocal.withInitial { mutableSetOf<PsiPolyVariantReference>() } } override final fun resolve(ref: T, incomplete: Boolean): Array<out ResolveResult> { val dependencies = resolveDependencies(ref, incomplete) val result = doResolve(ref, incomplete) dependencies?.clear() return result } private fun resolveDependencies(ref: T, incomplete: Boolean): MutableCollection<Any>? { if (ref in resolvingDependencies.get()) return null return collectDependencies(ref)?.mapNotNullTo(mutableListOf()) { if (ref === it) return@mapNotNullTo null try { resolvingDependencies.get().add(it) it.multiResolve(incomplete) } finally { resolvingDependencies.get().remove(it) } } } protected open fun collectDependencies(ref: T): Collection<PsiPolyVariantReference>? { val result = SmartList<PsiPolyVariantReference>() collectDependencies(ref, Consumer { result += it }) return result } protected open fun collectDependencies(ref: T, consumer: Consumer<in PsiPolyVariantReference>) {} protected abstract fun doResolve(ref: T, incomplete: Boolean): Array<out ResolveResult> }
apache-2.0
a6dfa9d0feca5480928a04e9125e0b58
37.661017
140
0.722368
4.46184
false
false
false
false
Softmotions/ncms
ncms-engine/ncms-engine-tests/src/test/java/com/softmotions/ncms/ui/BaseAdminUITest.kt
1
16277
package com.softmotions.ncms.ui import org.apache.commons.lang3.StringEscapeUtils import org.oneandone.qxwebdriver.By import org.oneandone.qxwebdriver.ui.Widget import org.oneandone.qxwebdriver.ui.form.MenuButton import org.oneandone.qxwebdriver.ui.table.Table import org.openqa.selenium.Keys import org.openqa.selenium.NoSuchElementException import org.openqa.selenium.support.ui.ExpectedConditions import org.testng.Assert.* import kotlin.test.assertEquals /** * @author Adamansky Anton ([email protected]) */ open class BaseAdminUITest(db: String) : BaseQXTest(db) { protected val assemblies = Assemblies() protected val selectFileDlg = SelectFileDlg() protected val pages = Pages() fun checkPopupNotificationShown(msg: String? = null) { //sm-app-popup// val w = qxd.findWidget(By.xpath("//div[contains(@class, 'sm-app-popup')]")) driverWait5.until(ExpectedConditions.visibilityOf(w)) if (msg != null) { w.findWidget("*/[@label=${msg}]") } } inner class Pages { /////////////////////////////////////////////////////////// // In `Pages` // /////////////////////////////////////////////////////////// fun activate(): Pages { findWidget("*/ncms.Toolbar/*/[@label=Pages]").click() return this } fun selectPageNode(label: String): Widget { var w = findWidget("*/ncms.pgs.PagesTreeSelector/*/sm.ui.tree.ExtendedVirtualTree/*/[@label=${label}]") if (w.classname != "sm.ui.tree.ExtendedVirtualTreeItem") { w = w.findWidget(By.xpath("./ancestor-or-self::node()[@qxclass='sm.ui.tree.ExtendedVirtualTreeItem']")) } w.click() try { w.contentElement.findElement(By.qxh("*/[@source=.*plus.gif]"))?.click() } catch (ignored: NoSuchElementException) { } return w } /** * Create a new page over selected node in page tree */ fun newPage(context: Widget, name: String, isDirectory: Boolean = false): Widget { actions.moveToElement(context.contentElement) actions.contextClick() actions.perform() findWidget("*/qx.ui.menu.Menu/*/[@label=New]").click() val dlg = findWidget("*/ncms.pgs.PageNewDlg") driverWait5.until { dlg.isDisplayed } actions.sendKeys(name).perform() dlg.findWidget("*/qx.ui.form.renderer.Single").executeInWidget(""" var items = this._form.getItems(); items['container'].setValue(${isDirectory}); """) dlg.findWidget("*/[@label=Save]").click() return selectPageNode(name) } fun activatePageEdit(): PagesEdit { findWidget(By.xpath( "(//${qxpn("ncms.pgs.PageEditor")}//${qxpn("qx.ui.tabview.TabButton")}//${qxpn("qx.ui.basic.Label", "Edit")})[1]")) .click() return PagesEdit() } } inner class PagesEdit { fun setPageTemplate(template: String) { try { val el = qxd.findElement(By.qxh("*/ncms.pgs.PagesSelectorDlg")) if (el != null && el.isDisplayed) { findWidget("*/ncms.pgs.PagesSelectorDlg/*/[@label=Cancel]").click() } } catch (ignored: NoSuchElementException) { } findWidget("*/ncms.pgs.PageEditorEditPage/*/sm.ui.form.ButtonField/*/[@label=Template]").click() actions.sendKeys(template).perform() // ncms.asm.AsmTable val table = findWidget("*/ncms.pgs.PagesSelectorDlg/*/ncms.asm.AsmTable") as Table var ind = -1L; driverWait5.until { ind = table.getRowIndexForCellText(1, template) ind >= 0 } table.selectRow(ind) findWidget("*/ncms.pgs.PagesSelectorDlg/*/[@label=Ok]").click() } } inner class SelectFileDlg { /////////////////////////////////////////////////////////// // Select file dialog // /////////////////////////////////////////////////////////// fun waitForDialogVisible(): Widget { val w = findWidget("*/ncms.mmgr.MediaSelectFileDlg") driverWait5.until(ExpectedConditions.visibilityOf(w)) return w } fun newFile(fileName: String) { var w = waitForDialogVisible() w = w.findWidget("*/[@icon=.*add.png]") w.click() w as MenuButton w.getSelectableItem("New file").click() actions.sendKeys(fileName).perform() findWidget("*/ncms.mmgr.MediaFileNewDlg/*/[@label=Save]").click() selectFile(fileName) } fun selectFile(fileName: String, invert: Boolean = false) { val w = findWidget("*/ncms.mmgr.MediaSelectFileDlg/*/ncms.mmgr.MediaFilesTable") w as Table var ind = -1L; driverWait5.until { ind = w.getRowIndexForCellText(0, fileName) if (invert) ind < 0 else ind > -1 } if (!invert) { w.selectRow(ind) } } fun deleteFile(fileName: String) { var w = waitForDialogVisible() selectFile(fileName) w = w.findWidget("*/[@icon=.*delete.png]") w.click() w = findWidget("*/sm.dialog.Confirm/*/[@label=Yes]") w.click() selectFile(fileName, invert = true) } fun setFileTextualContent(fileName: String, content: String) { var w = waitForDialogVisible() selectFile(fileName) w = w.findWidget("*/[@icon=.*edit-document.png]") assertEquals("true", w.getPropertyValue("enabled")?.toString()); w.click() w = findWidget("*/ncms.mmgr.MediaTextFileEditorDlg/*/ncms.mmgr.MediaTextFileEditor") w.findWidget(By.xpath("//textarea[contains(@class, 'ace_text-input')]")) w.executeInWidget("""this.setCode("${StringEscapeUtils.escapeEcmaScript(content.trimIndent())}");""") actions.sendKeys(Keys.chord(Keys.CONTROL, "s")).perform() checkPopupNotificationShown("File successfully saved") findWidget("*/ncms.mmgr.MediaTextFileEditorDlg/*/[@icon=.*close.gif]").click() } fun ok() { val w = findWidget("*/ncms.mmgr.MediaSelectFileDlg/*/[@label=Ok]") assertEquals("true", w.getPropertyValue("enabled")?.toString()); w.click() } } inner class Assemblies { /////////////////////////////////////////////////////////// // In `Assemblies` // /////////////////////////////////////////////////////////// fun activate(): Assemblies { findWidget("*/ncms.Toolbar/*/[@label=Assemblies]").click() return this } fun openSelectCoreDlg(): Widget { findWidget("*/ncms.asm.AsmEditor/*/[@icon=.*core_link.png]").click(); return selectFileDlg.waitForDialogVisible() } fun createAssembly(name: String) { val w = waitForWidget("*/ncms.asm.AsmNav"); actions.moveToElement(w.findWidget("*/qx.ui.table.pane.Scroller").contentElement) actions.contextClick() actions.perform() // Create new assembly findWidget("*/qx.ui.menu.Menu/*/[@label=New assembly]").click() actions.sendKeys(name).perform() findWidget("*/ncms.asm.AsmNewDlg/*/[@label=Save]").click() } fun selectAssembly(name: String) { val table: Table = findWidget("*/ncms.asm.AsmTable") as Table var ind: Long = table.getRowIndexForCellText(1, name) if (ind < 0) { val w = findWidget("*/sm.ui.form.SearchField/*/qx.ui.form.TextField") w.executeInWidget(""" this.setValue(''); this.focus(); """) actions.sendKeys(name).perform() } driverWait5.until { ind = table.getRowIndexForCellText(1, name) ind >= 0 } table.selectRow(ind) } fun setBasicAssemblyParams( description: String? = null, templateMode: String? = null) { val w = findWidget("*/ncms.asm.AsmEditor/qx.ui.core.scroll.ScrollPane/sm.ui.form.FlexFormRenderer") w.executeInWidget(""" var items = this._form.getItems(); var d = items['description']; d.focus(); ${if (description != null) "d.setValue('${description}');" else ""}; d.blur(); ${if (templateMode != null) "items['templateMode'].setModelSelection(['${templateMode}']);" else ""} """) } fun createBasicAttribute(type: String, name: String, label: String? = null, required: Boolean = false) { // Add new assembly attribute findWidget("*/ncms.asm.AsmAttrsTable/*/[@icon=.*add.png]").click() var w: Widget = findWidget("*/ncms.asm.AsmAttributeTypeSelectorDlg") actions.sendKeys(type).sendKeys(Keys.DOWN).perform() val table = w.findWidget("*/sm.table.Table") as Table assertNotNull(table.selectedRanges) assertEquals(table.selectedRanges.size, 1) w.findWidget("*/[@label=Ok]").click() // Fill the assembly attributes w = findWidget("*/ncms.asm.AsmAttrEditorDlg/*/sm.ui.form.FlexFormRenderer") w.executeInWidget(""" var items = this._form.getItems(); items['name'].setValue('${name}'); ${if (label != null) "items['label'].setValue('${label}');" else ""} items['required'].setValue(${required}); """) } fun removeAttribute(name: String) { findAttribute(name, select = true) findWidget("*/ncms.asm.AsmAttrsTable/*/[@icon=.*delete.png]").click() findWidget("*/sm.dialog.Confirm/*/[@label=Yes]").click() driverWait5.until { (findWidget("*/ncms.asm.AsmAttrsTable/sm.table.Table") as Table).getRowIndexForCellText(1, name) == -1L } } fun findAttribute(name: String, select: Boolean = false, invert: Boolean = false): Pair<Table, Long> { // Check attribute is saved val table = findWidget("*/ncms.asm.AsmAttrsTable/sm.table.Table") as Table var ind = -1L if (invert) { driverWait5.until { ind = table.getRowIndexForCellText(1, name) ind == -1L } } else { driverWait5.until { ind = table.getRowIndexForCellText(1, name) ind > -1L } if (select) { table.selectRow(ind) } } return table.to(ind) } fun checkAttributeExists(name: String, type: String? = null, label: String? = null, value: String? = null, select: Boolean = false, invert: Boolean = false) { val ret = findAttribute(name, select, invert = invert) if (invert) { assertEquals(-1L, ret.second) return } val table = ret.first val ind = ret.second if (type != null) { assertEquals(table.getCellText(ind, 3), type) } if (label != null) { assertEquals(table.getCellText(ind, 2), label) } if (value != null) { assertEquals(table.getCellText(ind, 4), value) } } fun getAsmCoreValue(): String? { val w = findWidget("*/ncms.asm.AsmEditor/qx.ui.core.scroll.ScrollPane/sm.ui.form.FlexFormRenderer") return w.executeInWidget(""" var items = this._form.getItems(); return items['core'].getValue(); """)?.toString() } fun attrDlgClickSave() { // Press the OK and save the assembly attribute val w = findWidget("*/ncms.asm.AsmAttrEditorDlg/*/[@label=Ok]") assertEquals(w.classname, "qx.ui.form.Button") w.click() } fun createStringAttr(name: String, required: Boolean = false, maxLength: Int = 0, label: String? = null, value: String? = null) { createBasicAttribute("string", name, label, required) val w = findWidget("*/ncms.asm.AsmAttrEditorDlg/*/sm.ui.cont.LazyStack/sm.ui.form.FlexFormRenderer") w.executeInWidget(""" var items = this._form.getItems(); items['maxLength'].setValue(${maxLength}); items['value'].setValue('${value ?: ""}'); """) attrDlgClickSave() checkAttributeExists( name = name, type = "string", label = label, value = value ) } fun createWikiAttr(name: String, label: String, required: Boolean = false, type: String = "wiki", value: String? = null) { createBasicAttribute("wiki", name, label, required) val w = findWidget("*/ncms.asm.AsmAttrEditorDlg/*/sm.ui.cont.LazyStack/sm.ui.form.FlexFormRenderer") /*w.executeInWidget(""" var items = this._form.getItems(); items['alias'].setValue('${value ?: ""}'); """)*/ attrDlgClickSave() checkAttributeExists( name = name, type = "wiki", label = label, value = value) } fun createAliasAttr(name: String = "alias", required: Boolean = false, label: String? = "Alias", value: String? = null) { createBasicAttribute("alias", name, label, required) val w = findWidget("*/ncms.asm.AsmAttrEditorDlg/*/sm.ui.cont.LazyStack/sm.ui.form.FlexFormRenderer") w.executeInWidget(""" var items = this._form.getItems(); items['alias'].setValue('${value ?: ""}'); """) attrDlgClickSave() checkAttributeExists( name = name, type = "alias", label = label, value = value ) } fun addAssemblyParent(parentName: String) { // Add new assembly parent findWidget("*/ncms.asm.AsmParentsTable/*/[@icon=.*add.png]").click() var table = findWidget("*/ncms.asm.AsmSelectorDlg/*/ncms.asm.AsmTable") as Table actions.sendKeys(parentName).sendKeys(Keys.DOWN).perform() var ind = table.getRowIndexForCellText(1, parentName) assertTrue(ind > -1) table.selectRow(ind) findWidget("*/ncms.asm.AsmSelectorDlg/*/[@label=Ok]").click() table = findWidget("*/ncms.asm.AsmParentsTable/*/sm.table.Table") as Table ind = table.getRowIndexForCellText(0, parentName) assertTrue(ind > -1) table.selectRow(ind) } } }
apache-2.0
433470607669c719049beff203ff9b0e
37.391509
135
0.499601
4.522645
false
false
false
false
rjhdby/motocitizen
Motocitizen/src/motocitizen/ui/fragments/DetailMessagesFragment.kt
1
5717
package motocitizen.ui.fragments import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageButton import android.widget.PopupWindow import android.widget.ScrollView import motocitizen.content.Content import motocitizen.content.accident.Accident import motocitizen.content.message.Message import motocitizen.datasources.database.StoreMessages import motocitizen.datasources.network.ApiResponse import motocitizen.datasources.network.requests.SendMessageRequest import motocitizen.main.R import motocitizen.ui.activity.AccidentDetailsActivity import motocitizen.ui.activity.AccidentDetailsActivity.Companion.ACCIDENT_ID_KEY import motocitizen.ui.menus.MessageContextMenu import motocitizen.ui.rows.message.MessageRowFactory import motocitizen.user.User import motocitizen.utils.hide import motocitizen.utils.show import motocitizen.utils.showToast import motocitizen.utils.tryOrDo class DetailMessagesFragment : FragmentForAccident() { private lateinit var rootView: View private lateinit var scrollView: ScrollView private lateinit var messagesView: ViewGroup private lateinit var formView: View private lateinit var sendButton: ImageButton private lateinit var inputField: EditText private lateinit var accident: Accident override fun setAccident(accident: Accident) { this.accident = accident } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_detail_messages, container, false) bindViews() setupNewMessageForm() update()//todo exterminatus return rootView } private fun bindViews() { scrollView = rootView.findViewById(R.id.activity__details_messages_scroll) messagesView = rootView.findViewById(R.id.details_messages_table) formView = rootView.findViewById(R.id.new_message_area) sendButton = rootView.findViewById(R.id.new_message_send) inputField = rootView.findViewById(R.id.new_message_text) } private fun setupNewMessageForm() { if (User.isReadOnly()) { formView.hide() return } formView.show() sendButton.setOnClickListener { val text = inputField.text.toString().replace("\\s".toRegex(), "") if (text.isNotEmpty()) { SendMessageRequest(inputField.text.toString(), accident.id, ::sendMessageCallback).call() inputField.setText("") } } } /** * Обновление сообщений в списке */ private fun update() { messagesView.removeAllViews() val messages = Content.messagesForAccident(accident) if (messages.isEmpty()) return var last = 0 val group = ArrayList<Message>() messages.forEach { if (last != it.owner && last != 0) { addMessageRows(group) group.clear() } group.add(it) last = it.owner } addMessageRows(group) updateUnreadMessages() } //todo pizdets private fun addMessageRows(list: List<Message>) = if (list.size == 1) { drawRow(MessageRowFactory.makeOne(activity, list.first()), list.first()) } else { drawRow(MessageRowFactory.makeFirst(activity, list.first()), list.first()) (1..list.size - 2).forEach { drawRow(MessageRowFactory.makeMiddle(activity, list[it]), list[it]) } drawRow(MessageRowFactory.makeLast(activity, list.last()), list.last()) } private fun drawRow(view: View, message: Message) { view.setOnLongClickListener(MessageRowLongClickListener(message)) messagesView.addView(view) } private fun updateUnreadMessages() { if (Content.messagesForAccident(accident).isEmpty()) return StoreMessages.setLast(accident.id, accident.messagesCount) } private fun sendMessageCallback(response: ApiResponse) { tryOrDo({ activity.showToast("Неизвестная ошибка" + response.toString()) }) { if (response.hasError()) { val text = response.error.text activity.runOnUiThread { activity.showToast(text) } } else { accident.messagesCount++ } } Content.requestDetailsForAccident(accident, { activity.runOnUiThread { (activity as AccidentDetailsActivity).update() update() scrollView.post { scrollView.fullScroll(ScrollView.FOCUS_DOWN) } } }) } private inner class MessageRowLongClickListener internal constructor(private val message: Message) : View.OnLongClickListener { override fun onLongClick(view: View): Boolean { val popupWindow: PopupWindow = MessageContextMenu(activity, message) val viewLocation = IntArray(2) view.getLocationOnScreen(viewLocation) popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, viewLocation[0], viewLocation[1]) return true } } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(ACCIDENT_ID_KEY, accident.id) super.onSaveInstanceState(outState) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (savedInstanceState == null) return accident = Content[savedInstanceState.getInt(ACCIDENT_ID_KEY)]!! } }
mit
2df29770c612a3aa9cb73c488a869ee4
34.685535
131
0.679767
4.724396
false
false
false
false
ibinti/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/EventDispatcher.kt
3
4908
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.recorder import com.intellij.openapi.actionSystem.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.SystemInfo import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorFrame import java.awt.Component import java.awt.Container import java.awt.KeyboardFocusManager import java.awt.Point import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.awt.event.MouseEvent.MOUSE_PRESSED import java.util.* import javax.swing.JFrame import javax.swing.KeyStroke import javax.swing.RootPaneContainer import javax.swing.SwingUtilities /** * @author Sergey Karashevich */ object EventDispatcher { private val LOG = Logger.getInstance("#${EventDispatcher::class.qualifiedName}") private val MAC_NATIVE_ACTIONS = arrayOf("ShowSettings", "EditorEscape") fun processMouseEvent(event: MouseEvent) { if (event.id != MOUSE_PRESSED) return val eventComponent: Component? = event.component if (isMainFrame(eventComponent)) return val mousePoint = event.point var actualComponent: Component? = null when (eventComponent) { is RootPaneContainer -> { val layeredPane = eventComponent.layeredPane val point = SwingUtilities.convertPoint(eventComponent, mousePoint, layeredPane) actualComponent = layeredPane.findComponentAt(point) } is Container -> actualComponent = eventComponent.findComponentAt(mousePoint) } if (actualComponent == null) actualComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner if (actualComponent != null) { LOG.info("Delegate click from component:${actualComponent}") val convertedPoint = Point(event.locationOnScreen.x - actualComponent.locationOnScreen.x, event.locationOnScreen.y - actualComponent.locationOnScreen.y) ScriptGenerator.clickComponent(actualComponent, convertedPoint, event) } } fun processKeyBoardEvent(keyEvent: KeyEvent) { if (isMainFrame(keyEvent.component)) return if (keyEvent.id == KeyEvent.KEY_TYPED) ScriptGenerator.processTyping(keyEvent) if (SystemInfo.isMac && keyEvent.id == KeyEvent.KEY_PRESSED) { //we are redirecting native Mac action as an Intellij actions LOG.info(keyEvent.toString()) val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent)) for(actionId in actionIds){ if(isMacNativeAction(keyEvent)) { val action = ActionManager.getInstance().getAction(actionId) val actionEvent = AnActionEvent.createFromInputEvent(keyEvent, ActionPlaces.UNKNOWN, action.templatePresentation, DataContext.EMPTY_CONTEXT) ScriptGenerator.processKeyActionEvent(action, actionEvent) } } } } fun processActionEvent(action: AnAction, event: AnActionEvent?) { if (event == null) return val inputEvent = event.inputEvent if (inputEvent is KeyEvent) { if(!isMacNativeAction(inputEvent)) { ScriptGenerator.processKeyActionEvent(action, event) } } else { val actionManager = ActionManager.getInstance() val mainActions = (actionManager.getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup).getFlatIdList() if (mainActions.contains(actionManager.getId(action))) ScriptGenerator.processMainMenuActionEvent(action) } } private fun ActionGroup.getFlatIdList(): List<String> { val actionManager = ActionManager.getInstance() val result = ArrayList<String>() this.getChildren(null).forEach { action -> if (action is ActionGroup) result.addAll(action.getFlatIdList()) else result.add(actionManager.getId(action)) } return result } private fun isMainFrame(component: Component?): Boolean { return component is JFrame && component.title == GuiScriptEditorFrame.GUI_SCRIPT_FRAME_TITLE } private fun isMacNativeAction(keyEvent: KeyEvent): Boolean{ if (!SystemInfo.isMac) return false val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent)) return actionIds.any { it in MAC_NATIVE_ACTIONS } } }
apache-2.0
a289cb665ec5b7ec406c55b601df4fe9
38.910569
123
0.73533
4.696651
false
false
false
false
VoIPGRID/vialer-android
app/src/main/java/com/voipgrid/vialer/audio/AudioFocus.kt
1
1597
package com.voipgrid.vialer.audio import android.media.AudioManager import com.voipgrid.vialer.logging.Logger /** * The class is completely responsible for controlling audio focus, all audio focus * requests should be made via thia. * */ class AudioFocus(private val manager: AudioManager) { private val logger = Logger(this) private val handler = AudioFocusHandler() /** * Focus audio for the incoming call ringer. * */ fun forRinger() { logger.i("Setting audio focus for RINGER") manager.apply { requestAudioFocus(handler, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN) mode = AudioManager.MODE_RINGTONE } } /** * Focus audio for calls. * */ fun forCall() { logger.i("Setting audio focus for CALL") manager.apply { requestAudioFocus(handler, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN) mode = AudioManager.MODE_IN_COMMUNICATION } } /** * Reset the audio focus back to its previous state. * */ fun reset() { logger.i("Resetting audio focus") manager.apply { mode = AudioManager.MODE_NORMAL isSpeakerphoneOn = false abandonAudioFocus(handler) } } class AudioFocusHandler: AudioManager.OnAudioFocusChangeListener { private val logger = Logger(this) override fun onAudioFocusChange(focusChange: Int) { logger.i("Received audio focus change event: $focusChange") } } }
gpl-3.0
f1c24ac7c3120bda315dcf47e25750e0
23.96875
100
0.6268
4.752976
false
false
false
false
mniami/android.kotlin.benchmark
app/src/main/java/guideme/volunteers/databases/actions/AddUser.kt
2
921
package guideme.volunteers.databases.actions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import guideme.volunteers.domain.User import io.reactivex.SingleEmitter class AddUser(private val database: FirebaseDatabase) { fun update(updatedUser: User, emitter: SingleEmitter<User>) { var id = updatedUser.id if (updatedUser.id.isEmpty()) { val key = database.reference.child(DatabaseTables.USERS).push().key if (key == null) { throw IllegalStateException() } id = key } val firebaseUser = FirebaseAuth.getInstance().currentUser val firebaseUserId = firebaseUser!!.uid database.reference.child(firebaseUserId).child(DatabaseTables.USERS).child(id).setValue(updatedUser).addOnCompleteListener { emitter.onSuccess(updatedUser) } } }
apache-2.0
ad6c026704963a75f195261924dddc86
35.88
132
0.686211
4.69898
false
false
false
false
jayrave/falkon
falkon-sql-builder-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/common/SimpleUpdateSqlBuilder.kt
1
1328
package com.jayrave.falkon.sqlBuilders.common import com.jayrave.falkon.sqlBuilders.lib.WhereSection import java.sql.SQLSyntaxErrorException object SimpleUpdateSqlBuilder { /** * Builds a `UPDATE ...` statement with the passed in info. Conditions for `WHERE` * clause are added in the iteration order of [whereSections] */ fun build( tableName: String, columns: Iterable<String>, whereSections: Iterable<WhereSection>?): String { // Add basic update stuff val updateSql = StringBuilder(120) updateSql.append("UPDATE $tableName SET ") // Add column names & their value placeholders var columnCount = 0 updateSql.append(columns.joinToString(separator = ", ") { columnCount++ "$it = $ARG_PLACEHOLDER" }) when (columnCount) { 0 -> throw SQLSyntaxErrorException( "UPDATE SQL without any columns for table: $tableName" ) else -> { // Add where clause if required val whereSql = whereSections?.buildWhereClause(ARG_PLACEHOLDER) if (whereSql != null) { updateSql.append(" $whereSql") } } } return updateSql.toString() } }
apache-2.0
d448b9af7a3606791ba430206c1f4a61
29.906977
98
0.581325
5.011321
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/network/data/NewsRssFeed.kt
1
413
package com.github.premnirmal.ticker.network.data import org.simpleframework.xml.ElementList import org.simpleframework.xml.Path import org.simpleframework.xml.Root @Root(name = "rss", strict = false) class NewsRssFeed { @get:ElementList(name = "item", inline = true) @get:Path("channel") @set:ElementList(name = "item", inline = true) @set:Path("channel") var articleList: List<NewsArticle>? = null }
gpl-3.0
c259ce597505026fdb21e038964e0e2b
28.571429
49
0.74092
3.470588
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/social/DivorceCommand.kt
1
3744
package net.perfectdreams.loritta.morenitta.commands.vanilla.social import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.tables.Profiles import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.extensions.await import net.perfectdreams.loritta.morenitta.utils.extensions.isEmote import net.perfectdreams.loritta.morenitta.utils.onReactionAddByAuthor import net.dv8tion.jda.api.EmbedBuilder import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.profile.ProfileUtils import net.perfectdreams.loritta.common.utils.Emotes import org.jetbrains.exposed.sql.update import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.utils.extensions.addReaction class DivorceCommand(loritta: LorittaBot) : AbstractCommand(loritta, "divorce", listOf("divorciar"), net.perfectdreams.loritta.common.commands.CommandCategory.SOCIAL) { companion object { const val LOCALE_PREFIX = "commands.command.divorce" const val DIVORCE_REACTION_EMOJI = "\uD83D\uDC94" const val DIVORCE_EMBED_URI = "https://cdn.discordapp.com/emojis/556524143281963008.png?size=2048" } override fun getDescriptionKey() = LocaleKeyData("$LOCALE_PREFIX.description") override suspend fun run(context: CommandContext,locale: BaseLocale) { val userProfile = context.lorittaUser._profile ?: run { // If the user doesn't have any profile, then he won't have any marriage anyway context.reply( LorittaReply( locale["commands.category.social.youAreNotMarried", "`${context.config.commandPrefix}casar`", Emotes.LORI_HEART], Constants.ERROR ) ) return } val marriage = ProfileUtils.getMarriageInfo(loritta, userProfile) ?: run { // Now that's for when the marriage doesn't exist context.reply( LorittaReply( locale["commands.category.social.youAreNotMarried", "`${context.config.commandPrefix}casar`", Emotes.LORI_HEART], Constants.ERROR ) ) return } val marriagePartner = marriage.partner val userMarriage = marriage.marriage val message = context.reply( LorittaReply( locale["$LOCALE_PREFIX.prepareToDivorce", Emotes.LORI_CRYING], "\uD83D\uDDA4" ), LorittaReply( locale["$LOCALE_PREFIX.pleaseConfirm", DIVORCE_REACTION_EMOJI], mentionUser = false ) ) message.onReactionAddByAuthor(context) { if (it.emoji.isEmote(DIVORCE_REACTION_EMOJI)) { // depois loritta.newSuspendedTransaction { Profiles.update({ Profiles.marriage eq userMarriage.id }) { it[Profiles.marriage] = null } userMarriage.delete() } message.delete().queue() context.reply( LorittaReply( locale["$LOCALE_PREFIX.divorced", Emotes.LORI_HEART] ) ) try { // We don't care if we can't find the user, just exit val partner = loritta.lorittaShards.retrieveUserById(marriagePartner.id) ?: return@onReactionAddByAuthor val userPrivateChannel = partner.openPrivateChannel().await() userPrivateChannel.sendMessageEmbeds( EmbedBuilder() .setTitle(locale["$LOCALE_PREFIX.divorcedTitle"]) .setDescription(locale["$LOCALE_PREFIX.divorcedDescription", context.userHandle.name]) .setThumbnail(DIVORCE_EMBED_URI) .setColor(Constants.LORITTA_AQUA) .build() ).queue() } catch (e: Exception) {} } } message.addReaction(DIVORCE_REACTION_EMOJI).queue() } }
agpl-3.0
4124ca47929e0d5bec6378d78efebac4
35.009615
168
0.744658
3.778002
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/DiscordOAuth2URLBuilders.kt
1
761
package net.perfectdreams.loritta.cinnamon.discord.utils import io.ktor.http.* // Examples: // https://discordapp.com/oauth2/authorize?redirect_uri=https://loritta.website%2Fdashboard&scope=identify%20guilds%20email&response_type=code&client_id=297153970613387264 // https://discordapp.com/oauth2/authorize?client_id=297153970613387264&scope=bot+identify+guilds+email+applications.commands&permissions=2080374975&response_type=code&redirect_uri=https://loritta.website/dashboard fun DiscordOAuth2AuthorizationURL( parameters: ParametersBuilder.() -> (Unit) ) = URLBuilder( protocol = URLProtocol.HTTPS, host = "discord.com", pathSegments = listOf("oauth2", "authorize"), parameters = ParametersBuilder().apply(parameters).build() ).build()
agpl-3.0
e88a73d114643815507858f126ad9c9d
49.8
214
0.78318
3.606635
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoConsecutiveBlankLinesRule.kt
1
1977
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType.CLASS import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER import com.pinterest.ktlint.core.ast.ElementType.PRIMARY_CONSTRUCTOR import com.pinterest.ktlint.core.ast.nextLeaf import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement public class NoConsecutiveBlankLinesRule : Rule("no-consecutive-blank-lines") { override fun visit( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { if (node is PsiWhiteSpace && node.prevSibling != null ) { val text = node.getText() val lfcount = text.count { it == '\n' } if (lfcount < 2) { return } val eof = node.nextLeaf() == null val prevNode = node.treePrev val betweenClassAndPrimaryConstructor = prevNode.elementType == IDENTIFIER && prevNode.treeParent.elementType == CLASS && node.treeNext.elementType == PRIMARY_CONSTRUCTOR if (lfcount > 2 || eof || betweenClassAndPrimaryConstructor) { val split = text.split("\n") emit(node.startOffset + split[0].length + split[1].length + 2, "Needless blank line(s)", true) if (autoCorrect) { val newText = buildString { append(split.first()) append("\n") if (!eof && !betweenClassAndPrimaryConstructor) append("\n") append(split.last()) } (node as LeafPsiElement).rawReplaceWithText(newText) } } } } }
mit
fa0a539ce6f4a70296a18f68220e8b4b
41.06383
110
0.594841
4.741007
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/doc/LangMarkdownUtils.kt
1
2082
package ee.lang.gen.doc import ee.common.ext.* import ee.lang.* import ee.lang.gen.KotlinContext open class MkContextBuilder<M>(name: String, val scope: String, macroController: MacroController, builder: M.() -> MkContext) : ContextBuilder<M>(name, macroController, builder) open class MkContext : GenerationContext { val namespaceLastPart: String constructor(namespace: String = "", moduleFolder: String = "", genFolder: String = "src/main/doc", genFolderDeletable: Boolean = false, genFolderPatternDeletable: Regex? = ".*Base.mk".toRegex(), derivedController: DerivedController, macroController: MacroController) : super(namespace, moduleFolder, genFolder, genFolderDeletable, genFolderPatternDeletable, derivedController, macroController) { namespaceLastPart = namespace.substringAfterLast(".") } override fun complete(content: String, indent: String): String { return "${toHeader(indent)}${toPackage(indent)}${toImports(indent)}$content${toFooter(indent)}" } private fun toPackage(indent: String): String { return namespaceLastPart.isNotEmpty().then { "${indent}package $namespaceLastPart$nL$nL" } } private fun toImports(indent: String): String { return "" } override fun n(item: ItemI<*>, derivedKind: String): String { val derived = types.addReturn(derivedController.derive(item, derivedKind)) if (derived.namespace().isEmpty() || derived.namespace().equals(namespace, true)) { return derived.name() } else { return """${derived.namespace().substringAfterLast(".").toLowerCase()}.${derived.name()}""" } } } val itemAndTemplateNameAsMkFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("${it.name().capitalize()}${name.capitalize()}.puml") } val templateNameAsMarkdownFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("$name.puml") } val itemNameAsMarkdownFileName: TemplateI<*>.(CompositeI<*>) -> Names = { Names("${it.name()}.md") }
apache-2.0
58b0f6fa6a506fcb28bca2b864b4a503
37.574074
114
0.667147
4.266393
false
false
false
false
jiangkang/KTools
tools/src/main/java/com/jiangkang/tools/widget/KDialog.kt
1
5279
package com.jiangkang.tools.widget import android.app.ProgressDialog import android.content.Context import android.content.DialogInterface import android.graphics.Bitmap import android.os.Handler import android.os.Looper import android.view.View import android.webkit.JsResult import android.widget.ImageView import androidx.appcompat.app.AlertDialog import java.util.* /** * Created by jiangkang on 2017/9/13. */ object KDialog { @JvmStatic fun showImgInDialog(context: Context?, bitmap: Bitmap?) { val imageView = ImageView(context) imageView.setImageBitmap(bitmap) AlertDialog.Builder(context!!) .setView(imageView) .setNegativeButton("关闭") { dialog, which -> dialog.dismiss() } .show() } @JvmStatic fun showMsgDialog(context: Context?, content: String?) { Handler(Looper.getMainLooper()) .post { AlertDialog.Builder(context!!) .setMessage(content) .setNegativeButton("关闭") { dialog, which -> dialog.dismiss() } .show() } } @JvmStatic fun showJsAlertDialog(context: Context?, content: String?, result: JsResult) { Handler(Looper.getMainLooper()) .post { AlertDialog.Builder(context!!) .setMessage(content) .setNegativeButton("关闭") { dialog, which -> result.confirm() dialog.dismiss() } .show() } } @JvmStatic fun showCustomViewDialog(context: Context?, title: String?, view: View?, positiveListener: DialogInterface.OnClickListener?, negativeListener: DialogInterface.OnClickListener?) { Handler(Looper.getMainLooper()) .post { AlertDialog.Builder(context!!) .setTitle(title) .setView(view) .setPositiveButton("确认", positiveListener) .setNegativeButton("取消", negativeListener) .show() } } @JvmStatic fun showSingleChoiceDialog(context: Context?, title: String?, items: Array<String>, callback: SingleSelectedCallback?) { val selectedIndex = IntArray(1) AlertDialog.Builder(context!!) .setTitle(title) .setSingleChoiceItems(items, 0) { dialog, which -> selectedIndex[0] = which } .setPositiveButton("确定") { dialog, which -> callback?.singleSelected(selectedIndex[0]) dialog.dismiss() } .setNegativeButton("取消") { dialog, which -> dialog.dismiss() } .setCancelable(false) .show() } @JvmStatic fun showMultiChoicesDialog(context: Context?, title: String?, items: Array<CharSequence?>, callback: MultiSelectedCallback?) { val selectedItems: IntArray val selected = BooleanArray(items.size) AlertDialog.Builder(context!!) .setTitle(title) .setMultiChoiceItems(items, BooleanArray(items.size)) { dialog, which, isChecked -> selected[which] = isChecked } .setPositiveButton("确定") { dialog, which -> val size = selected.size val selectedList: MutableList<Int> = ArrayList() if (callback != null) { for (i in 0 until size) { if (selected[i]) { selectedList.add(i) } } if (selectedList != null && selectedList.size > 0) { callback.multiSelected(selectedList) } else { callback.selectedNothing() } } dialog.dismiss() } .setNegativeButton("取消") { dialog, which -> dialog.dismiss() } .setCancelable(false) .show() } private var progressDialog: ProgressDialog? = null @JvmStatic fun showProgressDialog(context: Context?, progress: Int) { if (progressDialog == null) { progressDialog = ProgressDialog(context) } progressDialog!!.setCanceledOnTouchOutside(false) progressDialog!!.setCancelable(false) progressDialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL) progressDialog!!.max = 100 progressDialog!!.progress = progress progressDialog!!.show() if (progress >= 100) { if (progressDialog != null && progressDialog!!.isShowing) { progressDialog!!.dismiss() } } } interface SingleSelectedCallback { fun singleSelected(index: Int) } interface MultiSelectedCallback { fun multiSelected(list: List<Int>?) fun selectedNothing() } }
mit
e78ab175497cd8fbcc69281238b958ee
36.726619
134
0.53004
5.661987
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/network/domain/NetworkDataSyncInteractor.kt
1
10466
package com.ruuvi.station.network.domain import android.net.Uri import com.ruuvi.station.app.preferences.GlobalSettings import com.ruuvi.station.app.preferences.PreferencesRepository import com.ruuvi.station.bluetooth.BluetoothLibrary import com.ruuvi.station.database.TagRepository import com.ruuvi.station.database.tables.RuuviTagEntity import com.ruuvi.station.database.tables.TagSensorReading import com.ruuvi.station.image.ImageInteractor import com.ruuvi.station.network.data.NetworkSyncResult import com.ruuvi.station.network.data.NetworkSyncResultType import com.ruuvi.station.network.data.request.GetSensorDataRequest import com.ruuvi.station.network.data.response.GetSensorDataResponse import com.ruuvi.station.network.data.response.SensorDataMeasurementResponse import com.ruuvi.station.network.data.response.UserInfoResponseBody import com.ruuvi.station.util.extensions.diffGreaterThan import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import timber.log.Timber import java.io.File import java.net.URI import java.util.* @ExperimentalCoroutinesApi class NetworkDataSyncInteractor ( private val preferencesRepository: PreferencesRepository, private val tagRepository: TagRepository, private val networkInteractor: RuuviNetworkInteractor, private val imageInteractor: ImageInteractor ) { @Volatile private var syncJob: Job? = null private val syncResult = MutableStateFlow<NetworkSyncResult> (NetworkSyncResult(NetworkSyncResultType.NONE)) val syncResultFlow: StateFlow<NetworkSyncResult> = syncResult private val syncInProgress = MutableStateFlow<Boolean> (false) val syncInProgressFlow: StateFlow<Boolean> = syncInProgress fun syncNetworkData() { if (syncJob != null && syncJob?.isActive == true) { Timber.d("Already in sync mode") return } syncJob = CoroutineScope(IO).launch() { try { setSyncInProgress(true) val userInfo = networkInteractor.getUserInfo() if (userInfo?.data?.sensors == null) { setSyncResult(NetworkSyncResult(NetworkSyncResultType.NOT_LOGGED)) return@launch } val benchUpdate1 = Date() updateTags(userInfo.data) val benchUpdate2 = Date() Timber.d("benchmark-updateTags-finish - ${benchUpdate2.time - benchUpdate1.time} ms") Timber.d("benchmark-syncForPeriod-start") val benchSync1 = Date() syncForPeriod(userInfo.data, GlobalSettings.historyLengthHours) val benchSync2 = Date() Timber.d("benchmark-syncForPeriod-finish - ${benchSync2.time - benchSync1.time} ms") } catch (exception: Exception) { val message = exception.message message?.let { Timber.e(exception, "NetworkSync Exception") setSyncResult(NetworkSyncResult(NetworkSyncResultType.EXCEPTION, it)) } } finally { setSyncInProgress(false) } setSyncInProgress(false) } } private suspend fun syncForPeriod(userInfoData: UserInfoResponseBody, hours: Int) { if (networkInteractor.signedIn == false) { setSyncResult(NetworkSyncResult(NetworkSyncResultType.NOT_LOGGED)) return } withContext(IO) { val tagJobs = mutableListOf<Job>() for (tagInfo in userInfoData.sensors) { val job = launch { Timber.d("benchmark-syncSensorDataForPeriod-${tagInfo.sensor}-start") val benchUpdate1 = Date() syncSensorDataForPeriod(tagInfo.sensor, hours) val benchUpdate2 = Date() Timber.d("benchmark-syncSensorDataForPeriod-${tagInfo.sensor}-finish - ${benchUpdate2.time - benchUpdate1.time} ms") } tagJobs.add(job) } for (job in tagJobs) { job.join() } } setSyncResult(NetworkSyncResult(NetworkSyncResultType.SUCCESS)) preferencesRepository.setLastSyncDate(Date().time) } suspend fun syncSensorDataForPeriod(tagId: String, period: Int) { Timber.d("Synchronizing... $tagId") val tag = tagRepository.getTagById(tagId) if (tag != null && tag.isFavorite) { val cal = Calendar.getInstance() cal.time = Date() cal.add(Calendar.HOUR, -period) var since = cal.time if (tag.networkLastSync ?: Date(Long.MIN_VALUE) > since) since = tag.networkLastSync val originalSince = since // if we have data for recent minute - skipping update if (!since.diffGreaterThan(60*1000)) return val benchRequest1 = Date() var result = getSince(tagId, since, 5000) val measurements = mutableListOf<SensorDataMeasurementResponse>() var count = 1 while (result != null && result.data?.total ?: 0 > 0) { val data = result.data?.measurements result = null if (data != null && data.size > 0) { measurements.addAll(data) var maxTimestamp = data.maxBy { it.timestamp }?.timestamp if (maxTimestamp != null) { maxTimestamp++ since = Date(maxTimestamp * 1000) if (since.diffGreaterThan(60*1000)) { result = getSince(tagId, since, 5000) count++ } } } } val benchRequest2 = Date() Timber.d("benchmark-getSensorData($count)-finish ${tagId} - ${benchRequest2.time - benchRequest1.time} ms") if (measurements.size > 0) { val benchUpdate1 = Date() val existData = tagRepository.getTagReadingsDate(tagId, originalSince)?.map { it.createdAt } saveSensorData(tag, measurements, existData ?: listOf()) val benchUpdate2 = Date() Timber.d("benchmark-saveSensorData-finish ${tagId} Data points count ${measurements.size} - ${benchUpdate2.time - benchUpdate1.time} ms") } } } private suspend fun setSyncResult(status: NetworkSyncResult) = withContext(Dispatchers.Main) { Timber.d("SyncStatus = $status") syncResult.value = status } private suspend fun setSyncInProgress(status: Boolean) = withContext(Dispatchers.Main) { Timber.d("SyncInProgress = $status") syncInProgress.value = status } private fun saveSensorData(tag: RuuviTagEntity, measurements: List<SensorDataMeasurementResponse>, existsData: List<Date>): Int { val list = mutableListOf<TagSensorReading>() tag.id?.let{ tagId -> measurements.forEach { measurement -> val createdAt = Date(measurement.timestamp * 1000) if (!existsData.contains(createdAt)) { try { if (measurement.data.isNotEmpty()) { val reading = BluetoothLibrary.decode(tagId, measurement.data, measurement.rssi) list.add(TagSensorReading(reading, tag, createdAt)) } } catch (e: Exception) { Timber.e(e, "NetworkData: $tagId measurement = $measurement") } } } } if (list.size > 0) { val newestPoint = list.sortedByDescending { it.createdAt }.first() tag.updateData(newestPoint) tagRepository.updateTag(tag) TagSensorReading.saveList(list) return list.size } return 0 } private suspend fun updateTags(userInfoData: UserInfoResponseBody) { userInfoData.sensors.forEach { sensor -> Timber.d("updateTags: $sensor") var tagDb = tagRepository.getTagById(sensor.sensor) if (tagDb == null) { tagDb = RuuviTagEntity() tagDb.id = sensor.sensor tagDb.name = if (sensor.name.isEmpty()) sensor.sensor else sensor.name tagDb.favorite = true tagDb.defaultBackground = (Math.random() * 9.0).toInt() tagDb.createDate = Date() tagDb.insert() } else { if (tagDb.favorite == false) { tagDb.favorite = true tagDb.createDate = Date() } if (sensor.name.isNotEmpty()) tagDb.name = sensor.name tagDb.update() } if (sensor.picture.isNullOrEmpty() == false) { val networkImageGuid = File(URI(sensor.picture).path).nameWithoutExtension if (networkImageGuid != tagDb.networkBackground) { Timber.d("updating image $networkImageGuid") try { val imageFile = imageInteractor.downloadImage( "cloud_${sensor.sensor}", sensor.picture ) tagRepository.updateTagBackground( sensor.sensor, Uri.fromFile(imageFile).toString(), null, networkImageGuid ) } catch (e: Exception) { Timber.e(e, "Failed to load image: ${sensor.picture}") } } } } } suspend fun getSince(tagId: String, since: Date, limit: Int): GetSensorDataResponse? { Timber.d("benchmark-getSince-$tagId since $since") val request = GetSensorDataRequest( tagId, since = since, sort = "asc", limit = limit ) return networkInteractor.getSensorData(request) } fun syncStatusShowed() { syncResult.value = NetworkSyncResult(NetworkSyncResultType.NONE) } }
mit
34ed7b430587017c82ff85feac38675d
39.413127
153
0.578731
4.899813
false
false
false
false
emilybache/Racing-Car-Katas
kotlin/TirePressureMonitoringSystem/src/main/kotlin/tddmicroexercises/tirepressuremonitoringsystem/Alarm.kt
1
473
package tddmicroexercises.tirepressuremonitoringsystem class Alarm { private val LowPressureThreshold = 17.0 private val HighPressureThreshold = 21.0 internal var sensor = Sensor() var isAlarmOn = false internal set fun check() { val psiPressureValue = sensor.popNextPressurePsiValue() if (psiPressureValue < LowPressureThreshold || HighPressureThreshold < psiPressureValue) { isAlarmOn = true } } }
mit
4b0c1b0011af6750c8952fa6a34177ff
23.894737
98
0.684989
4.548077
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/handler/rpl/Rpl332Handler.kt
1
1044
package chat.willow.warren.handler.rpl import chat.willow.kale.IMetadataStore import chat.willow.kale.KaleHandler import chat.willow.kale.irc.message.rfc1459.rpl.Rpl332Message import chat.willow.kale.irc.message.rfc1459.rpl.Rpl332MessageType import chat.willow.warren.helper.loggerFor import chat.willow.warren.state.CaseMappingState import chat.willow.warren.state.JoinedChannelsState class Rpl332Handler(val channelsState: JoinedChannelsState, val caseMappingState: CaseMappingState) : KaleHandler<Rpl332MessageType>(Rpl332Message.Parser) { private val LOGGER = loggerFor<Rpl332Handler>() override fun handle(message: Rpl332MessageType, metadata: IMetadataStore) { val channel = channelsState[message.channel] val topic = message.content if (channel == null) { LOGGER.warn("got a topic for a channel we don't think we're in, not doing anything: $message") return } LOGGER.debug("channel topic for ${channel.name}: $topic") channel.topic = topic } }
isc
2bcfeef1c9983a2d003619f27eeb5c3b
33.8
156
0.744253
4.142857
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/management/config/subcontent/caller/CallableSubContent.kt
1
1471
package com.example.android.eyebody.management.config.subcontent.caller import android.app.Activity import com.example.android.eyebody.management.config.subcontent.CMBaseSubContent import junit.framework.Assert /** * Created by YOON on 2017-12-02 * fragment 에서 fragment 를 call 하려면 DialogCallerSubContent 로 Down Casting 하여 사용 */ abstract class CallableSubContent(text: String, preferenceName: String?, hasSwitch: Boolean, preferenceValueExplanation: List<String>? = null, private val callableList: List<Any?>?, val requestCode: Int=0) : CMBaseSubContent( text = text, preferenceName = preferenceName, hasSwitch = hasSwitch, preferenceValueExplanation = preferenceValueExplanation ) { init { Assert.assertTrue("Assertion failed : must both (preferenceValueExplanation, callableList) size are same\n" + "or both are contain equal or less than 1 storedInt\n", ((preferenceValueExplanation == null || preferenceValueExplanation.size <= 1) && (callableList == null || callableList.size <= 1)) || (callableList?.size == preferenceValueExplanation?.size)) } open fun canCall(order: Int): Boolean = callableList?.get(order) != null abstract fun call(callerActivity: Activity, order: Int) }
mit
1ce35d06549b2e6696a809baadb745ba
47.3
146
0.642512
4.629393
false
true
false
false
intrigus/chemie
android/src/main/kotlin/de/intrigus/chem/fragments/PseListFragment.kt
1
5346
/*Copyright 2015 Simon Gerst Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package de.intrigus.chem.fragments import android.content.Context import android.database.Cursor import android.os.Bundle import android.support.v4.app.ListFragment import android.support.v4.app.LoaderManager import android.support.v4.content.Loader import android.support.v7.widget.Toolbar import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CursorAdapter import android.widget.ListView import android.widget.TextView import de.intrigus.chem.ChemieActivity import de.intrigus.chem.R import de.intrigus.chem.util.DBSchema import de.intrigus.chem.util.PseDatabaseHelper import de.intrigus.chem.util.SimpleCursorLoader class PseListFragment : ListFragment(), LoaderManager.LoaderCallbacks<Cursor> { //Kotlin doesn't support importing constants as far as I know val ATOMIC_NUMBER: String = DBSchema.ETable.Cols.ATOMIC_NUMBER val SYMBOL: String = DBSchema.ETable.Cols.SYMBOL val NAME: String = DBSchema.ETable.Cols.NAME val ELEMENT_STATE: String = DBSchema.ETable.Cols.ELEMENT_STATE override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.pse_list, container, false) (activity as ChemieActivity).setupToolbar(view.findViewById(R.id.toolbar) as Toolbar) (activity as ChemieActivity).supportActionBar.title = "Periodic Table" (view.findViewById(android.R.id.list) as ListView).addHeaderView(LayoutInflater.from(activity).inflate(R.layout.pse_list_header, null)) return view } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) listAdapter = PseListAdapter(context, null) loaderManager.initLoader(0, null, this); } override fun onLoadFinished(loader: Loader<Cursor>?, data: Cursor?) { (listAdapter as CursorAdapter).swapCursor(data); } override fun onLoaderReset(loader: Loader<Cursor>?) { //(listAdapter as CursorAdapter).swapCursor(null); } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor>? { return object : SimpleCursorLoader(activity) { override fun loadInBackground(): Cursor { val elementCursor: Cursor = PseDatabaseHelper.getInstance(context).readableDatabase.rawQuery("SELECT $ATOMIC_NUMBER _id, * FROM elements ORDER BY $ATOMIC_NUMBER", null) //TODO Optimize, we don't need the whole table return elementCursor } } } inner class PseListAdapter : CursorAdapter { override fun bindView(view: View?, context: Context?, cursor: Cursor?) { // Save the element number, because it will be different in the click listener val elementNumber = cursor!!.getInt(cursor.getColumnIndexOrThrow(ATOMIC_NUMBER)) val elementNumberView = view!!.findViewById(R.id.element_number) as TextView elementNumberView.text = elementNumber.toString() + " " val elementSymbol = view.findViewById(R.id.element_symbol) as TextView //I'm unable to directly set the textcolor, so I've used html... val colorString: String = when (cursor.getString(cursor.getColumnIndex(ELEMENT_STATE))) { "gaseous" -> java.lang.String.format("#%06X", (0xFFFFFF and activity.resources.getColor(R.color.gaseous_color))) "liquid" -> java.lang.String.format("#%06X", (0xFFFFFF and activity.resources.getColor(R.color.liquid_color))) "solid" -> java.lang.String.format("#%06X", (0xFFFFFF and activity.resources.getColor(R.color.solid_color))) else -> java.lang.String.format("#%06X", (0xFFFFFF and activity.resources.getColor(R.color.solid_color))) } elementSymbol.text = Html.fromHtml("<font color=\"$colorString\">" + cursor.getString(cursor.getColumnIndex(SYMBOL)) + "</font>") val elementName = view.findViewById(R.id.element_name) as TextView elementName.text = " " + cursor.getString(cursor.getColumnIndex(NAME)) view.setOnClickListener { v -> (activity as ChemieActivity).switchScreen(PseDetailFragment(elementNumber)) } } override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View? { return LayoutInflater.from(context).inflate(R.layout.pse_list_row, parent, false) } constructor(context: Context?, c: Cursor?) : super(context, c) constructor(context: Context?, c: Cursor?, flags: Int) : super(context, c, flags) constructor(context: Context?, c: Cursor?, autoRequery: Boolean) : super(context, c, autoRequery) } }
apache-2.0
86401074f9d26c7ee561c96b6eaf7b94
45.495652
184
0.710251
4.216088
false
false
false
false
android/camera-samples
CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/PhotoFragment.kt
1
1860
/* * 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.android.example.cameraxbasic.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.fragment.app.Fragment import com.android.example.cameraxbasic.R import com.bumptech.glide.Glide import java.io.File /** Fragment used for each individual page showing a photo inside of [GalleryFragment] */ class PhotoFragment internal constructor() : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = ImageView(context) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val args = arguments ?: return val resource = args.getString(FILE_NAME_KEY)?.let { File(it) } ?: R.drawable.ic_photo Glide.with(view).load(resource).into(view as ImageView) } companion object { private const val FILE_NAME_KEY = "file_name" fun create(image: File) = PhotoFragment().apply { arguments = Bundle().apply { putString(FILE_NAME_KEY, image.absolutePath) } } } }
apache-2.0
cbafe0699f4490498a424b2167c77838
34.788462
93
0.710753
4.418052
false
false
false
false
google/ksp
integration-tests/src/test/resources/javaNestedClass/test-processor/src/main/kotlin/ValidateProcessor.kt
1
1490
import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.validate class ValidateProcessor(env: SymbolProcessorEnvironment) : SymbolProcessor { var logger: KSPLogger = env.logger override fun process(resolver: Resolver): List<KSAnnotated> { val javaClass = resolver.getClassDeclarationByName("com.example.JavaClass")!! val nestedClass = javaClass.declarations.filterIsInstance<KSClassDeclaration>() .single { it.simpleName.asString() == "NestedClass" } val provideString = nestedClass.declarations.filterIsInstance<KSFunctionDeclaration>() .single { it.simpleName.asString() == "provideString" } if (provideString.returnType!!.resolve().isError) { logger.error("provideString.returnType: not ok") } if (nestedClass.asStarProjectedType().isError == true) { logger.error("$javaClass.asStarProjectedType(): not ok") } if (!nestedClass.validate()) { logger.error("Failed to validate $nestedClass") } if (!javaClass.validate()) { logger.error("Failed to validate $javaClass") } return emptyList() } } class ValidateProcessorProvider : SymbolProcessorProvider { override fun create( env: SymbolProcessorEnvironment ): SymbolProcessor { return ValidateProcessor(env) } }
apache-2.0
6cfb45a8bbb3443baaaefe7f1c348736
38.210526
94
0.680537
5.050847
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIViewAnimation.kt
1
444
package com.yy.codex.uikit /** * Created by cuiminghui on 2017/1/16. */ class UIViewAnimation { var cancelled = false private set var finished = false private set internal var completion: Runnable? = null fun cancel() { if (!finished) { cancelled = true completion?.run() } } fun markFinished() { finished = true completion = null } }
gpl-3.0
44ffa50bdbf3d6ba10c6f71fbe43664c
14.857143
45
0.545045
4.484848
false
false
false
false
Sjtek/sjtekcontrol-core
core/src/main/kotlin/nl/sjtek/control/core/media/PlayerHandler.kt
1
2023
package nl.sjtek.control.core.media import io.habets.artparser.models.TrackResult import nl.sjtek.control.data.response.Music class PlayerHandler(private val moduleKey: String, mopidyUrl: String, chromeCastIp: String, update: (name: String) -> Unit) { private val chromeCast = ChromeCastPlayer("chromecast", chromeCastIp, update).open() private val mopidy = MopidyPlayer("mopidy", mopidyUrl, update).open() val activePlayer: MediaPlayer get() = when { mopidy.active -> mopidy chromeCast.active -> chromeCast !mopidy.connected -> chromeCast else -> mopidy } val response: Music get() { val player = activePlayer val track = player.track val name: String val artists: String val album: String val result = ArtParserHolder.get(track.uri) as? TrackResult if (track.needsFullResolve) { name = result?.name ?: track.name artists = result?.artists ?: track.artist album = result?.album ?: track.album } else { name = track.name artists = track.artist album = track.album } return Music(moduleKey, true, activePlayer.track.state.convert(), name, artists, album, track.uri, result?.image ?: "", result?.secondImage ?: "", track.volume, result?.color1?.red ?: -1, result?.color1?.green ?: -1, result?.color1?.blue ?: -1) } private fun MediaPlayer.State.convert(): Music.State = when (this) { MediaPlayer.State.PAUSED -> Music.State.PAUSED MediaPlayer.State.PLAYING -> Music.State.PLAYING MediaPlayer.State.STOPPED -> Music.State.STOPPED MediaPlayer.State.DISCONNECTED -> Music.State.STOPPED } }
gpl-3.0
bc176ebb2bc9b337dff7c4fa253451e3
35.8
125
0.553633
4.515625
false
false
false
false
http4k/http4k
http4k-contract/src/test/kotlin/org/http4k/contract/openapi/v3/JacksonJsonNamingAnnotatedTest.kt
1
2206
package org.http4k.contract.openapi.v3 import com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE import com.fasterxml.jackson.databind.PropertyNamingStrategies.UpperCamelCaseStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming import com.fasterxml.jackson.module.kotlin.KotlinModule import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import org.http4k.format.ConfigurableJackson import org.http4k.format.Jackson import org.http4k.format.asConfigurable import org.http4k.format.withStandardMappings import org.junit.jupiter.api.Test internal class JacksonJsonNamingAnnotatedTest { @JsonNaming(UpperCamelCaseStrategy::class) data class Renamed( val renamedValue: String = "bob", val nullable: String? = "nullable", val user_name: String = "name" ) data class Snake(val renamedValue: String = "bob") private val standard = JacksonJsonNamingAnnotated() @Test fun `finds value from object`() { assertThat( "nonNullable", standard(Renamed(), "RenamedValue"), equalTo(Field("bob", false, FieldMetadata.empty)) ) assertThat( "nonNullableNoRename", standard(Snake(), "renamedValue"), equalTo(Field("bob", false, FieldMetadata.empty)) ) assertThat("nullable", standard(Renamed(), "Nullable"), equalTo(Field("nullable", true, FieldMetadata.empty))) } @Test fun `throws on no field found`() { assertThat( "non existent", { JacksonJsonNamingAnnotated(Jackson)(Renamed(), "non existent") }, throws<NoFieldFound>() ) } object CustomJackson : ConfigurableJackson( KotlinModule.Builder().build() .asConfigurable() .withStandardMappings() .done().setPropertyNamingStrategy(SNAKE_CASE) ) @Test fun `use custom Jackson naming strategy`() { assertThat( JacksonJsonNamingAnnotated(CustomJackson)(Snake(), "renamed_value"), equalTo(Field("bob", false, FieldMetadata.empty)) ) } }
apache-2.0
051764b556408699bf1a6961e272aeff
31.925373
118
0.674071
4.465587
false
true
false
false
prfarlow1/nytc-meet
app/src/main/kotlin/org/needhamtrack/nytc/ui/ButterKnife.kt
1
6987
package org.needhamtrack.nytc.ui /** * Created by peter.farlow on 12/8/17. */ import android.app.Activity import android.app.Dialog import android.app.DialogFragment import android.app.Fragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty import android.support.v4.app.DialogFragment as SupportDialogFragment import android.support.v4.app.Fragment as SupportFragment public fun <V : View> View.bindView(id: Int) : ReadOnlyProperty<View, V> = required(id, viewFinder) public fun <V : View> Activity.bindView(id: Int) : ReadOnlyProperty<Activity, V> = required(id, viewFinder) public fun <V : View> Dialog.bindView(id: Int) : ReadOnlyProperty<Dialog, V> = required(id, viewFinder) public fun <V : View> DialogFragment.bindView(id: Int) : ReadOnlyProperty<DialogFragment, V> = required(id, viewFinder) public fun <V : View> SupportDialogFragment.bindView(id: Int) : ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder) public fun <V : View> Fragment.bindView(id: Int) : ReadOnlyProperty<Fragment, V> = required(id, viewFinder) public fun <V : View> SupportFragment.bindView(id: Int) : ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder) public fun <V : View> ViewHolder.bindView(id: Int) : ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder) public fun <V : View> View.bindOptionalView(id: Int) : ReadOnlyProperty<View, V?> = optional(id, viewFinder) public fun <V : View> Activity.bindOptionalView(id: Int) : ReadOnlyProperty<Activity, V?> = optional(id, viewFinder) public fun <V : View> Dialog.bindOptionalView(id: Int) : ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder) public fun <V : View> DialogFragment.bindOptionalView(id: Int) : ReadOnlyProperty<DialogFragment, V?> = optional(id, viewFinder) public fun <V : View> SupportDialogFragment.bindOptionalView(id: Int) : ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder) public fun <V : View> Fragment.bindOptionalView(id: Int) : ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder) public fun <V : View> SupportFragment.bindOptionalView(id: Int) : ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder) public fun <V : View> ViewHolder.bindOptionalView(id: Int) : ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder) public fun <V : View> View.bindViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = required(ids, viewFinder) public fun <V : View> Activity.bindViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder) public fun <V : View> Dialog.bindViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder) public fun <V : View> DialogFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<DialogFragment, List<V>> = required(ids, viewFinder) public fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder) public fun <V : View> Fragment.bindViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder) public fun <V : View> SupportFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder) public fun <V : View> ViewHolder.bindViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder) public fun <V : View> View.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder) public fun <V : View> Activity.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder) public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder) public fun <V : View> DialogFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<DialogFragment, List<V>> = optional(ids, viewFinder) public fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder) public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder) public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder) public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder) private val View.viewFinder: View.(Int) -> View? get() = { findViewById(it) } private val Activity.viewFinder: Activity.(Int) -> View? get() = { findViewById(it) } private val Dialog.viewFinder: Dialog.(Int) -> View? get() = { findViewById(it) } private val DialogFragment.viewFinder: DialogFragment.(Int) -> View? get() = { dialog?.findViewById(it) ?: view?.findViewById(it) } private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View? get() = { dialog?.findViewById(it) ?: view?.findViewById(it) } private val Fragment.viewFinder: Fragment.(Int) -> View? get() = { view.findViewById(it) } private val SupportFragment.viewFinder: SupportFragment.(Int) -> View? get() = { view!!.findViewById(it) } private val ViewHolder.viewFinder: ViewHolder.(Int) -> View? get() = { itemView.findViewById(it) } private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing = throw IllegalStateException("View ID $id for '${desc.name}' not found.") @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc -> t.finder(id) as V? } @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() } // Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> { private object EMPTY private var value: Any? = EMPTY override fun getValue(thisRef: T, property: KProperty<*>): V { if (value == EMPTY) { value = initializer(thisRef, property) } @Suppress("UNCHECKED_CAST") return value as V } }
mit
dc9d5be48214900c30158c748400c6bf
42.135802
100
0.699442
3.892479
false
false
false
false
Aunmag/a-zombie-shooter-game
src/main/java/aunmag/shooter/client/states/Game.kt
1
1431
package aunmag.shooter.client.states import aunmag.nightingale.input.Input import aunmag.nightingale.utilities.UtilsGraphics import aunmag.shooter.client.App import aunmag.shooter.client.Player import aunmag.shooter.client.graphics.CameraShaker import aunmag.shooter.client.graphics.Crosshair import aunmag.shooter.scenarios.ScenarioEncircling import aunmag.shooter.environment.World import aunmag.shooter.ux.Hud import org.lwjgl.glfw.GLFW class Game { val world = World() val player = Player(world) private val scenario = ScenarioEncircling(world) private val crosshair = Crosshair(player.actor) // TODO: Change implementation private val hud = Hud() fun resume() { world.playSounds() } fun suspend() { world.stopSounds() } fun update() { player.updateInput() world.update() scenario.update() player.updateCameraPosition() CameraShaker.update() if (Input.keyboard.isKeyPressed(GLFW.GLFW_KEY_ESCAPE)) { App.main.isPause = true } hud.update() } fun render() { world.render() player.renderUx() UtilsGraphics.drawPrepare() crosshair.render() scenario.render() hud.render() } fun remove() { world.remove() scenario.remove() hud.remove() } }
apache-2.0
0b5ae28f1c2f8ac4e0011baaf7badf78
22.254237
82
0.628232
4.233728
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/CardTemplate.kt
2
2519
/* * Copyright (c) 2020 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.cardviewer import androidx.annotation.CheckResult import java.lang.IllegalStateException class CardTemplate(template: String) { private var mPreStyle: String? = null private var mPreScript: String? = null private var mPreClass: String? = null private var mPreContent: String? = null private var mPostContent: String? = null @CheckResult fun render(content: String, style: String, script: String, cardClass: String): String { return mPreStyle + style + mPreScript + script + mPreClass + cardClass + mPreContent + content + mPostContent } init { // Note: This refactoring means the template must be in the specific order of style, class, content. // Since this is a const loaded from an asset file, I'm fine with this. val classDelim = "::class::" val styleDelim = "::style::" val scriptDelim = "::script::" val contentDelim = "::content::" val styleIndex = template.indexOf(styleDelim) val scriptIndex = template.indexOf(scriptDelim) val classIndex = template.indexOf(classDelim) val contentIndex = template.indexOf(contentDelim) try { mPreStyle = template.substring(0, styleIndex) mPreScript = template.substring(styleIndex + styleDelim.length, scriptIndex) mPreClass = template.substring(scriptIndex + scriptDelim.length, classIndex) mPreContent = template.substring(classIndex + classDelim.length, contentIndex) mPostContent = template.substring(contentIndex + contentDelim.length) } catch (ex: StringIndexOutOfBoundsException) { throw IllegalStateException("The card template had replacement string order, or content changed", ex) } } }
gpl-3.0
949474ea3dbab63654dc44064e3cfa71
46.528302
117
0.700675
4.373264
false
false
false
false
SergeySave/SpaceGame
core/src/com/sergey/spacegame/common/game/command/FormationCommandExecutable.kt
1
6025
package com.sergey.spacegame.common.game.command import com.badlogic.ashley.core.Entity import com.badlogic.gdx.math.Matrix3 import com.badlogic.gdx.math.Vector2 import com.sergey.spacegame.common.ecs.component.OrderComponent import com.sergey.spacegame.common.ecs.component.PositionComponent import com.sergey.spacegame.common.ecs.component.RotationComponent import com.sergey.spacegame.common.ecs.component.ShipComponent import com.sergey.spacegame.common.ecs.component.SizeComponent import com.sergey.spacegame.common.game.Level import com.sergey.spacegame.common.game.orders.FaceOrder import com.sergey.spacegame.common.game.orders.MoveOrder import com.sergey.spacegame.common.util.ceil //KotlinUtils import com.sergey.spacegame.common.util.floor //KotlinUtils /** * Represents a command executable that puts the entities into a formation * * @author sergeys * * @constructor Creates a new FormationCommandExecutable */ abstract class FormationCommandExecutable : CommandExecutable { override fun issue(entitySource: Iterable<Entity>, numEntities: Int, start: Vector2, end: Vector2, level: Level) { if (numEntities <= 1) return //Center of all of the ships val center = Vector2() //Fleet facing direction val facingVector = Vector2() var length = 0f var width = 0f //Compute the center position and the average facing direction entitySource.forEach { e -> center.add(PositionComponent.MAPPER.get(e).setVector(VEC)) if (RotationComponent.MAPPER.has(e)) { facingVector.add(VEC.set(1f, 0f).rotate(RotationComponent.MAPPER.get(e).r)) } if (SizeComponent.MAPPER.has(e)) { val size = SizeComponent.MAPPER.get(e) length = maxOf(length, size.w) width = maxOf(width, size.h) } } center.scl(1f / numEntities) if (length == 0f) length = 1f if (width == 0f) length = 1f val angle = facingVector.angle().toDouble() MTX.setToTranslation(center) MTX.rotate(angle.toFloat()) MTX.scale(length, width) //Match up each entity with a position val entityIterator = entitySource.iterator() getDeltaPositions(numEntities).forEach { v -> v.mul(MTX) //Apply transformation val entity = entityIterator.next() var order = OrderComponent.MAPPER.get(entity) if (order == null) { order = OrderComponent() entity.add(order) } val ship = ShipComponent.MAPPER.get(entity) val positionComponent = PositionComponent.MAPPER.get(entity) val deltaPos = v.cpy().sub(positionComponent.setVector(VEC)) order.addOrder(FaceOrder(deltaPos.angle().toDouble(), ship.rotateSpeed)) order.addOrder(MoveOrder(v.x.toDouble(), v.y.toDouble(), ship.moveSpeed)) order.addOrder(FaceOrder(angle, ship.rotateSpeed)) } } /** * Get the delta positions of the entities without rotation * * +X is positive facing direction * +Y is 90˚ counterclockwise from +X * * A single unit on the X or Y axis is the maximum length along that axis * * @param count - the amount of positions to generate * * @return an iterable of vectors representing the positions */ protected abstract fun getDeltaPositions(count: Int): Iterable<Vector2> //The point of overriding equals here and calling testEquals is to make it so that subclasses dont have to define //hashCode override fun equals(other: Any?): Boolean = testEquals(other) protected abstract fun testEquals(other: Any?): Boolean override fun hashCode(): Int = javaClass.hashCode() private companion object { val VEC = Vector2() val MTX = Matrix3() } } /** * A command executable that puts the ships into a square formation by spiraling * * @author sergeys */ class SquareFormationCommandExecutable : FormationCommandExecutable() { override fun getDeltaPositions(count: Int): Iterable<Vector2> { val positions = ArrayList<Vector2>() var dirX = 1 var dirY = 0 var length = 1 var x = 0 var y = 0 var lenWalked = 0 for (i in 0 until count) { positions.add(Vector2(x.toFloat(), y.toFloat())) x += dirX y += dirY if (++lenWalked == length) { lenWalked = 0 val temp = dirX dirX = -dirY dirY = temp if (dirY == 0) { ++length } } } return positions } override fun testEquals(other: Any?): Boolean = other is SquareFormationCommandExecutable } /** * A command executable that puts the ships into a triangle formation * * @author sergeys */ class TriangleFormationCommandExecutable : FormationCommandExecutable() { override fun getDeltaPositions(count: Int): Iterable<Vector2> { val positions = ArrayList<Vector2>() val levelsNeeded = -0.5 + 0.5 * Math.sqrt(8 * count.toDouble() + 1) - 1 for (i in 0..levelsNeeded.floor()) { for (j in 0..i) { positions.add(Vector2(levelsNeeded.toFloat() / 2f - i, i / 2f - j)) } } val remaining = count - positions.size - 1 for (j in 0..remaining) { positions.add(Vector2(levelsNeeded.toFloat() / 2f - levelsNeeded.ceil(), remaining / 2f - j)) } return positions } override fun testEquals(other: Any?): Boolean = other is TriangleFormationCommandExecutable }
mit
f8f74839eb53e5c3bc79baba89efd2e0
32.848315
118
0.60425
4.413187
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/postbox_ref/AddPostboxRefForm.kt
1
1586
package de.westnordost.streetcomplete.quests.postbox_ref import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.databinding.QuestRefBinding import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.AnswerItem import de.westnordost.streetcomplete.util.TextChangedWatcher class AddPostboxRefForm : AbstractQuestFormAnswerFragment<PostboxRefAnswer>() { override val contentLayoutResId = R.layout.quest_ref private val binding by contentViewBinding(QuestRefBinding::bind) override val otherAnswers = listOf( AnswerItem(R.string.quest_ref_answer_noRef) { confirmNoRef() } ) private val ref get() = binding.refInput.text?.toString().orEmpty().trim() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.refInput.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() }) } override fun onClickOk() { applyAnswer(Ref(ref)) } private fun confirmNoRef() { val ctx = context ?: return AlertDialog.Builder(ctx) .setTitle(R.string.quest_generic_confirmation_title) .setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> applyAnswer(NoRefVisible) } .setNegativeButton(R.string.quest_generic_confirmation_no, null) .show() } override fun isFormComplete() = ref.isNotEmpty() }
gpl-3.0
69584a4844cfa1130faa63b8e3a0aa11
36.761905
109
0.74338
4.692308
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/AddTactilePavingCrosswalk.kt
1
2765
package de.westnordost.streetcomplete.quests.tactile_paving import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND import de.westnordost.streetcomplete.ktx.toYesNo class AddTactilePavingCrosswalk : OsmElementQuestType<Boolean> { private val crossingFilter by lazy { """ nodes with ( highway = traffic_signals and crossing = traffic_signals and foot != no or highway = crossing and foot != no ) and ( !tactile_paving or tactile_paving = unknown or tactile_paving = no and tactile_paving older today -4 years or tactile_paving = yes and tactile_paving older today -8 years ) """.toElementFilterExpression() } private val excludedWaysFilter by lazy { """ ways with highway = cycleway and foot !~ yes|designated or highway = service and service = driveway or highway and access ~ private|no """.toElementFilterExpression() } override val commitMessage = "Add tactile pavings on crosswalks" override val wikiLink = "Key:tactile_paving" override val icon = R.drawable.ic_quest_blind_pedestrian_crossing override val enabledInCountries = COUNTRIES_WHERE_TACTILE_PAVING_IS_COMMON override val questTypeAchievements = listOf(BLIND) override fun getTitle(tags: Map<String, String>) = R.string.quest_tactilePaving_title_crosswalk override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> { val excludedWayNodeIds = mutableSetOf<Long>() mapData.ways .filter { excludedWaysFilter.matches(it) } .flatMapTo(excludedWayNodeIds) { it.nodeIds } return mapData.nodes .filter { crossingFilter.matches(it) && it.id !in excludedWayNodeIds } } override fun isApplicableTo(element: Element): Boolean? = if (!crossingFilter.matches(element)) false else null override fun createForm() = TactilePavingForm() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("tactile_paving", answer.toYesNo()) } override val defaultDisabledMessage = R.string.default_disabled_msg_boring }
gpl-3.0
125714cc7895ae504537428d08fc4f3d
41.538462
99
0.725859
4.82548
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/Long.kt
1
3510
package com.boardgamegeek.extensions import android.content.Context import android.text.format.DateUtils.* import androidx.annotation.StringRes import com.boardgamegeek.R import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit fun Long.isOlderThan(duration: Int, timeUnit: TimeUnit) = System.currentTimeMillis() - this > timeUnit.toMillis(duration.toLong()) fun Long.isToday(): Boolean = isToday(this) fun Long.asPastDaySpan(context: Context, @StringRes zeroResId: Int = R.string.never, includeWeekDay: Boolean = false): CharSequence { return if (this == 0L) context.getString(zeroResId) else { var flags = FORMAT_SHOW_DATE or FORMAT_SHOW_YEAR or FORMAT_ABBREV_ALL if (includeWeekDay) flags = flags or FORMAT_SHOW_WEEKDAY getRelativeTimeSpanString(this, System.currentTimeMillis(), DAY_IN_MILLIS, flags) } } fun Long.asDate(context: Context, @StringRes zeroResId: Int = R.string.never, includeWeekDay: Boolean = false): CharSequence { return if (this == 0L) context.getString(zeroResId) else { var flags = FORMAT_SHOW_DATE or FORMAT_SHOW_YEAR or FORMAT_ABBREV_ALL if (includeWeekDay) flags = flags or FORMAT_SHOW_WEEKDAY formatDateTime(context, this, flags) } } fun Long.asDateTime( context: Context, @StringRes zeroResId: Int = R.string.never, abbreviate: Boolean = true, includeWeekDay: Boolean = false ): CharSequence { return if (this == 0L) context.getString(zeroResId) else { var flags = FORMAT_SHOW_DATE or FORMAT_SHOW_YEAR or FORMAT_SHOW_TIME if (abbreviate) flags = flags or FORMAT_ABBREV_ALL if (includeWeekDay) flags = flags or FORMAT_SHOW_WEEKDAY formatDateTime(context, this, flags) } } fun Long.howManyMinutesOld(): Int { return ((System.currentTimeMillis() - this + 30_000) / MINUTE_IN_MILLIS).toInt() } fun Long.howManyHoursOld(): Int { return ((System.currentTimeMillis() - this) / HOUR_IN_MILLIS).toInt() } fun Long.howManyWeeksOld(): Int { return ((System.currentTimeMillis() - this) / WEEK_IN_MILLIS).toInt() } fun Long.forDatabase(): String { val c = Calendar.getInstance() c.timeInMillis = this return FORMAT_DATABASE.format(c.time) } fun Long.formatTimestamp(context: Context, includeTime: Boolean, isForumTimestamp: Boolean = false): CharSequence { var flags = FORMAT_SHOW_DATE or FORMAT_SHOW_YEAR or FORMAT_ABBREV_MONTH if (includeTime) flags = flags or FORMAT_SHOW_TIME val prefs = context.preferences() return if (isForumTimestamp && prefs[KEY_ADVANCED_DATES, false] == true) { formatDateTime(context, this, flags) } else { if (this == 0L) { context.getString(R.string.text_unknown) } else getRelativeTimeSpanString(this, System.currentTimeMillis(), MINUTE_IN_MILLIS, flags) } } private val FORMAT_API: DateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) private val FORMAT_DATABASE: DateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) fun Long?.asDateForApi(): String { if (this == null) return "" if (this == 0L) return "" val c = Calendar.getInstance() c.timeInMillis = this return FORMAT_API.format(c.time) } fun Long.fromLocalToUtc(): Long { val timeZone = TimeZone.getDefault() val standardTime = this - timeZone.rawOffset return standardTime - if (timeZone.inDaylightTime(Date(standardTime))) timeZone.dstSavings else 0 }
gpl-3.0
cdc994015ecb0461cbdd70c72b767d18
34.816327
133
0.704274
3.836066
false
false
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/opengl/model/GLRect.kt
1
1415
package br.com.insanitech.spritekit.opengl.model import br.com.insanitech.spritekit.core.ValueAssign /** * Created by anderson on 7/3/15. */ internal class GLRect() : ValueAssign<GLRect> { val origin: GLPoint = GLPoint() val size: GLSize = GLSize() constructor(x: Float, y: Float, width: Float, height: Float) : this() { this.origin.x = x this.origin.y = y this.size.width = width this.size.height = height } constructor(point: GLPoint, size: GLSize) : this() { this.origin.assignByValue(point) this.size.assignByValue(size) } val x: Float get() = this.origin.x val y: Float get() = this.origin.y val width: Float get() = this.size.width val height: Float get() = this.size.height fun containsPoint(point: GLPoint): Boolean { return point.x > this.origin.x && point.y > this.origin.y && point.x < this.origin.x + this.size.width && point.y < this.origin.y + this.size.height } override fun assignByValue(other: GLRect) { this.origin.assignByValue(other.origin) this.size.assignByValue(other.size) } companion object { fun centerRect(point: GLPoint, size: GLSize): GLRect = GLRect(point.x - size.width / 2, point.y - size.height / 2, size.width, size.height) } }
bsd-3-clause
7057647f82a0f66ffe73d2dfcbdda1e7
26.211538
100
0.59576
3.564232
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/config/WorldConfigObject.kt
1
3318
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.config import org.lanternpowered.api.util.Tristate import org.lanternpowered.api.world.difficulty.Difficulties import org.spongepowered.api.entity.living.player.gamemode.GameModes class ChunksObject : ConfigObject() { // TODO var test by setting(default = true, name = "test") companion object : Factory<ChunksObject> by { ChunksObject() } } class WorldGameModeObject : ConfigObject() { var mode by setting(default = GameModes.SURVIVAL.get(), name = "mode", description = "The default game mode of this world.") var forced by setting(default = true, name = "forced", description = "Whether players are forced to the default game mode on join.") companion object : Factory<WorldGameModeObject> by { WorldGameModeObject() } } class WorldConfigObject : ConfigObject() { val chunks by ChunksObject.with(name = "chunks") var pvp by setting(default = true, name = "pvp", description = "Enable if this world allows PVP combat.") var hardcore by setting(default = false, name = "hardcore", description = "Enable if this world should use the hardcore mode.") var enabled by setting(default = true, name = "enabled", description = "Enable if this world should be allowed to load.") var loadOnStartup by setting(default = false, name = "load-on-startup", description = "Enable if this world should load on startup.") var keepSpawnLoaded by setting(default = true, name = "keep-spawn-loaded", description = "Enable if this world's spawn should remain loaded with no players.") var waterEvaporates by setting(default = Tristate.UNDEFINED, name = "water-evaporates", description = "Enable if the water in this world should evaporate.") var allowPlayerRespawns by setting(default = true, name = "allow-player-respawns", description = "Enable if the player may respawn in this world.") var maxBuildHeight by setting(default = 255, name = "max-build-height", description = "The maximum build height of this world.") var lowHorizon by setting(default = false, name = "low-horizon", description = "Enable this if the the horizon of this world should be lower, from y = 63 to y = 0") var difficulty by setting(default = Difficulties.NORMAL.get(), name = "difficulty", description = "The difficulty of this world.") val gameMode by WorldGameModeObject.with(name = "game-mode") var viewDistance by setting(default = ViewDistance.USE_GLOBAL_SETTING, name = "view-distance", description = "The view distance. The value must be between ${ViewDistance.MINIMUM} and ${ViewDistance.MAXIMUM} (inclusive). Or\n" + "set the value to ${ViewDistance.USE_GLOBAL_SETTING} if you want to use the setting defined in the global config.") companion object : Factory<WorldConfigObject> by { WorldConfigObject() } }
mit
fa0388273827442b0ea227e13fe2d8a6
42.090909
144
0.691682
4.275773
false
true
false
false
AoiKuiyuyou/AoikWinWhich-Kotlin
src/aoikwinwhich/AoikWinWhich.kt
1
4642
// package aoikwinwhich import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.util.LinkedHashSet import java.util.LinkedList // object AoikWinWhich { fun find_executable(prog: String): List<String> { // 8f1kRCu val env_var_PATHEXT = System.getenv("PATHEXT") /// can be null // 6qhHTHF // split into a list of extensions var ext_s = if (env_var_PATHEXT == null) listOf<String>() else env_var_PATHEXT.split(File.pathSeparator).toList() // 2pGJrMW // strip ext_s = ext_s.map({x -> x.trim()}) // 2gqeHHl // remove empty ext_s = ext_s.filter({x -> x != ""}) // 2zdGM8W // convert to lowercase ext_s = ext_s.map({x -> x.toLowerCase()}) // 2fT8aRB // uniquify ext_s = LinkedHashSet(ext_s).toList() /// LinkedHashSet keeps the original order. // 4ysaQVN val env_var_PATH = System.getenv("PATH") /// can be null // 6mPI0lg var dir_path_s = if (env_var_PATH == null) linkedListOf<String>() else env_var_PATH.split(File.pathSeparator).toLinkedList() // 5rT49zI // insert empty dir path to the beginning // // Empty dir handles the case that |prog| is a path, either relative or // absolute. See code 7rO7NIN. dir_path_s.add(0, "") // 2klTv20 // uniquify dir_path_s = LinkedHashSet(dir_path_s).toLinkedList() /// LinkedHashSet keeps the original order. // val prog_lc = prog.toLowerCase() val prog_has_ext = ext_s.any({ext -> prog_lc.endsWith(ext)}) // 6bFwhbv var exe_path_s = linkedListOf<String>() for (dir_path in dir_path_s) { // 7rO7NIN // synthesize a path with the dir and prog val path = if (dir_path == "") prog else Paths.get(dir_path, prog).toString() // 6kZa5cq // assume the path has extension, check if it is an executable if (prog_has_ext && Files.isRegularFile(Paths.get(path))) { exe_path_s.add(path) } // 2sJhhEV // assume the path has no extension for (ext in ext_s) { // 6k9X6GP // synthesize a new path with the path and the executable extension val path_plus_ext = path + ext // 6kabzQg // check if it is an executable if (Files.isRegularFile(Paths.get(path_plus_ext))) { exe_path_s.add(path_plus_ext) } } } // 8swW6Av // uniquify exe_path_s = LinkedHashSet(exe_path_s).toLinkedList() /// LinkedHashSet keeps the original order. // return exe_path_s } fun main(args: Array<String>) { // 9mlJlKg // check if one cmd arg is given if (args.size != 1) { // 7rOUXFo // print program usage println("""Usage: aoikwinwhich PROG""") println() println("""#/ PROG can be either name or path""") println("""aoikwinwhich notepad.exe""") println("""aoikwinwhich C:\Windows\notepad.exe""") println("") println("""#/ PROG can be either absolute or relative""") println("""aoikwinwhich C:\Windows\notepad.exe""") println("""aoikwinwhich Windows\notepad.exe""") println("") println("""#/ PROG can be either with or without extension""") println("""aoikwinwhich notepad.exe""") println("""aoikwinwhich notepad""") println("""aoikwinwhich C:\Windows\notepad.exe""") println("""aoikwinwhich C:\Windows\notepad""") // 3nqHnP7 return } // 9m5B08H // get name or path of a program from cmd arg val prog = args[0] // 8ulvPXM // find executables val path_s = find_executable(prog) // 5fWrcaF // has found none, exit if (path_s.size == 0) { // 3uswpx0 return } // 9xPCWuS // has found some, output val txt = path_s.join("\n") println(txt) // 4s1yY1b return } } // fun main(args: Array<String>) { AoikWinWhich.main(args) }
mit
64bec09d160b2f6431eb51a4363d953c
26.630952
83
0.501939
3.957374
false
false
false
false
jrenner/kotlin-algorithms-ds
src/test/Test.kt
1
1120
package test import java.util.ArrayList import datastructs.fundamental.bag.ArrayBag import datastructs.fundamental.bag.Bag val tests = ArrayList<Test>() public open class Test(val name: String, testFunc: () -> Unit) { open val runTest = testFunc { tests.add(this) } } fun main(args: Array<String>) { createBagTests() createQueueTests() createLinkedListTests() createStackTests() createBinarySearchTreeTests() for (test in tests) { println("Running test: ${test.name}") test.runTest() } } val DO_BENCHMARKING = false public class BenchmarkTest(name: String, testFunc: () -> Unit, val loopCount: Int) : Test(name, testFunc) { class object { val defaultLoopCount = 1000 } override val runTest = { if (DO_BENCHMARKING) { val start = System.currentTimeMillis() for (n in 1..loopCount) { testFunc() } val timeTaken = System.currentTimeMillis() - start println("\ttime: ${timeTaken} ms") } else { testFunc() } } }
apache-2.0
c081f989e02921d730cbcd384b4e4dba
20.132075
107
0.598214
4.057971
false
true
false
false
ageery/kwicket
kwicket-kotlinx-html/src/main/kotlin/org/kwicket/kotlinx/html/ListViewRegion.kt
1
735
package org.kwicket.kotlinx.html import org.apache.wicket.model.IModel import org.kwicket.component.q import org.kwicket.wicket.core.markup.html.list.KListView import org.kwicket.wicket.core.markup.html.panel.KPanel class ListViewRegion<T, C : List<T>>( id: String, model: IModel<C>, region: (IModel<T>) -> RegionInfo ) : KPanel(id = id, model = model) { init { q( KListView( id = "view", renderBodyOnly = true, model = model, populate = { listItem -> listItem.add(RegionInfoPanel(id = "content", model = listItem.model, region = region, renderBodyOnly = true)) } ) ) } }
apache-2.0
080c64d7d5e9d7431e874af6f9d6f47b
26.259259
129
0.568707
3.909574
false
false
false
false
GeoffreyMetais/vlc-android
application/television/src/main/java/org/videolan/television/ui/browser/GridFragment.kt
1
2052
/***************************************************************************** * GridFragment.java * * Copyright © 2014-2015 VLC authors, VideoLAN and VideoLabs * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.television.ui.browser import android.os.Bundle import androidx.fragment.app.FragmentActivity import androidx.leanback.app.VerticalGridSupportFragment import androidx.leanback.widget.ArrayObjectAdapter import androidx.leanback.widget.VerticalGridPresenter import org.videolan.television.ui.CardPresenter import org.videolan.vlc.interfaces.BrowserFragmentInterface open class GridFragment : VerticalGridSupportFragment(), BrowserFragmentInterface { protected lateinit var adapter: ArrayObjectAdapter internal var context: FragmentActivity? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context = activity val gridPresenter = VerticalGridPresenter() gridPresenter.numberOfColumns = NUM_COLUMNS setGridPresenter(gridPresenter) adapter = ArrayObjectAdapter(CardPresenter(requireActivity())) adapter.clear() adapter = adapter } override fun refresh() {} companion object { protected const val TAG = "VLC/GridFragment" private const val NUM_COLUMNS = 4 } }
gpl-2.0
cfd95d33a2219b1dac30c190743c87e0
36.290909
83
0.726341
4.987835
false
false
false
false
JurajBegovac/RxKotlinTraits
sample/src/main/kotlin/com/jurajbegovac/sample/statemachine/SystemOperator.kt
1
1547
package com.jurajbegovac.sample.statemachine import com.jurajbegovac.rxkotlin.traits.driver.Driver import com.jurajbegovac.rxkotlin.traits.driver.DriverSharingStrategy import com.jurajbegovac.rxkotlin.traits.driver.asDriverCompleteOnError import com.jurajbegovac.rxkotlin.traits.shared_sequence.* import rx.Observable import rx.Scheduler import rx.subjects.ReplaySubject /** Created by juraj on 23/05/2017. */ object Observables { fun <S, C> system( initState: S, accumulator: (S, C) -> S, scheduler: Scheduler, vararg feedbacks: (Observable<S>) -> Observable<C>): Observable<S> { return Observable.defer { val replaySubject: ReplaySubject<S> = ReplaySubject.createWithSize(1) val command = Observable.merge(feedbacks.map { it(replaySubject) }) .observeOn(scheduler) command.scan(initState, accumulator) .doOnNext { replaySubject.onNext(it) } } } } fun <S, C> SharedSequence.Companion.system( initialState: S, accumulator: (S, C) -> S, vararg feedback: (Driver<S>) -> Driver<C>): SharedSequence<DriverSharingStrategy, S> { return DriverSharingStrategy.defer { val replaySubject: ReplaySubject<S> = ReplaySubject.createWithSize(1) val outputDriver = replaySubject.asDriverCompleteOnError() val command = DriverSharingStrategy.merge(feedback.map { it(outputDriver) }) command.scan(errorValue = initialState, initialValue = initialState, accumulator = accumulator) .doOnNext { replaySubject.onNext(it) } } }
mit
9eb1f45a5112ecbc23e3ac3d3327890b
34.159091
99
0.718811
4.125333
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/CommandsManager.kt
1
9249
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp import android.util.Log import com.pedro.rtmp.amf.v0.* import com.pedro.rtmp.flv.FlvPacket import com.pedro.rtmp.rtmp.chunk.ChunkStreamId import com.pedro.rtmp.rtmp.chunk.ChunkType import com.pedro.rtmp.rtmp.message.* import com.pedro.rtmp.rtmp.message.command.CommandAmf0 import com.pedro.rtmp.rtmp.message.control.Event import com.pedro.rtmp.rtmp.message.control.Type import com.pedro.rtmp.rtmp.message.control.UserControl import com.pedro.rtmp.rtmp.message.data.DataAmf0 import com.pedro.rtmp.utils.CommandSessionHistory import com.pedro.rtmp.utils.RtmpConfig import java.io.* /** * Created by pedro on 21/04/21. */ class CommandsManager { private val TAG = "CommandsManager" val sessionHistory = CommandSessionHistory() var timestamp = 0 private var commandId = 0 var streamId = 0 var host = "" var port = 1935 var appName = "" var streamName = "" var tcUrl = "" var user: String? = null var password: String? = null var onAuth = false var akamaiTs = false var startTs = 0L var readChunkSize = RtmpConfig.DEFAULT_CHUNK_SIZE var audioDisabled = false var videoDisabled = false private var width = 640 private var height = 480 private var fps = 30 private var sampleRate = 44100 private var isStereo = true fun setVideoResolution(width: Int, height: Int) { this.width = width this.height = height } fun setFps(fps: Int) { this.fps = fps } fun setAudioInfo(sampleRate: Int, isStereo: Boolean) { this.sampleRate = sampleRate this.isStereo = isStereo } fun setAuth(user: String?, password: String?) { this.user = user this.password = password } private fun getCurrentTimestamp(): Int { return (System.currentTimeMillis() / 1000 - timestamp).toInt() } @Throws(IOException::class) fun sendChunkSize(output: OutputStream) { if (RtmpConfig.writeChunkSize != RtmpConfig.DEFAULT_CHUNK_SIZE) { val chunkSize = SetChunkSize(RtmpConfig.writeChunkSize) chunkSize.header.timeStamp = getCurrentTimestamp() chunkSize.header.messageStreamId = streamId chunkSize.writeHeader(output) chunkSize.writeBody(output) output.flush() Log.i(TAG, "send $chunkSize") } else { Log.i(TAG, "using default write chunk size ${RtmpConfig.DEFAULT_CHUNK_SIZE}") } } @Throws(IOException::class) fun sendConnect(auth: String, output: OutputStream) { val connect = CommandAmf0("connect", ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_CONNECTION.mark)) val connectInfo = AmfObject() connectInfo.setProperty("app", appName + auth) connectInfo.setProperty("flashVer", "FMLE/3.0 (compatible; Lavf57.56.101)") connectInfo.setProperty("swfUrl", "") connectInfo.setProperty("tcUrl", tcUrl + auth) connectInfo.setProperty("fpad", false) connectInfo.setProperty("capabilities", 239.0) if (audioDisabled) { connectInfo.setProperty("audioCodecs", 3191.0) } if (videoDisabled) { connectInfo.setProperty("videoCodecs", 252.0) connectInfo.setProperty("videoFunction", 1.0) } connectInfo.setProperty("pageUrl", "") connectInfo.setProperty("objectEncoding", 0.0) connect.addData(connectInfo) connect.writeHeader(output) connect.writeBody(output) output.flush() sessionHistory.setPacket(commandId, "connect") Log.i(TAG, "send $connect") } @Throws(IOException::class) fun createStream(output: OutputStream) { val releaseStream = CommandAmf0("releaseStream", ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_STREAM.mark)) releaseStream.addData(AmfNull()) releaseStream.addData(AmfString(streamName)) releaseStream.writeHeader(output) releaseStream.writeBody(output) sessionHistory.setPacket(commandId, "releaseStream") Log.i(TAG, "send $releaseStream") val fcPublish = CommandAmf0("FCPublish", ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_STREAM.mark)) fcPublish.addData(AmfNull()) fcPublish.addData(AmfString(streamName)) fcPublish.writeHeader(output) fcPublish.writeBody(output) sessionHistory.setPacket(commandId, "FCPublish") Log.i(TAG, "send $fcPublish") val createStream = CommandAmf0("createStream", ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_CONNECTION.mark)) createStream.addData(AmfNull()) createStream.writeHeader(output) createStream.writeBody(output) output.flush() sessionHistory.setPacket(commandId, "createStream") Log.i(TAG, "send $createStream") } @Throws(IOException::class) fun readMessageResponse(input: InputStream): RtmpMessage { val message = RtmpMessage.getRtmpMessage(input, readChunkSize, sessionHistory) sessionHistory.setReadHeader(message.header) Log.i(TAG, "read $message") return message } @Throws(IOException::class) fun sendMetadata(output: OutputStream) { val name = "@setDataFrame" val metadata = DataAmf0(name, getCurrentTimestamp(), streamId) metadata.addData(AmfString("onMetaData")) val amfEcmaArray = AmfEcmaArray() amfEcmaArray.setProperty("duration", 0.0) if (videoDisabled) { amfEcmaArray.setProperty("width", width.toDouble()) amfEcmaArray.setProperty("height", height.toDouble()) amfEcmaArray.setProperty("videocodecid", 7.0) amfEcmaArray.setProperty("framerate", fps.toDouble()) amfEcmaArray.setProperty("videodatarate", 0.0) } if (audioDisabled) { amfEcmaArray.setProperty("audiocodecid", 10.0) amfEcmaArray.setProperty("audiosamplerate", sampleRate.toDouble()) amfEcmaArray.setProperty("audiosamplesize", 16.0) amfEcmaArray.setProperty("audiodatarate", 0.0) } amfEcmaArray.setProperty("stereo", isStereo) amfEcmaArray.setProperty("filesize", 0.0) metadata.addData(amfEcmaArray) metadata.writeHeader(output) metadata.writeBody(output) output.flush() Log.i(TAG, "send $metadata") } @Throws(IOException::class) fun sendPublish(output: OutputStream) { val name = "publish" val publish = CommandAmf0(name, ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_STREAM.mark)) publish.addData(AmfNull()) publish.addData(AmfString(streamName)) publish.addData(AmfString("live")) publish.writeHeader(output) publish.writeBody(output) output.flush() sessionHistory.setPacket(commandId, name) Log.i(TAG, "send $publish") } @Throws(IOException::class) fun sendWindowAcknowledgementSize(output: OutputStream) { val windowAcknowledgementSize = WindowAcknowledgementSize(RtmpConfig.acknowledgementWindowSize, getCurrentTimestamp()) windowAcknowledgementSize.writeHeader(output) windowAcknowledgementSize.writeBody(output) output.flush() } fun sendPong(event: Event, output: OutputStream) { val pong = UserControl(Type.PONG_REPLY, event) pong.writeHeader(output) pong.writeBody(output) output.flush() Log.i(TAG, "send pong") } @Throws(IOException::class) fun sendClose(output: OutputStream) { val name = "closeStream" val closeStream = CommandAmf0(name, ++commandId, getCurrentTimestamp(), streamId, BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_STREAM.mark)) closeStream.addData(AmfNull()) closeStream.writeHeader(output) closeStream.writeBody(output) output.flush() sessionHistory.setPacket(commandId, name) Log.i(TAG, "send $closeStream") } @Throws(IOException::class) fun sendVideoPacket(flvPacket: FlvPacket, output: OutputStream): Int { if (akamaiTs) { flvPacket.timeStamp = ((System.nanoTime() / 1000 - startTs) / 1000) } val video = Video(flvPacket, streamId) video.writeHeader(output) video.writeBody(output) output.flush() return video.header.getPacketLength() //get packet size with header included to calculate bps } @Throws(IOException::class) fun sendAudioPacket(flvPacket: FlvPacket, output: OutputStream): Int { if (akamaiTs) { flvPacket.timeStamp = ((System.nanoTime() / 1000 - startTs) / 1000) } val audio = Audio(flvPacket, streamId) audio.writeHeader(output) audio.writeBody(output) output.flush() return audio.header.getPacketLength() //get packet size with header included to calculate bps } fun reset() { startTs = 0 timestamp = 0 streamId = 0 commandId = 0 sessionHistory.reset() } }
apache-2.0
625c57357cf52e7c73f38490e0819c5c
32.273381
148
0.717483
3.860184
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorViewList.kt
1
3846
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.Scalars.GraphQLString import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.acl.IndicatorViewManagement import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorView import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorViewService import net.nemerosa.ontrack.extension.indicators.ui.IndicatorViewController import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.ui.resource.AbstractLinkResourceDecorator import net.nemerosa.ontrack.ui.resource.Link import net.nemerosa.ontrack.ui.resource.linkIfGlobal import net.nemerosa.ontrack.ui.resource.linkTo import org.springframework.stereotype.Component import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on /** * Management of [IndicatorView] list. */ @Component class GQLTypeIndicatorViewList( private val gqlTypeIndicatorView: GQLTypeIndicatorView, private val indicatorViewService: IndicatorViewService, private val fieldContributors: List<GQLFieldContributor> ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("List of indicator views and management links.") .field { it.name("views") .description("List of indicator views") .type(listType(gqlTypeIndicatorView.typeRef)) .argument { a -> a.name(ARG_ID) .description("ID of the view to put in the list") .type(GraphQLString) } .argument { a -> a.name(ARG_NAME) .description("Name of the view to put in the list") .type(GraphQLString) } .dataFetcher { env -> val id: String? = env.getArgument(ARG_ID) val name: String? = env.getArgument(ARG_NAME) if (id != null) { listOfNotNull( indicatorViewService.findIndicatorViewById(id) ) } else if (name != null) { listOfNotNull( indicatorViewService.findIndicatorViewByName(name) ) } else { indicatorViewService.getIndicatorViews() } } } // Links .fields(IndicatorViewList::class.java.graphQLFieldContributions(fieldContributors)) //OK .build() override fun getTypeName(): String = IndicatorViewList::class.java.simpleName companion object { const val ARG_ID = "id" const val ARG_NAME = "name" } } class IndicatorViewList private constructor() { companion object { val INSTANCE = IndicatorViewList() } } @Component class IndicatorViewListResourceDecorator : AbstractLinkResourceDecorator<IndicatorViewList>(IndicatorViewList::class.java) { override fun getLinkDefinitions() = listOf( Link.CREATE linkTo { _: IndicatorViewList -> on(IndicatorViewController::class.java).create(IndicatorViewController.IndicatorViewForm("", emptyList())) } linkIfGlobal IndicatorViewManagement::class ) }
mit
c4e5ef64fa02240430b065ff7eb90d0a
40.365591
118
0.628445
5.297521
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddDeriveIntention.kt
1
2504
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsStructOrEnumItemElement import org.rust.lang.core.psi.ext.findOuterAttr import org.rust.lang.core.psi.ext.parentOfType class AddDeriveIntention : RsElementBaseIntentionAction<AddDeriveIntention.Context>() { override fun getFamilyName() = "Add derive clause" override fun getText() = "Add derive clause" class Context( val item: RsStructOrEnumItemElement, val itemStart: PsiElement ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val item = element.parentOfType<RsStructOrEnumItemElement>() ?: return null val keyword = when (item) { is RsStructItem -> item.vis ?: item.struct is RsEnumItem -> item.vis ?: item.enum else -> null } ?: return null return Context(item, keyword) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val deriveAttr = findOrCreateDeriveAttr(project, ctx.item, ctx.itemStart) val reformattedDeriveAttr = reformat(project, ctx.item, deriveAttr) moveCaret(editor, reformattedDeriveAttr) } private fun findOrCreateDeriveAttr(project: Project, item: RsStructOrEnumItemElement, keyword: PsiElement): RsOuterAttr { val existingDeriveAttr = item.findOuterAttr("derive") if (existingDeriveAttr != null) { return existingDeriveAttr } val attr = RsPsiFactory(project).createOuterAttr("derive()") return item.addBefore(attr, keyword) as RsOuterAttr } private fun reformat(project: Project, item: RsStructOrEnumItemElement, deriveAttr: RsOuterAttr): RsOuterAttr { val marker = Object() PsiTreeUtil.mark(deriveAttr, marker) val reformattedItem = CodeStyleManager.getInstance(project).reformat(item) return PsiTreeUtil.releaseMark(reformattedItem, marker) as RsOuterAttr } private fun moveCaret(editor: Editor, deriveAttr: RsOuterAttr) { val offset = deriveAttr.metaItem.metaItemArgs?.rparen?.textOffset ?: deriveAttr.rbrack.textOffset ?: deriveAttr.textOffset editor.caretModel.moveToOffset(offset) } }
mit
56f7bae14a61a626aaea4434a35368ac
38.125
125
0.71246
4.628466
false
false
false
false
langara/MyIntent
myintent/src/main/java/pl/mareklangiewicz/myintent/MIApplication.kt
1
948
package pl.mareklangiewicz.myintent import android.app.Application import pl.mareklangiewicz.myloggers.MyAndroLogger import pl.mareklangiewicz.myloggers.* import pl.mareklangiewicz.myutils.MyLogLevel val APP_START_TIME = System.currentTimeMillis() /** * Created by Marek Langiewicz on 20.10.15. */ class MIApplication : Application() { init { if(!BuildConfig.DEBUG) MY_DEFAULT_ANDRO_LOGGER = MyAndroLogger(false) // FIXME LATER: this is a hack. TODO LATER: Delete this MY_DE.. global and use Dagger2 to provide appropriate loggers MY_DEFAULT_ANDRO_LOGGER.history.level = MyLogLevel.INFO } lateinit var FUNNY_QUOTES: Array<String> lateinit var SMART_QUOTES: Array<String> override fun onCreate() { FUNNY_QUOTES = resources.getStringArray(R.array.mr_funny_quotes) SMART_QUOTES = resources.getStringArray(R.array.mr_smart_quotes) super.onCreate() } }
apache-2.0
3ff016b4d28aec6987d1deda5175c909
26.882353
129
0.712025
3.917355
false
false
false
false
dinomite/forgetsy-jvm
src/main/kotlin/net/dinomite/forgetsy/Delta.kt
1
4000
package net.dinomite.forgetsy import org.slf4j.LoggerFactory import redis.clients.jedis.JedisPool import java.time.Duration import java.time.Instant /** * @param jedisPool A <a href="https://github.com/xetorthio/jedis">Jedis</a> pool instance * @param name This delta's name * @param lifetime Optional if Delta already exists in Redis, mean lifetime of observation * @param [start] Optional, an instant to start replaying from */ open class Delta(jedisPool: JedisPool, name: String, lifetime: Duration? = null, start: Instant? = null) { private val logger = LoggerFactory.getLogger(this.javaClass.name) companion object { val NORMAL_TIME_MULTIPLIER = 2 } val primarySet: Set val secondarySet: Set init { val primaryKey: String = name val secondaryKey: String = "${name}_2t" if (lifetime == null) { logger.info("Reifying Delta $name") try { primarySet = Set(jedisPool, primaryKey) secondarySet = Set(jedisPool, secondaryKey) } catch (e: IllegalStateException) { throw IllegalStateException("Delta doesn't exist (pass lifetime to create it)") } } else { val now = Instant.now() val startTime = start ?: now.minus(lifetime) logger.info("Creating new Delta, $name, with lifetime $lifetime and start time $startTime") primarySet = Set(jedisPool, primaryKey, lifetime, startTime) // Secondary for retrospective observations val secondaryLifetime = Duration.ofSeconds(lifetime.seconds * NORMAL_TIME_MULTIPLIER) val secondaryStart = now.minus(Duration.ofSeconds(Duration.between(startTime, now).seconds * NORMAL_TIME_MULTIPLIER)) logger.debug("Secondary set, $secondaryKey, with lifetime $lifetime and start time $secondaryStart") secondarySet = Set(jedisPool, secondaryKey, secondaryLifetime, secondaryStart) } } /** * Fetch the top bins * * @param limit The number of bins to fetch * @param [decay] Optional, whether to decay before fetch * @param [scrub] Optional, whether to scrube before fetch */ fun fetch(limit: Int? = null, decay: Boolean = true, scrub: Boolean = true): Map<String, Double> { if (decay) decay() if (scrub) scrub() val counts = primarySet.fetch() val norm = secondarySet.fetch() val result: List<Pair<String, Double>> = counts.map { val normV = norm[it.key] val newValue = if (normV == null) 0.0 else it.value / normV it.key to newValue } val trim = if (limit != null && limit <= result.size) limit else result.size return result.subList(0, trim).toMap() } /** * Fetch an individual bin * * @param bin The bin to fetch * @param [decay] Optional, whether to decay before fetch * @param [scrub] Optional, whether to scrube before fetch */ fun fetch(bin: String, decay: Boolean = true, scrub: Boolean = true): Map<String, Double?> { if (decay) decay() if (scrub) scrub() val counts = primarySet.fetch() val norm = secondarySet.fetch() val normV = norm[bin] if (normV == null) { return mapOf(bin to null) } else { return mapOf(bin to (counts[bin]!! / normV)) } } /** * Decay the data. */ fun decay() { primarySet.decayData() secondarySet.decayData() } /** * Scrub old entries */ fun scrub() { primarySet.scrubData() secondarySet.scrubData() } /** * Increment a bin */ fun increment(bin: String, amount: Double = 1.0) { logger.debug("Incrementing $bin by $amount") sets().forEach { it.increment(bin, amount) } } private fun sets() = listOf(primarySet, secondarySet) }
apache-2.0
66401b72b8dc951749579132e62a4bb5
31.266129
129
0.603
4.171011
false
false
false
false
oboehm/jfachwert
src/main/kotlin/de/jfachwert/math/PackedDecimal.kt
1
21447
/* * Copyright (c) 2018-2020 by Oliver Boehm * * 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. * * (c)reated 29.03.2018 by oboehm ([email protected]) */ package de.jfachwert.math import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.ser.std.ToStringSerializer import de.jfachwert.KFachwert import de.jfachwert.KSimpleValidator import de.jfachwert.pruefung.NullValidator import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException import org.apache.commons.lang3.StringUtils import java.math.BigDecimal import java.math.RoundingMode import java.util.* import java.util.logging.Logger /** * Die Klasse PackedDecimal dienst zum speicherschonende Speichern von Zahlen. * Sie greift die Idee von COBOL auf, wo es den numerischen Datentyp * "COMPUTATIONAL-3 PACKED" gibt, wo die Zahlen in Halb-Bytes (Nibbles) * abgespeichert wird. D.h. In einem Byte lassen sich damit 2 Zahlen * abspeichern. Diese Praesentation ist auch als BCD (Binary Coded Decimal) * bekannt (s. [BCD-Code](https://de.wikipedia.org/wiki/BCD-Code) * in Wikipedia). * * Dieser Datentyp eignet sich damit fuer: * * * Abspeichern grosser Menge von Zahlen, wenn dabei die interne * Speichergroesse relevant ist, * * Abspeichern von Zahlen beliebiger Groesse * (Ersatz fuer [java.math.BigDecimal], * * Abspeichern von Zahlen mit fuehrender Null (z.B. Vorwahl). * * Eine noch kompaktere Darstellung (ca. 20%) laesst sich mit der Chen-Ho- oder * Densely-Packed-Decimal-Kodierung (s. * [A Summary of Densely Packed Decimal encoding](http://speleotrove.com/decimal/DPDecimal.html)). * Diese kommt hier aber nicht zum Einsatz. Stattdessen kommt der BCD-Algorithmus * zum Einsatz. Dadurch koennen auch weitere Trenn- und Fuell-Zeichen aufgenommen * werden: * * * Vorzeichen (+, -) * * Formattierung ('.', ',') * * Leerzeichen * * Trennzeichen (z.B. fuer Telefonnummern) * * Die einzelnen Werte, die ein Halb-Byte (Nibble) aufnimmt, sind (angelehnt an * [COMPUTATIONAL-3 PACKED](http://acc-gmbh.com/dochtml/Datentypen4.html) * in COBOL): * <pre> * +-----+---+--------------------------------------------------+ * | 0x0 | 0 | Ziffer 0 | * | 0x1 | 1 | Ziffer 1 | * | ... | | | * | 0x9 | 9 | Ziffer 9 | * | 0xA | / | Trennzeichen fuer Brueche | * | 0xB | | Leerzeichen (Blank) | * | 0xC | + | positives Vorzeichen | * | 0xD | - | negatives Vorzeichen | * | 0xE | . | Formatzeichen Tausenderstelle (im Deutschen) | * | 0xF | , | Trennung Vorkomma/Nachkommastelle (im Deutschen) | * +-----+---+--------------------------------------------------+ </pre> * * * Damit koennen auch Zeichenketten nachgebildet werden, die strenggenommen * keine Dezimalzahl darstellen, z.B. "+49/811 32 16-8". Dies ist zwar * zulaessig, jedoch duerfen damit keine mathematische Operation angewendet * werden. Ansonsten kann die Klasse ueberall dort eingesetzt werden, wo * auch eine [java.math.BigDecimal] verwendet wird. * * Die API orientiert sich an die API von [BigDecimal] und ist auch von * der [Number]-Klasse abgeleitet. Allerdings werden noch nicht alle * Methoden von [unterstuetzt][BigDecimal]. In diesem Fall kann man auf * die Methode [.toBigDecimal] ausweichen. * * Da diese Klasse eher eine technische als eine fachliche Klasse ist, wurde * die englische Bezeichnung aus COBOL uebernommen. Sie wird von einigen * Fachwert-Klassen intern verwendet, kann aber auch fuer eigene Zwecke * verwendet werden. * * @author oboehm * @since 0.6 (29.03.2018) */ @JsonSerialize(using = ToStringSerializer::class) open class PackedDecimal @JvmOverloads constructor(zahl: String, validator: KSimpleValidator<String> = VALIDATOR) : AbstractNumber(), KFachwert { private val code: ByteArray constructor(zahl: Int): this(zahl.toLong()) {} companion object { private val LOG = Logger.getLogger(PackedDecimal::class.java.name) private val VALIDATOR: NullValidator<String> = NullValidator<String>() private val CACHE = arrayOfNulls<PackedDecimal>(10) private val WEAK_CACHE = WeakHashMap<String, PackedDecimal>() init { for (i in CACHE.indices) { CACHE[i] = PackedDecimal(i) } } /** Null-Konstante fuer Initialisierungen. */ @JvmField val NULL = PackedDecimal("") /** Leere PackedDecimal. */ @JvmField val EMPTY = PackedDecimal("") /** Die Zahl 0. */ @JvmField val ZERO = CACHE[0] /** Die Zahl 1. */ @JvmField val ONE = CACHE[1] /** Die Zahl 10. */ @JvmField val TEN = of(10) /** * Liefert den uebergebenen String als [PackedDecimal] zurueck. * Diese Methode ist dem Konstruktor vorzuziehen, da fuer gaengige Zahlen * wie "0" oder "1" immer das gleiche Objekt zurueckgegeben wird. * * @param zahl beliebige long-Zahl * @return Zahl als [PackedDecimal] */ @JvmStatic fun valueOf(zahl: Long): PackedDecimal { return valueOf(zahl.toString()) } /** * Da alle anderen Klassen auch eine of-Methode vorweisen, hat auch diese * Klasse eine of-Methode. Ansonsten entspricht dies der valueOf-Methode. * * @param zahl beliebige long-Zahl * @return Zahl als [PackedDecimal] * @since 2.0 */ @JvmStatic fun of(zahl: Long): PackedDecimal { return valueOf(zahl) } /** * Liefert den uebergebenen String als [PackedDecimal] zurueck. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] */ @JvmStatic fun valueOf(zahl: Double): PackedDecimal { return valueOf(java.lang.Double.toString(zahl)) } /** * Da alle anderen Klassen auch eine of-Methode vorweisen, hat auch diese * Klasse eine of-Methode. Ansonsten entspricht dies der valueOf-Methode. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] * @since 2.0 */ @JvmStatic fun of(zahl: Double): PackedDecimal { return valueOf(zahl) } /** * Liefert den uebergebenen String als [PackedDecimal] zurueck. * Diese Methode ist dem Konstruktor vorzuziehen, da fuer gaengige Zahlen * wie "0" oder "1" immer das gleiche Objekt zurueckgegeben wird. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] */ @JvmStatic fun valueOf(zahl: BigDecimal): PackedDecimal { return valueOf(zahl.toString()) } /** * Da alle anderen Klassen auch eine of-Methode vorweisen, hat auch diese * Klasse eine of-Methode. Ansonsten entspricht dies der valueOf-Methode. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] * @since 2.0 */ @JvmStatic fun of(zahl: BigDecimal): PackedDecimal { return valueOf(zahl) } /** * Liefert den uebergebenen String als [PackedDecimal] zurueck. * * @param bruch beliebiger Bruch * @return Bruch als [PackedDecimal] */ @JvmStatic fun valueOf(bruch: AbstractNumber): PackedDecimal { return valueOf(bruch.toString()) } /** * Da alle anderen Klassen auch eine of-Methode vorweisen, hat auch diese * Klasse eine of-Methode. Ansonsten entspricht dies der valueOf-Methode. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] * @since 2.0 */ @JvmStatic fun of(zahl: AbstractNumber): PackedDecimal { return valueOf(zahl) } /** * Liefert den uebergebenen String als [PackedDecimal] zurueck. * Diese Methode ist dem Konstruktor vorzuziehen, da fuer gaengige Zahlen * wie "0" oder "1" immer das gleiche Objekt zurueckgegeben wird. * * Im Gegensatz zum String-Konstruktor darf man hier auch 'null' als Wert * uebergeben. In diesem Fall wird dies in [.EMPTY] uebersetzt. * * Die erzeugten PackedDecimals werden intern in einem "weak" Cache * abgelegt, damit bei gleichen Zahlen auch die gleichen PackedDecimals * zurueckgegeben werden. Dies dient vor allem zur Reduktion des * Speicherverbrauchs. * * @param zahl String aus Zahlen * @return Zahl als [PackedDecimal] */ @JvmStatic fun valueOf(zahl: String): PackedDecimal { val trimmed = StringUtils.trimToEmpty(zahl) if (StringUtils.isEmpty(trimmed)) { return EMPTY } return if (trimmed.length == 1 && Character.isDigit(trimmed[0])) { CACHE[Character.getNumericValue(trimmed[0])]!! } else { WEAK_CACHE.computeIfAbsent(zahl) { z: String -> PackedDecimal(z) } } } /** * Da alle anderen Klassen auch eine of-Methode vorweisen, hat auch diese * Klasse eine of-Methode. Ansonsten entspricht dies der valueOf-Methode. * * @param zahl beliebige Zahl * @return Zahl als [PackedDecimal] * @since 2.0 */ @JvmStatic fun of(zahl: String): PackedDecimal { return valueOf(zahl) } private fun asNibbles(zahl: String): ByteArray { val chars = "$zahl ".toCharArray() val bytes = ByteArray(chars.size / 2) try { for (i in bytes.indices) { val upper = decode(chars[i * 2]) val lower = decode(chars[i * 2 + 1]) bytes[i] = (upper shl 4 or lower).toByte() } } catch (ex: IllegalArgumentException) { throw LocalizedIllegalArgumentException(zahl, "number", ex) } return bytes } private fun decode(x: Char): Int { return when (x) { '0' -> 0x0 '1' -> 0x1 '2' -> 0x2 '3' -> 0x3 '4' -> 0x4 '5' -> 0x5 '6' -> 0x6 '7' -> 0x7 '8' -> 0x8 '9' -> 0x9 '/' -> 0xA '\t', ' ' -> 0xB '+' -> 0xC '-' -> 0xD '.' -> 0xE ',' -> 0xF else -> throw LocalizedIllegalArgumentException(x, "number") } } private fun encode(nibble: Int): Char { return when (0x0F and nibble) { 0x0 -> '0' 0x1 -> '1' 0x2 -> '2' 0x3 -> '3' 0x4 -> '4' 0x5 -> '5' 0x6 -> '6' 0x7 -> '7' 0x8 -> '8' 0x9 -> '9' 0xA -> '/' 0xB -> ' ' 0xC -> '+' 0xD -> '-' 0xE -> '.' 0xF -> ',' else -> throw IllegalStateException("internal error") } } } /** * Instanziiert ein PackedDecimal. * * @param zahl Zahl */ constructor(zahl: Long) : this(java.lang.Long.toString(zahl)) {} /** * Instanziiert ein PackedDecimal. * * @param zahl Zahl */ constructor(zahl: Double) : this(java.lang.Double.toString(zahl)) {} /** * Falls man eine [BigDecimal] in eine [PackedDecimal] wandeln * will, kann man diesen Konstruktor hier verwenden. Besser ist es * allerdings, wenn man dazu [.valueOf] verwendet. * * @param zahl eine Dezimalzahl */ constructor(zahl: BigDecimal) : this(zahl.toString()) {} /** * Liefert true zurueck, wenn die Zahl als Bruch angegeben ist. * * @return true oder false */ val isBruch: Boolean get() { val s = toString() return if (s.contains("/")) { try { Bruch.of(s) true } catch (ex: IllegalArgumentException) { LOG.fine("$s is not a fraction: $ex") false } } else { false } } /** * Da sich mit [PackedDecimal] auch Telefonnummer und andere * Zahlenkombinationen abspeichern lassen, die im eigentlichen Sinn * keine Zahl darstellen, kann man ueber diese Methode abfragen, ob * eine Zahl abespeichdert wurde oder nicht. * * @return true, falls es sich um eine Zahl handelt. */ val isNumber: Boolean get() { val packed = toString().replace(" ".toRegex(), "") return try { BigDecimal(packed) true } catch (nfe: NumberFormatException) { LOG.fine("$packed is not a number: $nfe") isBruch } } /** * Liefert die Zahl als Bruch zurueck. * * @return Bruch als Zahl */ fun toBruch(): Bruch { return Bruch.of(toString()) } /** * Liefert die gepackte Dezimalzahl wieder als [BigDecimal] zurueck. * * @return gepackte Dezimalzahl als [BigDecimal] */ override fun toBigDecimal(): BigDecimal { return BigDecimal(toString()) } /** * Summiert den uebergebenen Summanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param summand Summand * @return Summe */ fun add(summand: PackedDecimal): PackedDecimal { return if (isBruch || summand.isBruch) { add(summand.toBruch()) } else { add(summand.toBigDecimal()) } } /** * Summiert den uebergebenen Summanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param summand Operand * @return Differenz */ fun add(summand: BigDecimal): PackedDecimal { val summe = toBigDecimal().add(summand) return valueOf(summe) } /** * Summiert den uebergebenen Summanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param summand Operand * @return Differenz */ fun add(summand: Bruch): PackedDecimal { val summe = toBruch().add(summand) return valueOf(summe) } /** * Subtrahiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Summand * @return Summe */ fun subtract(operand: PackedDecimal): PackedDecimal { return if (isBruch || operand.isBruch) { subtract(operand.toBruch()) } else { subtract(operand.toBigDecimal()) } } /** * Subtrahiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Differenz */ fun subtract(operand: BigDecimal): PackedDecimal { val result = toBigDecimal().subtract(operand) return valueOf(result) } /** * Subtrahiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Differenz */ fun subtract(operand: Bruch): PackedDecimal { val result = toBruch().subtract(operand) return valueOf(result) } /** * Mulitpliziert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Summand * @return Produkt */ fun multiply(operand: PackedDecimal): PackedDecimal { return if (isBruch || operand.isBruch) { multiply(operand.toBruch()) } else { multiply(operand.toBigDecimal()) } } /** * Multipliziert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Produkt */ fun multiply(operand: BigDecimal): PackedDecimal { val produkt = toBigDecimal().multiply(operand) return valueOf(produkt) } /** * Multipliziert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Produkt */ fun multiply(operand: Bruch): PackedDecimal { val produkt = toBruch().multiply(operand) return valueOf(produkt) } /** * Dividiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Ergebnis der Division */ fun divide(operand: PackedDecimal): PackedDecimal { return if (isBruch || operand.isBruch) { divide(operand.toBruch()) } else { divide(operand.toBigDecimal()) } } /** * Dividiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Ergebnis der Division */ fun divide(operand: Bruch): PackedDecimal { return multiply(operand.kehrwert()) } /** * Dividiert den uebergebenen Operanden und liefert als Ergebnis eine neue * [PackedDecimal] zurueck * * @param operand Operand * @return Ergebnis der Division */ fun divide(operand: BigDecimal): PackedDecimal { val result = toBigDecimal().divide(operand, RoundingMode.HALF_UP) return valueOf(result) } /** * Verschiebt den Dezimalpunkt um n Stellen nach links. * * @param n Anzahl Stellen * @return eine neue [PackedDecimal] */ fun movePointLeft(n: Int): PackedDecimal { val result = toBigDecimal().movePointLeft(n) return valueOf(result) } /** * Verschiebt den Dezimalpunkt um n Stellen nach rechts. * * @param n Anzahl Stellen * @return eine neue [PackedDecimal] */ fun movePointRight(n: Int): PackedDecimal { val result = toBigDecimal().movePointRight(n) return valueOf(result) } /** * Setzt die Anzahl der Nachkommastellen. * * @param n z.B. 0, falls keine Nachkommastelle gesetzt sein soll * @param mode Rundungs-Mode * @return eine neue [PackedDecimal] */ fun setScale(n: Int, mode: RoundingMode): PackedDecimal { val result = toBigDecimal().setScale(n, mode) return valueOf(result) } override fun toString(): String { val buf = StringBuilder() for (b in code) { buf.append(encode(b.toInt() shr 4)) buf.append(encode(b.toInt() and 0x0F)) } return buf.toString().trim { it <= ' ' } } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ override fun hashCode(): Int { return this.toString().hashCode() } /** * Beim Vergleich zweier PackedDecimals werden auch fuehrende Nullen * beruecksichtigt. D.h. '711' und '0711' werden als unterschiedlich * betrachtet. * * @param other zu vergleichende PackedDedimal * @return true bei Gleichheit * @see Object.equals */ override fun equals(other: Any?): Boolean { return other is PackedDecimal && this.toString() == other.toString() } /** * Vergleicht die andere Zahl mit der aktuellen Zahl. * * @param other die andere Zahl, die verglichen wird * @return negtive Zahl, falls this &lt; other, 0 bei Gleichheit, ansonsten * positive Zahl. */ override fun compareTo(other: AbstractNumber): Int { return if (other is PackedDecimal) { compareTo(other) } else { super.compareTo(other) } } /** * Vergleicht die andere Zahl mit der aktuellen Zahl. * * @param other die andere [PackedDecimal], die verglichen wird. * @return negtive Zahl, falls this &lt; other, 0 bei Gleichheit, ansonsten * positive Zahl. */ operator fun compareTo(other: PackedDecimal): Int { return toBruch().compareTo(other.toBruch()) } init { code = asNibbles(validator.validate(zahl)) } }
apache-2.0
3a50caa640dbde1ed2c7934dc068def0
30.964232
145
0.573693
3.785878
false
false
false
false
thomcz/kotlin-todo-app
app/src/main/java/thomcz/kotlintodo/activity/MainActivity.kt
1
3215
package thomcz.kotlintodo.activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import thomcz.kotlintodo.data.Item import thomcz.kotlintodo.R import thomcz.kotlintodo.adapter.RecyclerViewAdapter import thomcz.kotlintodo.viewmodel.TodoListViewModel class MainActivity : AppCompatActivity() { private lateinit var viewModel : TodoListViewModel private lateinit var recyclerView : RecyclerView private lateinit var recyclerViewAdapter : RecyclerViewAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val fab = findViewById<FloatingActionButton>(R.id.fab) fab.setOnClickListener { startActivity(Intent(this, AddActivity::class.java)) } recyclerView = findViewById(R.id.recycler_view) recyclerViewAdapter = RecyclerViewAdapter(ArrayList(), View.OnClickListener { checkedTodo(it) updateItem(it) }) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = recyclerViewAdapter viewModel = ViewModelProviders.of(this).get(TodoListViewModel::class.java) viewModel.getItems()?.observe(this, Observer<List<Item>> { items -> items?.let { recyclerViewAdapter.addItems(it) } }) } private fun updateItem(it: View) { val item = (it.parent as View).tag as Item item.checked = !item.checked viewModel.updateItem(item) } fun deleteItem(view: View) { val item = (view.parent as View).tag as Item viewModel.deleteItem(item) } private fun checkedTodo(it: View) { val view = it.parent as View val title = view.findViewById<TextView>(R.id.todo_item_title) val desc = view.findViewById<TextView>(R.id.todo_item_desc) val item = view.tag as Item RecyclerViewAdapter.Companion.setStrikeThrough(item.checked, title, desc) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId return if (id == R.id.action_settings) { true } else super.onOptionsItemSelected(item) } }
mit
ca964ac26c59cc2d23b8434f38207241
32.489583
85
0.701089
4.625899
false
false
false
false
marcelgross90/Cineaste
app/src/main/kotlin/de/cineaste/android/viewholder/series/SeriesViewHolder.kt
1
2060
package de.cineaste.android.viewholder.series import android.content.Context import android.graphics.Color import android.view.View import android.widget.ImageButton import android.widget.TextView import de.cineaste.android.R import de.cineaste.android.adapter.series.SeriesListAdapter import de.cineaste.android.entity.series.Series import de.cineaste.android.fragment.WatchState import de.cineaste.android.listener.ItemClickListener class SeriesViewHolder( itemView: View, listener: ItemClickListener, context: Context, state: WatchState, private val onEpisodeWatchedClickListener: SeriesListAdapter.OnEpisodeWatchedClickListener ) : AbstractSeriesViewHolder(itemView, listener, context) { private val seasons: TextView = itemView.findViewById(R.id.season) private val currentStatus: TextView = itemView.findViewById(R.id.current) private val episodeSeen: ImageButton = itemView.findViewById(R.id.episode_seen) init { if (state == WatchState.WATCHED_STATE) { episodeSeen.visibility = View.GONE } } override fun assignData(series: Series, position: Int) { setBaseInformation(series) seasons.text = resources.getString(R.string.seasons, series.numberOfSeasons.toString()) currentStatus.text = resources.getString( R.string.currentStatus, series.currentNumberOfSeason.toString(), series.currentNumberOfEpisode.toString() ) episodeSeen.setOnClickListener { onEpisodeWatchedClickListener.onEpisodeWatchedClick( series, position ) } listener?.let { view.setOnClickListener { view -> listener.onItemClickListener( series.id, arrayOf(view, poster, title) ) } } } fun onItemSelected() { itemView.setBackgroundColor(Color.LTGRAY) } fun onItemClear() { itemView.setBackgroundColor(Color.WHITE) } }
gpl-3.0
e48c8885d155a8a3cb1395c9f6a400f6
29.746269
95
0.678155
4.824356
false
false
false
false
niranjan94/show-java
app/src/main/kotlin/com/njlabs/showjava/utils/Ads.kt
1
4088
/* * Show Java - A java/apk decompiler for android * Copyright (c) 2018 Niranjan Rajendran * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.njlabs.showjava.utils import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import com.google.ads.consent.* import com.google.android.gms.ads.MobileAds import com.njlabs.showjava.R import com.njlabs.showjava.activities.purchase.PurchaseActivity import timber.log.Timber import java.net.URL /** * Initialize the ads library. Also, takes care of showing a consent screen for users within EU * and persisting the consent. */ class Ads(val context: Context) { private val consentInformation: ConsentInformation = ConsentInformation.getInstance(context) private lateinit var consentForm: ConsentForm fun getPreferences(): SharedPreferences { return context.getSharedPreferences(UserPreferences.NAME, Context.MODE_PRIVATE) } @SuppressLint("ApplySharedPref") fun init() { MobileAds.initialize(context, context.getString(R.string.admobAppId)) val publisherIds = arrayOf(context.getString(R.string.admobPublisherId)) consentInformation.requestConsentInfoUpdate( publisherIds, object : ConsentInfoUpdateListener { override fun onConsentInfoUpdated(consentStatus: ConsentStatus) { getPreferences().edit() .putInt("consentStatus", consentStatus.ordinal) .commit() } override fun onFailedToUpdateConsentInfo(errorDescription: String) { getPreferences().edit() .putInt("consentStatus", ConsentStatus.UNKNOWN.ordinal) .commit() } }) } /** * Load the consent screen and prepare to display. */ fun loadConsentScreen(): ConsentForm? { consentForm = ConsentForm.Builder(context, URL(context.getString(R.string.privacyPolicyUrl))) .withListener(object : ConsentFormListener() { override fun onConsentFormLoaded() { if (context is Activity && !context.isFinishing) { consentForm.show() } } override fun onConsentFormOpened() { Timber.d("[consent-screen] onConsentFormOpened") } override fun onConsentFormClosed(consentStatus: ConsentStatus?, userPrefersAdFree: Boolean?) { consentStatus?.let { ConsentInformation.getInstance(context).consentStatus = it getPreferences().edit().putInt("consentStatus", consentStatus.ordinal).apply() } if (userPrefersAdFree != null && userPrefersAdFree) { context.startActivity(Intent(context, PurchaseActivity::class.java)) } } override fun onConsentFormError(errorDescription: String?) { Timber.d("[consent-screen] onConsentFormError: $errorDescription") } }) .withPersonalizedAdsOption() .withNonPersonalizedAdsOption() .withAdFreeOption() .build() consentForm.load() return consentForm } }
gpl-3.0
d389b96c6c782cbcfe45bac7090a49b9
39.088235
110
0.636986
5.015951
false
false
false
false
AndroidX/androidx
compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/settings/PreferenceAsState.kt
3
2988
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.demos.settings import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.preference.PreferenceManager /** * Returns a [State] that reads the shared preference with the given [key] from the [LocalContext]. * The state will be automatically updated whenever the shared preference changes. */ @Composable internal fun <T> preferenceAsState( key: String, readValue: SharedPreferences.() -> T ): State<T> { val context = LocalContext.current val sharedPreferences = remember(context) { PreferenceManager.getDefaultSharedPreferences(context) } val lifecycle = LocalLifecycleOwner.current.lifecycle // De-duplicate passing keys explicitly to remembers and effects below. return key(key, readValue, sharedPreferences) { val value = remember { mutableStateOf(sharedPreferences.readValue()) } // Update value when preference changes. DisposableEffect(Unit) { val listener = OnSharedPreferenceChangeListener { _, changedKey -> if (changedKey == key) { value.value = sharedPreferences.readValue() } } sharedPreferences.registerOnSharedPreferenceChangeListener(listener) onDispose { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) } } // Also update the value when resumed. DisposableEffect(lifecycle) { val obs = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) { value.value = sharedPreferences.readValue() } } lifecycle.addObserver(obs) onDispose { lifecycle.removeObserver(obs) } } return@key value } }
apache-2.0
cbd87dc3709fbdbbef6424339981963f
36.3625
99
0.703481
5.316726
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/DuckDuckGo.kt
1
4910
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import io.sentry.Sentry import moe.kyubey.akatsuki.annotations.Alias import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.utils.Http import net.dv8tion.jda.core.EmbedBuilder import okhttp3.HttpUrl import org.json.JSONObject import java.awt.Color import kotlin.math.min @Load @Argument("query", "string") @Alias("ddg") class DuckDuckGo : Command() { override val desc = "Search on DuckDuckGo." override fun run(ctx: Context) { Http.get(HttpUrl.Builder().apply { scheme("https") host("api.duckduckgo.com") addQueryParameter("format", "json") addQueryParameter("q", ctx.args["query"] as String) }.build()).thenAccept { res -> val body = res.body()!!.string() val json = JSONObject(body) val embed = EmbedBuilder().apply { setColor(Color(222, 88, 51)) if (json.optJSONObject("Infobox") != null) { val info = json.getJSONObject("Infobox") val content = info.getJSONArray("content") (0 until content.length()) .asSequence() .map { content.getJSONObject(it) } .filter { it.getString("data_type") == "string" } .forEach { descriptionBuilder.append("**${it.getString("label")}:** ${it.getString("value")}\n") } } if (!json.optString("Entity").isNullOrBlank()) { setAuthor(json.getString("Entity")) } if (!json.optString("Heading").isNullOrBlank()) { setTitle(json.getString("Heading"), json.optString("AbstractURL")) } if (!json.optString("AbstractText").isNullOrBlank()) { descriptionBuilder.append("\n${json.getString("AbstractText")}\n") } else if (!json.optString("Abstract").isNullOrBlank()) { descriptionBuilder.append("\n${json.getString("Abstract")}\n") } if (!json.getString("Image").isNullOrBlank()) { setThumbnail(json.getString("Image")) } if (json.optJSONArray("RelatedTopics") != null) { val topics = json.getJSONArray("RelatedTopics") if (topics.length() != 0) { descriptionBuilder.append("\n**Related Topics:**") } (0 until min(3, topics.length())) .asSequence() .map { topics.getJSONObject(it) } .forEach { addField( if (it.getString("Text").length > 256) it.getString("Text").substring(0, 253) + "..." else it.getString("Text"), it.getString("FirstURL"), true ) } } } if (embed.isEmpty) { res.close() return@thenAccept ctx.channel.sendMessage(ctx.lang.getString("no_results")).queue() } ctx.channel.sendMessage(embed.build()).queue() res.close() }.thenApply {}.exceptionally { ctx.logger.error("Error while trying to search DuckDuckGo", it) ctx.sendError(it) Sentry.capture(it) } } }
mit
907bc73b829466c3177120a492656529
39.586777
152
0.557434
4.842209
false
false
false
false
deva666/anko
anko/library/generator/src/org/jetbrains/android/anko/ClassProcessor.kt
4
2675
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko import org.jetbrains.android.anko.artifact.Artifact import org.jetbrains.android.anko.utils.ClassTree import org.objectweb.asm.ClassReader import org.objectweb.asm.tree.ClassNode import java.io.File import java.io.InputStream import java.util.zip.ZipFile class ClassProcessor(val artifact: Artifact) { fun genClassTree(): ClassTree { val classTree = ClassTree() for (classData in extractClasses()) { classTree.add(processClassData(classData.first), classData.second) } return classTree } private fun extractClasses(): Sequence<Pair<InputStream, Boolean>> { val hasTargetJars = artifact.targetJars.isNotEmpty() val platformClasses = (artifact.platformJars - artifact.targetJars) .asSequence().flatMap { getEntries(it) }.map { it to hasTargetJars } val targetJars = artifact.targetJars.asSequence().flatMap { getEntries(it) }.map { it to false } return platformClasses + targetJars } private fun getEntries(file: File): Sequence<InputStream> { if (file.extension == "jar") { val zipFile = ZipFile(file) return zipFile.entries().asSequence() .filter { it.name.endsWith(".class") } .map { zipFile.getInputStream(it) } } assert(file.extension == "aar") val zipFile = ZipFile(file) return zipFile.entries().asSequence() .filter { it.name.endsWith(".jar") } .map { File.createTempFile("anko", ".jar").apply { deleteOnExit() zipFile.getInputStream(it).copyTo(outputStream()) } }.flatMap { getEntries(it) } } private fun processClassData(classData: InputStream): ClassNode { return classData.use { val classNode = ClassNode() val classReader = ClassReader(classData) classReader.accept(classNode, 0) classNode } } }
apache-2.0
20fcc97909d4e62351ee52bf95a79c63
34.68
104
0.638879
4.588336
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/GroupMembership.kt
2
694
package com.habitrpg.android.habitica.models.social import com.habitrpg.android.habitica.models.BaseObject import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class GroupMembership : RealmObject, BaseObject { @PrimaryKey var combinedID: String = "" var userID: String = "" set(value) { field = value combinedID = userID + groupID } var groupID: String = "" set(value) { field = value combinedID = userID + groupID } constructor(userID: String, groupID: String) : super() { this.userID = userID this.groupID = groupID } constructor() : super() }
gpl-3.0
334db0e18559740c414db8e5088c3a1e
23.785714
60
0.618156
4.535948
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/codeassist/nonImportedCompletionHandler.kt
1
3329
package org.jetbrains.kotlin.ui.editors.codeassist import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.eclipse.jdt.core.search.TypeNameMatchRequestor import org.eclipse.jdt.core.search.TypeNameMatch import org.eclipse.jdt.core.Flags import org.eclipse.jdt.core.search.SearchEngine import org.eclipse.jdt.core.search.SearchPattern import org.eclipse.jdt.core.search.IJavaSearchConstants import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory import org.eclipse.jface.text.contentassist.ICompletionProposal import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.core.utils.ProjectUtils import org.eclipse.jdt.core.JavaCore import com.intellij.openapi.util.text.StringUtil fun lookupNonImportedTypes( simpleNameExpression: KtSimpleNameExpression, identifierPart: String, ktFile: KtFile, javaProject: IJavaProject): List<TypeNameMatch> { if (!identifierPart.isCapitalized()) return emptyList() val callTypeAndReceiver = CallTypeAndReceiver.detect(simpleNameExpression) val isAnnotation = callTypeAndReceiver is CallTypeAndReceiver.ANNOTATION if ((callTypeAndReceiver !is CallTypeAndReceiver.TYPE && callTypeAndReceiver !is CallTypeAndReceiver.DEFAULT && !isAnnotation) || callTypeAndReceiver.receiver != null) { return emptyList() } val importsSet = ktFile.importDirectives .mapNotNull { it.getImportedFqName()?.asString() } .toSet() val originPackage = ktFile.packageFqName.asString() // TODO: exclude variants by callType.descriptorKind return searchFor(identifierPart, javaProject, isAnnotation) .filter { it.fullyQualifiedName !in importsSet && it.packageName !in importsSet && it.packageName != originPackage } } private fun String.isCapitalized(): Boolean = isNotEmpty() && this[0].isUpperCase() private fun searchFor(identifierPart: String, javaProject: IJavaProject, isAnnotation: Boolean): List<TypeNameMatch> { val foundTypes = arrayListOf<TypeNameMatch>() val collector = object : TypeNameMatchRequestor() { override fun acceptTypeNameMatch(match: TypeNameMatch) { if (Flags.isPublic(match.modifiers)) { foundTypes.add(match) } } } val searchEngine = SearchEngine() val dependencyProjects = arrayListOf<IJavaProject>().apply { addAll(ProjectUtils.getDependencyProjects(javaProject).map { JavaCore.create(it) }) add(javaProject) } val javaProjectSearchScope = JavaSearchScopeFactory.getInstance().createJavaSearchScope(dependencyProjects.toTypedArray(), true) searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH, identifierPart.toCharArray(), SearchPattern.R_CAMELCASE_MATCH, if (isAnnotation) IJavaSearchConstants.ANNOTATION_TYPE else IJavaSearchConstants.TYPE, javaProjectSearchScope, collector, IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, null) return foundTypes }
apache-2.0
011b0ea7c4efb57bd207268d05d2b431
39.120482
132
0.705617
5.028701
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/formatter/kotlinFormatter.kt
1
6712
package org.jetbrains.kotlin.ui.formatter import com.intellij.formatting.Block import com.intellij.formatting.DependantSpacingImpl import com.intellij.formatting.DependentSpacingRule import com.intellij.formatting.FormatTextRanges import com.intellij.formatting.FormatterImpl import com.intellij.formatting.Indent import com.intellij.formatting.Spacing import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions import com.intellij.psi.formatter.FormatterUtil import com.intellij.util.text.CharArrayUtil import org.eclipse.core.resources.IFile import org.eclipse.jface.text.Document import org.eclipse.jface.text.IDocument import org.jetbrains.kotlin.core.model.getEnvironment import org.jetbrains.kotlin.eclipse.ui.utils.IndenterUtil import org.jetbrains.kotlin.eclipse.ui.utils.LineEndUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.formatter.KotlinCommonCodeStyleSettings import org.jetbrains.kotlin.idea.formatter.KotlinSpacingBuilderUtil import org.jetbrains.kotlin.idea.formatter.createSpacingBuilder import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import com.intellij.openapi.editor.Document as IdeaDocument @Volatile var settings: CodeStyleSettings = CodeStyleSettings(true) fun formatCode(source: String, fileName: String, psiFactory: KtPsiFactory, lineSeparator: String): String { return KotlinFormatter(source, fileName, psiFactory, lineSeparator).formatCode() } fun reformatAll(containingFile: KtFile, rootBlock: Block, settings: CodeStyleSettings, document: IDocument) { formatRange(containingFile, rootBlock, settings, document, containingFile.textRange) } fun formatRange(document: IDocument, range: EclipseDocumentRange, psiFactory: KtPsiFactory, fileName: String) { formatRange(document, range.toPsiRange(document), psiFactory, fileName) } fun formatRange(document: IDocument, range: TextRange, psiFactory: KtPsiFactory, fileName: String) { val ktFile = createKtFile(document.get(), psiFactory, fileName) val rootBlock = KotlinBlock(ktFile.getNode(), NULL_ALIGNMENT_STRATEGY, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings, KotlinSpacingBuilderUtilImpl)) formatRange(ktFile, rootBlock, settings, document, range) } private fun formatRange( containingFile: KtFile, rootBlock: Block, settings: CodeStyleSettings, document: IDocument, range: TextRange) { val formattingModel = buildModel(containingFile, rootBlock, settings, document, false) val ranges = FormatTextRanges(range, true) FormatterImpl().format(formattingModel, settings, settings.indentOptions, ranges, false) } fun adjustIndent(containingFile: KtFile, rootBlock: Block, settings: CodeStyleSettings, offset: Int, document: IDocument) { val formattingModel = buildModel(containingFile, rootBlock, settings, document, true) FormatterImpl().adjustLineIndent( formattingModel, settings, settings.indentOptions, offset, getSignificantRange(containingFile, offset)) } fun getMockDocument(document: IdeaDocument): IdeaDocument { return object : IdeaDocument by document { } } fun initializaSettings(options: IndentOptions) { with(options) { USE_TAB_CHARACTER = !IndenterUtil.isSpacesForTabs() INDENT_SIZE = IndenterUtil.getDefaultIndent() TAB_SIZE = IndenterUtil.getDefaultIndent() } } data class EclipseDocumentRange(val startOffset: Int, val endOffset: Int) private fun EclipseDocumentRange.toPsiRange(document: IDocument): TextRange { val startPsiOffset = LineEndUtil.convertCrToDocumentOffset(document, startOffset) val endPsiOffset = LineEndUtil.convertCrToDocumentOffset(document, endOffset) return TextRange(startPsiOffset, endPsiOffset) } val NULL_ALIGNMENT_STRATEGY = NodeAlignmentStrategy.fromTypes(KotlinAlignmentStrategy.wrap(null)) private fun buildModel( containingFile: KtFile, rootBlock: Block, settings: CodeStyleSettings, document: IDocument, forLineIndentation: Boolean): EclipseDocumentFormattingModel { initializaSettings(settings.indentOptions!!) val formattingDocumentModel = EclipseFormattingModel( DocumentImpl(containingFile.getViewProvider().getContents(), true), containingFile, settings, forLineIndentation) return EclipseDocumentFormattingModel(containingFile, rootBlock, formattingDocumentModel, document, settings) } private fun getSignificantRange(file: KtFile, offset: Int): TextRange { val elementAtOffset = file.findElementAt(offset) if (elementAtOffset == null) { val significantRangeStart = CharArrayUtil.shiftBackward(file.getText(), offset - 1, "\r\t "); return TextRange(Math.max(significantRangeStart, 0), offset); } return elementAtOffset.getTextRange() } private class KotlinFormatter(source: String, fileName: String, psiFactory: KtPsiFactory, val lineSeparator: String) { val ktFile = createKtFile(source, psiFactory, fileName) val sourceDocument = Document(source) fun formatCode(): String { FormatterImpl() val rootBlock = KotlinBlock(ktFile.getNode(), NULL_ALIGNMENT_STRATEGY, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings, KotlinSpacingBuilderUtilImpl)) reformatAll(ktFile, rootBlock, settings, sourceDocument) return sourceDocument.get() } } fun createPsiFactory(eclipseFile: IFile): KtPsiFactory { val environment = getEnvironment(eclipseFile) return KtPsiFactory(environment.project) } fun createKtFile(source: String, psiFactory: KtPsiFactory, fileName: String): KtFile { return psiFactory.createFile(fileName, StringUtil.convertLineSeparators(source)) } private fun createWhitespaces(countSpaces: Int) = IndenterUtil.SPACE_STRING.repeat(countSpaces) object KotlinSpacingBuilderUtilImpl : KotlinSpacingBuilderUtil { override fun createLineFeedDependentSpacing(minSpaces: Int, maxSpaces: Int, minimumLineFeeds: Int, keepLineBreaks: Boolean, keepBlankLines: Int, dependency: TextRange, rule: DependentSpacingRule): Spacing { return object : DependantSpacingImpl(minSpaces, maxSpaces, dependency, keepLineBreaks, keepBlankLines, rule) { } } override fun getPreviousNonWhitespaceLeaf(node: ASTNode?): ASTNode? { return FormatterUtil.getPreviousNonWhitespaceLeaf(node) } override fun isWhitespaceOrEmpty(node: ASTNode?): Boolean { return FormatterUtil.isWhitespaceOrEmpty(node) } }
apache-2.0
96ca1a50b026304c39acc1a4525e407a
35.68306
118
0.803486
4.21873
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/WorkEditionsViewHolder.kt
2
1821
package ru.fantlab.android.ui.adapter.viewholder import android.net.Uri import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.work_edition_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.EditionsBlocks import ru.fantlab.android.provider.scheme.LinkParserHelper.HOST_DATA import ru.fantlab.android.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS import ru.fantlab.android.provider.storage.WorkTypesProvider import ru.fantlab.android.ui.modules.edition.EditionActivity import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder class WorkEditionsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<EditionsBlocks.Edition, WorkEditionsViewHolder>) : BaseViewHolder<EditionsBlocks.Edition>(itemView, adapter) { override fun bind(edition: EditionsBlocks.Edition) { itemView.editionCover.setUrl(Uri.Builder().scheme(PROTOCOL_HTTPS) .authority(HOST_DATA) .appendPath("images") .appendPath("editions") .appendPath("small") .appendPath(edition.editionId.toString()) .toString(), WorkTypesProvider.getCoverByTypeId(25)) if (edition.year.toString().isNotEmpty() && edition.year != 0) { itemView.editionYear.text = edition.year.toString() itemView.editionYear.visibility = View.VISIBLE } else { itemView.editionYear.visibility = View.GONE } itemView.setOnClickListener { EditionActivity.startActivity(itemView.context, edition.editionId, edition.name) } } companion object { fun newInstance( viewGroup: ViewGroup, adapter: BaseRecyclerAdapter<EditionsBlocks.Edition, WorkEditionsViewHolder> ): WorkEditionsViewHolder = WorkEditionsViewHolder(getView(viewGroup, R.layout.work_edition_row_item), adapter) } }
gpl-3.0
2fca2ea73abbff4d8398e244f5149f0c
38.608696
122
0.798462
3.96732
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/cache/video/dao/VideoEntityDaoImpl.kt
2
1511
package org.stepik.android.cache.video.dao import android.content.ContentValues import android.database.Cursor import org.stepic.droid.storage.dao.DaoBase import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.util.getLong import org.stepic.droid.util.getString import org.stepik.android.cache.video.model.VideoEntity import org.stepik.android.cache.video.structure.VideoDbScheme import javax.inject.Inject class VideoEntityDaoImpl @Inject constructor( databaseOperations: DatabaseOperations ) : DaoBase<VideoEntity>(databaseOperations) { override fun getDbName(): String = VideoDbScheme.TABLE_NAME override fun getDefaultPrimaryColumn(): String = VideoDbScheme.Columns.ID override fun getDefaultPrimaryValue(persistentObject: VideoEntity): String = persistentObject.id.toString() override fun getContentValues(persistentObject: VideoEntity): ContentValues = ContentValues().apply { put(VideoDbScheme.Columns.ID, persistentObject.id) put(VideoDbScheme.Columns.DURATION, persistentObject.duration) put(VideoDbScheme.Columns.THUMBNAIL, persistentObject.thumbnail) } override fun parsePersistentObject(cursor: Cursor): VideoEntity = VideoEntity( id = cursor.getLong(VideoDbScheme.Columns.ID), duration = cursor.getLong(VideoDbScheme.Columns.DURATION), thumbnail = cursor.getString(VideoDbScheme.Columns.THUMBNAIL) ) }
apache-2.0
16eec3877fa9e41d0c7c916d8e938478
36.8
81
0.75182
4.537538
false
false
false
false
anrelic/Anci-OSS
logging/src/main/kotlin/su/jfdev/anci/logging/LoggingUtil.kt
1
1878
@file:Suppress("NOTHING_TO_INLINE") package su.jfdev.anci.logging import su.jfdev.anci.logging.LogLevel.* /** * As example Logger["foo"] + "bar" similar Logger["foo.bar"] */ operator fun Logger.plus(subPath: String) = Logger["$name.$subPath"] inline infix fun Logger.info(throwable: Throwable) = log(INFO, throwable) inline infix fun Logger.warn(throwable: Throwable) = log(WARN, throwable) inline infix fun Logger.error(throwable: Throwable) = log(ERROR, throwable) inline infix fun Logger.trace(throwable: Throwable) = log(TRACE, throwable) inline infix fun Logger.debug(throwable: Throwable) = log(DEBUG, throwable) inline fun Logger.info(throwable: Throwable, message: () -> String) = log(INFO, throwable, message) inline fun Logger.warn(throwable: Throwable, message: () -> String) = log(WARN, throwable, message) inline fun Logger.error(throwable: Throwable, message: () -> String) = log(ERROR, throwable, message) inline fun Logger.trace(throwable: Throwable, message: () -> String) = log(TRACE, throwable, message) inline fun Logger.debug(throwable: Throwable, message: () -> String) = log(DEBUG, throwable, message) inline infix fun Logger.info(message: () -> String) = log(INFO, message) inline infix fun Logger.warn(message: () -> String) = log(WARN, message) inline infix fun Logger.error(message: () -> String) = log(ERROR, message) inline infix fun Logger.trace(message: () -> String) = log(TRACE, message) inline infix fun Logger.debug(message: () -> String) = log(DEBUG, message) inline fun Logger.log(level: LogLevel, throwable: Throwable) { if (level in this) print(level, throwable) } inline fun Logger.log(level: LogLevel, throwable: Throwable, message: () -> String) { if (level in this) print(level, message(), throwable) } inline fun Logger.log(level: LogLevel, message: () -> String) { if (level in this) print(level, message()) }
mit
90a4ad253d95bedf8d26748ee5e6a120
44.829268
101
0.723642
3.646602
false
false
false
false
exponentjs/exponent
packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/albums/AlbumUtils.kt
2
2761
package expo.modules.medialibrary.albums import android.content.Context import android.os.Bundle import android.provider.MediaStore import android.provider.MediaStore.MediaColumns import expo.modules.core.Promise import expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD import expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD_PERMISSION import expo.modules.medialibrary.EXTERNAL_CONTENT_URI import expo.modules.medialibrary.MediaLibraryUtils.queryPlaceholdersFor import java.lang.IllegalArgumentException /** * Queries for assets filtered by given `selection`. * Resolves `promise` with [Bundle] of kind: `Array<{ id, title, assetCount }>` */ fun queryAlbum( context: Context, selection: String?, selectionArgs: Array<String>?, promise: Promise ) { val projection = arrayOf(MediaColumns.BUCKET_ID, MediaColumns.BUCKET_DISPLAY_NAME) val order = MediaColumns.BUCKET_DISPLAY_NAME try { context.contentResolver.query( EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, order ).use { albumsCursor -> if (albumsCursor == null) { promise.reject(ERROR_UNABLE_TO_LOAD, "Could not get album. Query is incorrect.") return } if (!albumsCursor.moveToNext()) { promise.resolve(null) return } val bucketIdIndex = albumsCursor.getColumnIndex(MediaColumns.BUCKET_ID) val bucketDisplayNameIndex = albumsCursor.getColumnIndex(MediaColumns.BUCKET_DISPLAY_NAME) val result = Bundle().apply { putString("id", albumsCursor.getString(bucketIdIndex)) putString("title", albumsCursor.getString(bucketDisplayNameIndex)) putInt("assetCount", albumsCursor.count) } promise.resolve(result) } } catch (e: SecurityException) { promise.reject( ERROR_UNABLE_TO_LOAD_PERMISSION, "Could not get albums: need READ_EXTERNAL_STORAGE permission.", e ) } catch (e: IllegalArgumentException) { promise.reject(ERROR_UNABLE_TO_LOAD, "Could not get album.", e) } } /** * Returns flat list of asset IDs (`_ID` column) for given album IDs (`BUCKET_ID` column) */ fun getAssetsInAlbums(context: Context, vararg albumIds: String?): List<String> { val assetIds = mutableListOf<String>() val selection = "${MediaColumns.BUCKET_ID} IN (${queryPlaceholdersFor(albumIds)} )" val projection = arrayOf(MediaColumns._ID) context.contentResolver.query( EXTERNAL_CONTENT_URI, projection, selection, albumIds, null ).use { assetCursor -> if (assetCursor == null) { return assetIds } while (assetCursor.moveToNext()) { val id = assetCursor.getString(assetCursor.getColumnIndex(MediaStore.Images.Media._ID)) assetIds.add(id) } } return assetIds }
bsd-3-clause
0d78bbb1029b8b555994a9054a987b9c
31.869048
96
0.709888
4.133234
false
false
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/ui/nowPlaying/components/PlaybackProgressDuration.kt
1
6836
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.media.playback.ui.nowPlaying.components import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.ContentAlpha import androidx.compose.material.LocalContentAlpha import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import app.ss.design.compose.extensions.isS import app.ss.design.compose.theme.Spacing16 import app.ss.design.compose.theme.Spacing4 import app.ss.design.compose.theme.Spacing8 import app.ss.design.compose.theme.SsColor import app.ss.design.compose.theme.darker import app.ss.design.compose.theme.onSurfaceSecondary import app.ss.design.compose.widget.material.Slider import app.ss.design.compose.widget.material.SliderDefaults import app.ss.media.playback.extensions.millisToDuration import app.ss.media.playback.model.PlaybackProgressState import kotlin.math.roundToLong private object ProgressColors { @Composable fun thumbColor(forceDark: Boolean): Color { return when { isS() -> MaterialTheme.colorScheme.onSurfaceVariant isSystemInDarkTheme() -> SsColor.BaseGrey1 forceDark -> SsColor.BaseGrey1 else -> SsColor.OffWhite.darker() } } @Composable fun activeTrackColor(forceDark: Boolean): Color = thumbColor(forceDark) @Composable fun inactiveTrackColor(forceDark: Boolean): Color { return when { isS() -> MaterialTheme.colorScheme.inverseOnSurface isSystemInDarkTheme() -> SsColor.BaseGrey3 forceDark -> SsColor.BaseGrey3 else -> SsColor.BaseGrey1 } } } @Composable internal fun PlaybackProgressDuration( isBuffering: Boolean, progressState: PlaybackProgressState, onSeekTo: (Long) -> Unit, modifier: Modifier = Modifier, forceDark: Boolean = false ) { val (draggingProgress, setDraggingProgress) = remember { mutableStateOf<Float?>(null) } Box( modifier = modifier.padding( horizontal = Spacing16 ) ) { PlaybackProgressSlider( isBuffering = isBuffering, progressState, draggingProgress, setDraggingProgress, forceDark = forceDark, onSeekTo = onSeekTo ) PlaybackProgressDuration( progressState, draggingProgress ) } } @Composable private fun BoxScope.PlaybackProgressSlider( isBuffering: Boolean, progressState: PlaybackProgressState, draggingProgress: Float?, setDraggingProgress: (Float?) -> Unit, height: Dp = 56.dp, thumbRadius: Dp = 4.dp, forceDark: Boolean = false, onSeekTo: (Long) -> Unit ) { val updatedProgressState by rememberUpdatedState(progressState) val updatedDraggingProgress by rememberUpdatedState(draggingProgress) val sliderColors = SliderDefaults.colors( thumbColor = ProgressColors.thumbColor(forceDark), activeTrackColor = ProgressColors.activeTrackColor(forceDark), inactiveTrackColor = ProgressColors.inactiveTrackColor(forceDark) ) Slider( value = draggingProgress ?: progressState.progress, onValueChange = { if (!isBuffering) setDraggingProgress(it) }, colors = sliderColors, thumbRadius = thumbRadius, modifier = Modifier .height(height) .align(Alignment.TopCenter) .padding(horizontal = Spacing4), onValueChangeFinished = { val position = (updatedProgressState.total.toFloat() * (updatedDraggingProgress ?: 0f)).roundToLong() onSeekTo(position) setDraggingProgress(null) } ) } @Composable private fun BoxScope.PlaybackProgressDuration( progressState: PlaybackProgressState, draggingProgress: Float? ) { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() .align(Alignment.BottomCenter) .padding(top = Spacing8) .padding(horizontal = Spacing4) ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { val currentDuration = when (draggingProgress != null) { true -> (progressState.total.toFloat() * (draggingProgress)).toLong().millisToDuration() else -> progressState.currentDuration } val textStyle = MaterialTheme.typography.titleSmall.copy( fontSize = 14.sp ) Text( currentDuration, style = textStyle, color = onSurfaceSecondary() ) Text( progressState.totalDuration, style = textStyle, color = onSurfaceSecondary() ) } } }
mit
8034e42f6ffd34b5f83364836a8f8df5
35.169312
113
0.702019
4.743928
false
false
false
false
realm/realm-java
realm/realm-library/src/androidTestObjectServer/kotlin/io/realm/ProgressListenerTests.kt
1
20139
/* * Copyright 2020 Realm 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 io.realm import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import io.realm.entities.DefaultSyncSchema import io.realm.entities.SyncDog import io.realm.entities.SyncStringOnly import io.realm.internal.OsRealmConfig import io.realm.kotlin.syncSession import io.realm.kotlin.where import io.realm.log.LogLevel import io.realm.log.RealmLog import io.realm.mongodb.User import io.realm.mongodb.close import io.realm.mongodb.registerUserAndLogin import io.realm.mongodb.sync.Progress import io.realm.mongodb.sync.ProgressListener import io.realm.mongodb.sync.ProgressMode import io.realm.mongodb.sync.SyncConfiguration import io.realm.mongodb.sync.SyncSession import io.realm.mongodb.sync.testRealmExists import io.realm.mongodb.sync.testSchema import io.realm.mongodb.sync.testSessionStopPolicy import io.realm.rule.BlockingLooperThread import org.bson.types.ObjectId import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertFailsWith @RunWith(AndroidJUnit4::class) class ProgressListenerTests { companion object { private const val TEST_SIZE: Long = 10 } private val looperThread = BlockingLooperThread() private val configurationFactory = TestSyncConfigurationFactory() private lateinit var app: TestApp private lateinit var partitionValue: String @Before fun setUp() { Realm.init(InstrumentationRegistry.getInstrumentation().targetContext) RealmLog.setLevel(LogLevel.TRACE) partitionValue = UUID.randomUUID().toString() app = TestApp() } @After fun tearDown() { if (this::app.isInitialized) { app.close() } RealmLog.setLevel(LogLevel.WARN) } @Test fun downloadProgressListener_changesOnly() { val allChangesDownloaded = CountDownLatch(1) val user1: User = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456") val user1Config = createSyncConfig(user1) createRemoteData(user1Config) val user2: User = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456") val user2Config = createSyncConfig(user2) Realm.getInstance(user2Config).use { realm -> realm.syncSession.addDownloadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { assertTransferComplete(progress, true) assertEquals(TEST_SIZE, getStoreTestDataSize(user2Config)) allChangesDownloaded.countDown() } } TestHelper.awaitOrFail(allChangesDownloaded) } } @Test fun downloadProgressListener_indefinitely() { val transferCompleted = AtomicInteger(0) val allChangesDownloaded = CountDownLatch(1) val startWorker = CountDownLatch(1) val user1: User = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456") // login(Credentials.anonymous()) val user1Config: SyncConfiguration = createSyncConfig(user1) // Create worker thread that puts data into another Realm. // This is to avoid blocking one progress listener while waiting for another to complete. val worker = Thread(Runnable { TestHelper.awaitOrFail(startWorker) createRemoteData(user1Config) }) worker.start() val user2: User = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456") // login(Credentials.anonymous()) val user2Config: SyncConfiguration = createSyncConfig(user2) Realm.getInstance(user2Config).use { user2Realm -> val session: SyncSession = user2Realm.syncSession session.addDownloadProgressListener(ProgressMode.INDEFINITELY) { progress -> val objectCounts = getStoreTestDataSize(user2Config) // The downloading progress listener could be triggered at the db version where only contains the meta // data. So we start checking from when the first 10 objects downloaded. RealmLog.warn(String.format( Locale.ENGLISH, "downloadProgressListener_indefinitely download %d/%d objects count:%d", progress.transferredBytes, progress.transferableBytes, objectCounts)) if (objectCounts != 0L && progress.isTransferComplete) { when (transferCompleted.incrementAndGet()) { 1 -> { assertEquals(TEST_SIZE, objectCounts) assertTransferComplete(progress, true) startWorker.countDown() } 2 -> { assertTransferComplete(progress, true) assertEquals(TEST_SIZE * 2, objectCounts) allChangesDownloaded.countDown() } else -> fail("Transfer complete called too many times:" + transferCompleted.get()) } } } writeSampleData(user2Realm) // Write first batch of sample data TestHelper.awaitOrFail(allChangesDownloaded) } // worker thread will hang if logout happens before listener triggered. worker.join() user1.logOut() user2.logOut() } // Make sure that a ProgressListener continues to report the correct thing, even if it crashed @Test fun uploadListener_worksEvenIfCrashed() { val transferCompleted = AtomicInteger(0) val testDone = CountDownLatch(1) val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession session.addUploadProgressListener(ProgressMode.INDEFINITELY) { progress -> if (progress.isTransferComplete) { when (transferCompleted.incrementAndGet()) { 1 -> { Realm.getInstance(config).use { realm -> writeSampleData(realm) } throw RuntimeException("Crashing the changelistener") } 2 -> { assertTransferComplete(progress, true) testDone.countDown() } else -> fail("Unsupported number of transfers completed: " + transferCompleted.get()) } } } writeSampleData(realm) // Write first batch of sample data TestHelper.awaitOrFail(testDone) } } @Test fun uploadProgressListener_changesOnly() { val allChangeUploaded = CountDownLatch(1) val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession assertEquals(SyncSession.State.ACTIVE, session.state) writeSampleData(realm) session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { assertTransferComplete(progress, true) allChangeUploaded.countDown() } } TestHelper.awaitOrFail(allChangeUploaded) } } @Test fun uploadProgressListener_indefinitely() { val transferCompleted = AtomicInteger(0) val testDone = CountDownLatch(1) val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession session.addUploadProgressListener(ProgressMode.INDEFINITELY) { progress -> if (progress.isTransferComplete) { when (transferCompleted.incrementAndGet()) { 1 -> { Realm.getInstance(config).use { realm -> writeSampleData(realm) } } 2 -> { assertTransferComplete(progress, true) testDone.countDown() } else -> fail("Unsupported number of transfers completed: " + transferCompleted.get()) } } } writeSampleData(realm) // Write first batch of sample data TestHelper.awaitOrFail(testDone) } } @Test fun addListenerInsideCallback() { val allChangeUploaded = CountDownLatch(1) val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession writeSampleData(realm) session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { Realm.getInstance(config).use { realm -> writeSampleData(realm) } session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { allChangeUploaded.countDown() } } } } TestHelper.awaitOrFail(allChangeUploaded) } } @Test fun addListenerInsideCallback_mixProgressModes() { val allChangeUploaded = CountDownLatch(3) val progressCompletedReported = AtomicBoolean(false) val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession session.addUploadProgressListener(ProgressMode.INDEFINITELY) { progress -> if (progress.isTransferComplete) { allChangeUploaded.countDown() if (progressCompletedReported.compareAndSet(false, true)) { Realm.getInstance(config).use { realm -> writeSampleData(realm) } session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { allChangeUploaded.countDown() } } } } } writeSampleData(realm) TestHelper.awaitOrFail(allChangeUploaded) } } @Test fun addProgressListener_triggerImmediatelyWhenRegistered() { val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession checkDownloadListener(session, ProgressMode.INDEFINITELY) checkUploadListener(session, ProgressMode.INDEFINITELY) checkDownloadListener(session, ProgressMode.CURRENT_CHANGES) checkUploadListener(session, ProgressMode.CURRENT_CHANGES) } } @Test fun addProgressListener_triggerImmediatelyWhenRegistered_waitForInitialRemoteData() { val user = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456") val config = SyncConfiguration.Builder(user, getTestPartitionValue()) .waitForInitialRemoteData() .modules(DefaultSyncSchema()) .build() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession checkDownloadListener(session, ProgressMode.INDEFINITELY) checkUploadListener(session, ProgressMode.INDEFINITELY) checkDownloadListener(session, ProgressMode.CURRENT_CHANGES) checkUploadListener(session, ProgressMode.CURRENT_CHANGES) } } @Test fun progressListenersWorkWhenUsingWaitForInitialRemoteData() = looperThread.runBlocking { val username = UUID.randomUUID().toString() val password = "password" var user: User = app.registerUserAndLogin(username, password) // 1. Copy a valid Realm to the server (and pray it does it within 10 seconds) val configOld: SyncConfiguration = configurationFactory.createSyncConfigurationBuilder(user, user.id) .testSchema(SyncStringOnly::class.java) .testSessionStopPolicy(OsRealmConfig.SyncSessionStopPolicy.IMMEDIATELY) .build() Realm.getInstance(configOld).use { realm -> realm.executeTransaction { realm -> for (i in 0..9) { realm.createObject(SyncStringOnly::class.java, ObjectId()).chars = "Foo$i" } } realm.syncSession.uploadAllLocalChanges() } user.logOut() assertFailsWith<IllegalStateException> { app.sync.getSession(configOld) } // 2. Local state should now be completely reset. Open the same sync Realm but different local name again with // a new configuration which should download the uploaded changes (pray it managed to do so within the time frame). // Use different user to trigger different path val user2 = app.registerUserAndLogin(TestHelper.getRandomEmail(), password) val config: SyncConfiguration = configurationFactory.createSyncConfigurationBuilder(user2, user.id) .testSchema(SyncStringOnly::class.java) .waitForInitialRemoteData() .build() assertFalse(config.testRealmExists()) val countDownLatch = CountDownLatch(2) val indefiniteListenerComplete = AtomicBoolean(false) val currentChangesListenerComplete = AtomicBoolean(false) val task = Realm.getInstanceAsync(config, object : Realm.Callback() { override fun onSuccess(realm: Realm) { realm.syncSession.addDownloadProgressListener(ProgressMode.INDEFINITELY, object : ProgressListener { override fun onChange(progress: Progress) { if (progress.isTransferComplete()) { indefiniteListenerComplete.set(true) countDownLatch.countDown() } } }) realm.syncSession.addDownloadProgressListener(ProgressMode.CURRENT_CHANGES, object : ProgressListener { override fun onChange(progress: Progress) { if (progress.isTransferComplete()) { currentChangesListenerComplete.set(true) countDownLatch.countDown() } } }) countDownLatch.await(100, TimeUnit.SECONDS) realm.close() if (!indefiniteListenerComplete.get()) { fail("Indefinite progress listener did not report complete.") } if (!currentChangesListenerComplete.get()) { fail("Current changes progress listener did not report complete.") } looperThread.testComplete() } override fun onError(exception: Throwable) { fail(exception.toString()) } }) looperThread.keepStrongReference(task) } @Test fun uploadListener_keepIncreasingInSize() { val config = createSyncConfig() Realm.getInstance(config).use { realm -> val session: SyncSession = realm.syncSession for (i in 0..9) { val changesUploaded = CountDownLatch(1) writeSampleData(realm) session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES) { progress -> if (progress.isTransferComplete) { assertTransferComplete(progress, true) changesUploaded.countDown() } } TestHelper.awaitOrFail(changesUploaded) } } } private fun checkDownloadListener(session: SyncSession, progressMode: ProgressMode) { val listenerCalled = CountDownLatch(1) session.addDownloadProgressListener(progressMode) { progress -> listenerCalled.countDown() } TestHelper.awaitOrFail(listenerCalled, 30) } private fun checkUploadListener(session: SyncSession, progressMode: ProgressMode) { val listenerCalled = CountDownLatch(1) session.addUploadProgressListener(progressMode) { progress -> listenerCalled.countDown() } TestHelper.awaitOrFail(listenerCalled, 30) } private fun writeSampleData(realm: Realm, partitionValue: String = getTestPartitionValue()) { realm.executeTransaction { for (i in 0 until TEST_SIZE) { val obj = SyncDog() obj.name = "Object $i" realm.insert(obj) } } } private fun assertTransferComplete(progress: Progress, nonZeroChange: Boolean) { assertTrue(progress.isTransferComplete) assertEquals(1.0, progress.fractionTransferred, 0.0) assertEquals(progress.transferableBytes, progress.transferredBytes) if (nonZeroChange) { assertTrue(progress.transferredBytes > 0) } } // Create remote data for a given user. private fun createRemoteData(config: SyncConfiguration) { Realm.getInstance(config).use { realm -> val changesUploaded = CountDownLatch(1) val session: SyncSession = realm.syncSession writeSampleData(realm) session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES, object : ProgressListener { override fun onChange(progress: Progress) { if (progress.isTransferComplete) { session.removeProgressListener(this) changesUploaded.countDown() } } }) TestHelper.awaitOrFail(changesUploaded) } } private fun getStoreTestDataSize(config: RealmConfiguration): Long { Realm.getInstance(config).use { realm -> return realm.where<SyncDog>().count() } } private fun createSyncConfig(user: User = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456"), partitionValue: String = getTestPartitionValue()): SyncConfiguration { return SyncConfiguration.Builder(user, partitionValue) .modules(DefaultSyncSchema()) .build() } private fun getTestPartitionValue(): String { if (!this::partitionValue.isInitialized) { fail("Test not setup correctly. Partition value is missing"); } return partitionValue } }
apache-2.0
f2b57b0c2ae35bebe42a84115e367fe6
41.308824
181
0.609216
5.496452
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt
1
10558
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.components.service import com.intellij.openapi.editor.Document import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.patterns.PlatformPatterns import com.intellij.patterns.PsiJavaPatterns.elementType import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.psi.PsiComment import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.smart.SmartCompletionSession import org.jetbrains.kotlin.idea.completion.stringTemplates.StringTemplateCompletion import org.jetbrains.kotlin.idea.completion.stringTemplates.wrapLookupElementForStringTemplateAfterDotCompletion import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import kotlin.math.max class KotlinCompletionContributor : CompletionContributor() { private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping( psiElement().withText(""), psiElement().withElementType(elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)) ) private val AFTER_INTEGER_LITERAL_AND_DOT = psiElement().afterLeafSkipping( psiElement().withText("."), psiElement().withElementType(elementType().oneOf(KtTokens.INTEGER_LITERAL)) ) companion object { // add '$' to ignore context after the caret const val DEFAULT_DUMMY_IDENTIFIER: String = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" } init { val provider = object : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { performCompletion(parameters, result) } } extend(CompletionType.BASIC, PlatformPatterns.psiElement(), provider) extend(CompletionType.SMART, PlatformPatterns.psiElement(), provider) } override fun beforeCompletion(context: CompletionInitializationContext) { val offset = context.startOffset val psiFile = context.file val tokenBefore = psiFile.findElementAt(max(0, offset - 1)) // this code will make replacement offset "modified" and prevents altering it by the code in CompletionProgressIndicator context.replacementOffset = context.replacementOffset val dummyIdentifierCorrected = service<CompletionDummyIdentifierProviderService>().correctPositionForStringTemplateEntry(context) if (dummyIdentifierCorrected) { return } context.dummyIdentifier = when { context.completionType == CompletionType.SMART -> DEFAULT_DUMMY_IDENTIFIER PackageDirectiveCompletion.ACTIVATION_PATTERN.accepts(tokenBefore) -> PackageDirectiveCompletion.DUMMY_IDENTIFIER else -> service<CompletionDummyIdentifierProviderService>().provideDummyIdentifier(context) } val tokenAt = psiFile.findElementAt(max(0, offset)) if (tokenAt != null) { /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */ if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document)) { var parent = tokenAt.parent if (parent is KtExpression && parent !is KtBlockExpression) { // search expression to be replaced - go up while we are the first child of parent expression var expression: KtExpression = parent parent = expression.parent while (parent is KtExpression && parent.getFirstChild() == expression) { expression = parent parent = expression.parent } val suggestedReplacementOffset = replacementOffsetByExpression(expression) if (suggestedReplacementOffset > context.replacementOffset) { context.replacementOffset = suggestedReplacementOffset } context.offsetMap.addOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET, expression.endOffset) val argumentList = (expression.parent as? KtValueArgument)?.parent as? KtValueArgumentList if (argumentList != null) { context.offsetMap.addOffset( SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET, argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset ) } } } // IDENTIFIER when 'f<caret>oo: Foo' // COLON when 'foo<caret>: Foo' if (tokenAt.node.elementType == KtTokens.IDENTIFIER || tokenAt.node.elementType == KtTokens.COLON) { val parameter = tokenAt.parent as? KtParameter if (parameter != null) { context.offsetMap.addOffset(VariableOrParameterNameWithTypeCompletion.REPLACEMENT_OFFSET, parameter.endOffset) } } } } private fun replacementOffsetByExpression(expression: KtExpression): Int { when (expression) { is KtCallExpression -> { val calleeExpression = expression.calleeExpression if (calleeExpression != null) { return calleeExpression.textRange!!.endOffset } } is KtQualifiedExpression -> { val selector = expression.selectorExpression if (selector != null) { return replacementOffsetByExpression(selector) } } } return expression.textRange!!.endOffset } private fun performCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val position = parameters.position val parametersOriginFile = parameters.originalFile if (position.containingFile !is KtFile || parametersOriginFile !is KtFile) return StringTemplateCompletion.correctParametersForInStringTemplateCompletion(parameters)?.let { correctedParameters -> doComplete(correctedParameters, result, ::wrapLookupElementForStringTemplateAfterDotCompletion) return } doComplete(parameters, result) } private fun doComplete( parameters: CompletionParameters, result: CompletionResultSet, lookupElementPostProcessor: ((LookupElement) -> LookupElement)? = null ) { val position = parameters.position if (position.getNonStrictParentOfType<PsiComment>() != null) { // don't stop here, allow other contributors to run return } if (shouldSuppressCompletion(parameters, result.prefixMatcher)) { result.stopHere() return } if (PackageDirectiveCompletion.perform(parameters, result)) { result.stopHere() return } for (extension in KotlinCompletionExtension.EP_NAME.extensionList) { if (extension.perform(parameters, result)) return } fun addPostProcessor(session: CompletionSession) { if (lookupElementPostProcessor != null) { session.addLookupElementPostProcessor(lookupElementPostProcessor) } } result.restartCompletionWhenNothingMatches() val configuration = CompletionSessionConfiguration(parameters) if (parameters.completionType == CompletionType.BASIC) { val session = BasicCompletionSession(configuration, parameters, result) addPostProcessor(session) if (parameters.isAutoPopup && session.shouldDisableAutoPopup()) { result.stopHere() return } val somethingAdded = session.complete() if (!somethingAdded && parameters.invocationCount < 2) { // Rerun completion if nothing was found val newConfiguration = CompletionSessionConfiguration( useBetterPrefixMatcherForNonImportedClasses = false, nonAccessibleDeclarations = false, javaGettersAndSetters = true, javaClassesNotToBeUsed = false, staticMembers = parameters.invocationCount > 0, dataClassComponentFunctions = true ) val newSession = BasicCompletionSession(newConfiguration, parameters, result) addPostProcessor(newSession) newSession.complete() } } else { val session = SmartCompletionSession(configuration, parameters, result) addPostProcessor(session) session.complete() } } private fun shouldSuppressCompletion(parameters: CompletionParameters, prefixMatcher: PrefixMatcher): Boolean { val position = parameters.position val invocationCount = parameters.invocationCount // no completion inside number literals if (AFTER_NUMBER_LITERAL.accepts(position)) return true // no completion auto-popup after integer and dot if (invocationCount == 0 && prefixMatcher.prefix.isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return true return false } private fun isAtEndOfLine(offset: Int, document: Document): Boolean { var i = offset val chars = document.charsSequence while (i < chars.length) { val c = chars[i] if (c == '\n') return true if (!Character.isWhitespace(c)) return false i++ } return true } } abstract class KotlinCompletionExtension { abstract fun perform(parameters: CompletionParameters, result: CompletionResultSet): Boolean companion object { val EP_NAME: ExtensionPointName<KotlinCompletionExtension> = ExtensionPointName.create("org.jetbrains.kotlin.completionExtension") } }
apache-2.0
93a59339dd128d8b331111831f768e37
41.922764
138
0.657606
5.747414
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/detail/PostMonthsAndYearsUseCase.kt
1
5706
package org.wordpress.android.ui.stats.refresh.lists.detail import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.fluxc.model.stats.PostDetailStatsModel import org.wordpress.android.fluxc.store.StatsStore.PostDetailType import org.wordpress.android.fluxc.store.stats.PostDetailStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewMonthsAndYearsStats import org.wordpress.android.ui.stats.refresh.lists.BLOCK_ITEM_COUNT import org.wordpress.android.ui.stats.refresh.lists.VIEW_ALL_ITEM_COUNT import org.wordpress.android.ui.stats.refresh.lists.detail.PostDetailMapper.ExpandedYearUiState import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.UseCaseMode.BLOCK import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.UseCaseMode.VIEW_ALL import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Header import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Link import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Title import org.wordpress.android.ui.stats.refresh.lists.sections.insights.InsightUseCaseFactory import org.wordpress.android.ui.stats.refresh.utils.StatsPostProvider import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import javax.inject.Inject import javax.inject.Named @Suppress("LongParameterList") class PostMonthsAndYearsUseCase( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val statsSiteProvider: StatsSiteProvider, private val statsPostProvider: StatsPostProvider, private val postDetailStore: PostDetailStore, private val postDetailMapper: PostDetailMapper, private val useCaseMode: UseCaseMode ) : BaseStatsUseCase<PostDetailStatsModel, ExpandedYearUiState>( PostDetailType.MONTHS_AND_YEARS, mainDispatcher, backgroundDispatcher, ExpandedYearUiState() ) { private val itemsToLoad = if (useCaseMode == VIEW_ALL) VIEW_ALL_ITEM_COUNT else BLOCK_ITEM_COUNT override suspend fun loadCachedData(): PostDetailStatsModel? { return statsPostProvider.postId?.let { postId -> postDetailStore.getPostDetail( statsSiteProvider.siteModel, postId ) } } override suspend fun fetchRemoteData(forced: Boolean): State<PostDetailStatsModel> { val response = statsPostProvider.postId?.let { postId -> postDetailStore.fetchPostDetail(statsSiteProvider.siteModel, postId, forced) } val model = response?.model val error = response?.error return when { error != null -> State.Error(error.message ?: error.type.name) model != null && model.hasData() -> State.Data(model) else -> State.Empty() } } override fun buildUiModel(domainModel: PostDetailStatsModel, uiState: ExpandedYearUiState): List<BlockListItem> { val items = mutableListOf<BlockListItem>() if (useCaseMode == BLOCK) { items.add(Title(R.string.stats_detail_months_and_years)) } val header = Header( R.string.stats_months_and_years_period_label, R.string.stats_months_and_years_views_label ) items.add( header ) val shownYears = domainModel.yearsTotal.sortedByDescending { it.year }.takeLast(itemsToLoad) val yearList = postDetailMapper.mapYears( shownYears, uiState, header, this::onUiState ) items.addAll(yearList) if (useCaseMode == BLOCK && domainModel.yearsTotal.size > itemsToLoad) { items.add( Link( text = R.string.stats_insights_view_more, navigateAction = ListItemInteraction.create(this::onLinkClick) ) ) } return items } private fun PostDetailStatsModel?.hasData(): Boolean { return this != null && this.yearsTotal.isNotEmpty() && this.yearsTotal.any { it.value > 0 } } private fun onLinkClick() { navigateTo(ViewMonthsAndYearsStats) } override fun buildLoadingItem(): List<BlockListItem> { return listOf(Title(R.string.stats_detail_months_and_years)) } class PostMonthsAndYearsUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val statsSiteProvider: StatsSiteProvider, private val statsPostProvider: StatsPostProvider, private val postDetailMapper: PostDetailMapper, private val postDetailStore: PostDetailStore ) : InsightUseCaseFactory { override fun build(useCaseMode: UseCaseMode) = PostMonthsAndYearsUseCase( mainDispatcher, backgroundDispatcher, statsSiteProvider, statsPostProvider, postDetailStore, postDetailMapper, useCaseMode ) } }
gpl-2.0
05b4b91833b292479c1d06ab97f75e4e
42.227273
117
0.691377
4.594203
false
false
false
false
danielgimenes/Kotlin-Koans
src/i_introduction/_7_Nullable_Types/n07NullableTypes.kt
1
1107
package i_introduction._7_Nullable_Types import util.TODO import util.doc7 fun test() { val s: String = "this variable cannot store null references" val q: String? = null if (q != null) q.length // you have to check to dereference val i: Int? = q?.length // null val j: Int = q?.length ?: 0 // 0 } fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO( """ Task 7. Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression. Declarations of Client, PersonalInfo and Mailer are given below. """, documentation = doc7(), references = { JavaCode7().sendMessageToClient(client, message, mailer) } ) fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) { val email = client?.personalInfo?.email if (message != null && email != null) { mailer.sendMessage(email, message) } } class Client(val personalInfo: PersonalInfo?) class PersonalInfo(val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
mit
8c7c0b0c1fe7946a6dc26369c2ecd90f
28.918919
88
0.657633
4.025455
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/suggestion/SuggestionActivity.kt
1
10300
package org.wordpress.android.ui.suggestion import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.database.DataSetObserver import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.KeyEvent import android.view.inputmethod.EditorInfo import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.SuggestUsersActivityBinding import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.networking.ConnectionChangeReceiver.ConnectionChangeEvent import org.wordpress.android.ui.LocaleAwareActivity import org.wordpress.android.ui.suggestion.FinishAttempt.NotExactlyOneAvailable import org.wordpress.android.ui.suggestion.FinishAttempt.OnlyOneAvailable import org.wordpress.android.ui.suggestion.adapters.SuggestionAdapter import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.ToastUtils import org.wordpress.android.widgets.SuggestionAutoCompleteText import javax.inject.Inject class SuggestionActivity : LocaleAwareActivity() { private var suggestionAdapter: SuggestionAdapter? = null private var siteId: Long? = null @Inject lateinit var viewModel: SuggestionViewModel private lateinit var binding: SuggestUsersActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (application as WordPress).component().inject(this) with(SuggestUsersActivityBinding.inflate(layoutInflater)) { setContentView(root) binding = this } val siteModel = intent.getSerializableExtra(INTENT_KEY_SITE_MODEL) as? SiteModel val suggestionType = intent.getSerializableExtra(INTENT_KEY_SUGGESTION_TYPE) as? SuggestionType when { siteModel == null -> abortDueToMissingIntentExtra(INTENT_KEY_SITE_MODEL) suggestionType == null -> abortDueToMissingIntentExtra(INTENT_KEY_SUGGESTION_TYPE) else -> initializeActivity(siteModel, suggestionType) } } private fun abortDueToMissingIntentExtra(key: String) { val message = "${this.javaClass.simpleName} started without $key. Finishing Activity." AppLog.e(T.EDITOR, message) finish() } override fun onBackPressed() { viewModel.trackExit(false) super.onBackPressed() } private fun initializeActivity(siteModel: SiteModel, suggestionType: SuggestionType) { siteId = siteModel.siteId viewModel.init(suggestionType, siteModel).let { supportsSuggestions -> if (!supportsSuggestions) { finish() return } } initializeSuggestionAdapter() // The previous activity is visible "behind" this Activity if the list of Suggestions does not fill // the entire screen. If the user taps a part of the screen showing the still-visible previous // Activity, then finish this Activity and return the user to the previous Activity. binding.rootView.setOnClickListener { viewModel.trackExit(false) finish() } binding.autocompleteText.apply { initializeWithPrefix(viewModel.suggestionPrefix) setOnItemClickListener { _, _, position, _ -> val suggestionUserId = suggestionAdapter?.getItem(position)?.value finishWithValue(suggestionUserId) } setOnKeyListener { _, keyCode, event -> if (event.action == KeyEvent.ACTION_UP) { if (keyCode == KeyEvent.KEYCODE_ENTER) { exitIfOnlyOneMatchingUser() return@setOnKeyListener true } } false } setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { exitIfOnlyOneMatchingUser() true } else { false } } setOnFocusChangeListener { _, _ -> // The purpose of this Activity is to allow the user to select a user, so we want // the dropdown to always be visible. post { showDropDown() } } viewModel.suggestionPrefix.let { prefix -> // Ensure the text always starts with appropriate prefix addTextChangedListener(object : TextWatcher { var matchesPrefixBeforeChanged: Boolean? = null override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { matchesPrefixBeforeChanged = s?.let { it.length == 1 && it[0] == prefix } } override fun afterTextChanged(s: Editable?) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s == null) { return } else if (s.isEmpty() && matchesPrefixBeforeChanged == true) { // Tapping delete when only the prefix is shown exits the suggestions UI viewModel.trackExit(false) finish() } else if (s.startsWith("$prefix ")) { // Tapping the space key directly after the prefix exits the suggestions UI finishWithValue("", false) } else if (!s.startsWith(prefix)) { // Re-insert prefix if it was deleted val string = "$prefix$s" binding.autocompleteText.setText(string) binding.autocompleteText.setSelection(1) showDropDown() } matchesPrefixBeforeChanged = null } }) if (text.isEmpty()) { setText("$prefix") setSelection(1) } } updateEmptyView() post { requestFocus() } showDropdownOnTouch() } viewModel.suggestionData.observe(this, { suggestionResult -> suggestionAdapter?.suggestionList = suggestionResult.suggestions // Calling forceFiltering is needed to force the suggestions list to always // immediately refresh when there is new data binding.autocompleteText.forceFiltering(binding.autocompleteText.text) // Ensure that the suggestions list is displayed wth the new data. This is particularly needed when // suggestion list was empty before the new data was received, otherwise the no-longer-empty // suggestion list will not display when it is updated. Wrapping this in the isAttachedToWindow // check avoids a crash if the suggestions are loaded when the view is not attached. if (binding.autocompleteText.isAttachedToWindow) { binding.autocompleteText.showDropDown() } updateEmptyView() }) } private fun exitIfOnlyOneMatchingUser() { when (val finishAttempt = viewModel.onAttemptToFinish( suggestionAdapter?.filteredSuggestions, binding.autocompleteText.text.toString() )) { is OnlyOneAvailable -> { finishWithValue(finishAttempt.onlySelectedValue) } is NotExactlyOneAvailable -> { ToastUtils.showToast(this@SuggestionActivity, finishAttempt.errorMessage) } } } @SuppressLint("ClickableViewAccessibility") private fun SuggestionAutoCompleteText.showDropdownOnTouch() { setOnTouchListener { _, _ -> // Prevent touching the view from dismissing the suggestion list if it's not empty if (!adapter.isEmpty) { showDropDown() } false } } override fun finish() { super.finish() overridePendingTransition(R.anim.do_nothing, R.anim.do_nothing) } private fun finishWithValue(value: String?, withSuggestion: Boolean = true) { viewModel.trackExit(withSuggestion) setResult(Activity.RESULT_OK, Intent().apply { putExtra(SELECTED_VALUE, value) }) finish() } private fun initializeSuggestionAdapter() { suggestionAdapter = SuggestionAdapter(this, viewModel.suggestionPrefix).apply { setBackgroundColorAttr(R.attr.colorGutenbergBackground) registerDataSetObserver(object : DataSetObserver() { override fun onChanged() { updateEmptyView() } override fun onInvalidated() { updateEmptyView() } }) } binding.autocompleteText.setAdapter(suggestionAdapter) } private fun updateEmptyView() { binding.emptyView.apply { val (newText, newVisibility) = viewModel.getEmptyViewState(suggestionAdapter?.filteredSuggestions) text = newText visibility = newVisibility } } override fun onResume() { super.onResume() EventBus.getDefault().register(this) if (binding.autocompleteText.isAttachedToWindow) { binding.autocompleteText.showDropDown() } } override fun onPause() { EventBus.getDefault().unregister(this) super.onPause() } @Subscribe fun onEventMainThread(event: ConnectionChangeEvent) { viewModel.onConnectionChanged(event) updateEmptyView() } companion object { const val SELECTED_VALUE = "SELECTED_VALUE" const val INTENT_KEY_SUGGESTION_TYPE = "INTENT_KEY_SUGGESTION_TYPE" const val INTENT_KEY_SITE_MODEL = "INTENT_KEY_SITE_MODEL" } }
gpl-2.0
f1c641aebe8357e8cf70a02e6d0c2af6
37.721805
111
0.611359
5.519829
false
false
false
false
mdaniel/intellij-community
jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/test/JavaTestCaseWithConstructorInspectionTest.kt
1
3333
package com.intellij.codeInspection.tests.java.test import com.intellij.codeInspection.tests.ULanguage import com.intellij.codeInspection.tests.test.TestCaseWithConstructorInspectionTestBase class JavaTestCaseWithConstructorInspectionTest : TestCaseWithConstructorInspectionTestBase() { fun `test no highlighting parameterized test case`() { myFixture.testHighlighting(ULanguage.JAVA, """ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ParameterizedTest { private final int myX; private final int myY; public ParameterizedTest(int x, int y) { myX = x; myY = y; } @Test public void testMe() { System.out.println(myX * myY); } @Parameterized.Parameters public static Object[][] parameters() { return new Object[][] {{1, 2}, {3, 4}}; } } """.trimIndent(), "ParameterizedTest") } fun `test no highlighting trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection2 extends TestCase { public TestCaseWithConstructorInspection2() { super(); ; if (false) { System.out.println(); } } } """.trimIndent(), "TestCaseWithConstructorInspection2") } fun `test highlighting simple non-trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection1 extends TestCase { public <warning descr="Initialization logic in constructor 'TestCaseWithConstructorInspection1()' instead of 'setup' life cycle method">TestCaseWithConstructorInspection1</warning>() { System.out.println(""); } } """.trimIndent(), "TestCaseWithConstructorInspection1") } fun `test highlighting complex non-trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection3 extends TestCase { public <warning descr="Initialization logic in constructor 'TestCaseWithConstructorInspection3()' instead of 'setup' life cycle method">TestCaseWithConstructorInspection3</warning>() { super(); System.out.println("TestCaseWithConstructorInspection3.TestCaseWithConstructorInspection3"); } } """.trimIndent(), "TestCaseWithConstructorInspection3") } fun `test highlighting Junit 4`() { myFixture.testHighlighting(ULanguage.JAVA, """ public class JUnit4TestCaseWithConstructor { public <warning descr="Initialization logic in constructor 'JUnit4TestCaseWithConstructor()' instead of 'setup' life cycle method">JUnit4TestCaseWithConstructor</warning>() { System.out.println(); System.out.println(); System.out.println(); } @org.junit.Test public void testMe() {} } """.trimIndent(), "JUnit4TestCaseWithConstructor") } }
apache-2.0
d7157839cdeef2d1391da8c23940667e
34.468085
194
0.663966
5.257098
false
true
false
false
ingokegel/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/src/metaModel/impl/WorkspaceMetaModelProviderImpl.kt
1
13609
// 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.devkit.workspaceModel.metaModel.impl import com.intellij.devkit.workspaceModel.metaModel.WorkspaceMetaModelProvider import com.intellij.openapi.module.Module import com.intellij.openapi.util.registry.Registry import com.intellij.workspaceModel.codegen.deft.meta.* import com.intellij.workspaceModel.codegen.deft.meta.impl.* import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EqualsBy import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.annotations.Open import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.resolve.DescriptorUtils.isInterface import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isExtensionProperty import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import org.jetbrains.kotlin.types.typeUtil.supertypes import java.util.concurrent.ConcurrentHashMap class WorkspaceMetaModelProviderImpl : WorkspaceMetaModelProvider { private val objModuleByName = ConcurrentHashMap<String, Pair<CompiledObjModule, ModuleDescriptor>>() private val keepUnknownFields: Boolean get() = Registry.`is`("workspace.model.generator.keep.unknown.fields") private fun getObjClass(entityInterface: ClassDescriptor): ObjClass<*> { val objModule = getObjModule(entityInterface.containingPackage()!!.asString(), entityInterface.module) val entityInterfaceName = entityInterface.name.identifier return objModule.types.find { it.name == entityInterfaceName } ?: error("Cannot find $entityInterfaceName in $objModule") } override fun getObjModule(packageName: String, module: Module): CompiledObjModule { val sourceInfo = module.productionSourceInfo!! val resolutionFacade = KotlinCacheService.getInstance(module.project).getResolutionFacadeByModuleInfo(sourceInfo, sourceInfo.platform)!! val moduleDescriptor = resolutionFacade.moduleDescriptor return getObjModule(packageName, moduleDescriptor) } private fun getObjModule(packageName: String, moduleDescriptor: ModuleDescriptor): CompiledObjModule { val cached = objModuleByName[packageName] if (cached != null && cached.second == moduleDescriptor) return cached.first val packageViewDescriptor = moduleDescriptor.getPackage(FqName(packageName)) val objModuleStub = createObjModuleStub(packageViewDescriptor, packageName) val result = registerObjModuleContent(packageViewDescriptor, objModuleStub) objModuleByName[packageName] = result to moduleDescriptor return result } private fun registerObjModuleContent(packageViewDescriptor: PackageViewDescriptor, objModuleStub: ObjModuleStub): CompiledObjModule { val extensionProperties = packageViewDescriptor.fragments.flatMap { fragment -> fragment.getMemberScope().getContributedDescriptors(DescriptorKindFilter.VARIABLES) .filterIsInstance<PropertyDescriptor>() .filter { it.isExtensionProperty } } val externalProperties = extensionProperties .mapNotNull { property -> val receiver = property.extensionReceiverParameter?.value?.type?.constructor?.declarationDescriptor as? ClassDescriptor receiver?.let { property to receiver } } .filter { it.second.isEntityInterface && !it.second.isEntityBuilderInterface } return objModuleStub.registerContent(externalProperties) } private fun createObjModuleStub(packageViewDescriptor: PackageViewDescriptor, packageName: String): ObjModuleStub { val entityInterfaces = packageViewDescriptor.fragments.flatMap { fragment -> fragment.getMemberScope().getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS) .filterIsInstance<ClassDescriptor>() .filter { it.isEntityInterface } } val module = CompiledObjModuleImpl(packageName) val types = entityInterfaces.sortedBy { it.name }.withIndex().map { it.value to createObjTypeStub(it.value, module) } return ObjModuleStub(module, types) } private inner class ObjModuleStub(val module: CompiledObjModuleImpl, val types: List<Pair<ClassDescriptor, ObjClassImpl<Obj>>>) { fun registerContent(extProperties: List<Pair<PropertyDescriptor, ClassDescriptor>>): CompiledObjModule { var extPropertyId = 0 for ((classDescriptor, objType) in types) { val properties = classDescriptor.unsubstitutedMemberScope.getContributedDescriptors() .filterIsInstance<PropertyDescriptor>() .filter { it.kind.isReal } for ((propertyId, property) in properties.withIndex()) { objType.addField(createOwnProperty(property, propertyId, objType)) } classDescriptor.typeConstructor.supertypes.forEach { superType -> val superDescriptor = superType.constructor.declarationDescriptor if (superDescriptor is ClassDescriptor && superDescriptor.isEntityInterface) { val superClass = findObjClass(superDescriptor) objType.addSuperType(superClass) } else if (superDescriptor != null) { objType.addSuperType(KtInterfaceType(superDescriptor.name.identifier)) } } module.addType(objType) } for ((extProperty, receiverClass) in extProperties) { module.addExtension(createExtProperty(extProperty, receiverClass, extPropertyId++)) } return module } private fun createExtProperty(extProperty: PropertyDescriptor, receiverClass: ClassDescriptor, extPropertyId: Int): ExtProperty<*, *> { return ExtPropertyImpl(findObjClass(receiverClass), extProperty.name.identifier, convertType(extProperty.type), computeKind(extProperty), extProperty.isAnnotatedBy(StandardNames.OPEN_ANNOTATION), false, module, extPropertyId) } private fun createOwnProperty(property: PropertyDescriptor, propertyId: Int, receiver: ObjClassImpl<Obj>): OwnProperty<Obj, *> { val valueType = convertType(property.type, property.isAnnotatedBy(StandardNames.CHILD_ANNOTATION)) return OwnPropertyImpl(receiver, property.name.identifier, valueType, computeKind(property), property.isAnnotatedBy(StandardNames.OPEN_ANNOTATION), false, false, propertyId, property.isAnnotatedBy(StandardNames.EQUALS_BY_ANNOTATION)) } private fun convertType(type: KotlinType, hasChildAnnotation: Boolean = false): ValueType<*> { if (type.isMarkedNullable) { return ValueType.Optional(convertType(type.makeNotNullable(), hasChildAnnotation)) } val descriptor = type.constructor.declarationDescriptor if (descriptor is ClassDescriptor) { val fqName = descriptor.fqNameSafe val primitive = ObjTypeConverter.findPrimitive(fqName) if (primitive != null) return primitive if (fqName == StandardNames.LIST_INTERFACE) { return ValueType.List(convertType(type.arguments.first().type, hasChildAnnotation)) } if (fqName == StandardNames.SET_INTERFACE) { return ValueType.Set(convertType(type.arguments.first().type, hasChildAnnotation)) } if (fqName == StandardNames.MAP_INTERFACE) { return ValueType.Map(convertType(type.arguments.first().type, hasChildAnnotation), convertType(type.arguments.last().type, hasChildAnnotation)) } if (descriptor.isEntityInterface) { return ValueType.ObjRef(type.isAnnotatedBy(StandardNames.CHILD_ANNOTATION) || hasChildAnnotation, //todo leave only one target for @Child annotation findObjClass(descriptor)) } val superTypes = descriptor.defaultType.supertypes().mapNotNull { it.constructor.declarationDescriptor?.fqNameSafe?.asString() } if (descriptor.kind == ClassKind.OBJECT) { return ValueType.Object<Any>(fqName.asString(), superTypes) } if (descriptor.kind == ClassKind.ENUM_CLASS) { return ValueType.Blob<Any>(fqName.asString(), emptyList()) } if (descriptor.isData) { return ValueType.DataClass<Any>(fqName.asString(), superTypes, createProperties(descriptor)) } if (descriptor.isSealed()) { return ValueType.SealedClass<Any>(fqName.asString(), superTypes, descriptor.sealedSubclasses.map { convertType(it.defaultType) as ValueType.JvmClass<*> }) } if (ObjTypeConverter.isKnownInterface(fqName) || keepUnknownFields) { return ValueType.Blob<Any>(fqName.asString(), superTypes) } } error("Unsupported type $type") } private fun createProperties(descriptor: ClassDescriptor): List<ValueType.DataClassProperty> { return descriptor.unsubstitutedMemberScope.getContributedDescriptors(DescriptorKindFilter.VARIABLES) .filterIsInstance<PropertyDescriptor>() .map { ValueType.DataClassProperty(it.name.identifier, convertType(it.type)) } } private fun findObjClass(descriptor: ClassDescriptor): ObjClass<*> { if (descriptor.containingPackage()!!.asString() == module.name) { return types.find { it.first.typeConstructor == descriptor.typeConstructor }?.second ?: error("Cannot find ${descriptor.fqNameSafe} in $module") } return getObjClass(descriptor) } private fun computeKind(property: PropertyDescriptor): ObjProperty.ValueKind { val getter = property.getter ?: return ObjProperty.ValueKind.Plain if (!getter.hasBody()) return ObjProperty.ValueKind.Plain val declaration = getter.source.getPsi() as? KtDeclarationWithBody ?: return ObjProperty.ValueKind.Plain val getterText = (declaration.bodyExpression ?: declaration.bodyBlockExpression)?.text return when { getterText == null -> ObjProperty.ValueKind.Plain getter.isAnnotatedBy(StandardNames.DEFAULT_ANNOTATION) -> ObjProperty.ValueKind.WithDefault(getterText) else -> ObjProperty.ValueKind.Computable(getterText) } } } } private fun createObjTypeStub(interfaceDescriptor: ClassDescriptor, module: CompiledObjModuleImpl): ObjClassImpl<Obj> { val openness = when { interfaceDescriptor.isAnnotatedBy(StandardNames.ABSTRACT_ANNOTATION) -> ObjClass.Openness.abstract interfaceDescriptor.isAnnotatedBy(StandardNames.OPEN_ANNOTATION) -> ObjClass.Openness.open else -> ObjClass.Openness.final } return ObjClassImpl(module, interfaceDescriptor.name.identifier, openness) } private fun Annotated.isAnnotatedBy(fqName: FqName) = annotations.hasAnnotation(fqName) private object ObjTypeConverter { private val primitiveTypes = mapOf( "kotlin.Boolean" to ValueType.Boolean, "kotlin.Byte" to ValueType.Byte, "kotlin.Short" to ValueType.Short, "kotlin.Int" to ValueType.Int, "kotlin.Long" to ValueType.Long, "kotlin.Float" to ValueType.Float, "kotlin.Double" to ValueType.Double, "kotlin.UByte" to ValueType.UByte, "kotlin.UShort" to ValueType.UShort, "kotlin.UInt" to ValueType.UInt, "kotlin.ULong" to ValueType.ULong, "kotlin.Char" to ValueType.Char, "kotlin.String" to ValueType.String, ) private val knownInterfaces = setOf( VirtualFileUrl::class.qualifiedName!!, EntitySource::class.qualifiedName!!, PersistentEntityId::class.qualifiedName!!, ).map { FqName(it) } fun findPrimitive(fqName: FqName): ValueType.Primitive<*>? = primitiveTypes[fqName.asString()] fun isKnownInterface(fqName: FqName): Boolean = fqName in knownInterfaces } private object StandardNames { val DEFAULT_ANNOTATION = FqName(Default::class.qualifiedName!!) val OPEN_ANNOTATION = FqName(Open::class.qualifiedName!!) val ABSTRACT_ANNOTATION = FqName(Abstract::class.qualifiedName!!) val CHILD_ANNOTATION = FqName(Child::class.qualifiedName!!) val EQUALS_BY_ANNOTATION = FqName(EqualsBy::class.qualifiedName!!) val LIST_INTERFACE = FqName(List::class.qualifiedName!!) val SET_INTERFACE = FqName(Set::class.qualifiedName!!) val MAP_INTERFACE = FqName(Map::class.qualifiedName!!) } private val ClassDescriptor.isEntityInterface: Boolean get() { return isInterface(this) && defaultType.isSubclassOf(FqName(org.jetbrains.deft.Obj::class.java.name)) } private val ClassDescriptor.isEntityBuilderInterface: Boolean get() { return isEntityInterface && name.identifier == "Builder" //todo improve } private fun KotlinType.isSubclassOf(superClassName: FqName): Boolean { return constructor.supertypes.any { it.constructor.declarationDescriptor?.fqNameSafe == superClassName || it.isSubclassOf(superClassName) } }
apache-2.0
b445bd97b8cdf4841ee14156b6e3173b
49.779851
159
0.74098
4.945131
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/CompositeChildAbstractEntityImpl.kt
1
14457
package com.intellij.workspaceModel.storage.entities.test.api 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.ModifiableWorkspaceEntity 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.EntityLink 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.extractOneToAbstractManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CompositeChildAbstractEntityImpl : CompositeChildAbstractEntity, WorkspaceEntityBase() { companion object { internal val PARENTINLIST_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeAbstractEntity::class.java, SimpleAbstractEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeAbstractEntity::class.java, SimpleAbstractEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentChainEntity::class.java, CompositeAbstractEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) val connections = listOf<ConnectionId>( PARENTINLIST_CONNECTION_ID, CHILDREN_CONNECTION_ID, PARENTENTITY_CONNECTION_ID, ) } override val parentInList: CompositeAbstractEntity get() = snapshot.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this)!! override val children: List<SimpleAbstractEntity> get() = snapshot.extractOneToAbstractManyChildren<SimpleAbstractEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val parentEntity: ParentChainEntity? get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: CompositeChildAbstractEntityData?) : ModifiableWorkspaceEntityBase<CompositeChildAbstractEntity>(), CompositeChildAbstractEntity.Builder { constructor() : this(CompositeChildAbstractEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CompositeChildAbstractEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // 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 (_diff != null) { if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTINLIST_CONNECTION_ID, this) == null) { error("Field SimpleAbstractEntity#parentInList should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] == null) { error("Field SimpleAbstractEntity#parentInList should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field CompositeAbstractEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field CompositeAbstractEntity#children should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CompositeChildAbstractEntity this.entitySource = dataSource.entitySource if (parents != null) { this.parentInList = parents.filterIsInstance<CompositeAbstractEntity>().single() this.parentEntity = parents.filterIsInstance<ParentChainEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentInList: CompositeAbstractEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity } else { this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTINLIST_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] = value } changedProperty.add("parentInList") } override var children: List<SimpleAbstractEntity> get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyChildren<SimpleAbstractEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<SimpleAbstractEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<SimpleAbstractEntity> ?: emptyList() } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence()) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var parentEntity: ParentChainEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentChainEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentChainEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): CompositeChildAbstractEntityData = result ?: super.getEntityData() as CompositeChildAbstractEntityData override fun getEntityClass(): Class<CompositeChildAbstractEntity> = CompositeChildAbstractEntity::class.java } } class CompositeChildAbstractEntityData : WorkspaceEntityData<CompositeChildAbstractEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CompositeChildAbstractEntity> { val modifiable = CompositeChildAbstractEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): CompositeChildAbstractEntity { val entity = CompositeChildAbstractEntityImpl() entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CompositeChildAbstractEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CompositeChildAbstractEntity(entitySource) { this.parentInList = parents.filterIsInstance<CompositeAbstractEntity>().single() this.parentEntity = parents.filterIsInstance<ParentChainEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(CompositeAbstractEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CompositeChildAbstractEntityData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CompositeChildAbstractEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
e9f58f56a3ae6ae76c9b0bc9ddbf7a7d
42.026786
174
0.664661
5.515834
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/SerialOnlyTransitData.kt
1
2304
/* * SerialOnlyTransitData.kt * * Copyright 2015-2016 Michael Farrell <[email protected]> * Copyright 2018 Google Inc. * * Authors: Vladimir Serbinenko, Michael Farrell * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.ui.UriListItem abstract class SerialOnlyTransitData : TransitData() { protected open val extraInfo: List<ListItem>? get() = null protected abstract val reason: Reason final override val info get(): List<ListItem>? { val li = mutableListOf( ListItem(R.string.card_format, cardName), ListItem(R.string.card_serial_number, serialNumber)) li += extraInfo ?: emptyList() li += ListItem(R.string.serial_only_card_header, when (reason) { Reason.NOT_STORED -> R.string.serial_only_card_description_not_stored Reason.LOCKED -> R.string.serial_only_card_description_locked else -> R.string.serial_only_card_description_more_research } ) moreInfoPage?.let { li += UriListItem(R.string.unknown_more_info, R.string.unknown_more_info_desc, it) } return li } protected enum class Reason { UNSPECIFIED, /** The card doesn't store the balance */ NOT_STORED, /** The data we want is locked */ LOCKED, /** More research about the card format is needed */ MORE_RESEARCH_NEEDED } }
gpl-3.0
16dda2c1cf5e93676d9a3c6950c796a0
36.16129
94
0.667101
4.21978
false
false
false
false
RMHSProgrammingClub/Bot-Game
kotlin/src/main/kotlin/com/n9mtq4/botclient/ServerConnection.kt
1
2986
package com.n9mtq4.botclient import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.ConnectException import java.net.Socket import java.net.SocketException /** * Handles all the client to server connections * * Created by will on 11/27/15 at 11:16 PM. * * @property port the port to connect to * @param port the port to connect to * * @author Will "n9Mtq4" Bresnahan */ class ServerConnection(val port: Int) { private val client: Socket private val input: BufferedReader private val output: PrintWriter init { println("Connecting to server...") try { this.client = Socket("localhost", port) this.input = BufferedReader(InputStreamReader(client.inputStream)) this.output = PrintWriter(client.outputStream, true) println("Successfully connected to server") }catch (e: ConnectException) { System.err.println("Is the server running?") e.printStackTrace() throw e } } /** * Reads only one line from the server/ * * @return a single line of data * */ internal fun readLine(): String { val str = input.readLine() return str } /** * Reads all available data from the server. * * @return The data received (in a string) * */ @JvmName("read") internal fun read(): String { try { var text = input.readLine() // read the first line if (text.equals("{")) { // if we are dealing with a multi-line json string var command: String do { command = input.readLine() text += command + "\n" } while (command != "}") // read all the lines we have return text } else { return text // if its a normal string return the single line } }catch (e: SocketException) { System.err.println("Is the server running?") e.printStackTrace() throw e } /* var text = "" do { val command = input.readLine(); text += command + "\n" }while(command != null); return text.trim()*/ } /** * writes a string to the output socket with \n * */ internal fun writeln(msg: String) = write(msg + "\n") /** * writes a string to the output socket * */ internal fun write(msg: String) { output.print(msg) output.flush() } /** * Writes data to the server. * * @deprecated use writeWholeLog instead * @param msg the string to send * */ @Deprecated("Been replaced", ReplaceWith("writeWholeLog")) internal fun writeLogLine(msg: String) { output.print(msg) } /** * Writes data to the server. * * @param msg the turn log * */ @Throws(SocketException::class) internal fun writeWholeLog(msg: List<String>) { try { msg.forEach { output.println(it) } output.println("END") output.flush() }catch (e: SocketException) { System.err.println("Is the server running?") e.printStackTrace() throw e } } /** * Closes all server connections * */ internal fun close() { input.close() output.close() client.close() } }
mit
edeab4c2e61902c55f46e8db2626d597
20.177305
69
0.644675
3.44406
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/theme/usecase/BuyThemeUseCase.kt
1
1227
package io.ipoli.android.store.theme.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.Theme import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository import io.ipoli.android.store.theme.usecase.BuyThemeUseCase.Result.ThemeBought import io.ipoli.android.store.theme.usecase.BuyThemeUseCase.Result.TooExpensive /** * Created by Polina Zhelyazkova <[email protected]> * on 12/12/17. */ class BuyThemeUseCase(private val playerRepository: PlayerRepository) : UseCase<Theme, BuyThemeUseCase.Result> { override fun execute(parameters: Theme): Result { val theme = parameters val player = playerRepository.find() requireNotNull(player) require(!player!!.hasTheme(theme)) if (player.gems < theme.gemPrice) { return TooExpensive } val newPlayer = player.copy( gems = player.gems - theme.gemPrice, inventory = player.inventory.addTheme(theme) ) return ThemeBought(playerRepository.save(newPlayer)) } sealed class Result { data class ThemeBought(val player: Player) : Result() object TooExpensive : Result() } }
gpl-3.0
7ad454b023365cd572a350927a8ad459
31.315789
79
0.703341
4.11745
false
false
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/search/PsiSourcedWebSymbolRequestResultProcessor.kt
2
2837
package com.intellij.webSymbols.search import com.intellij.model.psi.PsiExternalReferenceHost import com.intellij.model.psi.PsiSymbolReferenceHints import com.intellij.model.psi.PsiSymbolReferenceService import com.intellij.model.psi.PsiSymbolService import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceService import com.intellij.psi.ReferenceRange import com.intellij.psi.search.RequestResultProcessor import com.intellij.util.Processor import com.intellij.webSymbols.PsiSourcedWebSymbol import com.intellij.webSymbols.references.WebSymbolReference class PsiSourcedWebSymbolRequestResultProcessor(private val targetElement: PsiElement, private val includeRegularReferences: Boolean) : RequestResultProcessor() { private val mySymbolReferenceService = service<PsiSymbolReferenceService>() private val myPsiReferenceService = PsiReferenceService.getService() override fun processTextOccurrence(element: PsiElement, offsetInElement: Int, consumer: Processor<in PsiReference>): Boolean { if (!targetElement.isValid) { return false } if (element is PsiExternalReferenceHost) { // Web symbol references mySymbolReferenceService.getReferences(element, PsiSymbolReferenceHints.offsetHint(offsetInElement)) .asSequence() .filterIsInstance<WebSymbolReference>() .filter { it.rangeInElement.containsOffset(offsetInElement) } .forEach { ref -> ProgressManager.checkCanceled() val psiSourcedWebSymbols = ref.resolveReference().filterIsInstance<PsiSourcedWebSymbol>() if (psiSourcedWebSymbols.isEmpty()) return@forEach val targetSymbol = PsiSymbolService.getInstance().asSymbol(targetElement) val equivalentSymbol = psiSourcedWebSymbols.find { it.isEquivalentTo(targetSymbol) } ?: return@forEach if (!consumer.process( PsiSourcedWebSymbolReference(equivalentSymbol, targetElement, element, ref.rangeInElement))) { return false } } } if (includeRegularReferences) { // Regular psi references val references = myPsiReferenceService.getReferences(element, PsiReferenceService.Hints(targetElement, offsetInElement)) //noinspection ForLoopReplaceableByForEach for (i in references.indices) { val ref = references[i] ProgressManager.checkCanceled() if (ReferenceRange.containsOffsetInElement(ref, offsetInElement) && ref.isReferenceTo(targetElement) && !consumer.process(ref)) { return false } } } return true } }
apache-2.0
e7cfea31c594c8bfbae0f03cad8e2919
44.047619
128
0.728939
5.111712
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Database/Dao/PlayerDao.kt
1
1007
package io.github.sdsstudios.ScoreKeeper.Database.Dao import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Query import io.github.sdsstudios.ScoreKeeper.Game.Player import io.github.sdsstudios.ScoreKeeper.Game.Results /** * Created by sethsch1 on 29/10/17. */ @Dao abstract class PlayerDao : BaseDao<Player>() { companion object { const val TABLE_NAME = "players" const val KEY_ID = "id" const val KEY_NAME = "name" const val KEY_COLOR = "color" const val KEY_ICON_NAME = "icon_name" const val KEY_LAST_ACTIVITY = "last_activity" } @Query("SELECT * FROM $TABLE_NAME") abstract fun getAllPlayers(): LiveData<List<Player>> @Query("SELECT * FROM $TABLE_NAME") abstract fun getAllResults(): LiveData<List<Results>> @Query("SELECT * FROM $TABLE_NAME WHERE id NOT IN (:arg0)") abstract fun getPlayersExcluding(idsToExclude: LongArray): LiveData<List<Player>> }
gpl-3.0
d692cdf48b92e3a0ae6e14ec6b15d8c9
29.545455
85
0.700099
3.814394
false
false
false
false
GunoH/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffScrollSupport.kt
8
4058
// 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.diff.tools.combined import com.intellij.diff.tools.util.PrevNextDifferenceIterable import com.intellij.diff.util.DiffUtil import com.intellij.openapi.Disposable import com.intellij.openapi.editor.* import com.intellij.openapi.editor.impl.ScrollingModelImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import java.awt.Point import javax.swing.JScrollPane import javax.swing.SwingUtilities enum class ScrollPolicy { DIFF_BLOCK, DIFF_CHANGE } internal class CombinedDiffScrollSupport(project: Project?, private val viewer: CombinedDiffViewer) { internal val currentPrevNextIterable = CombinedDiffPrevNextDifferenceIterable() internal val blockIterable = CombinedDiffPrevNextBlocksIterable() private val combinedEditorsScrollingModel = ScrollingModelImpl(CombinedEditorsScrollingModelHelper(project, viewer)) fun scroll(index: Int, block: CombinedDiffBlock<*>, scrollPolicy: ScrollPolicy){ val isEditorBased = viewer.diffViewers[block.id]?.isEditorBased ?: false if (scrollPolicy == ScrollPolicy.DIFF_BLOCK || !isEditorBased) { scrollToDiffBlock(index) } else if (scrollPolicy == ScrollPolicy.DIFF_CHANGE) { scrollToDiffChangeWithCaret() } } private fun scrollToDiffChangeWithCaret() { if (viewer.getCurrentDiffViewer().isEditorBased) { //avoid scrolling for non editor based viewers combinedEditorsScrollingModel.scrollToCaret(ScrollType.CENTER) } } private fun scrollToDiffBlock(index: Int) { if (viewer.diffBlocksPositions.values.contains(index)) { viewer.contentPanel.components.getOrNull(index)?.bounds?.let(viewer.contentPanel::scrollRectToVisible) } } internal inner class CombinedDiffPrevNextDifferenceIterable : PrevNextDifferenceIterable { override fun canGoNext(): Boolean { return viewer.getDifferencesIterable()?.canGoNext() == true } override fun canGoPrev(): Boolean { return viewer.getDifferencesIterable()?.canGoPrev() == true } override fun goNext() { viewer.getDifferencesIterable()?.goNext() scrollToDiffChangeWithCaret() } override fun goPrev() { viewer.getDifferencesIterable()?.goPrev() scrollToDiffChangeWithCaret() } } internal inner class CombinedDiffPrevNextBlocksIterable : PrevNextDifferenceIterable { var index = 0 override fun canGoNext(): Boolean = index < viewer.diffBlocks.size - 1 override fun canGoPrev(): Boolean = index > 0 override fun goNext() { index++ } override fun goPrev() { index-- } } private inner class CombinedEditorsScrollingModelHelper(project: Project?, disposable: Disposable) : ScrollingModel.Supplier, ScrollingModel.ScrollingHelper, Disposable { private val dummyEditor: Editor //needed for ScrollingModelImpl initialization init { dummyEditor = DiffUtil.createEditor(EditorFactory.getInstance().createDocument(""), project, true, true) Disposer.register(disposable, this) } override fun getEditor(): Editor = viewer.getDiffViewer(blockIterable.index)?.editor ?: dummyEditor override fun getScrollPane(): JScrollPane = viewer.scrollPane override fun getScrollingHelper(): ScrollingModel.ScrollingHelper = this override fun calculateScrollingLocation(editor: Editor, pos: VisualPosition): Point { val targetLocationInEditor = editor.visualPositionToXY(pos) return SwingUtilities.convertPoint(editor.component, targetLocationInEditor, scrollPane.viewport.view) } override fun calculateScrollingLocation(editor: Editor, pos: LogicalPosition): Point { val targetLocationInEditor = editor.logicalPositionToXY(pos) return SwingUtilities.convertPoint(editor.component, targetLocationInEditor, scrollPane.viewport.view) } override fun dispose() { EditorFactory.getInstance().releaseEditor(dummyEditor) } } }
apache-2.0
441c901b6581119927fe359a0b14e1a7
34.286957
120
0.756284
4.675115
false
false
false
false
GunoH/intellij-community
platform/elevation/daemon/src/com/intellij/execution/process/mediator/daemon/QuotaManager.kt
7
5582
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("EXPERIMENTAL_API_USAGE") package com.intellij.execution.process.mediator.daemon import kotlinx.coroutines.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.takeWhile import java.io.Closeable import java.util.concurrent.atomic.AtomicReference interface QuotaManager : Closeable { fun check(): Boolean /** * The returned job completes as soon as the quota is exceeded and all [runIfPermitted] blocks finished, * but never before [check] starts returning false. */ fun asJob(): Job } /** * Check if the quota has not been exceeded yet, * and prevents the manager from completing its [job][QuotaManager.asJob] until the block finishes. */ @Throws(QuotaExceededException::class) internal inline fun <R : Any> QuotaManager.runIfPermitted(block: () -> R): R { val childJob = Job(this.asJob()) // prevents the QuotaManager Job from finishing in case quota exceeds while running the block try { if (!this.check()) { throw QuotaExceededException() } check(childJob.isActive) { "check() returned true after asJob() has completed" } return block() } finally { childJob.complete() } } internal class TimeQuotaManager( coroutineScope: CoroutineScope, quotaOptions: QuotaOptions = QuotaOptions.UNLIMITED, ) : QuotaManager { private val stopwatchRef: AtomicReference<QuotaStopwatch> = AtomicReference(QuotaStopwatch.New(quotaOptions)) private val job = Job(coroutineScope.coroutineContext[Job]).apply { invokeOnCompletion { stopwatchRef.set(QuotaStopwatch.Expired) mutableStateFlow.value = null } } private val timeoutScope = coroutineScope + Job(job).also { if (job.complete()) { // doesn't in fact complete until the timeoutJob completes job.ensureActive() } } private val mutableStateFlow: MutableStateFlow<QuotaState?> = MutableStateFlow(stopwatchRef.get().toState()) val stateUpdateFlow: Flow<QuotaState> get() = mutableStateFlow.takeWhile { it != null }.filterNotNull() override fun asJob(): Job = job override fun check(): Boolean { val stopwatch = updateStopwatch { it.refresh() } return stopwatch !is QuotaStopwatch.Expired } fun adjustQuota(newOptions: QuotaOptions) { updateStopwatch { it.adjust(newOptions) } } private fun updateStopwatch(function: (t: QuotaStopwatch) -> QuotaStopwatch): QuotaStopwatch { return stopwatchRef.updateAndGet(function).also { stopwatch -> onStopwatchUpdated(stopwatch) } } private fun updateStopwatch(expectedStopwatch: QuotaStopwatch, stopwatch: QuotaStopwatch): Boolean { return stopwatchRef.compareAndSet(expectedStopwatch, stopwatch).also { success -> if (success) { onStopwatchUpdated(stopwatch) } } } private fun onStopwatchUpdated(stopwatch: QuotaStopwatch) { when (stopwatch) { is QuotaStopwatch.Active -> { if (!stopwatch.isUnlimited) { timeoutScope.launch(start = CoroutineStart.UNDISPATCHED) { delay(stopwatch.remaining()) updateStopwatch(stopwatch, QuotaStopwatch.Expired) } } } QuotaStopwatch.Expired -> { timeoutScope.cancel("expired") } else -> {} } mutableStateFlow.value = stopwatch.toState() } override fun close() { job.cancel("Closed") } } private sealed class QuotaStopwatch { abstract val options: QuotaOptions /** * This can only reduce the quota. An already exceeded quota doesn't change. */ abstract fun adjust(newOptions: QuotaOptions): QuotaStopwatch /** * Starts the stopwatch if it hasn't started yet. * This may reset the active stopwatch, if the quota allows to do so via [QuotaOptions.isRefreshable]. */ abstract fun refresh(): QuotaStopwatch abstract fun toState(): QuotaState data class New( override val options: QuotaOptions, ) : QuotaStopwatch() { override fun adjust(newOptions: QuotaOptions): QuotaStopwatch = copy(options = options.adjust(newOptions)) override fun refresh(): QuotaStopwatch = Active(options) // the very first process is always permitted override fun toState() = QuotaState.New(options) } data class Active( override val options: QuotaOptions, private val startTimeMillis: Long = System.currentTimeMillis(), ) : QuotaStopwatch() { val isUnlimited get() = options.isUnlimited fun elapsed(): Long = if (isUnlimited) 0 else System.currentTimeMillis() - startTimeMillis fun remaining(): Long = if (isUnlimited) Long.MAX_VALUE else options.timeLimitMs - elapsed() private fun isExpired(): Boolean = remaining() <= 0 override fun adjust(newOptions: QuotaOptions): QuotaStopwatch = when { isExpired() -> Expired else -> copy(options = options.adjust(newOptions)) } override fun refresh(): QuotaStopwatch = when { isExpired() -> Expired !options.isRefreshable -> this else -> copy(startTimeMillis = System.currentTimeMillis()) } override fun toState() = QuotaState.Active(options, elapsed()) } object Expired : QuotaStopwatch() { override val options: QuotaOptions get() = QuotaOptions.EXCEEDED override fun adjust(newOptions: QuotaOptions): QuotaStopwatch = this override fun refresh(): QuotaStopwatch = this override fun toState() = QuotaState.Expired } }
apache-2.0
aee625b3ad6e7c13bdb79005caeab87e
30.715909
129
0.709065
4.343969
false
false
false
false
ftomassetti/kolasu
core/src/test/kotlin/com/strumenta/kolasu/codegen/KotlinPrinter.kt
1
5452
package com.strumenta.kolasu.codegen class KotlinPrinter : ASTCodeGenerator<KCompilationUnit>() { override fun registerRecordPrinters() { recordPrinter<KCompilationUnit> { print(it.packageDecl) printList(prefix = "", it.imports, "\n", false, "") if (it.imports.isNotEmpty()) { println() } it.elements.forEach { print(it) } } recordPrinter<KPackageDecl> { print("package ") print(it.name) println() println() } recordPrinter<KImport> { print("import ") print(it.imported) println() } recordPrinter<KClassDeclaration> { printFlag(it.dataClass, "data ") printFlag(it.isAbstract, "abstract ") printFlag(it.isSealed, "sealed ") print("class ${it.name}") print(it.primaryConstructor) if (it.superTypes.isNotEmpty()) { print(": ") printList(it.superTypes) print(" ") } println(" {") println("}") println() } recordPrinter<KPrimaryConstructor> { printList("(", it.params, ")") } recordPrinter<KSuperTypeInvocation> { print(it.name) print("()") } recordPrinter<KParameterDeclaration> { when (it.persistemce) { KPersistence.VAR -> print("var ") KPersistence.VAL -> print("val ") else -> Unit } print(it.name) print(": ") print(it.type) } recordPrinter<KRefType> { print(it.name) printList("<", it.args, ">") } recordPrinter<KOptionalType> { print(it.base) print("?") } recordPrinter<KExtensionMethod> { print("fun ") print(it.extendedClass) print(".") print(it.name) printList("(", it.params, ")", printEvenIfEmpty = true) if (it.returnType != null) { print(": ") print(it.returnType) } println(" {") indent() printList(it.body, "\n") dedent() println("}") println() } recordPrinter<KQualifiedName> { print(it.container) print(".") print(it.name) } recordPrinter<KSimpleName> { print(it.name) } recordPrinter<KExpressionStatement> { print(it.expression) println() } recordPrinter<KFunctionCall> { print(it.function.name) printList("(", it.args, ")", printEvenIfEmpty = true) } recordPrinter<KReturnStatement> { print("return") print(it.value, prefix = " ") println() } recordPrinter<KWhenStatement> { print("when ") print(it.subject, "(", ") ") println("{") indent() printList(it.whenClauses, "") print(it.elseClause) dedent() println("}") } recordPrinter<KWhenClause> { print(it.condition) print(" -> ") print(it.body) } recordPrinter<KElseClause> { print("else -> ") print(it.body) } recordPrinter<KThisExpression> { print("this") } recordPrinter<KUniIsExpression> { print("is ") print(it.ktype) } recordPrinter<KMethodCallExpression> { print(it.qualifier) print(".") print(it.method.name) print("(") printList(it.args) print(")") print(it.lambda, " ") } recordPrinter<KInstantiationExpression> { print(it.type) print("(") printList(it.args) print(")") } recordPrinter<KThrowStatement> { print("throw ") println(it.exception) } recordPrinter<KFieldAccessExpr> { print(it.qualifier) print(".") print(it.field) } recordPrinter<KParameterValue> { print(it.name, "", "=") print(it.value) } recordPrinter<KLambda> { print("{") indent() printList(it.body, separator = "") dedent() println("}") } recordPrinter<KReferenceExpr> { print(it.symbol) } recordPrinter<KStringLiteral> { print('"') print(it.value) print('"') } recordPrinter<KIntLiteral> { print(it.value) } recordPrinter<KFunctionDeclaration> { print("fun ") print(it.name) print("(") // TODO print parameters println(") {") indent() // TODO print body dedent() println("}") } } fun printToString(expression: KExpression): String { val o = PrinterOutput(nodePrinters) o.print(expression) return o.text() } }
apache-2.0
1f05a37559e7e3c73b669d6ffe44a8c1
27.248705
67
0.45066
4.929476
false
false
false
false
jk1/intellij-community
platform/configuration-store-impl/src/ImportSettingsAction.kt
4
5805
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ImportSettingsFilenameFilter import com.intellij.ide.plugins.PluginManager import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.getParentPath import com.intellij.util.io.copy import com.intellij.util.io.exists import com.intellij.util.io.inputStream import com.intellij.util.io.systemIndependentPath import gnu.trove.THashSet import java.io.File import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths import java.util.zip.ZipException import java.util.zip.ZipInputStream // for Rider purpose open class ImportSettingsAction : AnAction(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isImportExportActionApplicable() } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext) chooseSettingsFile(PathManager.getConfigPath(), component, IdeBundle.message("title.import.file.location"), IdeBundle.message("prompt.choose.import.file.path")) .onSuccess { val saveFile = Paths.get(it) try { doImport(saveFile) } catch (e1: ZipException) { Messages.showErrorDialog( IdeBundle.message("error.reading.settings.file", saveFile, e1.message, promptLocationMessage()), IdeBundle.message("title.invalid.file")) } catch (e1: IOException) { Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file.2", saveFile, e1.message), IdeBundle.message("title.error.reading.file")) } } } protected open fun getExportableComponents(relativePaths: Set<String>): Map<Path, List<ExportableItem>> = getExportableComponentsMap(false, true, onlyPaths = relativePaths) protected open fun getMarkedComponents(components: Set<ExportableItem>): Set<ExportableItem> = components @Deprecated("", replaceWith = ReplaceWith("doImport(saveFile.toPath())")) protected open fun doImport(saveFile: File) { doImport(saveFile.toPath()) } protected open fun doImport(saveFile: Path) { if (!saveFile.exists()) { Messages.showErrorDialog(IdeBundle.message("error.cannot.find.file", saveFile), IdeBundle.message("title.file.not.found")) return } val relativePaths = getPaths(saveFile.inputStream()) if (!relativePaths.contains(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)) { Messages.showErrorDialog( IdeBundle.message("error.file.contains.no.settings.to.import", saveFile, promptLocationMessage()), IdeBundle.message("title.invalid.file")) return } val configPath = FileUtil.toSystemIndependentName(PathManager.getConfigPath()) val dialog = ChooseComponentsToExportDialog( getExportableComponents(relativePaths), false, IdeBundle.message("title.select.components.to.import"), IdeBundle.message("prompt.check.components.to.import")) if (!dialog.showAndGet()) { return } val tempFile = Paths.get(PathManager.getPluginTempPath()).resolve(saveFile.fileName) saveFile.copy(tempFile) val filenameFilter = ImportSettingsFilenameFilter(getRelativeNamesToExtract(getMarkedComponents(dialog.exportableComponents))) StartupActionScriptManager.addActionCommands(listOf( StartupActionScriptManager.UnzipCommand(tempFile.toFile(), File(configPath), filenameFilter), StartupActionScriptManager.DeleteCommand(tempFile.toFile()))) UpdateSettings.getInstance().forceCheckForUpdateAfterRestart() val action = IdeBundle.message(if (ApplicationManager.getApplication().isRestartCapable) "ide.restart.action" else "ide.shutdown.action") val message = IdeBundle.message("message.settings.imported.successfully", action, ApplicationNamesInfo.getInstance().fullProductName) if (Messages.showOkCancelDialog(message, IdeBundle.message("title.restart.needed"), Messages.getQuestionIcon()) == Messages.OK) { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun getRelativeNamesToExtract(chosenComponents: Set<ExportableItem>): Set<String> { val result = THashSet<String>() val root = Paths.get(PathManager.getConfigPath()) for ((file) in chosenComponents) { result.add(root.relativize(file).systemIndependentPath) } result.add(PluginManager.INSTALLED_TXT) return result } private fun promptLocationMessage() = IdeBundle.message("message.please.ensure.correct.settings") } fun getPaths(input: InputStream): Set<String> { val result = THashSet<String>() val zipIn = ZipInputStream(input) zipIn.use { while (true) { val entry = zipIn.nextEntry ?: break var path = entry.name result.add(path) while (true) { path = getParentPath(path) ?: break result.add("$path/") } } } return result }
apache-2.0
a6cd0127485007265cea93315839927e
41.372263
174
0.750043
4.647718
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt
1
4612
package eu.kanade.tachiyomi.ui.reader.viewer.pager import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView import eu.kanade.tachiyomi.ui.reader.viewer.ViewerConfig import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.EdgeNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.KindlishNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.LNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.RightAndLeftNavigation import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Configuration used by pager viewers. */ class PagerConfig( private val viewer: PagerViewer, scope: CoroutineScope, preferences: PreferencesHelper = Injekt.get() ) : ViewerConfig(preferences, scope) { var theme = preferences.readerTheme().get() private set var automaticBackground = false private set var dualPageSplitChangedListener: ((Boolean) -> Unit)? = null var imageScaleType = 1 private set var imageZoomType = ReaderPageImageView.ZoomStartPosition.LEFT private set var imageCropBorders = false private set var navigateToPan = false private set var landscapeZoom = false private set init { preferences.readerTheme() .register( { theme = it automaticBackground = it == 3 }, { imagePropertyChangedListener?.invoke() } ) preferences.imageScaleType() .register({ imageScaleType = it }, { imagePropertyChangedListener?.invoke() }) preferences.zoomStart() .register({ zoomTypeFromPreference(it) }, { imagePropertyChangedListener?.invoke() }) preferences.cropBorders() .register({ imageCropBorders = it }, { imagePropertyChangedListener?.invoke() }) preferences.navigateToPan() .register({ navigateToPan = it }) preferences.landscapeZoom() .register({ landscapeZoom = it }, { imagePropertyChangedListener?.invoke() }) preferences.navigationModePager() .register({ navigationMode = it }, { updateNavigation(navigationMode) }) preferences.pagerNavInverted() .register({ tappingInverted = it }, { navigator.invertMode = it }) preferences.pagerNavInverted().asFlow() .drop(1) .onEach { navigationModeChangedListener?.invoke() } .launchIn(scope) preferences.dualPageSplitPaged() .register( { dualPageSplit = it }, { imagePropertyChangedListener?.invoke() dualPageSplitChangedListener?.invoke(it) } ) preferences.dualPageInvertPaged() .register({ dualPageInvert = it }, { imagePropertyChangedListener?.invoke() }) } private fun zoomTypeFromPreference(value: Int) { imageZoomType = when (value) { // Auto 1 -> when (viewer) { is L2RPagerViewer -> ReaderPageImageView.ZoomStartPosition.LEFT is R2LPagerViewer -> ReaderPageImageView.ZoomStartPosition.RIGHT else -> ReaderPageImageView.ZoomStartPosition.CENTER } // Left 2 -> ReaderPageImageView.ZoomStartPosition.LEFT // Right 3 -> ReaderPageImageView.ZoomStartPosition.RIGHT // Center else -> ReaderPageImageView.ZoomStartPosition.CENTER } } override var navigator: ViewerNavigation = defaultNavigation() set(value) { field = value.also { it.invertMode = this.tappingInverted } } override fun defaultNavigation(): ViewerNavigation { return when (viewer) { is VerticalPagerViewer -> LNavigation() else -> RightAndLeftNavigation() } } override fun updateNavigation(navigationMode: Int) { navigator = when (navigationMode) { 0 -> defaultNavigation() 1 -> LNavigation() 2 -> KindlishNavigation() 3 -> EdgeNavigation() 4 -> RightAndLeftNavigation() else -> defaultNavigation() } navigationModeChangedListener?.invoke() } }
apache-2.0
79dbb871202eb82fdac40f49b3f0c50d
32.42029
97
0.634649
5.337963
false
false
false
false
cmzy/okhttp
okhttp/src/main/kotlin/okhttp3/FormBody.kt
4
4134
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.IOException import java.nio.charset.Charset import okhttp3.HttpUrl.Companion.FORM_ENCODE_SET import okhttp3.HttpUrl.Companion.canonicalize import okhttp3.HttpUrl.Companion.percentDecode import okhttp3.MediaType.Companion.toMediaType import okhttp3.internal.toImmutableList import okio.Buffer import okio.BufferedSink class FormBody internal constructor( encodedNames: List<String>, encodedValues: List<String> ) : RequestBody() { private val encodedNames: List<String> = encodedNames.toImmutableList() private val encodedValues: List<String> = encodedValues.toImmutableList() /** The number of key-value pairs in this form-encoded body. */ @get:JvmName("size") val size: Int get() = encodedNames.size @JvmName("-deprecated_size") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "size"), level = DeprecationLevel.ERROR) fun size(): Int = size fun encodedName(index: Int): String = encodedNames[index] fun name(index: Int): String = encodedName(index).percentDecode(plusIsSpace = true) fun encodedValue(index: Int): String = encodedValues[index] fun value(index: Int): String = encodedValue(index).percentDecode(plusIsSpace = true) override fun contentType(): MediaType = CONTENT_TYPE override fun contentLength(): Long = writeOrCountBytes(null, true) @Throws(IOException::class) override fun writeTo(sink: BufferedSink) { writeOrCountBytes(sink, false) } /** * Either writes this request to [sink] or measures its content length. We have one method * do double-duty to make sure the counting and content are consistent, particularly when it comes * to awkward operations like measuring the encoded length of header strings, or the * length-in-digits of an encoded integer. */ private fun writeOrCountBytes(sink: BufferedSink?, countBytes: Boolean): Long { var byteCount = 0L val buffer: Buffer = if (countBytes) Buffer() else sink!!.buffer for (i in 0 until encodedNames.size) { if (i > 0) buffer.writeByte('&'.code) buffer.writeUtf8(encodedNames[i]) buffer.writeByte('='.code) buffer.writeUtf8(encodedValues[i]) } if (countBytes) { byteCount = buffer.size buffer.clear() } return byteCount } class Builder @JvmOverloads constructor(private val charset: Charset? = null) { private val names = mutableListOf<String>() private val values = mutableListOf<String>() fun add(name: String, value: String) = apply { names += name.canonicalize( encodeSet = FORM_ENCODE_SET, plusIsSpace = false, // plus is encoded as `%2B`, space is encoded as plus. charset = charset ) values += value.canonicalize( encodeSet = FORM_ENCODE_SET, plusIsSpace = false, // plus is encoded as `%2B`, space is encoded as plus. charset = charset ) } fun addEncoded(name: String, value: String) = apply { names += name.canonicalize( encodeSet = FORM_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true, charset = charset ) values += value.canonicalize( encodeSet = FORM_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true, charset = charset ) } fun build(): FormBody = FormBody(names, values) } companion object { private val CONTENT_TYPE: MediaType = "application/x-www-form-urlencoded".toMediaType() } }
apache-2.0
ebea1701c820a00ede0153e1ab686bc3
31.809524
100
0.689405
4.218367
false
false
false
false
jovr/imgui
vk/src/main/kotlin/imgui/impl/vk_/anchor_.kt
2
8458
package imgui.impl.vk_ // Vulkan data lateinit var gVulkanInitInfo: ImplVulkan_.InitInfo var gRenderPass = 0L var gBufferMemoryAlignment = 256L var gPipelineCreateFlags = 0x00 var gDescriptorSetLayout = 0L var gPipelineLayout = 0L var gDescriptorSet = 0L var gPipeline = 0L var gSubpass = 0 var gShaderModuleVert = 0L var gShaderModuleFrag = 0L // Font data var gFontSampler = 0L var gFontMemory = 0L var gFontImage = 0L var gFontView = 0L var gUploadBufferMemory = 0L var gUploadBuffer = 0L // Render buffers val gMainWindowRenderBuffers = ImplVulkanH_.WindowRenderBuffers() //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- // glsl_shader.vert, compiled with: // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert /* #version 450 core layout(location = 0) in vec2 aPos; layout(location = 1) in vec2 aUV; layout(location = 2) in vec4 aColor; layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc; out gl_PerVertex { vec4 gl_Position; }; layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; void main() { Out.Color = aColor; Out.UV = aUV; gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); } */ val __glsl_shader_vert_spv = intArrayOf( 0x07230203, 0x00010000, 0x00080001, 0x0000002e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x000a000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x0000000f, 0x00000015, 0x0000001b, 0x0000001c, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d, 0x00000000, 0x00030005, 0x00000009, 0x00000000, 0x00050006, 0x00000009, 0x00000000, 0x6f6c6f43, 0x00000072, 0x00040006, 0x00000009, 0x00000001, 0x00005655, 0x00030005, 0x0000000b, 0x0074754f, 0x00040005, 0x0000000f, 0x6c6f4361, 0x0000726f, 0x00030005, 0x00000015, 0x00565561, 0x00060005, 0x00000019, 0x505f6c67, 0x65567265, 0x78657472, 0x00000000, 0x00060006, 0x00000019, 0x00000000, 0x505f6c67, 0x7469736f, 0x006e6f69, 0x00030005, 0x0000001b, 0x00000000, 0x00040005, 0x0000001c, 0x736f5061, 0x00000000, 0x00060005, 0x0000001e, 0x73755075, 0x6e6f4368, 0x6e617473, 0x00000074, 0x00050006, 0x0000001e, 0x00000000, 0x61635375, 0x0000656c, 0x00060006, 0x0000001e, 0x00000001, 0x61725475, 0x616c736e, 0x00006574, 0x00030005, 0x00000020, 0x00006370, 0x00040047, 0x0000000b, 0x0000001e, 0x00000000, 0x00040047, 0x0000000f, 0x0000001e, 0x00000002, 0x00040047, 0x00000015, 0x0000001e, 0x00000001, 0x00050048, 0x00000019, 0x00000000, 0x0000000b, 0x00000000, 0x00030047, 0x00000019, 0x00000002, 0x00040047, 0x0000001c, 0x0000001e, 0x00000000, 0x00050048, 0x0000001e, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000001e, 0x00000001, 0x00000023, 0x00000008, 0x00030047, 0x0000001e, 0x00000002, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040017, 0x00000008, 0x00000006, 0x00000002, 0x0004001e, 0x00000009, 0x00000007, 0x00000008, 0x00040020, 0x0000000a, 0x00000003, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000003, 0x00040015, 0x0000000c, 0x00000020, 0x00000001, 0x0004002b, 0x0000000c, 0x0000000d, 0x00000000, 0x00040020, 0x0000000e, 0x00000001, 0x00000007, 0x0004003b, 0x0000000e, 0x0000000f, 0x00000001, 0x00040020, 0x00000011, 0x00000003, 0x00000007, 0x0004002b, 0x0000000c, 0x00000013, 0x00000001, 0x00040020, 0x00000014, 0x00000001, 0x00000008, 0x0004003b, 0x00000014, 0x00000015, 0x00000001, 0x00040020, 0x00000017, 0x00000003, 0x00000008, 0x0003001e, 0x00000019, 0x00000007, 0x00040020, 0x0000001a, 0x00000003, 0x00000019, 0x0004003b, 0x0000001a, 0x0000001b, 0x00000003, 0x0004003b, 0x00000014, 0x0000001c, 0x00000001, 0x0004001e, 0x0000001e, 0x00000008, 0x00000008, 0x00040020, 0x0000001f, 0x00000009, 0x0000001e, 0x0004003b, 0x0000001f, 0x00000020, 0x00000009, 0x00040020, 0x00000021, 0x00000009, 0x00000008, 0x0004002b, 0x00000006, 0x00000028, 0x00000000, 0x0004002b, 0x00000006, 0x00000029, 0x3f800000, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000007, 0x00000010, 0x0000000f, 0x00050041, 0x00000011, 0x00000012, 0x0000000b, 0x0000000d, 0x0003003e, 0x00000012, 0x00000010, 0x0004003d, 0x00000008, 0x00000016, 0x00000015, 0x00050041, 0x00000017, 0x00000018, 0x0000000b, 0x00000013, 0x0003003e, 0x00000018, 0x00000016, 0x0004003d, 0x00000008, 0x0000001d, 0x0000001c, 0x00050041, 0x00000021, 0x00000022, 0x00000020, 0x0000000d, 0x0004003d, 0x00000008, 0x00000023, 0x00000022, 0x00050085, 0x00000008, 0x00000024, 0x0000001d, 0x00000023, 0x00050041, 0x00000021, 0x00000025, 0x00000020, 0x00000013, 0x0004003d, 0x00000008, 0x00000026, 0x00000025, 0x00050081, 0x00000008, 0x00000027, 0x00000024, 0x00000026, 0x00050051, 0x00000006, 0x0000002a, 0x00000027, 0x00000000, 0x00050051, 0x00000006, 0x0000002b, 0x00000027, 0x00000001, 0x00070050, 0x00000007, 0x0000002c, 0x0000002a, 0x0000002b, 0x00000028, 0x00000029, 0x00050041, 0x00000011, 0x0000002d, 0x0000001b, 0x0000000d, 0x0003003e, 0x0000002d, 0x0000002c, 0x000100fd, 0x00010038) // glsl_shader.frag, compiled with: // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag /* #version 450 core layout(location = 0) out vec4 fColor; layout(set=0, binding=0) uniform sampler2D sTexture; layout(location = 0) in struct { vec4 Color; vec2 UV; } In; void main() { fColor = In.Color * texture(sTexture, In.UV.st); } */ val __glsl_shader_frag_spv = intArrayOf( 0x07230203, 0x00010000, 0x00080001, 0x0000001e, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000d, 0x00030010, 0x00000004, 0x00000007, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d, 0x00000000, 0x00040005, 0x00000009, 0x6c6f4366, 0x0000726f, 0x00030005, 0x0000000b, 0x00000000, 0x00050006, 0x0000000b, 0x00000000, 0x6f6c6f43, 0x00000072, 0x00040006, 0x0000000b, 0x00000001, 0x00005655, 0x00030005, 0x0000000d, 0x00006e49, 0x00050005, 0x00000016, 0x78655473, 0x65727574, 0x00000000, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000d, 0x0000001e, 0x00000000, 0x00040047, 0x00000016, 0x00000022, 0x00000000, 0x00040047, 0x00000016, 0x00000021, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000009, 0x00000003, 0x00040017, 0x0000000a, 0x00000006, 0x00000002, 0x0004001e, 0x0000000b, 0x00000007, 0x0000000a, 0x00040020, 0x0000000c, 0x00000001, 0x0000000b, 0x0004003b, 0x0000000c, 0x0000000d, 0x00000001, 0x00040015, 0x0000000e, 0x00000020, 0x00000001, 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000, 0x00040020, 0x00000010, 0x00000001, 0x00000007, 0x00090019, 0x00000013, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000014, 0x00000013, 0x00040020, 0x00000015, 0x00000000, 0x00000014, 0x0004003b, 0x00000015, 0x00000016, 0x00000000, 0x0004002b, 0x0000000e, 0x00000018, 0x00000001, 0x00040020, 0x00000019, 0x00000001, 0x0000000a, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, 0x00000011, 0x0000000d, 0x0000000f, 0x0004003d, 0x00000007, 0x00000012, 0x00000011, 0x0004003d, 0x00000014, 0x00000017, 0x00000016, 0x00050041, 0x00000019, 0x0000001a, 0x0000000d, 0x00000018, 0x0004003d, 0x0000000a, 0x0000001b, 0x0000001a, 0x00050057, 0x00000007, 0x0000001c, 0x00000017, 0x0000001b, 0x00050085, 0x00000007, 0x0000001d, 0x00000012, 0x0000001c, 0x0003003e, 0x00000009, 0x0000001d, 0x000100fd, 0x00010038)
mit
d443a057ef5c7378ffb799ded396973e
64.069231
103
0.745921
2.516513
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/utils.kt
4
3427
// 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.postProcessing import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor fun KtExpression.unpackedReferenceToProperty(): KtProperty? = when (this) { is KtDotQualifiedExpression -> selectorExpression as? KtNameReferenceExpression is KtNameReferenceExpression -> this else -> null }?.references ?.firstOrNull { it is KtSimpleNameReference } ?.resolve() as? KtProperty fun KtDeclaration.type() = (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType fun KtReferenceExpression.resolve() = mainReference.resolve() fun KtPsiFactory.createGetter(body: KtExpression?, modifiers: String?): KtPropertyAccessor { val property = createProperty( "val x\n ${modifiers.orEmpty()} get" + when (body) { is KtBlockExpression -> "() { return 1 }" null -> "" else -> "() = 1" } + "\n" ) val getter = property.getter!! val bodyExpression = getter.bodyExpression bodyExpression?.replace(body!!) return getter } fun KtPsiFactory.createSetter(body: KtExpression?, fieldName: String?, modifiers: String?): KtPropertyAccessor { val modifiersText = modifiers.orEmpty() val property = when (body) { null -> createProperty("var x = 1\n get() = 1\n $modifiersText set") is KtBlockExpression -> createProperty("var x get() = 1\n $modifiersText set($fieldName) {\n field = $fieldName\n }") else -> createProperty("var x get() = 1\n $modifiersText set($fieldName) = TODO()") } val setter = property.setter!! if (body != null) { setter.bodyExpression?.replace(body) } return setter } fun KtElement.hasUsagesOutsideOf(inElement: KtElement, outsideElements: List<KtElement>): Boolean = ReferencesSearch.search(this, LocalSearchScope(inElement)).any { reference -> outsideElements.none { it.isAncestor(reference.element) } } inline fun <reified T : PsiElement> List<PsiElement>.descendantsOfType(): List<T> = flatMap { it.collectDescendantsOfType() } fun PsiElement.isInRange(outerRange: TextRange) = outerRange.contains(textRange) fun runUndoTransparentActionInEdt(inWriteAction: Boolean, action: () -> Unit) { ApplicationManager.getApplication().invokeAndWait { CommandProcessor.getInstance().runUndoTransparentAction { if (inWriteAction) { runWriteAction(action) } else { action() } } } }
apache-2.0
27ae04f6776e9b53bc7e04d2a8760764
36.67033
126
0.697111
4.847242
false
false
false
false
dahlstrom-g/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/NullArgumentMapping.kt
13
1680
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.resolve.api.* import org.jetbrains.plugins.groovy.lang.resolve.api.ApplicabilityResult.ArgumentApplicability class NullArgumentMapping<out P : CallParameter>(parameter: P) : ArgumentMapping<P> { override val arguments: Arguments = singleNullArgumentList override val expectedTypes: List<Pair<PsiType, Argument>> = parameter.type?.let { expectedType -> listOf(Pair(expectedType, singleNullArgument)) } ?: emptyList() override fun targetParameter(argument: Argument): P? = null override fun expectedType(argument: Argument): PsiType? = null // call `def foo(String a) {}` with `foo()` is actually `foo(null)` // Also see https://issues.apache.org/jira/browse/GROOVY-8248 override fun applicability(): Applicability = Applicability.applicable private companion object { private val singleNullArgument = JustTypeArgument(PsiType.NULL) private val singleNullArgumentList = listOf(singleNullArgument) } override fun highlightingApplicabilities(substitutor: PsiSubstitutor): ApplicabilityResult = object : ApplicabilityResult { override val applicability: Applicability get() = Applicability.applicable override val argumentApplicabilities: Map<Argument, ArgumentApplicability> get() = expectedTypes.associate { (type, argument) -> argument to ArgumentApplicability(type, Applicability.applicable) } } }
apache-2.0
72409aac680fce237d1cc468961b55ce
42.076923
140
0.772024
4.565217
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/NewModuleBuilder.kt
7
1053
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.projectWizard.NewProjectWizardConstants.Generators import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ui.UIBundle import com.intellij.util.ui.EmptyIcon import javax.swing.Icon class NewModuleBuilder : GeneratorNewProjectWizardBuilderAdapter(SimpleNewModuleWizard()) { class SimpleNewModuleWizard : GeneratorNewProjectWizard { override val id: String = Generators.SIMPLE_MODULE override val name: String = UIBundle.message("label.project.wizard.module.generator.name") override val description: String = UIBundle.message("label.project.wizard.module.generator.description") override val icon: Icon = EmptyIcon.ICON_0 override fun createStep(context: WizardContext) = RootNewProjectWizardStep(context) .chain(::NewProjectWizardBaseStep, ::NewProjectWizardLanguageStep) } }
apache-2.0
590e62a00cce82d69eda127263d47307
49.142857
158
0.79962
4.519313
false
false
false
false
DreierF/MyTargets
app/src/androidTest/java/de/dreier/mytargets/features/training/TrainingActivityTest.kt
1
3893
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.training import android.content.Intent import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.intent.rule.IntentsTestRule import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import de.dreier.mytargets.R import de.dreier.mytargets.app.ApplicationInstance import de.dreier.mytargets.base.fragments.EditableListFragmentBase import de.dreier.mytargets.test.base.UITestBase import de.dreier.mytargets.test.utils.matchers.RecyclerViewMatcher.Companion.withRecyclerView import de.dreier.mytargets.test.utils.rules.SimpleDbTestRule import org.hamcrest.Matchers.containsString import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import java.util.* @Ignore @RunWith(AndroidJUnit4::class) class TrainingActivityTest : UITestBase() { private val activityTestRule = IntentsTestRule( TrainingActivity::class.java, true, false ) @get:Rule val rule = RuleChain.outerRule(SimpleDbTestRule()) .around(activityTestRule) @Test fun navigation() { val trainings = ApplicationInstance.db.trainingDAO().loadTrainings() Collections.sort(trainings, Collections.reverseOrder()) val training = trainings[0] val i = Intent() i.putExtra(EditableListFragmentBase.ITEM_ID, training.id) activityTestRule.launchActivity(i) // intending(isInternal()) // .respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null)); onView(withRecyclerView(R.id.recyclerView).atPosition(0)) .check(matches(hasDescendant(withText(containsString("50m"))))) .check(matches(hasDescendant(withText("212/360")))) onView(withRecyclerView(R.id.recyclerView).atPosition(1)) .check(matches(hasDescendant(withText(containsString("30m"))))) .check(matches(hasDescendant(withText("203/360")))) // onView(withRecyclerView(R.id.recyclerView).atPosition(1)) // .perform(click()); // intended(allOf(hasClass(RoundActivity.class), // hasExtra(RoundFragment.ROUND_ID, training.loadRounds().get(1).getId()))); // // clickActionBarItem(R.id.action_statistics, R.string.statistic); // intended(allOf(hasClass(StatisticsActivity.class), // hasLongArrayExtra(StatisticsActivity.ROUND_IDS, training.loadRounds() // .map(Round::getId) // .toSet()))); // TODO investigate why this crashes on travis // clickActionBarItem(R.id.action_scoreboard, R.string.scoreboard); // intended(allOf(hasClass(ScoreboardActivity.class), // hasExtra(ScoreboardActivity.TRAINING_ID, training.getId()), // hasExtra(ScoreboardActivity.ROUND_ID, -1L))); // onView(supportFab()).perform(click()); // intended(allOf(hasClass(EditRoundActivity.class), // hasExtra(ITEM_ID, training.getId()))); } }
gpl-2.0
982974ee5b0c4fc742ab31831e1934da
41.78022
101
0.686103
4.479862
false
true
false
false
cbeust/klaxon
klaxon/src/main/kotlin/com/beust/klaxon/Lexer.kt
1
7346
package com.beust.klaxon import com.beust.klaxon.token.* import java.io.Reader import java.util.regex.Pattern /** * if `lenient` is true, names (the identifiers left of the colon) are allowed to not be surrounded by double quotes. */ class Lexer(passedReader: Reader, val lenient: Boolean = false): Iterator<Token> { var index = 0 var line = 1 private val NUMERIC = Pattern.compile("[-]?[0-9]+") private val DOUBLE = Pattern.compile(NUMERIC.toString() + "((\\.[0-9]+)?([eE][-+]?[0-9]+)?)")!! private fun isSpace(c: Char): Boolean { if (c == '\n') line++ return c == ' ' || c == '\r' || c == '\n' || c == '\t' } private val reader = passedReader.buffered() private var next: Char? private val isDone: Boolean get() = next == null init { val c = reader.read() next = if (c == -1) null else c.toChar() } private fun nextChar(): Char { if (isDone) throw IllegalStateException("Cannot get next char: EOF reached") val c = next!! next = reader.read().let { if (it == -1) null else it.toChar() } index++ // log("Next char: '$c' index:$index") return c } private fun peekChar() : Char { if (isDone) throw IllegalStateException("Cannot peek next char: EOF reached") return next!! } val BOOLEAN_LETTERS = "falsetrue".toSet() private fun isBooleanLetter(c: Char) : Boolean { return BOOLEAN_LETTERS.contains(Character.toLowerCase(c)) } val NULL_LETTERS = "null".toSet() fun isValueLetter(c: Char) : Boolean { return c == '-' || c == '+' || c == '.' || c.isDigit() || isBooleanLetter(c) || c in NULL_LETTERS } private var peeked: Token? = null fun peek() : Token { peeked = peeked ?: actualNextToken() return peeked!! } override fun next() = nextToken() override fun hasNext() = peek() !is EOF fun nextToken(): Token { return peeked?.also { peeked = null } ?: actualNextToken() } private var expectName = false private fun actualNextToken() : Token { if (isDone) { return EOF } val token: Token var c = nextChar() val currentValue = StringBuilder() while (!isDone && isSpace(c)) { c = nextChar() } if ('"' == c || (lenient && expectName)) { if (lenient) { currentValue.append(c) } loop@ do { if (isDone) { throw KlaxonException("Unterminated string") } c = if (lenient) peekChar() else nextChar() when (c) { '\\' -> { if (isDone) { throw KlaxonException("Unterminated string") } c = nextChar() when (c) { '\\' -> currentValue.append("\\") '/' -> currentValue.append("/") 'b' -> currentValue.append("\b") 'f' -> currentValue.append("\u000c") 'n' -> { currentValue.append("\n") line++ } 'r' -> currentValue.append("\r") 't' -> currentValue.append("\t") 'u' -> { val unicodeChar = StringBuilder(4) try { unicodeChar .append(nextChar()) .append(nextChar()) .append(nextChar()) .append(nextChar()) } catch(_: IllegalStateException) { throw KlaxonException("EOF reached in unicode char after: u$unicodeChar") } val intValue = try { java.lang.Integer.parseInt(unicodeChar.toString(), 16) } catch(e: NumberFormatException) { throw KlaxonException("Failed to parse unicode char: u$unicodeChar") } currentValue.append(intValue.toChar()) } else -> currentValue.append(c) } } '"' -> break@loop else -> if (lenient) { if (! c.isJavaIdentifierPart()) { expectName = false break@loop } else { currentValue.append(c) nextChar() } } else { currentValue.append(c) } } } while (true) token = Value(currentValue.toString()) } else if ('{' == c) { token = LEFT_BRACE expectName = true } else if ('}' == c) { token = RIGHT_BRACE expectName = false } else if ('[' == c) { token = LEFT_BRACKET expectName = false } else if (']' == c) { token = RIGHT_BRACKET expectName = false } else if (':' == c) { token = COLON expectName = false } else if (',' == c) { token = COMMA expectName = true } else if (!isDone) { while (isValueLetter(c)) { currentValue.append(c) if (isDone || !isValueLetter(peekChar())) { break } else { c = nextChar() } } val v = currentValue.toString() if (NUMERIC.matcher(v).matches()) { token = try { Value(java.lang.Integer.parseInt(v)) } catch (e: NumberFormatException){ try { Value(java.lang.Long.parseLong(v)) } catch(e: NumberFormatException) { Value(java.math.BigInteger(v)) } } } else if (DOUBLE.matcher(v).matches()) { token = Value(java.lang.Double.parseDouble(v)) } else if ("true" == v.toLowerCase()) { token = Value(true) } else if ("false" == v.toLowerCase()) { token = Value(false) } else if (v == "null") { token = Value(null) } else { throw KlaxonException("Unexpected character at position ${index-1}" + ": '$c' (ASCII: ${c.toInt()})'") } } else { token = EOF } return token } private fun log(s: String) { if (Debug.verbose) println(s) } }
apache-2.0
5507fd9a64369a2f01a05ac143fc9e4f
33.009259
117
0.410291
5.209929
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FileCopyPackagingElementEntityImpl.kt
1
10688
// 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.api 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.ModifiableWorkspaceEntity 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.EntityLink 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.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FileCopyPackagingElementEntityImpl(val dataSource: FileCopyPackagingElementEntityData) : FileCopyPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val filePath: VirtualFileUrl get() = dataSource.filePath override val renamedOutputFileName: String? get() = dataSource.renamedOutputFileName override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: FileCopyPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<FileCopyPackagingElementEntity>(), FileCopyPackagingElementEntity.Builder { constructor() : this(FileCopyPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FileCopyPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // 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().isFilePathInitialized()) { error("Field FileOrDirectoryPackagingElementEntity#filePath should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as FileCopyPackagingElementEntity this.entitySource = dataSource.entitySource this.filePath = dataSource.filePath this.renamedOutputFileName = dataSource.renamedOutputFileName if (parents != null) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var filePath: VirtualFileUrl get() = getEntityData().filePath set(value) { checkModificationAllowed() getEntityData().filePath = value changedProperty.add("filePath") val _diff = diff if (_diff != null) index(this, "filePath", value) } override var renamedOutputFileName: String? get() = getEntityData().renamedOutputFileName set(value) { checkModificationAllowed() getEntityData().renamedOutputFileName = value changedProperty.add("renamedOutputFileName") } override fun getEntityData(): FileCopyPackagingElementEntityData = result ?: super.getEntityData() as FileCopyPackagingElementEntityData override fun getEntityClass(): Class<FileCopyPackagingElementEntity> = FileCopyPackagingElementEntity::class.java } } class FileCopyPackagingElementEntityData : WorkspaceEntityData<FileCopyPackagingElementEntity>() { lateinit var filePath: VirtualFileUrl var renamedOutputFileName: String? = null fun isFilePathInitialized(): Boolean = ::filePath.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FileCopyPackagingElementEntity> { val modifiable = FileCopyPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): FileCopyPackagingElementEntity { return getCached(snapshot) { val entity = FileCopyPackagingElementEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FileCopyPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FileCopyPackagingElementEntity(filePath, entitySource) { this.renamedOutputFileName = [email protected] this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } 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::class != other::class) return false other as FileCopyPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.filePath != other.filePath) return false if (this.renamedOutputFileName != other.renamedOutputFileName) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FileCopyPackagingElementEntityData if (this.filePath != other.filePath) return false if (this.renamedOutputFileName != other.renamedOutputFileName) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + renamedOutputFileName.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + renamedOutputFileName.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.filePath?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
9191dc56c0fc783d12ce5dac9fe19dff
39.029963
176
0.716879
5.712453
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveTypeAliasToTopLevelFix.kt
1
1573
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeAlias import org.jetbrains.kotlin.psi.psiUtil.parents class MoveTypeAliasToTopLevelFix(element: KtTypeAlias) : KotlinQuickFixAction<KtTypeAlias>(element) { override fun getText() = KotlinBundle.message("fix.move.typealias.to.top.level") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val typeAlias = element ?: return val parents = typeAlias.parents.toList().reversed() val containingFile = parents.firstOrNull() as? KtFile ?: return val target = parents.getOrNull(1) ?: return containingFile.addAfter(typeAlias, target) containingFile.addAfter(KtPsiFactory(project).createNewLine(2), target) typeAlias.delete() } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = (diagnostic.psiElement as? KtTypeAlias)?.let { MoveTypeAliasToTopLevelFix(it) } } }
apache-2.0
f4091553e6ca35624c53aed51480e0de
46.666667
158
0.767959
4.520115
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/JpsCompilationRunner.kt
1
21911
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "HardCodedStringLiteral") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.diagnostic.DefaultLogger import com.intellij.openapi.diagnostic.Logger import com.intellij.util.containers.MultiMap import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.groovy.compiler.rt.GroovyRtConstants import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope import org.jetbrains.jps.api.GlobalOptions import org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter import org.jetbrains.jps.build.Standalone import org.jetbrains.jps.builders.BuildTarget import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.gant.Log4jFileLoggerFactory import org.jetbrains.jps.incremental.MessageHandler import org.jetbrains.jps.incremental.artifacts.ArtifactBuildTargetType import org.jetbrains.jps.incremental.artifacts.impl.ArtifactSorter import org.jetbrains.jps.incremental.artifacts.impl.JpsArtifactUtil import org.jetbrains.jps.incremental.dependencies.DependencyResolvingBuilder import org.jetbrains.jps.incremental.groovy.JpsGroovycRunner import org.jetbrains.jps.incremental.messages.* import org.jetbrains.jps.model.artifact.JpsArtifact import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.artifact.elements.JpsModuleOutputPackagingElement import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import java.beans.Introspector import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import java.util.function.BiConsumer internal class JpsCompilationRunner(private val context: CompilationContext) { private val compilationData = context.compilationData companion object { init { // Unset 'groovy.target.bytecode' which was possibly set by outside context // to get target bytecode version from corresponding java compiler settings System.clearProperty(GroovyRtConstants.GROOVY_TARGET_BYTECODE) setSystemPropertyIfUndefined(GlobalOptions.COMPILE_PARALLEL_OPTION, "true") setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_PARALLELISM_PROPERTY, Runtime.getRuntime().availableProcessors().toString()) setSystemPropertyIfUndefined(GlobalOptions.USE_DEFAULT_FILE_LOGGING_OPTION, "false") setSystemPropertyIfUndefined(JpsGroovycRunner.GROOVYC_IN_PROCESS, "true") setSystemPropertyIfUndefined(GroovyRtConstants.GROOVYC_ASM_RESOLVING_ONLY, "false") // https://youtrack.jetbrains.com/issue/IDEA-269280 System.setProperty("aether.connector.resumeDownloads", "false") // Produces Kotlin compiler incremental cache which can be reused later. // Unrelated to force rebuild controlled by JPS. setSystemPropertyIfUndefined("kotlin.incremental.compilation", "true") // Required for JPS Portable Caches setSystemPropertyIfUndefined(JavaBackwardReferenceIndexWriter.PROP_KEY, "true") } } init { setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_ENABLED_PROPERTY, (context.options.resolveDependenciesMaxAttempts > 1).toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_DELAY_MS_PROPERTY, context.options.resolveDependenciesDelayMs.toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_MAX_ATTEMPTS_PROPERTY, context.options.resolveDependenciesMaxAttempts.toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_BACKOFF_LIMIT_MS_PROPERTY, TimeUnit.MINUTES.toMillis(15).toString()) } fun buildModules(modules: List<JpsModule>) { val names = LinkedHashSet<String>() spanBuilder("collect dependencies") .setAttribute(AttributeKey.longKey("moduleCount"), modules.size.toLong()) .use { span -> val requiredDependencies = ArrayList<String>() for (module in modules) { requiredDependencies.clear() for (dependency in getModuleDependencies(module = module, includeTests = false)) { if (names.add(dependency)) { requiredDependencies.add(dependency) } } if (!requiredDependencies.isEmpty()) { span.addEvent("required dependencies", Attributes.of( AttributeKey.stringKey("module"), module.name, AttributeKey.stringArrayKey("module"), java.util.List.copyOf(requiredDependencies) )) } } } runBuild(moduleSet = names, allModules = false, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = false) } fun buildModulesWithoutDependencies(modules: Collection<JpsModule>, includeTests: Boolean) { runBuild(moduleSet = modules.map { it.name }, allModules = false, artifactNames = emptyList(), includeTests = includeTests, resolveProjectDependencies = false) } fun resolveProjectDependencies() { runBuild(moduleSet = emptyList(), allModules = false, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = true) } fun buildModuleTests(module: JpsModule) { runBuild(getModuleDependencies(module = module, includeTests = true), allModules = false, artifactNames = emptyList(), includeTests = true, resolveProjectDependencies = false) } fun buildAll() { runBuild(moduleSet = emptyList(), allModules = true, artifactNames = emptyList(), includeTests = true, resolveProjectDependencies = false) } fun buildProduction() { runBuild(moduleSet = emptyList(), allModules = true, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = false) } @Deprecated("", ReplaceWith("buildArtifacts(artifactNames = artifactNames, buildIncludedModules = true)")) fun buildArtifacts(artifactNames: Set<String>) { buildArtifacts(artifactNames = artifactNames, buildIncludedModules = true) } fun buildArtifacts(artifactNames: Set<String>, buildIncludedModules: Boolean) { val artifacts = getArtifactsWithIncluded(artifactNames) val missing = artifactNames.filter { name -> artifacts.none { it.name == name } } if (missing.isNotEmpty()) { context.messages.error("Artifacts aren't configured in the project: " + missing.joinToString()) } artifacts.forEach { if (context.compilationData.builtArtifacts.contains(it.name) && it.outputFilePath?.let(Path::of)?.let(Files::exists) != true) { context.messages.warning("${it.name} is expected to be already built at ${it.outputFilePath} but it's missing") context.compilationData.builtArtifacts.remove(it.name) } } val modules = if (buildIncludedModules) getModulesIncludedInArtifacts(artifacts) else emptyList() runBuild(moduleSet = modules, allModules = false, artifactNames = artifacts.map { it.name }, includeTests = false, resolveProjectDependencies = false) val failedToBeBuilt = artifacts.filter { if (it.outputFilePath?.let(Path::of)?.let(Files::exists) == true) { context.messages.info("${it.name} was successfully built at ${it.outputFilePath}") false } else { context.messages.warning("${it.name} is expected to be built at ${it.outputFilePath}") true } } if (failedToBeBuilt.isNotEmpty()) { compileMissingArtifactsModules(failedToBeBuilt) } } // FIXME: workaround for sporadically missing build artifacts, to be investigated private fun compileMissingArtifactsModules(artifacts: Collection<JpsArtifact>) { val modules = getModulesIncludedInArtifacts(artifacts) require(modules.isNotEmpty()) { "No modules found for artifacts ${artifacts.map { it.name }}" } artifacts.forEach { context.compilationData.builtArtifacts.remove(it.name) } context.messages.block("Compiling modules for missing artifacts: ${modules.joinToString()}") { runBuild(moduleSet = modules, allModules = false, artifactNames = artifacts.map { it.name }, includeTests = false, resolveProjectDependencies = false) } artifacts.forEach { if (it.outputFilePath?.let(Path::of)?.let(Files::exists) == false) { context.messages.error("${it.name} is expected to be built at ${it.outputFilePath}") } } } fun getModulesIncludedInArtifacts(artifactNames: Collection<String>): Collection<String> = getModulesIncludedInArtifacts(getArtifactsWithIncluded(artifactNames)) private fun getModulesIncludedInArtifacts(artifacts: Collection<JpsArtifact>): Set<String> { val modulesSet: MutableSet<String> = LinkedHashSet() for (artifact in artifacts) { JpsArtifactUtil.processPackagingElements(artifact.rootElement) { element -> if (element is JpsModuleOutputPackagingElement) { modulesSet.addAll(getModuleDependencies(context.findRequiredModule(element.moduleReference.moduleName), false)) } true } } return modulesSet } private fun getArtifactsWithIncluded(artifactNames: Collection<String>): Set<JpsArtifact> { val artifacts = JpsArtifactService.getInstance().getArtifacts(context.project).filter { it.name in artifactNames } return ArtifactSorter.addIncludedArtifacts(artifacts) } private fun setupAdditionalBuildLogging(compilationData: JpsCompilationData) { val categoriesWithDebugLevel = compilationData.categoriesWithDebugLevel val buildLogFile = compilationData.buildLogFile try { val factory = Log4jFileLoggerFactory(buildLogFile.toFile(), categoriesWithDebugLevel) JpsLoggerFactory.fileLoggerFactory = factory context.messages.info("Build log (${if (categoriesWithDebugLevel.isEmpty()) "info" else "debug level for $categoriesWithDebugLevel"}) " + "will be written to $buildLogFile") } catch (t: Throwable) { context.messages.warning("Cannot setup additional logging to $buildLogFile.absolutePath: ${t.message}") } } private fun runBuild(moduleSet: Collection<String>, allModules: Boolean, artifactNames: Collection<String>, includeTests: Boolean, resolveProjectDependencies: Boolean) { messageHandler = JpsMessageHandler(context) if (context.options.compilationLogEnabled) { setupAdditionalBuildLogging(compilationData) } Logger.setFactory(JpsLoggerFactory::class.java) val forceBuild = !context.options.incrementalCompilation val scopes = ArrayList<TargetTypeBuildScope>() for (type in JavaModuleBuildTargetType.ALL_TYPES) { if (includeTests || !type.isTests) { val namesToCompile = if (allModules) context.project.modules.mapTo(mutableListOf()) { it.name } else moduleSet.toMutableList() if (type.isTests) { namesToCompile.removeAll(compilationData.compiledModuleTests) compilationData.compiledModuleTests.addAll(namesToCompile) } else { namesToCompile.removeAll(compilationData.compiledModules) compilationData.compiledModules.addAll(namesToCompile) } if (namesToCompile.isEmpty()) { continue } val builder = TargetTypeBuildScope.newBuilder().setTypeId(type.typeId).setForceBuild(forceBuild) if (allModules) { scopes.add(builder.setAllTargets(true).build()) } else { scopes.add(builder.addAllTargetId(namesToCompile).build()) } } } if (resolveProjectDependencies && !compilationData.projectDependenciesResolved) { scopes.add(TargetTypeBuildScope.newBuilder().setTypeId("project-dependencies-resolving") .setForceBuild(false).setAllTargets(true).build()) } val artifactsToBuild = artifactNames - compilationData.builtArtifacts if (!artifactsToBuild.isEmpty()) { val builder = TargetTypeBuildScope.newBuilder().setTypeId(ArtifactBuildTargetType.INSTANCE.typeId).setForceBuild(forceBuild) scopes.add(builder.addAllTargetId(artifactsToBuild).build()) } val compilationStart = System.nanoTime() spanBuilder("compilation") .setAttribute("scope", "${if (allModules) "all" else moduleSet.size} modules") .setAttribute("includeTests", includeTests) .setAttribute("artifactsToBuild", artifactsToBuild.size.toLong()) .setAttribute("resolveProjectDependencies", resolveProjectDependencies) .setAttribute("modules", moduleSet.joinToString(separator = ", ")) .setAttribute("incremental", context.options.incrementalCompilation) .setAttribute("includeTests", includeTests) .setAttribute("cacheDir", compilationData.dataStorageRoot.toString()) .useWithScope { Standalone.runBuild({ context.projectModel }, compilationData.dataStorageRoot.toFile(), messageHandler, scopes, false) } if (!messageHandler.errorMessagesByCompiler.isEmpty) { for ((key, value) in messageHandler.errorMessagesByCompiler.entrySet()) { @Suppress("UNCHECKED_CAST") context.messages.compilationErrors(key, value as List<String>) } throw RuntimeException("Compilation failed") } else if (!compilationData.statisticsReported) { messageHandler.printPerModuleCompilationStatistics(compilationStart) context.messages.reportStatisticValue("Compilation time, ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStart).toString()) compilationData.statisticsReported = true } if (!artifactsToBuild.isEmpty()) { compilationData.builtArtifacts.addAll(artifactsToBuild) } if (resolveProjectDependencies) { compilationData.projectDependenciesResolved = true } } } private class JpsLoggerFactory : Logger.Factory { companion object { var fileLoggerFactory: Logger.Factory? = null } override fun getLoggerInstance(category: String): Logger = BackedLogger(category, fileLoggerFactory?.getLoggerInstance(category)) } private class JpsMessageHandler(private val context: CompilationContext) : MessageHandler { val errorMessagesByCompiler = MultiMap.createConcurrent<String, String>() val compilationStartTimeForTarget = ConcurrentHashMap<String, Long>() val compilationFinishTimeForTarget = ConcurrentHashMap<String, Long>() var progress = (-1.0).toFloat() override fun processMessage(message: BuildMessage) { val text = message.messageText when (message.kind) { BuildMessage.Kind.ERROR, BuildMessage.Kind.INTERNAL_BUILDER_ERROR -> { val compilerName: String val messageText: String if (message is CompilerMessage) { compilerName = message.compilerName val sourcePath = message.sourcePath messageText = if (sourcePath != null) { """ $sourcePath${if (message.line != -1L) ":" + message.line else ""}: $text """.trimIndent() } else { text } } else { compilerName = "" messageText = text } errorMessagesByCompiler.putValue(compilerName, messageText) } BuildMessage.Kind.WARNING -> context.messages.warning(text) BuildMessage.Kind.INFO, BuildMessage.Kind.JPS_INFO -> if (message is BuilderStatisticsMessage) { val buildKind = if (context.options.incrementalCompilation) " (incremental)" else "" context.messages.reportStatisticValue("Compilation time '${message.builderName}'$buildKind, ms", message.elapsedTimeMs.toString()) val sources = message.numberOfProcessedSources context.messages.reportStatisticValue("Processed files by '${message.builderName}'$buildKind", sources.toString()) if (!context.options.incrementalCompilation && sources > 0) { context.messages.reportStatisticValue("Compilation time per file for '${message.builderName}', ms", String.format(Locale.US, "%.2f", message.elapsedTimeMs.toDouble() / sources)) } } else if (!text.isEmpty()) { context.messages.info(text) } BuildMessage.Kind.PROGRESS -> if (message is ProgressMessage) { progress = message.done message.currentTargets?.let { reportProgress(it.targets, message.messageText) } } else if (message is BuildingTargetProgressMessage) { val targets = message.targets val target = targets.first() val targetId = "${target.id}${if (targets.size > 1) " and ${targets.size} more" else ""} (${target.targetType.typeId})" if (message.eventType == BuildingTargetProgressMessage.Event.STARTED) { reportProgress(targets, "") compilationStartTimeForTarget.put(targetId, System.nanoTime()) } else { compilationFinishTimeForTarget.put(targetId, System.nanoTime()) } } BuildMessage.Kind.OTHER, null -> context.messages.warning(text) } } fun printPerModuleCompilationStatistics(compilationStart: Long) { if (compilationStartTimeForTarget.isEmpty()) { return } Files.newBufferedWriter(context.paths.buildOutputDir.resolve("log/compilation-time.csv")).use { out -> compilationFinishTimeForTarget.forEach(BiConsumer { k, v -> val startTime = compilationStartTimeForTarget.getValue(k) - compilationStart val finishTime = v - compilationStart out.write("$k,$startTime,$finishTime\n") }) } val buildMessages = context.messages buildMessages.info("Compilation time per target:") val compilationTimeForTarget = compilationFinishTimeForTarget.entries.map { it.key to (it.value - compilationStartTimeForTarget.getValue(it.key)) } buildMessages.info(" average: ${String.format("%.2f", ((compilationTimeForTarget.sumOf { it.second }.toDouble()) / compilationTimeForTarget.size) / 1000000)}ms") val topTargets = compilationTimeForTarget.sortedBy { it.second }.asReversed().take(10) buildMessages.info(" top ${topTargets.size} targets by compilation time:") for (entry in topTargets) { buildMessages.info(" ${entry.first}: ${TimeUnit.NANOSECONDS.toMillis(entry.second)}ms") } } fun reportProgress(targets: Collection<BuildTarget<*>>, targetSpecificMessage: String) { val targetsString = targets.joinToString(separator = ", ") { Introspector.decapitalize(it.presentableName) } val progressText = if (progress >= 0) " (${(100 * progress).toInt()}%)" else "" val targetSpecificText = if (targetSpecificMessage.isEmpty()) "" else ", $targetSpecificMessage" context.messages.progress("Compiling$progressText: $targetsString$targetSpecificText") } } private class BackedLogger(category: String?, private val fileLogger: Logger?) : DefaultLogger(category) { override fun error(@Nls message: @NonNls String?, t: Throwable?, vararg details: String) { if (t == null) { messageHandler.processMessage(CompilerMessage(COMPILER_NAME, BuildMessage.Kind.ERROR, message)) } else { messageHandler.processMessage(CompilerMessage.createInternalBuilderError(COMPILER_NAME, t)) } fileLogger?.error(message, t, *details) } override fun warn(message: @NonNls String?, t: Throwable?) { messageHandler.processMessage(CompilerMessage(COMPILER_NAME, BuildMessage.Kind.WARNING, message)) fileLogger?.warn(message, t) } override fun info(message: String?) { fileLogger?.info(message) } override fun info(message: String?, t: Throwable?) { fileLogger?.info(message, t) } override fun isDebugEnabled(): Boolean { return fileLogger != null && fileLogger.isDebugEnabled } override fun debug(message: String?) { fileLogger?.debug(message) } override fun debug(t: Throwable?) { fileLogger?.debug(t) } override fun debug(message: String?, t: Throwable?) { fileLogger?.debug(message, t) } override fun isTraceEnabled(): Boolean { return fileLogger != null && fileLogger.isTraceEnabled } override fun trace(message: String?) { fileLogger?.trace(message) } override fun trace(t: Throwable?) { fileLogger?.trace(t) } } private lateinit var messageHandler: JpsMessageHandler @Nls private const val COMPILER_NAME = "build runner" private fun setSystemPropertyIfUndefined(name: String, value: String) { if (System.getProperty(name) == null) { System.setProperty(name, value) } } private fun getModuleDependencies(module: JpsModule, includeTests: Boolean): Set<String> { var enumerator = JpsJavaExtensionService.dependencies(module).recursively() if (!includeTests) { enumerator = enumerator.productionOnly() } return enumerator.modules.mapTo(HashSet()) { it.name } }
apache-2.0
4c308a4ef4b0f1ae9937d19282f4a084
42.562624
165
0.706814
4.742641
false
false
false
false
Kiskae/DiscordKt
implementation/src/main/kotlin/net/serverpeon/discord/internal/data/model/RoleNode.kt
1
3935
package net.serverpeon.discord.internal.data.model import net.serverpeon.discord.interaction.Editable import net.serverpeon.discord.internal.data.EventInput import net.serverpeon.discord.internal.rest.WrappedId import net.serverpeon.discord.internal.rest.retro.Guilds.EditRoleRequest import net.serverpeon.discord.internal.toFuture import net.serverpeon.discord.internal.ws.data.inbound.Guilds import net.serverpeon.discord.model.DiscordId import net.serverpeon.discord.model.PermissionSet import net.serverpeon.discord.model.Role import java.awt.Color import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger class RoleNode(private val root: DiscordNode, private val guild: GuildNode, override val id: DiscordId<Role>, override var name: String, override val imported: Boolean, override var grouped: Boolean, override var permissions: PermissionSet, override var color: Color, var position: Int) : Role, EventInput<RoleNode> { private val changeId = AtomicInteger(0) override fun edit(): Role.Edit { guild.selfAsMember.checkPermission(guild, PermissionSet.Permission.MANAGE_ROLES) return Transaction(color, grouped, name, permissions) } override fun delete(): CompletableFuture<Void> { guild.selfAsMember.checkPermission(guild, PermissionSet.Permission.MANAGE_ROLES) return root.api.Guilds.deleteRole(WrappedId(guild.id), WrappedId(id)).toFuture() } override fun toString(): String { return "Role(id=$id, name='$name', imported=$imported, grouped=$grouped, permissions=$permissions, color=$color)" } override fun handler(): EventInput.Handler<RoleNode> { return RoleEventHandler } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as RoleNode if (guild != other.guild) return false if (id != other.id) return false return true } override fun hashCode(): Int { var result = guild.hashCode() result += 31 * result + id.hashCode() return result } private object RoleEventHandler : EventInput.Handler<RoleNode> { override fun guildRoleUpdate(target: RoleNode, e: Guilds.Roles.Update) { target.changeId.incrementAndGet() e.role.let { target.color = it.color target.permissions = it.permissions target.grouped = it.hoist target.name = it.name target.position = it.position } } } private inner class Transaction(override var color: Color, override var grouped: Boolean, override var name: String, override var permissions: PermissionSet) : Role.Edit { private var completed = AtomicBoolean(false) private val changeIdAtInit = changeId.get() override fun commit(): CompletableFuture<Role> { if (changeId.compareAndSet(changeIdAtInit, changeIdAtInit + 1)) { throw Editable.ResourceChangedException(this@RoleNode) } else if (completed.getAndSet(true)) { throw IllegalStateException("Don't call complete() twice") } else { return root.api.Guilds.editRole(WrappedId(guild.id), WrappedId(id), EditRoleRequest( color = color, hoist = grouped, name = name, permissions = permissions )).toFuture().thenApply { Builder.role(it, guild) } } } } }
mit
3e8c7a52b0b3ef2ee76a10e876e54dd8
37.213592
121
0.625413
4.876084
false
false
false
false
allotria/intellij-community
plugins/git4idea/tests/git4idea/tests/GitChangeProviderNestedRepositoriesTest.kt
4
4312
// 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 git4idea.tests import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcsUtil.VcsUtil import git4idea.test.* import java.io.File class GitChangeProviderNestedRepositoriesTest : GitPlatformTest() { private lateinit var dirtyScopeManager: VcsDirtyScopeManager @Throws(Exception::class) public override fun setUp() { super.setUp() dirtyScopeManager = VcsDirtyScopeManager.getInstance(project) } override fun getDebugLogCategories() = super.getDebugLogCategories().plus(listOf("#com.intellij.openapi.vcs.changes", "#GitStatus")) // IDEA-149060 fun `test changes in 3-level nested root`() { // 1. prepare roots and files val repo = createRepository(project, projectPath) val childRepo = repo.createSubRepository("child") val grandChildRepo = childRepo.createSubRepository("grand") createFileStructure(repo.root, "a.txt") createFileStructure(childRepo.root, "in1.txt", "in2.txt", "grand/inin1.txt", "grand/inin2.txt") repo.addCommit("committed file structure") childRepo.addCommit("committed file structure") grandChildRepo.addCommit("committed file structure") refresh() // 2. make changes and make sure they are recognized cd(repo) overwrite("a.txt", "321") overwrite("child/in1.txt", "321") overwrite("child/in2.txt", "321") overwrite("child/grand/inin1.txt", "321") dirtyScopeManager.markEverythingDirty() changeListManager.ensureUpToDate() assertFileStatus("a.txt", FileStatus.MODIFIED) assertFileStatus("child/in1.txt", FileStatus.MODIFIED) assertFileStatus("child/in2.txt", FileStatus.MODIFIED) assertFileStatus("child/grand/inin1.txt", FileStatus.MODIFIED) // refresh parent root recursively dirtyScopeManager.filePathsDirty(listOf(getFilePath("child/in1.txt")), listOf(VcsUtil.getFilePath(repo.root))) changeListManager.ensureUpToDate() assertFileStatus("a.txt", FileStatus.MODIFIED) assertFileStatus("child/in1.txt", FileStatus.MODIFIED) assertFileStatus("child/in2.txt", FileStatus.MODIFIED) assertFileStatus("child/grand/inin1.txt", FileStatus.MODIFIED) assertEquals(4, changeListManager.allChanges.size) } fun `test new rename forcing old file path refresh`() { // 1. prepare roots and files val repo = createRepository(project, projectPath) cd(repo) touch("a.txt", "some file content") repo.addCommit("committed file structure") rm("a.txt") touch("b.txt", "some file content") dirtyScopeManager.markEverythingDirty() changeListManager.ensureUpToDate() assertEquals(1, changeListManager.allChanges.size) assertFileStatus("a.txt", FileStatus.DELETED) assertFileStatus("b.txt", FileStatus.UNKNOWN) git("add b.txt") dirtyScopeManager.fileDirty(getFilePath("b.txt")) changeListManager.ensureUpToDate() assertEquals(2, changeListManager.allChanges.size) assertFileStatus("a.txt", FileStatus.DELETED) assertFileStatus("b.txt", FileStatus.ADDED) git("add a.txt") dirtyScopeManager.fileDirty(getFilePath("a.txt")) changeListManager.ensureUpToDate() assertEquals(1, changeListManager.allChanges.size) assertFileStatus("b.txt", FileStatus.MODIFIED) } private fun assertFileStatus(relativePath: String, fileStatus: FileStatus) { if (fileStatus == FileStatus.UNKNOWN) { val vf = getVirtualFile(relativePath) assertTrue("$vf is not known as unversioned", changeListManager.isUnversioned(vf)) } else { val change = changeListManager.getChange(getFilePath(relativePath)) assertEquals(fileStatus, change?.fileStatus ?: FileStatus.NOT_CHANGED) } } private fun getVirtualFile(relativePath: String): VirtualFile { return VfsUtil.findFileByIoFile(File(projectPath, relativePath), true)!! } private fun getFilePath(relativePath: String): FilePath { return VcsUtil.getFilePath(File(projectPath, relativePath)) } }
apache-2.0
e7d702b0bc9ef4cefba79b019c037bdb
34.636364
140
0.742115
4.368794
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequests.kt
2
23677
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api import com.intellij.util.ThrowableConvertor import org.jetbrains.plugins.github.api.GithubApiRequest.* import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.api.data.request.* import org.jetbrains.plugins.github.api.util.GHSchemaPreview import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.api.util.GithubApiUrlQueryBuilder import java.awt.Image /** * Collection of factory methods for API requests used in plugin * TODO: improve url building (DSL?) */ object GithubApiRequests { object CurrentUser : Entity("/user") { @JvmStatic fun get(server: GithubServerPath) = get(getUrl(server, urlSuffix)) @JvmStatic fun get(url: String) = Get.json<GithubAuthenticatedUser>(url).withOperationName("get profile information") @JvmStatic fun getAvatar(url: String) = object : Get<Image>(url) { override fun extractResult(response: GithubApiResponse): Image { return response.handleBody(ThrowableConvertor { GithubApiContentHelper.loadImage(it) }) } }.withOperationName("get profile avatar") object Repos : Entity("/repos") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, type, visibility, affiliation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null): GithubApiRequest<GithubResponsePage<GithubRepo>> { if (type != Type.DEFAULT && (visibility != Visibility.DEFAULT || affiliation != Affiliation.DEFAULT)) { throw IllegalArgumentException("Param 'type' should not be used together with 'visibility' or 'affiliation'") } return get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(type.toString(), visibility.toString(), affiliation.toString(), pagination?.toString().orEmpty()))) } @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get user repositories") @JvmStatic fun create(server: GithubServerPath, name: String, description: String, private: Boolean, autoInit: Boolean? = null) = Post.json<GithubRepo>(getUrl(server, CurrentUser.urlSuffix, urlSuffix), GithubRepoRequest(name, description, private, autoInit)) .withOperationName("create user repository") } object Orgs : Entity("/orgs") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) fun get(url: String) = Get.jsonPage<GithubOrg>(url).withOperationName("get user organizations") } object RepoSubs : Entity("/subscriptions") { @JvmStatic fun pages(server: GithubServerPath) = GithubApiPagesLoader.Request(get(server), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get repository subscriptions") } } object Organisations : Entity("/orgs") { object Repos : Entity("/repos") { @JvmStatic fun pages(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, organisation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get organisation repositories") @JvmStatic fun create(server: GithubServerPath, organisation: String, name: String, description: String, private: Boolean) = Post.json<GithubRepo>(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix), GithubRepoRequest(name, description, private, null)) .withOperationName("create organisation repository") } } object Repos : Entity("/repos") { @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String) = Get.Optional.json<GithubRepoDetailed>(getUrl(server, urlSuffix, "/$username/$repoName")) .withOperationName("get information for repository $username/$repoName") @JvmStatic fun delete(server: GithubServerPath, username: String, repoName: String) = delete(getUrl(server, urlSuffix, "/$username/$repoName")).withOperationName("delete repository $username/$repoName") @JvmStatic fun delete(url: String) = Delete.json<Unit>(url).withOperationName("delete repository at $url") object Branches : Entity("/branches") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubBranch>(url).withOperationName("get branches") @JvmStatic fun getProtection(repository: GHRepositoryCoordinates, branchName: String): GithubApiRequest<GHBranchProtectionRules> = Get.json(getUrl(repository, urlSuffix, "/$branchName", "/protection"), GHSchemaPreview.BRANCH_PROTECTION.mimeType) } object Commits : Entity("/commits") { @JvmStatic fun compare(repository: GHRepositoryCoordinates, refA: String, refB: String) = Get.json<GHCommitsCompareResult>(getUrl(repository, "/compare/$refA...$refB")).withOperationName("compare refs") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, ref: String) = object : Get<String>(getUrl(repository, urlSuffix, "/$ref"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { it.reader().use { it.readText() } }) } }.withOperationName("get diff for ref") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, refA: String, refB: String) = object : Get<String>(getUrl(repository, "/compare/$refA...$refB"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { it.reader().use { it.readText() } }) } }.withOperationName("get diff between refs") } object Forks : Entity("/forks") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String) = Post.json<GithubRepo>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), Any()) .withOperationName("fork repository $username/$repoName for cuurent user") @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get forks") } object Assignees : Entity("/assignees") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUser>(url).withOperationName("get assignees") } object Labels : Entity("/labels") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueLabel>(url).withOperationName("get assignees") } object Collaborators : Entity("/collaborators") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUserWithPermissions>(url).withOperationName("get collaborators") @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, collaborator: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", collaborator)) } object Issues : Entity("/issues") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, body: String? = null, milestone: Long? = null, labels: List<String>? = null, assignees: List<String>? = null) = Post.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubCreateIssueRequest(title, body, milestone, labels, assignees)) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null) = GithubApiPagesLoader.Request(get(server, username, repoName, state, assignee), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("state", state); param("assignee", assignee); param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssue>(url).withOperationName("get issues in repository") @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, id: String) = Get.Optional.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id)) @JvmStatic fun updateState(server: GithubServerPath, username: String, repoName: String, id: String, open: Boolean) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubChangeIssueStateRequest(if (open) "open" else "closed")) @JvmStatic fun updateAssignees(server: GithubServerPath, username: String, repoName: String, id: String, assignees: Collection<String>) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubAssigneesCollectionRequest(assignees)) object Comments : Entity("/comments") { @JvmStatic fun create(repository: GHRepositoryCoordinates, issueId: Long, body: String) = create(repository.serverPath, repository.repositoryPath.owner, repository.repositoryPath.repository, issueId.toString(), body) @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, issueId: String, body: String) = Post.json<GithubIssueCommentWithHtml>( getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubCreateIssueCommentRequest(body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, issueId: String) = GithubApiPagesLoader.Request(get(server, username, repoName, issueId), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, issueId: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for issue") } object Labels : Entity("/labels") { @JvmStatic fun replace(server: GithubServerPath, username: String, repoName: String, issueId: String, labels: Collection<String>) = Put.jsonList<GithubIssueLabel>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubLabelsCollectionRequest(labels)) } } object PullRequests : Entity("/pulls") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, description: String, head: String, base: String) = Post.json<GithubPullRequestDetailed>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubPullRequestRequest(title, description, head, base)) .withOperationName("create pull request in $username/$repoName") @JvmStatic fun update(serverPath: GithubServerPath, username: String, repoName: String, number: Long, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(getUrl(serverPath, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/$number"), GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request $number") @JvmStatic fun update(url: String, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(url, GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request") @JvmStatic fun merge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.merge)) .withOperationName("merge pull request ${number}") @JvmStatic fun squashMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.squash)) .withOperationName("squash and merge pull request ${number}") @JvmStatic fun rebaseMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRebaseRequest(headSha)) .withOperationName("rebase and merge pull request ${number}") @JvmStatic fun getListETag(server: GithubServerPath, repoPath: GHRepositoryPath) = object : Get<String?>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(GithubRequestPagination(pageSize = 1)) })) { override fun extractResult(response: GithubApiResponse) = response.findHeader("ETag") }.withOperationName("get pull request list ETag") object Reviewers : Entity("/requested_reviewers") { @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Post.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) @JvmStatic fun remove(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Delete.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) } } } object Gists : Entity("/gists") { @JvmStatic fun create(server: GithubServerPath, contents: List<GithubGistRequest.FileContent>, description: String, public: Boolean) = Post.json<GithubGist>(getUrl(server, urlSuffix), GithubGistRequest(contents, description, public)) .withOperationName("create gist") @JvmStatic fun get(server: GithubServerPath, id: String) = Get.Optional.json<GithubGist>(getUrl(server, urlSuffix, "/$id")) .withOperationName("get gist $id") @JvmStatic fun delete(server: GithubServerPath, id: String) = Delete.json<Unit>(getUrl(server, urlSuffix, "/$id")) .withOperationName("delete gist $id") } object Search : Entity("/search") { object Issues : Entity("/issues") { @JvmStatic fun pages(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?) = GithubApiPagesLoader.Request(get(server, repoPath, state, assignee, query), ::get) @JvmStatic fun get(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", GithubApiSearchQueryBuilder.searchQuery { qualifier("repo", repoPath?.toString().orEmpty()) qualifier("state", state) qualifier("assignee", assignee) query(query) }) param(pagination) })) @JvmStatic fun get(server: GithubServerPath, query: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", query) param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonSearchPage<GithubSearchedIssue>(url).withOperationName("search issues in repository") } } object Auth : Entity("/authorizations") { @JvmStatic fun create(server: GithubServerPath, scopes: List<String>, note: String) = Post.json<GithubAuthorization>(getUrl(server, urlSuffix), GithubAuthorizationCreateRequest(scopes, note, null)) .withOperationName("create authorization $note") @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubAuthorization>(url) .withOperationName("get authorizations") @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) } abstract class Entity(val urlSuffix: String) private fun getUrl(server: GithubServerPath, suffix: String) = server.toApiUrl() + suffix private fun getUrl(repository: GHRepositoryCoordinates, vararg suffixes: String) = getUrl(repository.serverPath, Repos.urlSuffix, "/", repository.repositoryPath.toString(), *suffixes) fun getUrl(server: GithubServerPath, vararg suffixes: String) = StringBuilder(server.toApiUrl()).append(*suffixes).toString() private fun getQuery(vararg queryParts: String): String { val builder = StringBuilder() for (part in queryParts) { if (part.isEmpty()) continue if (builder.isEmpty()) builder.append("?") else builder.append("&") builder.append(part) } return builder.toString() } }
apache-2.0
de9b7e9266dfe65e1b15cce33866170d
46.931174
140
0.659205
5.177564
false
false
false
false
allotria/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/EventLogNotificationProxy.kt
2
1713
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.util.Disposer import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal class EventLogNotificationProxy(private val writer: StatisticsEventLogWriter, private val recorderId: String) : StatisticsEventLogWriter { override fun log(logEvent: LogEvent) { EventLogNotificationService.notifySubscribers(logEvent, recorderId) writer.log(logEvent) } override fun getActiveFile(): EventLogFile? = writer.getActiveFile() override fun getLogFilesProvider(): EventLogFilesProvider = writer.getLogFilesProvider() override fun cleanup() = writer.cleanup() override fun rollOver() = writer.rollOver() override fun dispose() = Disposer.dispose(writer) } @ApiStatus.Internal object EventLogNotificationService { private val subscribers = MultiMap.createConcurrent<String, (LogEvent) -> Unit>() fun notifySubscribers(logEvent: LogEvent, recorderId: String) { val copyOnWriteArraySet = subscribers[recorderId] for (onLogEvent in copyOnWriteArraySet) { onLogEvent(logEvent) } } fun subscribe(subscriber: (LogEvent) -> Unit, recorderId: String) { if (!getPluginInfo(subscriber.javaClass).isDevelopedByJetBrains()) { return } subscribers.putValue(recorderId, subscriber) } fun unsubscribe(subscriber: (LogEvent) -> Unit, recorderId: String) { subscribers.remove(recorderId, subscriber) } }
apache-2.0
6c878866b997ffe3f392faaef4989a62
33.979592
140
0.756567
4.680328
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/completion/ml/MLWeigherUtil.kt
1
3068
// 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.codeInsight.completion.ml import com.intellij.codeInsight.completion.CompletionLocation import com.intellij.codeInsight.completion.CompletionService import com.intellij.codeInsight.completion.CompletionSorter import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementWeigher import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.ForceableComparable import com.intellij.psi.Weigher import com.intellij.psi.WeigherExtensionPoint import com.intellij.psi.WeighingService import org.jetbrains.annotations.ApiStatus import kotlin.streams.asSequence @ApiStatus.Internal object MLWeigherUtil { const val ML_COMPLETION_WEIGHER_ID = "ml_weigh" @JvmStatic fun findMLWeigher(location: CompletionLocation): LookupElementWeigher? { val weigher: Weigher<Any, Any> = ApplicationManager.getApplication().extensionArea.getExtensionPoint<Any>("com.intellij.weigher") .extensions().asSequence() .filterIsInstance<WeigherExtensionPoint>() .filter { ML_COMPLETION_WEIGHER_ID == it.id && it.key == "completion" } .firstOrNull()?.instance ?: return null return MLWeigherWrapper(weigher, location) } @JvmStatic fun addWeighersToNonDefaultSorter(sorter: CompletionSorter, location: CompletionLocation, vararg weigherIds: String): CompletionSorter { // from BaseCompletionService.defaultSorter var result = sorter for (weigher in WeighingService.getWeighers(CompletionService.RELEVANCE_KEY)) { val id = weigher.toString() if (weigherIds.contains(id)) { result = result.weigh(object : LookupElementWeigher(id, true, false) { override fun weigh(element: LookupElement): Comparable<*>? { val weigh = weigher.weigh(element, location) ?: return DummyWeigherComparableDelegate.EMPTY return DummyWeigherComparableDelegate(weigh) } }) } } return result } private class MLWeigherWrapper(private val mlWeigher: Weigher<Any, Any>, private val location: CompletionLocation) : LookupElementWeigher(ML_COMPLETION_WEIGHER_ID) { override fun weigh(element: LookupElement): Comparable<*>? { return mlWeigher.weigh(element, location) } } } private class DummyWeigherComparableDelegate(private val weigh: Comparable<*>?) : Comparable<DummyWeigherComparableDelegate>, ForceableComparable { companion object { val EMPTY = DummyWeigherComparableDelegate(null) } override fun force() { if (weigh is ForceableComparable) { (weigh as ForceableComparable).force() } } override operator fun compareTo(other: DummyWeigherComparableDelegate): Int { return 0 } override fun toString(): String { return weigh?.toString() ?: "" } }
apache-2.0
6cbce5c8fe8c2ce64897a52504794038
38.333333
140
0.719035
4.698315
false
false
false
false
allotria/intellij-community
plugins/gradle/java/testSources/importing/GradleAttachSourcesProviderIntegrationTest.kt
1
2773
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.importing import com.intellij.openapi.application.runReadAction import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.OrderRootType import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.util.GradleAttachSourcesProvider import org.junit.Test class GradleAttachSourcesProviderIntegrationTest : GradleImportingTestCase() { @Test fun `test download sources dynamic task`() { importProject(GradleBuildScriptBuilderEx() .withJavaPlugin() .withIdeaPlugin() .withJUnit("4.12") .addPrefix("idea.module.downloadSources = false") .generate()) assertModules("project", "project.main", "project.test") val junitLib: LibraryOrderEntry = getModuleLibDeps("project.test", "Gradle: junit:junit:4.12").single() assertThat(junitLib.getRootFiles(OrderRootType.CLASSES)) .hasSize(1) .allSatisfy { assertEquals("junit-4.12.jar", it.name) } val psiFile = runReadAction { JavaPsiFacade.getInstance(myProject).findClass("junit.framework.Test", GlobalSearchScope.allScope(myProject))!!.containingFile } val output = mutableListOf<String>() val listener = object : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { output += text } } try { ExternalSystemProgressNotificationManager.getInstance().addNotificationListener(listener) val callback = GradleAttachSourcesProvider().getActions(mutableListOf(junitLib), psiFile) .single() .perform(mutableListOf(junitLib)) .apply { waitFor(5000) } assertNull(callback.error) } finally { ExternalSystemProgressNotificationManager.getInstance().removeNotificationListener(listener) } assertThat(output) .filteredOn{ it.startsWith("Sources were downloaded to") } .hasSize(1) .allSatisfy { assertThat(it).endsWith("junit-4.12-sources.jar") } assertThat(junitLib.getRootFiles(OrderRootType.SOURCES)) .hasSize(1) .allSatisfy { assertEquals("junit-4.12-sources.jar", it.name) } } }
apache-2.0
2b28eff38b565c872da4da4d81016199
42.34375
140
0.736026
4.839442
false
true
false
false
leafclick/intellij-community
platform/workspaceModel-core-tests/test/com/intellij/workspace/api/SerializationInProxyBasedStorageTest.kt
1
2504
package com.intellij.workspace.api import com.intellij.testFramework.rules.TempDirectory import org.junit.Rule import org.junit.Test internal data class SampleDataClassForSerialization( val url: VirtualFileUrl ) internal interface SampleEntityForSerialization : TypedEntity, ReferableTypedEntity { val parent: SampleEntity val booleanProperty: Boolean val stringProperty: String val stringListProperty: List<String> val children: List<SampleEntity> val fileProperty: VirtualFileUrl val dataClasses: List<SampleDataClassForSerialization> } internal interface ModifiableSampleEntityForSerialization : SampleEntityForSerialization, ModifiableTypedEntity<SampleEntityForSerialization> { override var booleanProperty: Boolean override var stringProperty: String override var stringListProperty: MutableList<String> override var fileProperty: VirtualFileUrl override var parent: SampleEntity override var dataClasses: List<SampleDataClassForSerialization> override var children: List<SampleEntity> } internal data class SampleEntityForSerializationSource(val name: String) : EntitySource class SerializationInProxyBasedStorageTest { @Rule @JvmField val tempDir = TempDirectory() @Test fun empty() { verifySerializationRoundTrip(TypedEntityStorageBuilder.create().toStorage()) } @Test fun smoke() { val tempFolder = tempDir.newFolder() val builder = TypedEntityStorageBuilder.create() val sampleEntity = builder.addSampleEntity("ggg", SampleEntitySource("y"), true, mutableListOf("5", "6"), tempFolder.toVirtualFileUrl()) val child1 = builder.addSampleEntity("c1") val child2 = builder.addSampleEntity("c2") builder.addEntity(ModifiableSampleEntityForSerialization::class.java, SampleEntityForSerializationSource("xx")) { parent = sampleEntity booleanProperty = true stringListProperty = mutableListOf("1", "2") children = listOf(child1, child2) fileProperty = tempFolder.toVirtualFileUrl() dataClasses = listOf( SampleDataClassForSerialization(tempFolder.toVirtualFileUrl()), SampleDataClassForSerialization(tempFolder.toVirtualFileUrl()) ) } verifySerializationRoundTrip(builder.toStorage()) } @Test fun singletonEntitySource() { val builder = TypedEntityStorageBuilder.create() builder.addSampleEntity("c2", source = SingletonEntitySource) verifySerializationRoundTrip(builder.toStorage()) } object SingletonEntitySource : EntitySource }
apache-2.0
70e4f84a9304a4309de57dcc6319f6d9
33.777778
143
0.781949
5.271579
false
true
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/poi/POIViewModel.kt
1
21334
package org.mtransit.android.ui.poi // //import android.content.Context //import android.hardware.SensorEvent //import android.location.Location //import android.widget.AbsListView //import androidx.annotation.WorkerThread //import androidx.lifecycle.LiveData //import androidx.lifecycle.MutableLiveData //import androidx.lifecycle.SavedStateHandle //import androidx.lifecycle.distinctUntilChanged //import androidx.lifecycle.liveData //import androidx.lifecycle.map //import androidx.lifecycle.switchMap //import androidx.lifecycle.viewModelScope //import dagger.hilt.android.lifecycle.HiltViewModel //import kotlinx.coroutines.Dispatchers //import kotlinx.coroutines.launch //import org.mtransit.android.ad.IAdManager //import org.mtransit.android.ad.IAdManager.RewardedAdListener //import org.mtransit.android.analytics.AnalyticsEvents //import org.mtransit.android.analytics.AnalyticsEventsParamsProvider //import org.mtransit.android.analytics.IAnalyticsManager //import org.mtransit.android.commons.Constants //import org.mtransit.android.commons.LocationUtils //import org.mtransit.android.commons.MTLog //import org.mtransit.android.commons.data.News //import org.mtransit.android.commons.data.POI //import org.mtransit.android.commons.data.POIStatus //import org.mtransit.android.commons.data.Schedule.ScheduleStatusFilter //import org.mtransit.android.commons.data.ServiceUpdate //import org.mtransit.android.commons.provider.NewsProviderContract //import org.mtransit.android.commons.provider.POIProviderContract //import org.mtransit.android.data.AgencyProperties //import org.mtransit.android.data.POIManager //import org.mtransit.android.data.ScheduleProviderProperties //import org.mtransit.android.datasource.DataSourceRequestManager //import org.mtransit.android.datasource.DataSourcesRepository //import org.mtransit.android.provider.FavoriteRepository //import org.mtransit.android.provider.location.MTLocationProvider //import org.mtransit.android.provider.sensor.MTSensorManager //import org.mtransit.android.provider.sensor.MTSensorManager.CompassListener //import org.mtransit.android.provider.sensor.MTSensorManager.SensorTaskCompleted //import org.mtransit.android.task.ServiceUpdateLoader //import org.mtransit.android.task.ServiceUpdateLoader.ServiceUpdateLoaderListener //import org.mtransit.android.task.StatusLoader //import org.mtransit.android.task.StatusLoader.StatusLoaderListener //import org.mtransit.android.ui.MTViewModelWithLocation //import org.mtransit.android.ui.news.details.NewsDetailsViewModel //import org.mtransit.android.ui.view.common.Event //import org.mtransit.android.ui.view.common.IActivity //import org.mtransit.android.ui.view.common.PairMediatorLiveData //import org.mtransit.android.util.DegreeUtils.convertToPositive360Degree //import org.mtransit.android.util.UITimeUtils //import java.util.concurrent.TimeUnit //import javax.inject.Inject // //@HiltViewModel //class POIViewModel @Inject constructor( // savedStateHandle: SavedStateHandle, // private val dataSourcesRepository: DataSourcesRepository, // private val dataSourceRequestManager: DataSourceRequestManager, // private val favoriteRepository: FavoriteRepository, // private val sensorManager: MTSensorManager, // private val locationProvider: MTLocationProvider, // private val adManager: IAdManager, // private val analyticsManager: IAnalyticsManager, // private val statusLoader: StatusLoader, // private val serviceUpdateLoader: ServiceUpdateLoader, // // private val lclPrefRepository: LocalPreferenceRepository, //) : MTViewModelWithLocation() { // // // companion object { // private val LOG_TAG = POIViewModel::class.java.simpleName // // internal const val EXTRA_AUTHORITY = "extra_agency_authority" // internal const val EXTRA_POI_UUID = "extra_poi_uuid" // } // // override fun getLogTag(): String = LOG_TAG // // val uuid: LiveData<String?> = savedStateHandle.getLiveData<String?>(EXTRA_POI_UUID).distinctUntilChanged() // // private val _authority: LiveData<String?> = savedStateHandle.getLiveData<String?>(NewsDetailsViewModel.EXTRA_AUTHORITY).distinctUntilChanged() // // val agency: LiveData<AgencyProperties?> = this._authority.switchMap { authority -> // authority?.let { // this.dataSourcesRepository.readingAgency(authority) // #onModulesUpdated // } ?: MutableLive Data(null) // } // // private val _favoriteUpdatedTrigger = MutableLiveData(0) // // val dataSourceRemovedEvent = MutableLiveData<Event<Boolean>>() // // private val _poimMutable = MutableLiveData<POIManager?>(null) // // private val _poim: LiveData<POIManager?> = _poimMutable.distinctUntilChanged() // // val poimTrigger: LiveData<Any?> = PairMediatorLiveData(agency, uuid).map { (agency, uuid) -> // use agency // #onModulesUpdated // //liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { // // emit(getPOIManager(agency, uuid)) // loadPOIManager(agency, uuid) // // emit(null) // // } // null // } // // @Deprecated(message = "use smaller data") // val poim: LiveData<POIManager?> = _poim // FIXME remove // // val poimV: POIManager? // get() = this._poim.value // // val poi: LiveData<POI?> = _poim.map { // it?.poi // }.distinctUntilChanged() // // val poiDistanceAndString: LiveData<Pair<Float, CharSequence?>?> = _poim.map { poim -> // // locationProvider.updateDistanceWithString(poim, deviceLocation) // // this._poimMutable.value = poim // poim?.let { it.distance to it.distanceString } // }.distinctUntilChanged() // // val poiDistanceTrigger = PairMediatorLiveData(_poim, deviceLocation).map { (poim, deviceLocation) -> // locationProvider.updateDistanceWithString(poim, deviceLocation) // this._poimMutable.value = poim // } // // fun updatePOIDistanceWithString( // poim: POIManager? = this._poimMutable.value, // deviceLocation: Location? = this.deviceLocation.value, // ) { // // TO DO this does not work, poim is not updated!!!!!! // // val poim = this._poimMutable.value // locationProvider.updateDistanceWithString(poim ?: return, deviceLocation) // this._poimMutable.value = poim // } // // val poiStatus: LiveData<POIStatus?> = _poim.map { // it?.statusOrNull // }.distinctUntilChanged() // // fun onStatusLoaded(status: POIStatus) { // MTLog.v(this, "onStatusLoaded($status)") // val poim = this._poimMutable.value // poim?.setStatus(status) // this._poimMutable.value = poim // } // // fun refreshStatus(context: Context?, statusLoaderListener: StatusLoaderListener) { // val poim = this._poimMutable.value // poim?.apply { // setStatusLoaderListener(statusLoaderListener) // getStatus(context, statusLoader) // } // this._poimMutable.value = poim // } // // fun onServiceUpdatesLoaded(serviceUpdates: List<ServiceUpdate>?) { // val poim = this._poimMutable.value // poim?.setServiceUpdates(serviceUpdates) // this._poimMutable.value = poim // } // // fun refreshServiceUpdate(context: Context?, serviceUpdateLoaderListener: ServiceUpdateLoaderListener) { // val poim = this._poimMutable.value // poim?.apply { // setServiceUpdateLoaderListener(serviceUpdateLoaderListener) // getServiceUpdates(context, serviceUpdateLoader) // } // this._poimMutable.value = poim // } // // val poiServiceUpdates: LiveData<List<ServiceUpdate>?> = _poim.map { // it?.serviceUpdatesOrNull // }.distinctUntilChanged() // // .distinctUntilChanged() // // val poiTypeAndStatus: LiveData<Pair<Int, Int>?> = _poim.map { // it?.let { it.poi.type to it.statusType } // }.distinctUntilChanged() // // private fun loadPOIManager(agency: AgencyProperties?, uuid: String?) { // viewModelScope.launch(context = viewModelScope.coroutineContext + Dispatchers.IO) { // _poimMutable.postValue(getPOIManager(agency, uuid)) // } // } // // private fun getPOIManager(agency: AgencyProperties?, uuid: String?): POIManager? { // if (uuid.isNullOrEmpty()) { // MTLog.d(this, "getPOI() > SKIP (no uuid)") // return null // } // if (agency == null) { // if (_poim.value != null) { // MTLog.d(this, "getPOI() > data source removed (no more agency)") // dataSourceRemovedEvent.postValue(Event(true)) // } // return null // } // return this.dataSourceRequestManager.findPOIM(agency.authority, POIProviderContract.Filter.getNewUUIDFilter(uuid)) // ?.apply { // isInFocus = true // setScheduleMaxDataRequests(ScheduleStatusFilter.DATA_REQUEST_MONTHS) // resetLastFindTimestamps() // // updatePOIDistanceWithString(poim = this) // locationProvider.updateDistanceWithString(this, deviceLocation.value) // } ?: run { // MTLog.d(this, "getPOI() > SKIP (data source removed!)") // dataSourceRemovedEvent.postValue(Event(true)) // null // } // } // // val poiColor: LiveData<Int?> = PairMediatorLiveData(poi, agency).map { (poi, agency) -> // // poim?.getColor { agency } // poi?.let { POIManager.getNewColor(it) { agency } } // }.distinctUntilChanged() // // val poimOneLineDescription: LiveData<String?> = PairMediatorLiveData(agency, poi).map { (agency, poi) -> // poi?.let { POIManager.getNewOneLineDescription(it) { agency } } // }.distinctUntilChanged() // // fun onShowDirectionClick() { // analyticsManager.logEvent(AnalyticsEvents.OPENED_GOOGLE_MAPS_TRIP_PLANNER) // } // // fun onShowedAppUpdatePOI(agency: AgencyProperties? = this.agency.value) { // val params = AnalyticsEventsParamsProvider() // agency?.let { // params.put(AnalyticsEvents.Params.PKG, it.pkg) // } // analyticsManager.logEvent(AnalyticsEvents.SHOWED_APP_UPDATE_POI, params) // } // // fun onHiddenAppUpdatePOI(agency: AgencyProperties? = this.agency.value) { // val params = AnalyticsEventsParamsProvider() // agency?.let { // params.put(AnalyticsEvents.Params.PKG, it.pkg) // } // analyticsManager.logEvent(AnalyticsEvents.HIDDEN_APP_UPDATE_POI, params) // } // // fun onClickAppUpdatePOI(agency: AgencyProperties? = this.agency.value) { // val params = AnalyticsEventsParamsProvider() // agency?.let { // params.put(AnalyticsEvents.Params.PKG, it.pkg) // } // analyticsManager.logEvent(AnalyticsEvents.CLICK_APP_UPDATE_POI, params) // } // // private val _rewardedAdStatus = MutableLiveData(RewardedAdStatus(this.adManager)) // val rewardedAdStatus: LiveData<RewardedAdStatus?> = _rewardedAdStatus.distinctUntilChanged() // // // private val _rewardedAdNowUntilInMs = MutableLiveData(if (this.adManager.isRewardedNow) this.adManager.rewardedUntilInMs else null) // // val rewardedAdNowUntilInMs: LiveData<Long?> = _rewardedAdNowUntilInMs.distinctUntilChanged() // // // // private val _rewardedAdAmount = MutableLiveData(this.adManager.rewardedAdAmount) // // val rewardedAdAmount: LiveData<Int?> = _rewardedAdAmount.distinctUntilChanged() // // // // private val _rewardedAdAvailableToShow = MutableLiveData(this.adManager.isRewardedAdAvailableToShow) // // val rewardedAdAvailableToShow: LiveData<Boolean?> = _rewardedAdAvailableToShow.distinctUntilChanged() // // // fun onResumeRewardedAd(activity: IActivity, rewardedAdListener: RewardedAdListener) { // this.adManager.setRewardedAdListener(rewardedAdListener) // this.adManager.refreshRewardedAdStatus(activity) // } // // fun onPauseRewardedAd() { // adManager.setRewardedAdListener(null) // } // // fun onRewardedAdStatusChanged() { // // _rewardedAdNowUntilInMs.postValue(if (this.adManager.isRewardedNow) this.adManager.rewardedUntilInMs else null) // // _rewardedAdAmount.postValue(this.adManager.rewardedAdAmount) // // _rewardedAdAvailableToShow.postValue(this.adManager.isRewardedAdAvailableToShow) // _rewardedAdStatus.postValue(RewardedAdStatus(this.adManager)) // } // // fun skipRewardedAd() = this.adManager.shouldSkipRewardedAd() // // fun onRewardedAdClick(activity: IActivity): Boolean? { // if (activity.activity == null) { // MTLog.w(this, "onRewardedAdClick() > skip (no view or no activity)") // return false // hide // } // if (!this.adManager.isRewardedAdAvailableToShow) { // MTLog.w(this, "onRewardedAdClick() > skip (no ad available)") // return false // hide // } // val adShowTriggered = this.adManager.showRewardedAd(activity) // return if (!adShowTriggered) false else null // } // // val poiFavorite: LiveData<Boolean?> = PairMediatorLiveData(_favoriteUpdatedTrigger, poi).switchMap { (_, poi) -> // liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { // poi?.let { // emit(getPOIFavorite(poi)) // } ?: run { emit(null) } // } // } // // fun getPOIFavorite(poi: POI): Boolean { // return POIManager.isFavoritable(poi) && favoriteRepository.isFavorite(poi.uuid) // } // // // fun onFavoriteUpdated() { // _favoriteUpdatedTrigger.value = (_favoriteUpdatedTrigger.value ?: 0) + 1 // } // // // fun onAddRemoveFavoriteClick(activity: Activity, listener: FavoriteUpdateListener) { // // val poim: POIManager = this.poim.value ?: return // // if (poim.isFavoritable) { // // favoriteRepository.addRe // // } // // } // // // @WorkerThread // fun isFavorite(uuid: String): Boolean { // MTLog.v(this, "isFavorite($uuid)") // val poiUUID = this.uuid.value // if (poiUUID == uuid) { // poiFavorite.value?.let { // return it // } // } // return favoriteRepository.isFavorite(uuid) // } // // val locationDeclination: LiveData<Float?> = deviceLocation.map { newDeviceLocation -> // newDeviceLocation?.let { sensorManager.getLocationDeclination(it) } // } // // private val _accelerometerValues = FloatArray(3) // // private val _magneticFieldValues = FloatArray(3) // // fun onSensorChanged(activity: IActivity, event: SensorEvent, compassListener: CompassListener) { // sensorManager.checkForCompass(activity, event, this._accelerometerValues, this._magneticFieldValues, compassListener) // } // // private val _lastCompassInDegree = MutableLiveData<Int?>(null) // val lastCompassInDegree: LiveData<Int?> = _lastCompassInDegree // // // private var _lastCompassInDegree: Int? = null // private var _lastCompassChanged = -1L // // fun updateCompass(orientation: Float, force: Boolean, onSensorTaskCompleted: SensorTaskCompleted) { // val now = UITimeUtils.currentTimeMillis() // val roundedOrientation = convertToPositive360Degree(orientation.toInt()) // val deviceLocation = this.deviceLocation.value // sensorManager.updateCompass( // force, // deviceLocation, // roundedOrientation, // now, // AbsListView.OnScrollListener.SCROLL_STATE_IDLE, // this._lastCompassChanged, // this._lastCompassInDegree.value, // Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS, // onSensorTaskCompleted // ) // } // // fun onSensorTaskCompleted(result: Boolean, roundedOrientation: Int, now: Long) { // if (result) { // this._lastCompassInDegree.postValue(roundedOrientation) // this._lastCompassChanged = now // // if (this.deviceLocation.value != null && this._lastCompassInDegree ?: -1 >= 0) { // // this.compassUpdatesEnabled && // // val poim: POIManager = getPoimOrNull() // // if (poim != null) { // // POIViewController.updatePOIDistanceAndCompass(getPOIView(getView()), poim, this) // // } // // } // } // } // // val latestNewsArticleList: LiveData<List<News>?> = poi.switchMap { poi -> // liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { // emit(getLatestNewsArticles(poi)) // } // } // // private fun getLatestNewsArticles(poi: POI?): List<News>? { // MTLog.v(this, "getLatestNewsArticles($poi)") // if (poi == null) { // return null // } // val nowInMs = UITimeUtils.currentTimeMillis() // val last2Weeks = nowInMs - TimeUnit.DAYS.toMillis(14L) // val newsFilter = NewsProviderContract.Filter // .getNewTargetFilter(poi) // .setMinCreatedAtInMs(last2Weeks) // // val allNews = mutableListOf<News>() // val allNews = dataSourcesRepository.getNewsProviders(poi) // .mapNotNull { newsProvider -> // this.dataSourceRequestManager.findNews(newsProvider, newsFilter) // }.flatten() // .toMutableList() // allNews.sortWith(News.NEWS_SEVERITY_COMPARATOR) // // allNews.sortedWith(compareBy({ it.severity }, { it.createdAtInMs })) // val selectedNews = mutableListOf<News>() // var noteworthiness = 1L // while (selectedNews.isEmpty() && noteworthiness < 10L) { // for (news in allNews) { // if (news.createdAtInMs + news.noteworthyInMs * noteworthiness < nowInMs) { // continue // news too old to be worthy // } // selectedNews.add(0, news) // break // found news article // } // noteworthiness++ // } // return selectedNews // } // // val scheduleProviders: LiveData<List<ScheduleProviderProperties>> = _authority.switchMap { authority -> // this.dataSourcesRepository.readingScheduleProviders(authority) // } // // // like Home screen (no infinite loading like in Nearby screen) // val nearbyPOIs: LiveData<List<POIManager>?> = poi.switchMap { poi -> // liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { // emit(getNearbyPOIs(poi)) // } // } // // private fun getNearbyPOIs(poi: POI?): List<POIManager>? { // return getNearbyPOIs(poi?.authority, poi?.lat, poi?.lng) // } // // private fun getNearbyPOIs( // authority: String? = poi.value?.authority, // lat: Double? = poi.value?.lat, // lng: Double? = poi.value?.lng, // excludedUUID: String? = poi.value?.uuid // ): List<POIManager>? { // MTLog.v(this, "getNearbyPOIs()") // if (Constants.FORCE_NEARBY_POI_LIST_OFF) { // return null // } // if (authority == null || lat == null || lng == null) { // return null // } // val nearbyPOIs = mutableListOf<POIManager>() // val ad = LocationUtils.getNewDefaultAroundDiff() // // TODO latter ? var lastTypeAroundDiff: Double? = null // val maxSize = LocationUtils.MAX_POI_NEARBY_POIS_LIST // val minCoverageInMeters = LocationUtils.MIN_POI_NEARBY_POIS_LIST_COVERAGE_IN_METERS.toFloat() // while (true) { // val aroundDiff = ad.aroundDiff // val maxDistance = LocationUtils.getAroundCoveredDistanceInMeters(lat, lng, aroundDiff) // val poiFilter = POIProviderContract.Filter.getNewAroundFilter(lat, lng, aroundDiff).apply { // addExtra(POIProviderContract.POI_FILTER_EXTRA_AVOID_LOADING, true) // // addExtra(GTFSProviderContract.POI_FILTER_EXTRA_DESCENT_ONLY, false) // } // dataSourceRequestManager.findPOIMs(authority, poiFilter) // ?.filterNot { it.poi.uuid == excludedUUID } // ?.let { agencyPOIs -> // LocationUtils.updateDistance(agencyPOIs, lat, lng) // LocationUtils.removeTooFar(agencyPOIs, maxDistance) // LocationUtils.removeTooMuchWhenNotInCoverage(agencyPOIs, minCoverageInMeters, maxSize) // nearbyPOIs.addAll(agencyPOIs) // } // if (nearbyPOIs.size > LocationUtils.MIN_NEARBY_LIST // enough POI // || LocationUtils.searchComplete(lat, lng, aroundDiff) // world explored // ) { // // && LocationUtils.getAroundCoveredDistanceInMeters(lat, lng, aroundDiff) >= minCoverageInMeters // break // } else { // // TODO latter ? lastTypeAroundDiff = if (nearbyPOIs.isNullOrEmpty()) aroundDiff else null // LocationUtils.incAroundDiff(ad) // } // } // return nearbyPOIs.take(LocationUtils.MAX_POI_NEARBY_POIS_LIST) // } //}
apache-2.0
a5cc8bd70083d2729cf4bed5cdbaea45
43.355509
148
0.650839
4.043594
false
false
false
false
DanielMartinus/Konfetti
konfetti/xml/src/main/java/nl/dionsegijn/konfetti/xml/DrawShapes.kt
1
1874
package nl.dionsegijn.konfetti.xml import android.graphics.BlendMode import android.graphics.BlendModeColorFilter import android.graphics.Canvas import android.graphics.Paint import android.graphics.PorterDuff import android.os.Build import nl.dionsegijn.konfetti.core.models.Shape import nl.dionsegijn.konfetti.core.models.Shape.Circle import nl.dionsegijn.konfetti.core.models.Shape.Circle.rect import nl.dionsegijn.konfetti.core.models.Shape.DrawableShape import nl.dionsegijn.konfetti.core.models.Shape.Rectangle import nl.dionsegijn.konfetti.core.models.Shape.Square /** * Draw a shape to `canvas`. Implementations are expected to draw within a square of size * `size` and must vertically/horizontally center their asset if it does not have an equal width * and height. */ fun Shape.draw(canvas: Canvas, paint: Paint, size: Float) { when (this) { Square -> canvas.drawRect(0f, 0f, size, size, paint) Circle -> { rect.set(0f, 0f, size, size) canvas.drawOval(rect, paint) } is Rectangle -> { val height = size * heightRatio val top = (size - height) / 2f canvas.drawRect(0f, top, size, top + height, paint) } is DrawableShape -> { if (tint) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { drawable.colorFilter = BlendModeColorFilter(paint.color, BlendMode.SRC_IN) } else { drawable.setColorFilter(paint.color, PorterDuff.Mode.SRC_IN) } } else { drawable.alpha = paint.alpha } val height = (size * heightRatio).toInt() val top = ((size - height) / 2f).toInt() drawable.setBounds(0, top, size.toInt(), top + height) drawable.draw(canvas) } } }
isc
c49e3d9fc530d02ba854635609a54920
35.038462
96
0.633938
4.091703
false
false
false
false
alibaba/transmittable-thread-local
ttl2-compatible/src/test/java/com/alibaba/demo/ttl/TtlWrapperDemo.kt
2
1244
package com.alibaba.demo.ttl import com.alibaba.ttl.TransmittableThreadLocal import com.alibaba.ttl.TtlCallable import com.alibaba.ttl.TtlRunnable import java.util.concurrent.Callable import java.util.concurrent.Executors /** * @author Jerry Lee (oldratlee at gmail dot com) */ fun main() { val executorService = Executors.newCachedThreadPool() val context = TransmittableThreadLocal<String>() context.set("value-set-in-parent") println("[parent thread] set ${context.get()}") ///////////////////////////////////// // Runnable / TtlRunnable ///////////////////////////////////// val task = Runnable { println("[child thread] get ${context.get()} in Runnable") } val ttlRunnable = TtlRunnable.get(task)!! executorService.submit(ttlRunnable).get() ///////////////////////////////////// // Callable / TtlCallable ///////////////////////////////////// val call = Callable { println("[child thread] get ${context.get()} in Callable") 42 } val ttlCallable = TtlCallable.get(call)!! executorService.submit(ttlCallable).get() ///////////////////////////////////// // cleanup ///////////////////////////////////// executorService.shutdown() }
apache-2.0
eee4bad560f0f655e94b700986b70553
28.619048
86
0.558682
4.784615
false
false
false
false