content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ch.softappeal.yass.transport import ch.softappeal.yass.remote.* import ch.softappeal.yass.remote.session.* import ch.softappeal.yass.serialize.* fun packetSerializer(messageSerializer: Serializer) = object : Serializer { override fun read(reader: Reader): Packet { val requestNumber = reader.readInt() return if (isEndPacket(requestNumber)) EndPacket else Packet(requestNumber, messageSerializer.read(reader) as Message) } override fun write(writer: Writer, value: Any?) { val packet = value as Packet if (packet.isEnd) writer.writeInt(EndRequestNumber) else { writer.writeInt(packet.requestNumber) messageSerializer.write(writer, packet.message) } } }
kotlin/yass/main/ch/softappeal/yass/transport/PacketSerializer.kt
3618682742
/* * 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.jetbrains.micropython.settings import com.intellij.application.options.ModuleAwareProjectConfigurable import com.intellij.openapi.module.Module import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project /** * @author vlan */ class MicroPythonProjectConfigurable(project: Project) : ModuleAwareProjectConfigurable<Configurable>(project, "MicroPython", null) { override fun createModuleConfigurable(module: Module?) = MicroPythonModuleConfigurable(module!!) }
src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonProjectConfigurable.kt
1992926033
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger /** * A breakpoint in the browser JavaScript virtual machine. The `set*` * method invocations will not take effect until * [.flush] is called. */ public interface Breakpoint { companion object { /** * This value is used when the corresponding parameter is absent */ public val EMPTY_VALUE: Int = -1 /** * A breakpoint has this ID if it does not reflect an actual breakpoint in a * JavaScript VM debugger. */ public val INVALID_ID: Int = -1 } public val target: BreakpointTarget public val line: Int /** * @return whether this breakpoint is enabled */ /** * Sets whether this breakpoint is enabled. * Requires subsequent [.flush] call. */ public var enabled: Boolean /** * Sets the breakpoint condition as plain JavaScript (`null` to clear). * Requires subsequent [.flush] call. * @param condition the new breakpoint condition */ public var condition: String? public val isResolved: Boolean /** * Be aware! V8 doesn't provide reliable debugger API, so, sometimes actual locations is empty - in this case this methods return "true". * V8 debugger doesn't report about resolved breakpoint if it is happened after initial breakpoint set. So, you cannot trust "actual locations". */ public open fun isActualLineCorrect(): Boolean = true } /** * Visitor interface that includes all extensions. */ public interface TargetExtendedVisitor<R> : FunctionSupport.Visitor<R>, ScriptRegExpSupportVisitor<R>
platform/script-debugger/backend/src/org/jetbrains/debugger/Breakpoint.kt
2403299596
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.action.manager import android.content.Context import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.action.ActionFile import jp.hazuki.yuzubrowser.legacy.action.SingleAction import java.io.File import java.io.IOException import java.util.* class SoftButtonActionArrayFile(private val FOLDER_NAME: String, private val id: Int) : ActionFile() { val list: MutableList<SoftButtonActionFile> = ArrayList() fun add(action: SingleAction) { val array = SoftButtonActionFile() array.press.add(action) list.add(array) } fun add(action: SingleAction, longPress: SingleAction) { val array = SoftButtonActionFile() array.press.add(action) array.lpress.add(longPress) list.add(array) } fun add(action: SoftButtonActionFile) { val array = SoftButtonActionFile() array.press.addAll(action.press) array.lpress.addAll(action.lpress) array.up.addAll(action.up) array.down.addAll(action.down) array.left.addAll(action.left) array.right.addAll(action.right) list.add(array) } operator fun get(no: Int): SoftButtonActionFile { return list[no] } fun getActionList(no: Int): SoftButtonActionFile { if (no < 0) throw IllegalArgumentException("no < 0") expand(no + 1) return list[no] } fun expand(size: Int): Int { if (size < 0) throw IllegalArgumentException("size < 0") for (i in list.size - size..-1) list.add(SoftButtonActionFile()) return list.size } override fun getFile(context: Context): File { return File(context.getDir(FOLDER_NAME, Context.MODE_PRIVATE), id.toString() + ".dat") } override fun reset() { list.clear() } @Throws(IOException::class) override fun load(reader: JsonReader): Boolean { if (reader.peek() != JsonReader.Token.BEGIN_ARRAY) return false reader.beginArray() while (reader.hasNext()) { val action = SoftButtonActionFile() if (!action.load(reader)) { return if (reader.peek() == JsonReader.Token.END_ARRAY) break else false } list.add(action) } reader.endArray() return true } @Throws(IOException::class) override fun write(writer: JsonWriter): Boolean { writer.beginArray() list.forEach { it.write(writer) } writer.endArray() return true } companion object { private const val serialVersionUID = -8451972340596132660L } }
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/manager/SoftButtonActionArrayFile.kt
3457615976
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.core.exception import kotlin.reflect.KClass /** * Thrown when a service is attempted to be retrieved, but none exists. */ class UnregisteredServiceException(type: KClass<*>): Exception("No service is registered for " + type.qualifiedName)
rpk-core/src/main/kotlin/com/rpkit/core/exception/UnregisteredServiceException.kt
1609057492
package io.kotlinthree.extension import android.view.View /** * Created by jameson on 12/19/15. */ fun <T : View> View.findView(id: Int): T = findViewById(id) as T fun View.slideExit() { if (translationY == 0f) animate().translationY(-height.toFloat()) } fun View.slideEnter() { if (translationY < 0f) animate().translationY(0f) }
app/src/main/java/io/kotlinthree/extension/KView.kt
1667785109
package org.evomaster.core.taint import org.evomaster.client.java.controller.api.dto.AdditionalInfoDto import org.evomaster.client.java.instrumentation.shared.StringSpecialization import org.evomaster.client.java.instrumentation.shared.StringSpecializationInfo import org.evomaster.client.java.instrumentation.shared.TaintInputName import org.evomaster.client.java.instrumentation.shared.TaintType import org.evomaster.core.database.DbAction import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.problem.rest.RestActionBuilderV3 import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.search.Action import org.evomaster.core.search.Individual import org.evomaster.core.search.gene.collection.* import org.evomaster.core.search.gene.interfaces.TaintableGene import org.evomaster.core.search.gene.regex.RegexGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.service.Randomness import org.slf4j.Logger import org.slf4j.LoggerFactory object TaintAnalysis { private val log: Logger = LoggerFactory.getLogger(TaintAnalysis::class.java) fun getRegexTaintedValues(action: Action): List<String> { return action.seeTopGenes() .flatMap { it.flatView() } .filterIsInstance<StringGene>() .filter { it.getSpecializationGene() != null && it.getSpecializationGene() is RegexGene } .map { it.getSpecializationGene()!!.getValueAsRawString() } } /** * Analyze if any tainted value was used in the SUT in some special way. * If that happened, then such info would end up in the AdditionalInfoDto. * Then, we would extend the genotype (but not the phenotype!!!) of this test. */ fun doTaintAnalysis(individual: Individual, additionalInfoList: List<AdditionalInfoDto>, randomness: Randomness) { if (individual.seeMainExecutableActions().size < additionalInfoList.size) { throw IllegalArgumentException("Less main actions than info entries") } if (log.isTraceEnabled) { log.trace("do taint analysis for individual which contains dbactions: {} and rest actions: {}", individual.seeInitializingActions().joinToString(",") { if (it is DbAction) it.getResolvedName() else it.getName() }, individual.seeAllActions().joinToString(",") { if (it is RestCallAction) it.resolvedPath() else it.getName() } ) log.trace("do taint analysis for {} additionalInfoList: {}", additionalInfoList.size, additionalInfoList.flatMap { a -> a.stringSpecializations.keys }.joinToString(",")) } /* The old approach of checking the taint only for current main action was quite limiting: 1) it would ignore taint in SQL actions 2) a previous HTTP call could put a tainted value in the DB, read by a following action. So, regardless of the main action in which the taint was detected, we check its gene in ALL actions in the individual, including _previous_ ones. An optimization would be to ignore the _following_ actions. Ideally, it should not be a problem, as tainted values are supposed to be unique. This is not currently enforce, so with low chances it could happened that 2 different genes have same tainted value. "Likely" rare, and "likely" with little to no side-effects if it happens (we ll see if it ll be indeed the case). Note, even if we force the invariant that 2 genes cannot share the same taint in a individual, we cannot guarantee of the taint values detected in the SUT. The string there might be manipulated (although it is _extremely_ unlike that a manipulated taint would still pass the taint regex check...) */ val allTaintableGenes: List<TaintableGene> = individual.seeAllActions() .flatMap { a -> a.seeTopGenes().flatMap { it.flatView() } .filterIsInstance<TaintableGene>() } val inputVariables = individual.seeAllActions() .flatMap { getRegexTaintedValues(it) } .toSet() for (element in additionalInfoList) { if (element.stringSpecializations == null || element.stringSpecializations.isEmpty()) { continue } val specsMap = element.stringSpecializations.entries .map { it.key to it.value.map { s -> StringSpecializationInfo( StringSpecialization.valueOf(s.stringSpecialization), s.value, TaintType.valueOf(s.type) ) } }.toMap() handleSingleGenes(specsMap, allTaintableGenes, randomness, inputVariables) handleMultiGenes(specsMap, allTaintableGenes, randomness, inputVariables) handleTaintedArrays(specsMap, allTaintableGenes, randomness, inputVariables) } } private fun handleTaintedArrays( specsMap: Map<String, List<StringSpecializationInfo>>, allTaintableGenes: List<TaintableGene>, randomness: Randomness, inputVariables: Set<String>) { val taintedArrays = allTaintableGenes.filterIsInstance<TaintedArrayGene>() if (taintedArrays.isEmpty()) { return } for (entry in specsMap.entries) { val taintedInput = entry.key val specs = entry.value if (specs.isEmpty()) { throw IllegalArgumentException("No specialization info for value $taintedInput") } val genes = taintedArrays.filter { it.getPossiblyTaintedValue().equals(taintedInput, true) } if (genes.isEmpty()) { continue } if (specs.size > 1) { log.warn("More than one possible specialization for tainted array '$taintedInput': $specs") } val s = specs.find { it.stringSpecialization == StringSpecialization.JSON_OBJECT } ?: randomness.choose(specs) val template = if (s.stringSpecialization == StringSpecialization.JSON_OBJECT) { val schema = s.value val t = schema.subSequence(0, schema.indexOf(":")).trim().toString() val ref = t.subSequence(1, t.length - 1).toString() RestActionBuilderV3.createObjectGenesForDTOs(ref, schema) } else { /* TODO this could be more sophisticated, like considering numeric and boolean arrays as well, and already initializing the values in array with some of taints. but, as this "likely" would be rare (ie JSON array of non-objects as root element in parsing), no need for now. */ StringGene("element") } genes.forEach { it.resolveTaint( ArrayGene(it.name, template.copy()).apply { doInitialize(randomness) } ) } } } private fun handleMultiGenes( specsMap: Map<String, List<StringSpecializationInfo>>, allTaintableGenes: List<TaintableGene>, randomness: Randomness, inputVariables: Set<String>) { val specs = specsMap.entries .flatMap { it.value } .filter { it.type == TaintType.PARTIAL_MATCH } .toSet() for (s in specs) { val genes = allTaintableGenes.filter { specsMap.entries .filter { e -> e.key.contains(it.getPossiblyTaintedValue(), true) } .any { e -> e.value.any { d -> d == s } } }.filterIsInstance<StringGene>() if (genes.size <= 1) { continue } /* TODO handling this properly is very complex. Something to do in the future, but for now we just keep a very basic, ad-hoc solution */ if (!s.stringSpecialization.isRegex || genes.size != 2) { continue } /* TODO we just handle for now this special case, but we would need a general approach */ val divider = "\\Q-\\E" val pos = s.value.indexOf(divider) if (pos < 0) { continue } val left = "(" + s.value.subSequence(0, pos).toString() + ")$" val right = "^(" + s.value.subSequence(pos + divider.length, s.value.length).toString() + ")" val taintInput = specsMap.entries.first { it.value.any { it == s } }.key val choices = if (taintInput.indexOf(genes[0].getValueAsRawString()) == 0) { listOf(left, right) } else { listOf(right, left) } try { genes[0].addSpecializations( genes[0].getValueAsRawString(), listOf(StringSpecializationInfo(StringSpecialization.REGEX_WHOLE, choices[0])), randomness) genes[1].addSpecializations( genes[1].getValueAsRawString(), listOf(StringSpecializationInfo(StringSpecialization.REGEX_WHOLE, choices[1])), randomness) } catch (e: Exception) { LoggingUtil.uniqueWarn(log, "Cannot handle partial match on regex: ${s.value}") } } } private fun handleSingleGenes( specsMap: Map<String, List<StringSpecializationInfo>>, allTaintableGenes: List<TaintableGene>, randomness: Randomness, inputVariables: Set<String>) { for (entry in specsMap.entries) { val taintedInput = entry.key if (entry.value.isEmpty()) { throw IllegalArgumentException("No specialization info for value $taintedInput") } //TODO what was the difference between these 2? val fullMatch = specsMap[taintedInput]!!.filter { it.type == TaintType.FULL_MATCH } val partialMatch = specsMap[taintedInput]!!.filter { it.type == TaintType.PARTIAL_MATCH } if (fullMatch.isNotEmpty()) { val genes = allTaintableGenes .filter { (TaintInputName.isTaintInput(it.getPossiblyTaintedValue()) || inputVariables.contains(it.getPossiblyTaintedValue())) && it.getPossiblyTaintedValue().equals(taintedInput, true) } .filterIsInstance<StringGene>() addSpecializationToGene(genes, taintedInput, fullMatch, randomness) } //partial match on single genes if (partialMatch.isNotEmpty()) { val genes = allTaintableGenes .filter { (TaintInputName.isTaintInput(it.getPossiblyTaintedValue()) || inputVariables.contains(it.getPossiblyTaintedValue())) && taintedInput.contains(it.getPossiblyTaintedValue(), true) } .filterIsInstance<StringGene>() addSpecializationToGene(genes, taintedInput, partialMatch, randomness) } } } private fun addSpecializationToGene( genes: List<StringGene>, taintedInput: String, specializations: List<StringSpecializationInfo>, randomness: Randomness ) { if (genes.isEmpty()) { /* This can happen if the taint input is manipulated, but still with same prefix and postfix. However, it would be extremely rare, and for sure not in any of E2E, unless we explicitly write one for it */ log.warn("No taint input found '{}'", taintedInput) /* FIXME put back once debug issue on Linux. The issue is that H2 is caching requests... our fix for that work on local machines (including Linux) but fails somehow on CI */ //assert(false) // crash in tests, but not production } else { if (genes.size > 1 && TaintInputName.isTaintInput(taintedInput) && genes.none { x -> genes.any { y -> x.isDirectBoundWith(y) || x.is2DepthDirectBoundWith(y) || x.isAnyParentBoundWith(y) } } ) { //shouldn't really be a problem... but let keep track for it, for now at least. // note, cannot really guarantee that a taint from regex is unique, as regex could generate // any kind of string... // also if genes are bound, then of course going to be more than 2... log.warn("More than 2 genes have the taint '{}'", taintedInput) //FIXME possible bug in binding handling. // assert(false) } genes.forEach { it.addSpecializations(taintedInput, specializations, randomness) } } } }
core/src/main/kotlin/org/evomaster/core/taint/TaintAnalysis.kt
1964867873
package com.github.badoualy.telegram.api.utils import com.github.badoualy.telegram.tl.api.* val TLAbsMessageAction.title: String? get() = when (this) { is TLMessageActionChannelCreate -> title is TLMessageActionChatCreate -> title is TLMessageActionChatEditTitle -> title is TLMessageActionChannelMigrateFrom -> title else -> null } val TLAbsMessageAction.userIdList: IntArray? get() = when (this) { is TLMessageActionChatAddUser -> users.toIntArray() is TLMessageActionChatCreate -> users.toIntArray() is TLMessageActionChatDeleteUser -> intArrayOf(userId) is TLMessageActionChatJoinedByLink -> intArrayOf(inviterId) else -> null }
api/src/main/kotlin/com/github/badoualy/telegram/api/utils/TLMessageActionUtils.kt
4233276060
package day09.part2 import java.io.File private data class State(val garbages: Int, val ignoreNext: Boolean, val inGarbage: Boolean) { fun increase() = this.copy(garbages = garbages + 1) } private fun countGarbage(s: String): Int = s.toCharArray() .fold(State(garbages = 0, ignoreNext = false, inGarbage = false), { state, c -> handle(state, c) }) .garbages private fun handle(state: State, c: Char): State { return if (state.ignoreNext) { state.copy(ignoreNext = false) } else { when (c) { '!' -> state.copy(ignoreNext = true) '<' -> if (state.inGarbage) state.increase() else state.copy(inGarbage = true) '>' -> state.copy(inGarbage = false) else -> if (state.inGarbage) state.increase() else state } } } fun main(args: Array<String>) { val input = File("src/day09/input.txt").readLines().first() println(countGarbage(input)) }
2017/src/day09/part2/part02.kt
248614700
/* * 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.impl import com.intellij.openapi.util.ClassLoaderUtil import com.intellij.util.lang.UrlClassLoader import java.net.URL import kotlin.concurrent.thread class FirstStarter { } fun main(args: Array<String>) { startRobotRoutine() startIdeMainRoutine(args) } private fun startIdeMainRoutine(args: Array<String>) { val defaultClassloader = FirstStarter::class.java.classLoader Thread.currentThread().contextClassLoader = defaultClassloader val ideMainClass = Class.forName("com.intellij.idea.Main", true, defaultClassloader) val mainMethod = ideMainClass.getMethod("main", Array<String>::class.java) mainMethod.isAccessible = true mainMethod.invoke(null, args) } private fun startRobotRoutine() { val robotClassLoader = createRobotClassLoader() fun awtIsNotStarted() = !(Thread.getAllStackTraces().keys.any { thread -> thread.name.toLowerCase().contains("awt-eventqueue") }) thread(name = "Wait Awt and Start", contextClassLoader = robotClassLoader) { while (awtIsNotStarted()) Thread.sleep(100) val companion = Class.forName("com.intellij.testGuiFramework.impl.FirstStart\$Companion", true, robotClassLoader) val firstStartClass = Class.forName("com.intellij.testGuiFramework.impl.FirstStart", true, robotClassLoader) val value = firstStartClass.getField("Companion").get(Any()) val method = companion.getDeclaredMethod("guessIdeAndStartRobot") method.isAccessible = true method.invoke(value) } } fun createRobotClassLoader(): UrlClassLoader { val builder = UrlClassLoader.build() .urls(getUrlOfBaseClassLoader()) .allowLock() .usePersistentClasspathIndexForLocalClassDirectories() .useCache() ClassLoaderUtil.addPlatformLoaderParentIfOnJdk9(builder) val newClassLoader = builder.get() return newClassLoader!! } fun getUrlOfBaseClassLoader(): List<URL> { val classLoader = Thread.currentThread().contextClassLoader val urlClassLoaderClass = classLoader.javaClass val getUrlsMethod = urlClassLoaderClass.methods.filter { it.name.toLowerCase() == "geturls" }.firstOrNull()!! @Suppress("UNCHECKED_CAST") val urlsListOrArray = getUrlsMethod.invoke(classLoader) if (urlsListOrArray is Array<*>) return urlsListOrArray.toList() as List<URL> else return urlsListOrArray as List<URL> }
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/FirstStarter.kt
2105583522
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.client import android.net.Uri 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.bumptech.glide.load.resource.bitmap.CenterInside import cx.ring.R import cx.ring.utils.GlideApp import cx.ring.utils.GlideOptions /** * A placeholder fragment containing a simple view. */ class MediaViewerFragment : Fragment() { private var mUri: Uri? = null private var mImage: ImageView? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.fragment_media_viewer, container, false) as ViewGroup mImage = view.findViewById(R.id.image) showImage() return view } override fun onDestroyView() { super.onDestroyView() mImage = null } override fun onStart() { super.onStart() val activity = activity ?: return mUri = activity.intent.data showImage() } private fun showImage() { mUri?.let {uri -> activity?.let {a -> mImage?.let {image -> GlideApp.with(a) .load(uri) .apply(PICTURE_OPTIONS) .into(image) } } } } companion object { private val PICTURE_OPTIONS = GlideOptions().transform(CenterInside()) } }
ring-android/app/src/main/java/cx/ring/client/MediaViewerFragment.kt
1806790645
package com.gmail.blueboxware.libgdxplugin import com.gmail.blueboxware.libgdxplugin.inspections.gradle.GradleKotlinOutdatedVersionInspection import com.gmail.blueboxware.libgdxplugin.inspections.gradle.GradleOutdatedVersionsInspection import com.gmail.blueboxware.libgdxplugin.inspections.gradle.GradlePropertiesOutdatedVersionsInspection import com.gmail.blueboxware.libgdxplugin.utils.getLibraryFromExtKey import com.gmail.blueboxware.libgdxplugin.versions.Libraries import com.gmail.blueboxware.libgdxplugin.versions.Library import com.gmail.blueboxware.libgdxplugin.versions.VersionService import com.gmail.blueboxware.libgdxplugin.versions.libs.LibGDXLibrary import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.service import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.util.text.DateFormatUtil import org.jetbrains.kotlin.config.MavenComparableVersion import org.jetbrains.plugins.groovy.GroovyFileType import org.junit.Before import java.io.File import java.io.StringReader import java.util.* /* * Copyright 2017 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @Suppress("ReplaceNotNullAssertionWithElvisReturn") class TestVersionHandlingLocalhost : LibGDXCodeInsightFixtureTestCase() { private val RUN_TESTS = false private lateinit var versionService: VersionService override fun shouldRunTest(): Boolean = if (RUN_TESTS) { testname() != "testingAgainstLocalHostIsDisabled" } else { testname() == "testingAgainstLocalHostIsDisabled" } fun testTestingAgainstLocalHostIsDisabled() { fail("Testing against localhost is disabled") } fun testOutdatedVersionsGradleInspection1() { myFixture.enableInspections(GradleOutdatedVersionsInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test1.gradle") } fun testOutdatedVersionsGradleInspection2() { myFixture.enableInspections(GradleOutdatedVersionsInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test2.gradle") } fun testOutdatedVersionsGradleInspection3() { myFixture.enableInspections(GradleOutdatedVersionsInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test3.gradle") } fun testOutdatedVersionsGradleInspection4() { addLibsFromProperties() myFixture.enableInspections(GradleOutdatedVersionsInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test4.gradle") } fun testOutdatedVersionsGradleKotlinInspection1() { myFixture.enableInspections(GradleKotlinOutdatedVersionInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test1.gradle.kt") } fun testOutdatedVersionsGradleKotlinInspection2() { addLibsFromProperties() myFixture.enableInspections(GradleKotlinOutdatedVersionInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "test2.gradle.kt") } fun testOutdatedVersionsGradlePropertiesInspection() { myFixture.enableInspections(GradlePropertiesOutdatedVersionsInspection::class.java) myFixture.testHighlightingAllFiles(true, false, false, "gradle.properties") } fun testGetLatestVersions() { assertEquals(MavenComparableVersion("1.0"), versionService.getLatestVersion(Libraries.LIBGDX_ANNOTATIONS)) assertEquals(MavenComparableVersion("1.9.5"), versionService.getLatestVersion(Libraries.LIBGDX)) assertEquals(MavenComparableVersion("1.8.1"), versionService.getLatestVersion(Libraries.AI)) assertEquals(MavenComparableVersion("1.7.3"), versionService.getLatestVersion(Libraries.ASHLEY)) assertEquals(MavenComparableVersion("1.4"), versionService.getLatestVersion(Libraries.BOX2dLIGHTS)) assertEquals(MavenComparableVersion("0.1.1"), versionService.getLatestVersion(Libraries.OVERLAP2D)) assertEquals(MavenComparableVersion("1.9.5"), versionService.getLatestVersion(Libraries.BOX2D)) assertEquals(MavenComparableVersion("2.2.1.9.9-b1"), versionService.getLatestVersion(Libraries.KIWI)) assertEquals(MavenComparableVersion("2.3.0"), versionService.getLatestVersion(Libraries.SHAPE_DRAWER)) assertEquals(MavenComparableVersion("5.0.0"), versionService.getLatestVersion(Libraries.TEN_PATCH)) } private val libsToTest = listOf( Libraries.KTX_APP, Libraries.TEN_PATCH, Libraries.AI, Libraries.SHAPE_DRAWER, Libraries.GDXFACEBOOK, Libraries.KTX_I18N, Libraries.AUTUMN, Libraries.LML, Libraries.VISUI ) fun testLatestVersionAvailability() { for (lib in libsToTest) { assertNotNull(lib.toString(), versionService.getLatestVersion(lib)) } } fun testUsedVersions() { addDummyLibrary(Libraries.AUTUMN_MVC, "1.2.3") assertEquals("1.2.3", versionService.getUsedVersion(Libraries.AUTUMN_MVC).toString()) addDummyLibrary(Libraries.KTX_ACTORS, "4.5.6") assertEquals("4.5.6", versionService.getUsedVersion(Libraries.KTX_ACTORS).toString()) addDummyLibrary(Libraries.LIBGDXUTILS_BOX2D, "7.8") assertEquals("7.8", versionService.getUsedVersion(Libraries.LIBGDXUTILS_BOX2D).toString()) } @Before fun testSavedState() { PropertiesComponent.getInstance()?.let { propertiesComponent -> for (lib in libsToTest) { if (lib.library !is LibGDXLibrary) { assertEquals( lib.library.name, versionService.getLatestVersion(lib).toString(), propertiesComponent.getValue(lib.library.versionKey) ) } } } } override fun setUp() { if (!RUN_TESTS) { return } VersionService.BATCH_SIZE = Libraries.values().size / 2 VersionService.SCHEDULED_UPDATE_INTERVAL = 2 * DateFormatUtil.SECOND VersionService.LIBRARY_CHANGED_TIME_OUT = 5 * DateFormatUtil.SECOND Library.TEST_URL = "http://127.0.0.1/maven/" super.setUp() WriteCommandAction.runWriteCommandAction(project) { FileTypeManager.getInstance().associateExtension(GroovyFileType.GROOVY_FILE_TYPE, "gradle") } versionService = project.service() for (lib in Libraries.values()) { addDummyLibrary(lib, "0.0") } addDummyLibrary(Libraries.LIBGDX, "1.9.3") if (testname() !in listOf("usedVersions", "testingAgainstLocalHostIsDisabled")) { Thread.sleep(2 * VersionService.LIBRARY_CHANGED_TIME_OUT) } } override fun getBasePath() = "versions/" private fun addLibsFromProperties() { val properties = StringReader( File(testDataPath + "gradle.properties") .readText() .replace(Regex("<.?warning.*?>"), "") ).let { input -> Properties().apply { load(input) } } val gdxVersion = properties.getProperty("gdxVersion")!! properties.propertyNames().iterator().forEach { name -> getLibraryFromExtKey(name as String)?.let { lib -> val version = if (lib.library is LibGDXLibrary) { gdxVersion } else { properties.getProperty(name)!! } addDummyLibrary(lib, version) } } } }
src/test/kotlin/com/gmail/blueboxware/libgdxplugin/TestVersionHandlingLocalhost.kt
353628922
package com.sonnyrodriguez.fittrainer.fittrainerbasic.models import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutHistoryObject import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit data class LocalStatObject(val title: String, val dateString: String, val totalExercisesString: String, val muscleGroups: String, val durationString: String) { companion object { fun durationString(workoutHistoryObject: WorkoutHistoryObject): String { val timeDifferenceInMs = Date(workoutHistoryObject.timeEnded).time - Date(workoutHistoryObject.timeStarted).time val days = TimeUnit.MILLISECONDS.toDays(timeDifferenceInMs) val hours = TimeUnit.MILLISECONDS.toHours(timeDifferenceInMs) - TimeUnit.DAYS.toHours(days) val minutes = TimeUnit.MILLISECONDS.toMinutes(timeDifferenceInMs) - TimeUnit.HOURS.toMinutes(hours) val seconds = TimeUnit.MILLISECONDS.toSeconds(timeDifferenceInMs) - TimeUnit.MINUTES.toSeconds(minutes) if (minutes > 0) { return "$minutes minutes, $seconds seconds" } else { return "$seconds seconds" } } fun dateCompleteString(workoutHistoryObject: WorkoutHistoryObject): String { val dateDone = Date(workoutHistoryObject.timeStarted) return SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(dateDone) } fun totalExercisesDone(workoutHistoryObject: WorkoutHistoryObject): String { var titles = "" workoutHistoryObject.names.forEachIndexed { index, titleString -> if (index == 0) { titles = "$titleString" } else { titles = "$titles, $titleString" } } return titles } fun musclesString(workoutHistoryObject: WorkoutHistoryObject): String { var muscles = "" workoutHistoryObject.muscles.forEach { muscles = "${muscles},${MuscleEnum.fromMuscleNumber(it.toInt()).title}" } return muscles } fun totalCount(workoutHistoryObject: WorkoutHistoryObject): String { return "${workoutHistoryObject.exercises.count()} exercises" } } }
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/models/LocalStatObject.kt
3358121548
@MyAnnotation(argsNoDefault = ["foo", "oof"], arg = "bar") var string: String? = "foo" @MyAnnotation(argNoDefault = "object") object KotlinObject { fun m() { } @MyAnnotation(args = arrayOf("123", "456"), argsNoDefault = ["789"]) fun annotatedMethod() { } val s = "" @MyAnnotation(arg = "xyz") val t = "" fun f(): KotlinClass { return KotlinClass() } } @MyAnnotation(argNoDefault = "kotlin", args = ["123"]) open class KotlinClass { @MyAnnotation(args = ["a", "b"]) val string: String? = "string" @MyAnnotation(args = arrayOf("a", "b")) val kotlinClass = KotlinClass() val kotlinClassNA: KotlinClass? = KotlinClass() fun m() {} @MyAnnotation(args = ["me", "thod"]) fun annotatedMethod() {} companion object { @MyAnnotation(argsNoDefault = ["xyz"]) val s = "" fun coMethod() {} fun f(): KotlinClass? { @MyAnnotation(arg = "local") val l = 3 return KotlinClass() } @MyAnnotation(argsNoDefault = arrayOf("g")) fun g() {} } } class SubClass: KotlinClass() { }
src/test/testdata/annotationUtils/KotlinClass.kt
63476283
package com.aman_arora.multi_thread_downloader.downloader import com.aman_arora.multi_thread_downloader.downloader.IDownloadTask.OnDownloadTaskEventListener import java.io.BufferedInputStream import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL internal class DownloadTask(val webUrl: URL, val thread: Int, val startByte: Long, val endByte: Long?, val partFile: File, val listener: OnDownloadTaskEventListener) : IDownloadTask { private val partSize = endByte?.minus(startByte)?.plus(1) private var isPaused = false internal var isDownloaded = false override fun run() { if (endByte != null && this.startByte + partFile.length() >= endByte) { return } val httpConnection = getHttpConnection(this.startByte + partFile.length(), endByte) httpConnection.connect() val isr = BufferedInputStream(httpConnection.inputStream) val outputStream = FileOutputStream(partFile, true) val byteInputBuffer = ByteArray(1024) var bytesRead: Int var progress: Float var totalRead = partFile.length() while (true) { synchronized(isPaused) { if (isPaused) { isr.close() return } bytesRead = isr.read(byteInputBuffer) if (bytesRead == -1) { if (endByte == null || partFile.length() == partSize) { isDownloaded = true listener.onDownloadComplete() } return } outputStream.write(byteInputBuffer, 0, bytesRead) totalRead += bytesRead if (partSize != null) { progress = totalRead.toFloat().div(partSize) listener.onProgressUpdated(thread, progress) } } } } override fun stopDownload() = synchronized(isPaused) { if (isPaused) { throw IllegalStateException() } isPaused = true return@synchronized } private fun getHttpConnection(startByte: Long,endByte: Long?): HttpURLConnection { val httpConnection = webUrl.openConnection() as HttpURLConnection httpConnection.setRequestProperty("Range", "bytes=$startByte-$endByte") return httpConnection } }
multithreaddownloader/src/main/java/com/aman_arora/multi_thread_downloader/downloader/DownloadTask.kt
3827291344
package com.openconference.model.backend.schedule /** * This data structure will be retuned from * * @author Hannes Dorfmann */ data class BackendScheduleResponse<T> private constructor(val isNewerDataAvailable: Boolean, val data: List<T>) { companion object { fun <R> nothingChanged() = BackendScheduleResponse(false, emptyList<R>()) fun <T> dataChanged(data: List<T>) = BackendScheduleResponse(true, data) } }
app/src/main/java/com/openconference/model/backend/schedule/BackendScheduleResponse.kt
3783040926
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType", "KDocMissingDocumentation") package jp.nephy.penicillin.models import jp.nephy.jsonkt.JsonObject import jp.nephy.jsonkt.delegation.int import jp.nephy.jsonkt.delegation.nullableString import jp.nephy.jsonkt.delegation.string import jp.nephy.penicillin.core.session.ApiClient import jp.nephy.penicillin.extensions.penicillinModelList data class PremiumSearchCount(override val json: JsonObject, override val client: ApiClient): PremiumSearchModel { val results by penicillinModelList<Count>() val totalCount by int override val next by nullableString val requestParameters by penicillinModelList<RequestParameters>() data class Count(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val timePeriod by string val count by int } data class RequestParameters(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val fromDate by nullableString val toDate by nullableString val bucketRaw by nullableString } }
src/main/kotlin/jp/nephy/penicillin/models/PremiumSearchCount.kt
3744278680
package org.openbase.jul.communication.data data class RPCResponse<RETURN>( val response: RETURN, val properties: Map<String,String> )
module/communication/default/src/main/java/org/openbase/jul/communication/data/RPCResponse.kt
3085135769
package com.jayrave.falkon.engine.test import org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown import kotlin.reflect.KClass /** * Executes [op] & if it doesn't throw an exception of instance [expectedExceptionClass], * an [AssertionError] will be thrown */ internal fun failIfOpDoesNotThrow( expectedExceptionClass: KClass<out Exception> = Exception::class, op: () -> Any?) { try { op.invoke() failBecauseExceptionWasNotThrown(expectedExceptionClass.java) } catch (e: Exception) { when { expectedExceptionClass.java.isInstance(e) -> { /* Expected expected. Just swallow */ } else -> throw e } } }
falkon-engine-test-common/src/main/kotlin/com/jayrave/falkon/engine/test/TestUtils.kt
2344763167
package com.example.kotlinbasiclogging import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log class MainActivity : AppCompatActivity() { private val TAG: String = javaClass.simpleName override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG, "onCreate: HIT") Log.e(TAG, "onCreate: something wrong?") } }
KotlinBasicLogging/app/src/main/java/com/example/kotlinbasiclogging/MainActivity.kt
292951141
package com.arcao.feedback import android.os.Build import com.arcao.feedback.collector.AccountInfoCollector import com.arcao.feedback.collector.AppInfoCollector import com.arcao.feedback.collector.BuildConfigCollector import com.arcao.feedback.collector.ConfigurationCollector import com.arcao.feedback.collector.ConstantsCollector import com.arcao.feedback.collector.DisplayManagerCollector import com.arcao.feedback.collector.LocusMapInfoCollector import com.arcao.feedback.collector.LogCatCollector import com.arcao.feedback.collector.MemoryCollector import com.arcao.feedback.collector.SharedPreferencesCollector import org.koin.core.qualifier.named import org.koin.dsl.module val DEP_FEEDBACK_COLLECTORS = named("feedbackCollectors") internal val feedbackModule = module { single(DEP_FEEDBACK_COLLECTORS) { arrayOf( AppInfoCollector(get()), BuildConfigCollector(), ConfigurationCollector(get()), ConstantsCollector(Build::class.java, "BUILD"), ConstantsCollector(Build.VERSION::class.java, "VERSION"), MemoryCollector(), SharedPreferencesCollector(get()), DisplayManagerCollector(get()), AccountInfoCollector(get(), get()), LocusMapInfoCollector(get()), // LogCat collector has to be the latest one to receive exceptions from collectors LogCatCollector() ) } single { FeedbackHelper(get(), get(DEP_FEEDBACK_COLLECTORS), get()) } }
app/src/main/java/com/arcao/feedback/FeedbackModule.kt
3764285900
/* * 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 androidx.compose.samples.crane.base import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.samples.crane.R import androidx.compose.samples.crane.data.ExploreModel import androidx.compose.samples.crane.home.OnExploreItemClicked import androidx.compose.samples.crane.ui.BottomSheetShape import androidx.compose.samples.crane.ui.crane_caption import androidx.compose.samples.crane.ui.crane_divider_color import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import coil.annotation.ExperimentalCoilApi import coil.compose.AsyncImagePainter import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import coil.request.ImageRequest import coil.request.ImageRequest.Builder import com.google.accompanist.insets.navigationBarsHeight @Composable fun ExploreSection( modifier: Modifier = Modifier, title: String, exploreList: List<ExploreModel>, onItemClicked: OnExploreItemClicked ) { Surface(modifier = modifier.fillMaxSize(), color = Color.White, shape = BottomSheetShape) { Column(modifier = Modifier.padding(start = 24.dp, top = 20.dp, end = 24.dp)) { Text( text = title, style = MaterialTheme.typography.caption.copy(color = crane_caption) ) Spacer(Modifier.height(8.dp)) // TODO Codelab: derivedStateOf step // TODO: Show "Scroll to top" button when the first item of the list is not visible val listState = rememberLazyListState() ExploreList(exploreList, onItemClicked, listState = listState) } } } @Composable private fun ExploreList( exploreList: List<ExploreModel>, onItemClicked: OnExploreItemClicked, modifier: Modifier = Modifier, listState: LazyListState = rememberLazyListState() ) { LazyColumn(modifier = modifier, state = listState) { items(exploreList) { exploreItem -> Column(Modifier.fillParentMaxWidth()) { ExploreItem( modifier = Modifier.fillParentMaxWidth(), item = exploreItem, onItemClicked = onItemClicked ) Divider(color = crane_divider_color) } } item { Spacer(modifier = Modifier.navigationBarsHeight()) } } } @OptIn(ExperimentalCoilApi::class) @Composable private fun ExploreItem( modifier: Modifier = Modifier, item: ExploreModel, onItemClicked: OnExploreItemClicked ) { Row( modifier = modifier .clickable { onItemClicked(item) } .padding(top = 12.dp, bottom = 12.dp) ) { ExploreImageContainer { Box { val painter = rememberAsyncImagePainter( model = Builder(LocalContext.current) .data(item.imageUrl) .crossfade(true) .build() ) Image( painter = painter, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(), ) if (painter.state is AsyncImagePainter.State.Loading) { Image( painter = painterResource(id = R.drawable.ic_crane_logo), contentDescription = null, modifier = Modifier .size(36.dp) .align(Alignment.Center), ) } } } Spacer(Modifier.width(24.dp)) Column { Text( text = item.city.nameToDisplay, style = MaterialTheme.typography.h6 ) Spacer(Modifier.height(8.dp)) Text( text = item.description, style = MaterialTheme.typography.caption.copy(color = crane_caption) ) } } } @Composable private fun ExploreImageContainer(content: @Composable () -> Unit) { Surface(Modifier.size(width = 60.dp, height = 60.dp), RoundedCornerShape(4.dp)) { content() } }
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/base/ExploreSection.kt
1630753873
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.scripts import java.io.File import java.lang.ref.WeakReference import java.lang.reflect.Modifier /** * The base class for scripting languages, allowing game code to be dynamically loaded. * * Note, you game's main entry point should register the script language(s) you require e.g. : * * GroovyLanguage().register() * * Also, you must add the path(s) where script files are located. * However, the default launchers: Tickle and EditorMain will do the following automatically : * * ScriptManager.setClasspath(File(resourcesFile.parent, "scripts")) */ abstract class Language { abstract val fileExtension: String abstract val name: String /** * Key is the name of the filename without extension. * Value is the Class contained in that file. * Note. the filename is used, rather than the Class.name, because Kotlin creates classes with names like : * Line_3$ExampleRole. Grr. */ private val classes = mutableMapOf<String, Class<*>>() /** * Note, when a script is reloaded, this map will contain the old and new classes, * and therefore will grow larger than [classes] map. * A WeakReference is used so that old (unused) classes can be garbage collected. */ private val classToName = mutableMapOf<WeakReference<Class<*>>, String>() open fun register() { ScriptManager.register(this) } abstract fun setClasspath(directory: File) /** * Clear all classes, ready for them to be reloaded */ open fun clear() { classes.clear() classToName.clear() } abstract fun loadScript(file: File): Class<*> fun addScript(file: File) { val klass = loadScript(file) val name = file.nameWithoutExtension classes[name] = klass classToName[WeakReference(klass)] = name } fun classForName(name: String): Class<*>? { return classes[name] } fun nameForClass(klass: Class<*>): String? { for ((weakKlass, name) in classToName) { if (weakKlass.get() === klass) { return name } } return null } /** * Returns classes known by this script language, that are sub-classes of the type given. * For example, it can be used to find all the scripted Roles, or scripted Directors etc. */ fun subTypes(type: Class<*>): List<Class<*>> { return classes.filter { !it.value.isInterface && !Modifier.isAbstract(it.value.modifiers) && type.isAssignableFrom(it.value) }.toSortedMap().map { it.value } } fun createScript(scriptDirectory: File, scriptName: String, type: Class<*>? = null): File { val file = File(scriptDirectory, scriptName + ".${fileExtension}") if (!scriptDirectory.exists()) { scriptDirectory.mkdirs() } file.writeText(generateScript(scriptName, type)) ScriptManager.load(file) return file } abstract fun generateScript(name: String, type: Class<*>?): String }
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/scripts/Language.kt
2436853149
package com.fsck.k9.backends import android.content.Context import com.fsck.k9.Account import com.fsck.k9.mail.AuthenticationFailedException import com.fsck.k9.mail.oauth.OAuth2TokenProvider import com.fsck.k9.preferences.AccountManager import java.io.IOException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import net.openid.appauth.AuthState import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationException.AuthorizationRequestErrors import net.openid.appauth.AuthorizationException.GeneralErrors import net.openid.appauth.AuthorizationService class RealOAuth2TokenProvider( context: Context, private val accountManager: AccountManager, private val account: Account ) : OAuth2TokenProvider { private val authService = AuthorizationService(context) private var requestFreshToken = false override fun getToken(timeoutMillis: Long): String { val latch = CountDownLatch(1) var token: String? = null var exception: AuthorizationException? = null val authState = account.oAuthState?.let { AuthState.jsonDeserialize(it) } ?: throw AuthenticationFailedException("Login required") if (requestFreshToken) { authState.needsTokenRefresh = true } val oldAccessToken = authState.accessToken authState.performActionWithFreshTokens(authService) { accessToken: String?, _, authException: AuthorizationException? -> token = accessToken exception = authException latch.countDown() } latch.await(timeoutMillis, TimeUnit.MILLISECONDS) val authException = exception if (authException == GeneralErrors.NETWORK_ERROR || authException == GeneralErrors.SERVER_ERROR || authException == AuthorizationRequestErrors.SERVER_ERROR || authException == AuthorizationRequestErrors.TEMPORARILY_UNAVAILABLE ) { throw IOException("Error while fetching an access token", authException) } else if (authException != null) { account.oAuthState = null accountManager.saveAccount(account) throw AuthenticationFailedException( message = "Failed to fetch an access token", throwable = authException, messageFromServer = authException.error ) } else if (token != oldAccessToken) { requestFreshToken = false account.oAuthState = authState.jsonSerializeString() accountManager.saveAccount(account) } return token ?: throw AuthenticationFailedException("Failed to fetch an access token") } override fun invalidateToken() { requestFreshToken = true } }
app/k9mail/src/main/java/com/fsck/k9/backends/RealOAuth2TokenProvider.kt
3952963987
package com.fwdekker.randomness.ui import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.assertj.swing.edt.FailOnThreadViolationRepaintManager import org.assertj.swing.edt.GuiActionRunner import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import javax.swing.JSpinner /** * Unit tests for the extension functions in `JSpinnerHelperKt`. */ object JSpinnerRangeTest : Spek({ beforeGroup { FailOnThreadViolationRepaintManager.install() } describe("constructor") { it("throws an exception if the range is negative") { assertThatThrownBy { bindSpinners(createJSpinner(), createJSpinner(), -37.20) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("maxRange must be a positive number.") } } describe("automatic range correction") { it("updates the minimum spinner if the maximum goes below its value") { val min = createJSpinner(150.38) val max = createJSpinner(244.54) bindSpinners(min, max) GuiActionRunner.execute { max.value = -284.85 } assertThat(min.value).isEqualTo(-284.85) } it("updates the maximum spinner if the minimum goes above its value") { val min = createJSpinner(-656.88) val max = createJSpinner(105.41) bindSpinners(min, max) GuiActionRunner.execute { min.value = 684.41 } assertThat(max.value).isEqualTo(684.41) } } }) private fun createJSpinner() = GuiActionRunner.execute<JSpinner> { JSpinner() } private fun createJSpinner(value: Double) = GuiActionRunner.execute<JSpinner> { JSpinner().also { it.value = value } }
src/test/kotlin/com/fwdekker/randomness/ui/JSpinnerRangeTest.kt
2334079406
package coil.sample import coil.memory.MemoryCache sealed class Screen { object List : Screen() data class Detail( val image: Image, val placeholder: MemoryCache.Key?, ) : Screen() }
coil-sample-common/src/main/java/coil/sample/Screen.kt
3999918038
/* * Copyright 2020 Michael Rozumyanskiy * * 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.michaelrocks.lightsaber.processor.analysis import io.michaelrocks.grip.Grip import io.michaelrocks.lightsaber.processor.ErrorReporter import io.michaelrocks.lightsaber.processor.model.InjectionContext import java.io.File class Analyzer( private val grip: Grip, private val errorReporter: ErrorReporter, private val projectName: String ) { fun analyze(files: Collection<File>): InjectionContext { val analyzerHelper = AnalyzerHelperImpl(grip.classRegistry, ScopeRegistry(), errorReporter) val (injectableTargets, providableTargets) = InjectionTargetsAnalyzerImpl(grip, analyzerHelper, errorReporter).analyze(files) val bindingRegistry = BindingsAnalyzerImpl(grip, analyzerHelper, errorReporter).analyze(files) val factories = FactoriesAnalyzerImpl(grip, analyzerHelper, errorReporter, projectName).analyze(files) val moduleProviderParser = ModuleProviderParserImpl(grip, errorReporter) val moduleParser = ModuleParserImpl(grip, moduleProviderParser, bindingRegistry, analyzerHelper, projectName) val moduleRegistry = ModuleRegistryImpl(grip, moduleParser, errorReporter, providableTargets, factories, files) val components = ComponentsAnalyzerImpl(grip, moduleRegistry, errorReporter).analyze(files) return InjectionContext(components, injectableTargets, providableTargets, factories, bindingRegistry.bindings) } }
processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/Analyzer.kt
1441366658
/* * 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.jetbrains.python.testing.universalTests import com.intellij.execution.Executor import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.jetbrains.python.PythonHelper import com.jetbrains.python.testing.PythonTestConfigurationsModel import com.jetbrains.python.testing.VFSTestFrameworkListener /** * Py.test runner */ class PyUniversalPyTestSettingsEditor(configuration: PyUniversalTestConfiguration) : PyUniversalTestSettingsEditor( PyUniversalTestForm.create(configuration, PyUniversalTestForm.CustomOption( PyUniversalPyTestConfiguration::keywords.name, TestTargetType.PATH, TestTargetType.PYTHON))) class PyUniversalPyTestExecutionEnvironment(configuration: PyUniversalPyTestConfiguration, environment: ExecutionEnvironment) : PyUniversalTestExecutionEnvironment<PyUniversalPyTestConfiguration>(configuration, environment) { override fun getRunner() = PythonHelper.PYTEST } class PyUniversalPyTestConfiguration(project: Project, factory: PyUniversalPyTestFactory) : PyUniversalTestConfiguration(project, factory) { @ConfigField var keywords = "" override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? = PyUniversalPyTestExecutionEnvironment(this, environment) override fun createConfigurationEditor(): SettingsEditor<PyUniversalTestConfiguration> = PyUniversalPyTestSettingsEditor(this) override fun getCustomRawArgumentsString(forRerun: Boolean): String = when { keywords.isEmpty() -> "" else -> "-k $keywords" } override fun isFrameworkInstalled() = VFSTestFrameworkListener.getInstance().isPyTestInstalled(sdk) } object PyUniversalPyTestFactory : PyUniversalTestFactory<PyUniversalPyTestConfiguration>() { override fun createTemplateConfiguration(project: Project) = PyUniversalPyTestConfiguration(project, this) override fun getName(): String = PythonTestConfigurationsModel.PY_TEST_NAME }
python/src/com/jetbrains/python/testing/universalTests/PyUniversalPyTest.kt
3609804247
package xyz.jmullin.drifter.rendering.shader import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.glutils.ShaderProgram import com.badlogic.gdx.math.Matrix3 import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.math.Vector3 import xyz.jmullin.drifter.debug.log import xyz.jmullin.drifter.extensions.drifter import xyz.jmullin.drifter.rendering.shader.delegate.UniformDelegate /** * Given files to load shader definitions from, compiles and wraps a [[ShaderProgram]] and functionality * for reloading the program. Define init() and tick() methods to set shader uniforms. * * @param fragmentShaderName Filename of the fragment shader to load. * @param vertexShaderName Filename of the vertex shader to load. */ open class ShaderSet(private val fragmentShaderName: String, private val vertexShaderName: String = "default") { var uniforms = emptyList<ShaderUniform<*>>() private val vert = Gdx.files.internal("shader/$vertexShaderName.vert")!! private val frag = Gdx.files.internal("shader/$fragmentShaderName.frag")!! /** * System ms time at which this shader was last compiled. */ private var lastCompileTime = 0L /** * The loaded shader program. */ var program: ShaderProgram? = null init { compile() } /** * Compile the shader program from the specified source. */ private fun compile() { program = ShaderProgram(vert, frag).apply { if(isCompiled) { log("Shader ($frag, $vert) compiled successfully.") } else { log("Shader ($frag, $vert) failed to compile:\n${log.split("\n").joinToString("\n") { "\t" + it }}") } } lastCompileTime = System.currentTimeMillis() } /** * Reload the shader from source if the files have been changed since compilation. */ private fun refresh() { if (vert.lastModified() > lastCompileTime || frag.lastModified() > lastCompileTime) { compile() log("Reloaded shader $fragmentShaderName / $vertexShaderName.") } } fun update() { if(drifter().devMode) { refresh() } uniforms.forEach(ShaderUniform<*>::setFromTick) tick() } /** * Extend to set shader parameters on a tick-by-tick basis. */ open fun tick() {} } /** * Uniform delegates intended for use in member assignment. */ val ShaderSet.booleanUniform get() = UniformDelegate.make(this) { name -> BooleanUniform(program!!, name, null) } val ShaderSet.intUniform get() = UniformDelegate.make(this) { name -> IntUniform(program!!, name, null) } val ShaderSet.floatUniform get() = UniformDelegate.make(this) { name -> FloatUniform(program!!, name, null) } val ShaderSet.vector2Uniform get() = UniformDelegate.make(this) { name -> Vector2Uniform(program!!, name, null) } val ShaderSet.vector3Uniform get() = UniformDelegate.make(this) { name -> Vector3Uniform(program!!, name, null) } val ShaderSet.matrix3Uniform get() = UniformDelegate.make(this) { name -> Matrix3Uniform(program!!, name, null) } val ShaderSet.matrix4Uniform get() = UniformDelegate.make(this) { name -> Matrix4Uniform(program!!, name, null) } val ShaderSet.colorUniform get() = UniformDelegate.make(this) { name -> ColorUniform(program!!, name, null) } val ShaderSet.booleanArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.boolean, null) } val ShaderSet.intArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.int, null) } val ShaderSet.floatArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.float, null) } val ShaderSet.vector2ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.vector2, null) } val ShaderSet.vector3ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.vector3, null) } val ShaderSet.matrix3ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.matrix3, null) } val ShaderSet.matrix4ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.matrix4, null) } val ShaderSet.colorArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.color, null) } /** * Uniform registrars intended for use in side-effecting shader declarations. */ fun ShaderSet.booleanUniform(name: String, tick: (() -> Boolean)?) = BooleanUniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.intUniform(name: String, tick: (() -> Int)?) = IntUniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.floatUniform(name: String, tick: (() -> Float)?) = FloatUniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.vector2Uniform(name: String, tick: (() -> Vector2)?) = Vector2Uniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.vector3Uniform(name: String, tick: (() -> Vector3)?) = Vector3Uniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.matrix3Uniform(name: String, tick: (() -> Matrix3)?) = Matrix3Uniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.matrix4Uniform(name: String, tick: (() -> Matrix4)?) = Matrix4Uniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.colorUniform(name: String, tick: (() -> Color)?) = ColorUniform(program!!, name, tick).apply { uniforms += this } fun ShaderSet.booleanArrayUniform(name: String, tick: (() -> List<Boolean>)?) = ArrayUniform(program!!, name, Uniforms.boolean, tick).apply { uniforms += this } fun ShaderSet.intArrayUniform(name: String, tick: (() -> List<Int>)?) = ArrayUniform(program!!, name, Uniforms.int, tick).apply { uniforms += this } fun ShaderSet.floatArrayUniform(name: String, tick: (() -> List<Float>)?) = ArrayUniform(program!!, name, Uniforms.float, tick).apply { uniforms += this } fun ShaderSet.vector2ArrayUniform(name: String, tick: (() -> List<Vector2>)?) = ArrayUniform(program!!, name, Uniforms.vector2, tick).apply { uniforms += this } fun ShaderSet.vector3ArrayUniform(name: String, tick: (() -> List<Vector3>)?) = ArrayUniform(program!!, name, Uniforms.vector3, tick).apply { uniforms += this } fun ShaderSet.matrix3ArrayUniform(name: String, tick: (() -> List<Matrix3>)?) = ArrayUniform(program!!, name, Uniforms.matrix3, tick).apply { uniforms += this } fun ShaderSet.matrix4ArrayUniform(name: String, tick: (() -> List<Matrix4>)?) = ArrayUniform(program!!, name, Uniforms.matrix4, tick).apply { uniforms += this } fun ShaderSet.colorArrayUniform(name: String, tick: (() -> List<Color>)?) = ArrayUniform(program!!, name, Uniforms.color, tick).apply { uniforms += this } fun ShaderSet.booleanUniform(name: String, v: Boolean) = BooleanUniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.intUniform(name: String, v: Int) = IntUniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.floatUniform(name: String, v: Float) = FloatUniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.vector2Uniform(name: String, v: Vector2) = Vector2Uniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.vector3Uniform(name: String, v: Vector3) = Vector3Uniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.matrix3Uniform(name: String, v: Matrix3) = Matrix3Uniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.matrix4Uniform(name: String, v: Matrix4) = Matrix4Uniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.colorUniform(name: String, v: Color) = ColorUniform(program!!, name, { v }).apply { uniforms += this } fun ShaderSet.booleanArrayUniform(name: String, v: List<Boolean>) = ArrayUniform(program!!, name, Uniforms.boolean, { v }).apply { uniforms += this } fun ShaderSet.intArrayUniform(name: String, v: List<Int>) = ArrayUniform(program!!, name, Uniforms.int, { v }).apply { uniforms += this } fun ShaderSet.floatArrayUniform(name: String, v: List<Float>) = ArrayUniform(program!!, name, Uniforms.float, { v }).apply { uniforms += this } fun ShaderSet.vector2ArrayUniform(name: String, v: List<Vector2>) = ArrayUniform(program!!, name, Uniforms.vector2, { v }).apply { uniforms += this } fun ShaderSet.vector3ArrayUniform(name: String, v: List<Vector3>) = ArrayUniform(program!!, name, Uniforms.vector3, { v }).apply { uniforms += this } fun ShaderSet.matrix3ArrayUniform(name: String, v: List<Matrix3>) = ArrayUniform(program!!, name, Uniforms.matrix3, { v }).apply { uniforms += this } fun ShaderSet.matrix4ArrayUniform(name: String, v: List<Matrix4>) = ArrayUniform(program!!, name, Uniforms.matrix4, { v }).apply { uniforms += this } fun ShaderSet.colorArrayUniform(name: String, v: List<Color>) = ArrayUniform(program!!, name, Uniforms.color, { v }).apply { uniforms += this }
src/main/kotlin/xyz/jmullin/drifter/rendering/shader/ShaderSet.kt
3448218491
package com.konifar.materialcat.presentation.gallery import android.databinding.BaseObservable import com.konifar.materialcat.domain.model.CatImage class GalleryItemViewModel(catImage: CatImage) : BaseObservable() { val id = catImage.id val imageUrl: String = catImage.imageUrl }
app/src/main/kotlin/com/konifar/materialcat/presentation/gallery/GalleryItemViewModel.kt
2881118463
package org.projectbass.bass.flux /** * @author A-Ar Andrew Concepcion */ class AppError(val statusCode: Int, val errorCode: Int, val errorMessage: String, val network: Boolean?) { companion object { fun createNetwork(errorMessage: String): AppError { return AppError(-1, -1, errorMessage, true) } fun createHttp(errorMessage: String): AppError { return AppError(-1, -1, errorMessage, false) } fun createHttp(statusCode: Int, errorCode: Int, errorMessage: String): AppError { return AppError(statusCode, errorCode, errorMessage, false) } } }
app/src/main/java/org/projectbass/bass/flux/AppError.kt
176351936
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @file:Suppress("UNCHECKED_CAST") package com.vladsch.smart import java.util.* enum class SmartScopes(val flags: Int) { SELF(1), PARENT(2), ANCESTORS(4), CHILDREN(8), DESCENDANTS(16), RESULT_TOP(32), // result always in top scope, else SELF INDICES(64); // across indices within a scope, maybe? companion object : BitSetEnum<SmartScopes>(SmartScopes::class.java, { it.flags }) { @JvmStatic val SELF_DOWN = setOf(SELF, CHILDREN, DESCENDANTS) @JvmStatic val TOP_DOWN = setOf(RESULT_TOP, SELF, CHILDREN, DESCENDANTS) fun isValidSet(scope: SmartScopes): Boolean = isValidSet(scope.flags) fun isValidSet(scopes: Set<SmartScopes>): Boolean = isValidSet(asFlags(scopes)) fun isValidSet(flags: Int): Boolean = !(isAncestorsSet(flags) && isDescendantSet(flags)) && !isIndicesSet(flags) fun isIndicesSet(scope: SmartScopes): Boolean = isIndicesSet(scope.flags) fun isIndicesSet(scopes: Set<SmartScopes>): Boolean = isIndicesSet(asFlags(scopes)) fun isIndicesSet(flags: Int): Boolean = flags and INDICES.flags > 0 fun isAncestorsSet(scope: SmartScopes): Boolean = isAncestorsSet(scope.flags) fun isAncestorsSet(scopes: Set<SmartScopes>): Boolean = isAncestorsSet(asFlags(scopes)) fun isAncestorsSet(flags: Int): Boolean = flags and (PARENT.flags or ANCESTORS.flags) > 0 fun isDescendantSet(scope: SmartScopes): Boolean = isDescendantSet(scope.flags) fun isDescendantSet(scopes: Set<SmartScopes>): Boolean = isDescendantSet(asFlags(scopes)) fun isDescendantSet(flags: Int): Boolean = flags and (CHILDREN.flags or DESCENDANTS.flags) > 0 } } @Suppress("UNCHECKED_CAST") abstract class SmartDataKey<V : Any>(id: String, nullValue: V, scopes: Set<SmartScopes>) { val myId: String = id val myNullValue: V = nullValue val myNullData: SmartImmutableData<V> val myScopes: Int fun onInit() { SmartDataScopeManager.registerKey(this) } val isIndependent: Boolean get() = dependencies.isEmpty() || dependencies.size == 1 && dependencies.first() == this abstract val dependencies: List<SmartDataKey<*>> abstract fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) fun values(data: SmartDataScope): HashMap<Int, SmartVersionedDataHolder<V>> { return data.getValues(this) as HashMap<Int, SmartVersionedDataHolder<V>> } fun value(cache: SmartDataScope, index: Int): SmartVersionedDataHolder<V>? { return cache.getValue(this, index) as SmartVersionedDataHolder<V>? } fun value(value: Any): V { return value as V } fun value(values: HashMap<SmartDataKey<*>, *>): V { return (values[this] ?: myNullValue) as V } fun list(list: List<*>): List<V> { return list as List<V> } fun createValues(): HashMap<Int, SmartVersionedDataHolder<V>> { return HashMap() } fun createDataAlias(): SmartVersionedDataAlias<V> { return SmartVersionedDataAlias(myNullData) } fun createDataAlias(data: SmartVersionedDataHolder<*>): SmartVersionedDataAlias<V> { return SmartVersionedDataAlias(data as SmartVersionedDataHolder<V>) } fun createDataAlias(scope: SmartDataScope, index: Int): SmartVersionedDataAlias<V> { val alias = SmartVersionedDataAlias(myNullData) scope.setValue(this, index, alias) return alias } fun createData(): SmartVersionedDataHolder<V> { return SmartVolatileData(myNullValue) } fun createList(): ArrayList<V> { return ArrayList() } override fun toString(): String { return super.toString() + " id: $myId" } fun addItem(list: ArrayList<*>, item: Any) { (list as ArrayList<V>).add(item as V) } fun setAlias(item: SmartVersionedDataAlias<*>, value: SmartVersionedDataHolder<V>) { (item as SmartVersionedDataAlias<V>).alias = value } fun setAlias(item: SmartVersionedDataAlias<*>, scope: SmartDataScope, index: Int) { val value = scope.getValue(this, index) as SmartVersionedDataHolder<V>? ?: myNullData (item as SmartVersionedDataAlias<V>).alias = if (value is SmartVersionedDataAlias<V>) value.alias else value } fun setNullData(scope: SmartDataScope, index: Int) { scope.setValue(this, index, myNullData) } fun setValue(scope: SmartDataScope, index: Int, value: SmartVersionedDataHolder<*>) { scope.setValue(this, index, value as SmartVersionedDataHolder<V>) } fun dataPoint(scope: SmartDataScope, index: Int): SmartVersionedDataAlias<V> { return scope.dataPoint(this, index) as SmartVersionedDataAlias<V> } init { this.myNullData = SmartImmutableData("$myId.nullValue", nullValue) this.myScopes = SmartScopes.asFlags(scopes) } } // values computed from corresponding parent values open class SmartVolatileDataKey<V : Any>(id: String, nullValue: V) : SmartDataKey<V>(id, nullValue, setOf(SmartScopes.SELF)) { override val dependencies: List<SmartDataKey<*>> get() = listOf() init { onInit() } open operator fun set(scope: SmartDataScope, index: Int, value: V) { val dataPoint = scope.getRawValue(this, index) if (dataPoint == null) { scope.setValue(this, index, SmartVolatileData(myId, value)) } else if (dataPoint is SmartVersionedVolatileDataHolder<*>) { (dataPoint as SmartVersionedVolatileDataHolder<V>).set(value) } else { throw IllegalStateException("non alias or volatile data point for volatile data key") } } open operator fun get(scope: SmartDataScope, index: Int): V { return ((scope.getRawValue(this, index) ?: myNullData) as SmartVersionedDataHolder<V>).get() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { // only first set will be used since there can only be one self for (source in sources) { for (index in indices) { // val dependent = value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") // val resultItem = result.getValue(this, index) result.setValue(this, index, myNullData) } break } } } open class SmartParentComputedDataKey<V : Any>(id: String, nullValue: V, val computable: DataValueComputable<V, V>) : SmartDataKey<V>(id, nullValue, setOf(SmartScopes.PARENT)) { constructor(id: String, nullValue: V, computable: (V) -> V) : this(id, nullValue, DataValueComputable { computable(it) }) val myComputable: IterableDataComputable<V> = IterableDataComputable { computable.compute(it.first()) } override val dependencies: List<SmartDataKey<*>> get() = listOf(this) init { onInit() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { // only first set will be used since there can only be one parent for (source in sources) { for (index in indices) { val dependent = value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") // val resultItem = result.getValue(this, index) result.setValue(this, index, SmartVectorData(listOf(dependent), myComputable)) } break } } } open class SmartComputedDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<*>>, scopes: Set<SmartScopes>, val computable: DataValueComputable<HashMap<SmartDataKey<*>, List<*>>, V>) : SmartDataKey<V>(id, nullValue, scopes) { constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<*>>, scopes: Set<SmartScopes>, computable: (dependencies: HashMap<SmartDataKey<*>, List<*>>) -> V) : this(id, nullValue, dependencies, scopes, DataValueComputable { computable(it) }) val myComputable: DataValueComputable<Iterable<SmartVersionedDataHolder<*>>, V> = DataValueComputable { // here we create a hash map of by out dependent keys to lists of passed in source scopes val params = HashMap<SmartDataKey<*>, List<*>>() val iterator = it.iterator() do { for (depKey in dependencies) { val list = params[depKey] as ArrayList<*>? ?: depKey.createList() depKey.addItem(list, iterator.next()) } } while (iterator.hasNext()) computable.compute(params) } init { if (SmartScopes.isValidSet(this.myScopes)) throw IllegalArgumentException("Scopes cannot contain both parent/ancestors and children/descendants") onInit() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { for (index in indices) { val dependents = ArrayList<SmartVersionedDataHolder<*>>() for (dependencyKey in dependencies) { for (source in sources) { val dependent = dependencyKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") dependents.add(dependent) } } result.setValue(this, index, SmartIterableData(dependents, myComputable)) } } } open class SmartDependentDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<*>>, scope: SmartScopes, val computable: DataValueComputable<HashMap<SmartDataKey<*>, *>, V>) : SmartDataKey<V>(id, nullValue, setOf(scope)) { constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<*>>, scope: SmartScopes, computable: (dependencies: HashMap<SmartDataKey<*>, *>) -> V) : this(id, nullValue, dependencies, scope, DataValueComputable { computable(it) }) val myComputable: DataValueComputable<Iterable<SmartVersionedDataHolder<*>>, V> = DataValueComputable { // here we create a hash map of by out dependent keys to lists of passed in source scopes val params = HashMap<SmartDataKey<*>, Any>() val iterator = it.iterator() for (depKey in dependencies) { params[depKey] = iterator.next().get() } if (iterator.hasNext()) throw IllegalStateException("iterator hasNext() is true after all parameters have been used up") computable.compute(params) } init { if (scope != SmartScopes.SELF && scope != SmartScopes.PARENT) throw IllegalArgumentException("TransformedDataKey can only be applied to SELF or PARENT scope") onInit() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { for (index in indices) { val dependents = ArrayList<SmartVersionedDataHolder<*>>() for (dependencyKey in dependencies) { for (source in sources) { val dependent = dependencyKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") dependents.add(dependent) break } } result.setValue(this, index, SmartIterableData(dependents, myComputable)) } } } open class SmartTransformedDataKey<V : Any, R : Any>(id: String, nullValue: V, dependency: SmartDataKey<R>, scope: SmartScopes, computable: DataValueComputable<R, V>) : SmartDependentDataKey<V>(id, nullValue, listOf(dependency), scope, DataValueComputable { computable.compute(dependency.value(it[dependency]!!)) }) { constructor(id: String, nullValue: V, dependency: SmartDataKey<R>, scope: SmartScopes, computable: (R) -> V) : this(id, nullValue, dependency, scope, DataValueComputable { computable(it) }) } open class SmartVectorDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<V>>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) : SmartDataKey<V>(id, nullValue, scopes) { constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scope: SmartScopes, computable: IterableDataComputable<V>) : this(id, nullValue, dependencies, setOf(scope, SmartScopes.SELF), computable) constructor(id: String, nullValue: V, dependency: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) : this(id, nullValue, listOf(dependency), scopes, computable) constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, scopes, IterableDataComputable { computable(it) }) constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scope: SmartScopes, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, setOf(scope, SmartScopes.SELF), computable) constructor(id: String, nullValue: V, dependency: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, listOf(dependency), scopes, computable) private val myComputable = computable init { onInit() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { for (index in indices) { if (SmartDataScopeManager.INSTANCE.trace) println("creating connections for $myId[$index] on scope: ${result.name}") val dependents = ArrayList<SmartVersionedDataHolder<V>>() for (source in sources) { for (dataKey in dependencies) { val dependent = dataKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") if (SmartDataScopeManager.INSTANCE.trace) println("adding dependent: $dependent") dependents.add(dependent) } } result.setValue(this, index, SmartVectorData(dependents, myComputable)) if (SmartDataScopeManager.INSTANCE.trace) println("created connections for $myId[$index] on scope: ${result.name}") } } } open class SmartAggregatedScopesDataKey<V : Any>(id: String, nullValue: V, dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) : SmartVectorDataKey<V>(id, nullValue, listOf(dataKey), scopes, computable) { constructor(id: String, nullValue: V, dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, dataKey, scopes, IterableDataComputable { computable(it) }) } open class SmartAggregatedDependenciesDataKey<V : Any>(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, isTopScope: Boolean, computable: IterableDataComputable<V>) : SmartVectorDataKey<V>(id, nullValue, dependencies, if (isTopScope) setOf(SmartScopes.RESULT_TOP, SmartScopes.SELF) else setOf(SmartScopes.SELF), computable) { constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, isTopScope: Boolean, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, isTopScope, IterableDataComputable { computable(it) }) } class SmartLatestDataKey<V : Any>(id: String, nullValue: V, val dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>) : SmartDataKey<V>(id, nullValue, scopes) { override val dependencies: List<SmartDataKey<V>> get() = listOf(dataKey) init { onInit() } override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) { for (index in indices) { val dependents = ArrayList<SmartVersionedDataHolder<V>>() for (source in sources) { val dependent = dataKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing") dependents.add(dependent) } result.setValue(this, index, SmartLatestDependentData(dependents)) } } } class SmartDataScopeManager { companion object { @JvmField val INSTANCE = SmartDataScopeManager() val dependentKeys: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() = INSTANCE.dependentKeys val keyComputeLevel: Map<SmartDataKey<*>, Int> get() = INSTANCE.keyComputeLevel fun computeKeyOrder(keys: Set<SmartDataKey<*>>): List<List<SmartDataKey<*>>> = INSTANCE.computeKeyOrder(keys) fun registerKey(dataKey: SmartDataKey<*>) { INSTANCE.registerKey(dataKey) } fun resolveDependencies() { INSTANCE.resolveDependencies() } fun createDataScope(name: String): SmartDataScope = INSTANCE.createDataScope(name) } private val myKeys = HashSet<SmartDataKey<*>>() private val myIndependentKeys = HashSet<SmartDataKey<*>>() private val myDependentKeys = HashMap<SmartDataKey<*>, HashSet<SmartDataKey<*>>>() private var myDependenciesResolved = true // private var myKeyDependencyMap = HashMap<SmartDataKey<*>, HashSet<SmartDataKey<*>>>() private var myComputeLevel = HashMap<SmartDataKey<*>, Int>() private var myTrace = false var trace: Boolean get() = myTrace set(value) { myTrace = value } val dependentKeys: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() { return myDependentKeys } // val dependencyMap: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() { // if (!myDependenciesResolved) resolveDependencies() // return myKeyDependencyMap // } val keyComputeLevel: Map<SmartDataKey<*>, Int> get() { if (!myDependenciesResolved) resolveDependencies() return myComputeLevel } fun computeKeyOrder(keys: Set<SmartDataKey<*>>): List<List<SmartDataKey<*>>> { val needKeys = HashSet<SmartDataKey<*>>() needKeys.addAll(keys) for (key in keys) { needKeys.addAll(key.dependencies) } val orderedKeyList = HashMap<Int, ArrayList<SmartDataKey<*>>>() for (entry in keyComputeLevel) { if (needKeys.contains(entry.key)) { orderedKeyList.putIfMissing(entry.value, { arrayListOf() }) orderedKeyList[entry.value]!!.add(entry.key) } } val resultList = arrayListOf<List<SmartDataKey<*>>>() for (computeLevel in orderedKeyList.keys.sorted()) { val list = orderedKeyList[computeLevel] ?: continue resultList.add(list) } return resultList } fun registerKey(dataKey: SmartDataKey<*>) { myKeys.add(dataKey) myDependenciesResolved = false if (dataKey.isIndependent) { myIndependentKeys.add(dataKey) } else { val resultDeps: Set<SmartDataKey<*>> = myDependentKeys[dataKey] ?: setOf() for (sourceKey in dataKey.dependencies) { myDependentKeys.putIfMissing(sourceKey, { HashSet() }) myDependentKeys[sourceKey]!!.add(dataKey) if (resultDeps.contains(sourceKey)) { throw IllegalArgumentException("sourceKey $sourceKey has resultKey $dataKey as dependency, circular dependency in $dataKey") } } } } fun createDataScope(name: String): SmartDataScope { return SmartDataScope(name, null) } @Suppress("UNCHECKED_CAST") fun resolveDependencies() { // compute dependency levels so that we can take a consumer key and get a list of keys that must be computed, sorted by order // of these computations val unresolvedKeys = myKeys.clone() as HashSet<SmartDataKey<*>> val resolvedKeys = myIndependentKeys.clone() as HashSet<SmartDataKey<*>> myComputeLevel = HashMap<SmartDataKey<*>, Int>() myComputeLevel.putAll(myIndependentKeys.map { Pair(it, 0) }) var computeOrder = 1 unresolvedKeys.removeAll(myIndependentKeys) while (!unresolvedKeys.isEmpty()) { // take out all the keys that no longer have any dependencies that are not computed val currentKeys = unresolvedKeys.filter { it.dependencies.intersect(unresolvedKeys).isEmpty() } if (currentKeys.isEmpty()) throw IllegalStateException("computation level has no keys, means remaining have circular dependencies") resolvedKeys.addAll(currentKeys) unresolvedKeys.removeAll(currentKeys) myComputeLevel.putAll(currentKeys.map { Pair(it, computeOrder) }) computeOrder++ } myDependenciesResolved = true } } // if the data point has a consumer then the corresponding entry will contain a SmartVersionedDataAlias, else it will contain null // so when a version data point provider is computed and the data point has non-null non-alias then it is a conflict and exception time // // all points that are provided have to be in existence before the call to finalizeAllScopes(), at which point all computed data keys that provide // consumed data will have their inputs computed, and the inputs of those computed points, until every consumer can be satisfied. // if there is an input for which only a non-computed key exists then that data point will get the key's nullValue and be immutable data. // // data points for which no consumers exist will not be created, and will not cause intermediate data points be created nor computed // open class SmartDataScope(val name: String, val parent: SmartDataScope?) { protected val myValues = HashMap<SmartDataKey<*>, HashMap<Int, SmartVersionedDataHolder<*>>>() protected val myChildren = HashSet<SmartDataScope>() // children protected val myDescendants = HashSet<SmartDataScope>() // descendants protected val myAncestors = HashSet<SmartDataScope>() // ancestors protected val myConsumers = HashMap<SmartDataKey<*>, ArrayList<Int>>() // list of indices per key for which consumers are available for this iteration val children: Set<SmartDataScope> get() = myChildren val descendants: Set<SmartDataScope> get() = myDescendants val ancestors: Set<SmartDataScope> get() = myAncestors val consumers: Map<SmartDataKey<*>, List<Int>> get() = myConsumers val level: Int init { parent?.addChild(this) level = (parent?.level ?: -1) + 1 } fun addChild(scope: SmartDataScope) { myChildren.add(scope) parent?.addDescendant(scope) } fun addDescendant(scope: SmartDataScope) { myDescendants.add(scope) scope.addAncestor(this) parent?.addDescendant(scope) } fun addAncestor(scope: SmartDataScope) { myAncestors.add(scope) } fun createDataScope(name: String): SmartDataScope { return SmartDataScope(name, this) } fun getValues(key: SmartDataKey<*>): Map<Int, SmartVersionedDataHolder<*>>? { return myValues[key] } fun getValue(key: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*>? { val value = getRawValue(key, index) ?: parent?.getValue(key, index) return if (value is SmartVersionedDataAlias<*>) value.alias else value } fun getRawValue(key: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*>? { val value = myValues[key] ?: return null return value[index] } fun <V : Any> setValue(key: SmartDataKey<V>, index: Int, value: SmartVersionedDataHolder<V>) { var valList = myValues[key] if (valList == null) { valList = hashMapOf(Pair(index, value)) myValues.put(key, valList) } else { val item = valList[index] if (item != null) { if (item is SmartVersionedDataAlias<*>) { if (value is SmartVersionedDataAlias<*>) throw IllegalStateException("data point in $name for $key already has an alias $item, second alias $value is in error") key.setAlias(item, value) } else { throw IllegalStateException("data point in $name for $key already has a data value $item, second value $value is in error") } } else { valList.put(index, value) } } } private fun canSetDataPoint(key: SmartDataKey<*>, index: Int): Boolean { val item = getRawValue(key, index) return item == null || item is SmartVersionedDataAlias<*> } open operator fun get(dataKey: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*> = dataPoint(dataKey, index) open operator fun set(dataKey: SmartDataKey<*>, index: Int, value: SmartVersionedDataHolder<*>) { dataKey.setValue(this, index, value) } open operator fun set(dataKey: SmartDataKey<*>, value: SmartVersionedDataHolder<*>) { val index = myValues[dataKey]?.size ?: 0 dataKey.setValue(this, index, value) } fun dataPoint(dataKey: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*> { var dataPoint = getRawValue(dataKey, index) if (dataPoint == null) { // not yet computed dataPoint = dataKey.createDataAlias(this, index) myConsumers.putIfMissing(dataKey, { arrayListOf() }) myConsumers[dataKey]!!.add(index) } return dataPoint } private fun addConsumedScopes(keys: HashMap<SmartDataKey<*>, HashSet<SmartDataScope>>) { for (entry in myConsumers) { keys.putIfMissing(entry.key, { HashSet() }) val scopesSet = keys[entry.key]!! // include self in computations if scopes were added on our behalf if (addKeyScopes(entry.key.myScopes, scopesSet) > 0) scopesSet.add(this) } } private fun addKeyScopes(scopes: Int, scopesSet: HashSet<SmartDataScope>): Int { var count = 0 if (scopes.and(SmartScopes.ANCESTORS.flags) > 0) { scopesSet.addAll(myAncestors) count += myAncestors.size } if (parent != null && scopes.and(SmartScopes.PARENT.flags) > 0) { scopesSet.add(parent) count++ } if (scopes.and(SmartScopes.SELF.flags) > 0) { scopesSet.add(this) count++ } if (scopes.and(SmartScopes.CHILDREN.flags) > 0) { scopesSet.addAll(myChildren) count += myChildren.size } if (scopes.and(SmartScopes.DESCENDANTS.flags) > 0) { scopesSet.addAll(myDescendants) count += myDescendants.size } return count } private fun addConsumedKeyIndices(dataKey: SmartDataKey<*>, scopesSet: Set<SmartDataScope>, indices: HashSet<Int>) { for (scope in scopesSet) { scope.addKeyIndices(dataKey, indices) } } private fun addKeyIndices(dataKey: SmartDataKey<*>, indicesSet: HashSet<Int>) { val indices = myConsumers[dataKey] ?: return for (index in indices) { val rawValue = getRawValue(dataKey, index) if (rawValue == null || (rawValue is SmartVersionedDataAlias<*> && rawValue.alias === dataKey.myNullData)) { indicesSet.add(index) } } } private fun addConsumedKeys(keys: HashSet<SmartDataKey<*>>) { for (entry in myConsumers) { keys.add(entry.key) } } /** * used to create smart data relationships * * can only be invoked from top level scope */ fun finalizeAllScopes() { if (parent != null) throw IllegalStateException("finalizeScope can only be invoked on top level dataScope object") val consumedKeys = HashSet<SmartDataKey<*>>() val keyScopes = myChildren.union(myDescendants).union(setOf(this)) for (scope in keyScopes) { scope.addConsumedKeys(consumedKeys) } val computeKeys = SmartDataScopeManager.computeKeyOrder(consumedKeys) // compute the keys in order for (keyList in computeKeys) { for (key in keyList) { finalizeKey(key, consumedKeys) } } // copy parent values to child consumers that have defaults finalizeParentProvided() // FIX: validate that all have been computed before clearing consumers for possible next batch traceAndClear() for (scope in keyScopes) { scope.traceAndClear() } } private fun traceAndClear() { if (SmartDataScopeManager.INSTANCE.trace) { for ((dataKey, indices) in consumers) { print("$name: consumer of ${dataKey.myId} ") for (index in indices) { print("[$index: ${dataKey.value(this, index)?.get()}] ") } println() } } myConsumers.clear() } private fun finalizeParentProvided() { if (parent != null) { for (entry in myConsumers) { for (index in entry.value) { val value = getRawValue(entry.key, index) if (value is SmartVersionedDataAlias<*>) { if (value.alias === entry.key.myNullData) { // see if the parent has a value entry.key.setAlias(value, parent, index) } } } } } for (scope in children) { scope.finalizeParentProvided() } } private fun finalizeKey(dataKey: SmartDataKey<*>, consumedKeys: Set<SmartDataKey<*>>) { if (parent != null) throw IllegalStateException("finalizeKey should only be called from top level scope") val keyScopes = myChildren.union(myDescendants).union(setOf(this)) val indicesSet = HashSet<Int>() val dependents = SmartDataScopeManager.dependentKeys[dataKey] ?: setOf() addConsumedKeyIndices(dataKey, keyScopes, indicesSet) for (dependentKey in dependents) { addConsumedKeyIndices(dependentKey, keyScopes, indicesSet) } if (!indicesSet.isEmpty()) { // we add a value at the top level for all dependencies of this key if one does not exist, this will provide the missing default for all descendants for (key in dataKey.dependencies) { for (index in indicesSet) { if (getValue(key, index) == null) { key.setNullData(this, index) } } } // now we compute if (dataKey.myScopes and SmartScopes.RESULT_TOP.flags > 0) { // results go to the top scope finalizeKeyScope(dataKey, consumedKeys, keyScopes, indicesSet) } else { // results go to the individual scopes, finalization is done top down val sortedScopes = keyScopes.sortedBy { it.level } for (scope in sortedScopes) { scope.finalizeKeyScope(dataKey, consumedKeys, keyScopes, indicesSet) } } } } @Suppress("UNUSED_PARAMETER") private fun finalizeKeyScope(dataKey: SmartDataKey<*>, consumedKeys: Set<SmartDataKey<*>>, allScopeSet: Set<SmartDataScope>, allIndicesSet: Set<Int>) { val scopesSet = HashSet<SmartDataScope>() addKeyScopes(dataKey.myScopes, scopesSet) if (!scopesSet.isEmpty()) { val indicesSet = HashSet<Int>() for (index in allIndicesSet) { if (canSetDataPoint(dataKey, index)) indicesSet.add(index) } if (!indicesSet.isEmpty()) { if (SmartDataScopeManager.INSTANCE.trace) println("finalizing $name[$dataKey] indices $indicesSet on ${scopesSet.fold("") { a, b -> a + " " + b.name }}") dataKey.createData(this, scopesSet, indicesSet) } } } }
src/com/vladsch/smart/SmartDataScope.kt
1048800627
package furhatos.app.openaichat import furhatos.app.openaichat.flow.* import furhatos.skills.Skill import furhatos.flow.kotlin.* import furhatos.nlu.LogisticMultiIntentClassifier class OpenaichatSkill : Skill() { override fun start() { Flow().run(Init) } } fun main(args: Array<String>) { LogisticMultiIntentClassifier.setAsDefault() Skill.main(args) }
OpenAIChat/src/main/kotlin/furhatos/app/openaichat/main.kt
1142863066
package com.sampsonjoliver.firestarter import android.app.Application import com.facebook.FacebookSdk import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.core.ImagePipelineConfig class FirestarterApplication : Application() { override fun onCreate() { super.onCreate() FacebookSdk.sdkInitialize(applicationContext) Fresco.initialize(this, ImagePipelineConfig.newBuilder(this).setDownsampleEnabled(true).build()) } }
app/src/main/java/com/sampsonjoliver/firestarter/FirestarterApplication.kt
2285053382
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 io.lumeer.core.adapter import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.api.model.common.Resource import io.lumeer.api.model.viewConfig.FormConfig import io.lumeer.api.util.PermissionUtils import io.lumeer.core.exception.NoDocumentPermissionException import io.lumeer.core.exception.NoLinkInstancePermissionException import io.lumeer.core.exception.NoPermissionException import io.lumeer.core.exception.NoResourcePermissionException import io.lumeer.core.util.DocumentUtils import io.lumeer.core.util.FunctionRuleJsParser import io.lumeer.core.util.LinkInstanceUtils import io.lumeer.core.util.QueryUtils import io.lumeer.storage.api.dao.* class PermissionAdapter( private val userDao: UserDao, private val groupDao: GroupDao, private val viewDao: ViewDao, private val linkTypeDao: LinkTypeDao, private val collectionDao: CollectionDao ) { private val usersCache = mutableMapOf<String, List<User>>() private val viewCache = mutableMapOf<String, View>() private val collectionCache = mutableMapOf<String, Collection>() private val userCache = mutableMapOf<String, User>() private val groupsCache = mutableMapOf<String, List<Group>>() private val linkTypes = lazy { linkTypeDao.allLinkTypes } private val collections = lazy { collectionDao.allCollections } private var currentViewId: String? = null fun setViewId(viewId: String) { currentViewId = viewId } fun getViewId() = currentViewId fun activeView(): View? { if (currentViewId.orEmpty().isNotEmpty()) { return getView(currentViewId!!) } return null } fun invalidateUserCache() { usersCache.clear() userCache.clear() groupsCache.clear() } fun invalidateCollectionCache() { collectionCache.clear() } fun isPublic(organization: Organization?, project: Project?) = project?.isPublic ?: false fun canReadAllInWorkspace(organization: Organization, project: Project?, userId: String): Boolean { val user = getUser(userId) val groups = PermissionUtils.getUserGroups(organization, user, getGroups(organization.id)) if (PermissionUtils.getUserRolesInResource(organization, user, groups).any { role -> role.isTransitive && role.type === RoleType.Read }) { return true } return project?.let { PermissionUtils.getUserRolesInResource(it, user, groups).any { role -> role.isTransitive && role.type === RoleType.Read } } ?: false } fun getOrganizationUsersByRole(organization: Organization, roleType: RoleType): Set<String> { return PermissionUtils.getOrganizationUsersByRole(organization, getUsers(organization.id), getGroups(organization.id), roleType) } fun getOrganizationReadersDifference(organization1: Organization, organization2: Organization): RolesDifference { return PermissionUtils.getOrganizationUsersDifferenceByRole(organization1, organization2, getUsers(organization1.id), getGroups(organization1.id), RoleType.Read) } fun getProjectUsersByRole(organization: Organization, project: Project?, roleType: RoleType): Set<String> { return PermissionUtils.getProjectUsersByRole(organization, project, getUsers(organization.id), getGroups(organization.id), roleType) } fun getProjectReadersDifference(organization: Organization, project1: Project, project2: Project): RolesDifference { return PermissionUtils.getProjectUsersDifferenceByRole(organization, project1, project2, getUsers(organization.id), getGroups(organization.id), RoleType.Read) } fun <T : Resource> getResourceUsersByRole(organization: Organization, project: Project?, resource: T, roleType: RoleType): Set<String> { return PermissionUtils.getResourceUsersByRole(organization, project, resource, getUsers(organization.id), getGroups(organization.id), roleType) } fun getLinkTypeUsersByRole(organization: Organization, project: Project?, linkType: LinkType, roleType: RoleType): Set<String> { return PermissionUtils.getLinkTypeUsersByRole(organization, project, linkType, getLinkTypeCollections(linkType), getUsers(organization.id), getGroups(organization.id), roleType) } fun <T : Resource> getResourceReadersDifference(organization: Organization?, project: Project?, resource1: T, resource2: T): RolesDifference { if (resource1.type == ResourceType.ORGANIZATION) { return getOrganizationReadersDifference(resource1 as Organization, resource2 as Organization) } if (organization != null) { if (resource1.type == ResourceType.PROJECT) { return getProjectReadersDifference(organization, resource1 as Project, resource2 as Project) } return PermissionUtils.getResourceUsersDifferenceByRole(organization, project, resource1, resource2, getUsers(organization.id), getGroups(organization.id), RoleType.Read) } return RolesDifference(setOf(), setOf()) } fun getLinkTypeReadersDifference(organization: Organization, project: Project?, linkType1: LinkType, linkType2: LinkType): RolesDifference { return PermissionUtils.getLinkTypeUsersDifferenceByRole(organization, project, linkType1, linkType2, getLinkTypeCollections(linkType1), getUsers(organization.id), getGroups(organization.id), RoleType.Read) } fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, userId: String): Set<RoleType> { return getUserRolesInResource(organization, project, resource, getUser(userId)) } fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, user: User): Set<RoleType> { return PermissionUtils.getUserRolesInResource(organization, project, resource, user, getGroups(organization?.id ?: resource.id)) } fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, group: Group): Set<RoleType> { return PermissionUtils.getGroupRolesInResource(organization, project, resource, group) } fun getUserRolesInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, user: User): Set<RoleType> { val view = activeView() if (view != null) { val viewRoles = getUserRolesInResource(organization, project, view, user) val authorId = view.authorId.orEmpty() val collectionIds = QueryUtils.getViewCollectionIds(view, linkTypes.value) if (collectionIds.contains(collection.id) && authorId.isNotEmpty()) { // does the view contain the collection? val authorRoles = getUserRolesInResource(organization, project, collection, authorId) return viewRoles.intersect(authorRoles) } } return emptySet() } fun getUserRolesInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, user: User): Set<RoleType> { val view = activeView() if (view != null) { val viewRoles = getUserRolesInResource(organization, project, view, user) val authorId = view.authorId.orEmpty() val linkTypeIds = view.allLinkTypeIds if (linkTypeIds.contains(linkType.id) && authorId.isNotEmpty()) { // does the view contain the linkType? val authorRoles = getUserRolesInLinkType(organization, project, linkType, getUser(authorId)) return viewRoles.intersect(authorRoles) } } return emptySet() } fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, userId: String): Set<RoleType> { return getUserRolesInLinkType(organization, project, linkType, getUser(userId)) } fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, user: User): Set<RoleType> { return getUserRolesInLinkType(organization, project, linkType, getLinkTypeCollections(linkType), user) } fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, userId: String): Set<RoleType> { return getUserRolesInLinkType(organization, project, linkType, collections, getUser(userId)) } fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, user: User): Set<RoleType> { return PermissionUtils.getUserRolesInLinkType(organization, project, linkType, collections, user, getGroups(organization.id)) } fun checkRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, userId: String) { if (!hasRole(organization, project, resource, role, userId)) { throw NoResourcePermissionException(resource) } } fun checkAllRoles(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String) { if (!hasAllRoles(organization, project, resource, roles, userId)) { throw NoResourcePermissionException(resource) } } fun hasAllRoles(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String): Boolean { return roles.all { hasRole(organization, project, resource, it, userId) } } fun checkAnyRole(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String) { if (!hasAnyRole(organization, project, resource, roles, userId)) { throw NoResourcePermissionException(resource) } } fun hasAnyRole(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String): Boolean { return roles.any { hasRole(organization, project, resource, it, userId) } } fun checkRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String) { if (!hasRoleInCollectionWithView(organization, project, collection, role, userId)) { throw NoResourcePermissionException(collection) } } fun hasRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String): Boolean { return hasRole(organization, project, collection, role, userId) || hasRoleInCollectionViaView(organization, project, collection, role, role, userId, activeView()) } fun hasAnyRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, roles: List<RoleType>, userId: String): Boolean { return roles.any { hasRoleInCollectionWithView(organization, project, collection, it, userId) } } fun checkCanDelete(organization: Organization?, project: Project?, resource: Resource, userId: String) { if (!hasRole(organization, project, resource, RoleType.Manage, userId) || resource.isNonRemovable) { throw NoResourcePermissionException(resource) } } fun checkCanDelete(organization: Organization, project: Project?, linkType: LinkType, userId: String) { if (!hasRole(organization, project, linkType, getLinkTypeCollections(linkType), RoleType.Manage, userId)) { throw NoPermissionException(ResourceType.LINK_TYPE.toString()) } } private fun hasRoleInCollectionViaView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, viewRole: RoleType, userId: String, view: View?): Boolean { if (view != null && (hasRole(organization, project, view, viewRole, userId) || hasExtendedPermissionsInCollectionViaView(organization, project, collection, role, userId, view))) { // does user have access to the view? val authorId = view.authorId.orEmpty() val collectionIds = QueryUtils.getViewCollectionIds(view, linkTypes.value) if (collectionIds.contains(collection.id) && authorId.isNotEmpty()) { // does the view contain the collection? if (hasRole(organization, project, collection, role, authorId)) { // has the view author access to the collection? return true // grant access } } } return false } private fun hasExtendedPermissionsInCollectionViaView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String, view: View?): Boolean { if (view?.perspective == Perspective.Form) { val additionalIds = QueryUtils.getViewAdditionalCollectionIds(view, linkTypes.value) if (additionalIds.contains(collection.id)) { return when (role) { RoleType.DataRead -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite), userId) else -> false } } } return false } fun checkCanReadDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) { if (!canReadDocument(organization, project, document, collection, userId)) { throw NoDocumentPermissionException(document) } } fun canReadDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean { if (document == null) return false return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataRead, userId)) || (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId)) } fun checkCanReadLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String) { if (!canReadLinkInstance(organization, project, linkInstance, linkType, userId)) { throw NoLinkInstancePermissionException(linkInstance) } } fun canReadLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean { if (linkInstance == null) return false return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataRead, userId)) || (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId)) } fun checkCanCreateDocuments(organization: Organization, project: Project?, collection: Collection, userId: String) { if (!canCreateDocuments(organization, project, collection, userId)) { throw NoResourcePermissionException(collection) } } fun checkCanCreateLinkInstances(organization: Organization, project: Project?, linkType: LinkType, userId: String) { if (!canCreateLinkInstances(organization, project, linkType, userId)) { throw NoPermissionException(ResourceType.LINK_TYPE.toString()) } } fun canCreateDocuments(organization: Organization, project: Project?, collection: Collection, userId: String): Boolean { return canReadWorkspace(organization, project, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataContribute, userId) } fun canReadWorkspace(organization: Organization, project: Project?, userId: String): Boolean { return project != null && hasRole(organization, project, project, RoleType.Read, userId) } fun canCreateLinkInstances(organization: Organization, project: Project?, linkType: LinkType, userId: String): Boolean { return canReadWorkspace(organization, project, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataContribute, userId) } fun checkCanEditDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) { if (!canEditDocument(organization, project, document, collection, userId)) { throw NoDocumentPermissionException(document) } } fun checkCanEditLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance, linkType: LinkType, userId: String) { if (!canEditLinkInstance(organization, project, linkInstance, linkType, userId)) { throw NoLinkInstancePermissionException(linkInstance) } } fun canEditDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean { if (document == null) return false return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataWrite, userId)) || (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId)) } fun canEditLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean { if (linkInstance == null) return false return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataWrite, userId)) || (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId)) } fun checkCanDeleteDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) { if (!canDeleteDocument(organization, project, document, collection, userId)) { throw NoDocumentPermissionException(document) } } fun checkCanDeleteLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String) { if (!canDeleteLinkInstance(organization, project, linkInstance, linkType, userId)) { throw NoLinkInstancePermissionException(linkInstance) } } fun canDeleteDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean { if (document == null) return false return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataDelete, userId)) || (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId)) } fun canDeleteLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean { if (linkInstance == null) return false return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataDelete, userId)) || (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId)) } private fun isDocumentOwner(organization: Organization, project: Project?, document: Document, collection: Collection, userId: String): Boolean { return isDocumentContributor(organization, project, document, collection, userId) || DocumentUtils.isDocumentOwnerByPurpose(collection, document, getUser(userId), getGroups(organization.id), getUsers(organization.id)) } private fun isDocumentContributor(organization: Organization, project: Project?, document: Document, collection: Collection, userId: String): Boolean { return hasRoleInCollectionWithView(organization, project, collection, RoleType.DataContribute, userId) && DocumentUtils.isDocumentOwner(collection, document, userId) } private fun isLinkOwner(organization: Organization, project: Project?, linkInstance: LinkInstance, linkType: LinkType, userId: String): Boolean { return hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataContribute, userId) && LinkInstanceUtils.isLinkInstanceOwner(linkType, linkInstance, userId) } fun checkRoleInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String) { if (!hasRoleInLinkTypeWithView(organization, project, linkType, role, userId)) { throw NoPermissionException(ResourceType.LINK_TYPE.toString()) } } fun hasRoleInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String): Boolean { val collections = getLinkTypeCollections(linkType) return hasRole(organization, project, linkType, collections, role, userId) || hasRoleInLinkTypeViaView(organization, project, linkType, collections, role, role, userId, activeView()) } private fun getLinkTypeCollections(linkType: LinkType) = // on custom permissions collections are not needed if (linkType.permissionsType == LinkPermissionsType.Custom) listOf() else linkType.collectionIds.orEmpty().subList(0, 2).map { getCollection(it) } private fun hasRoleInLinkTypeViaView(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, role: RoleType, viewRole: RoleType, userId: String, view: View?): Boolean { if (view != null && (hasRole(organization, project, view, viewRole, userId) || hasExtendedPermissionsInLinkTypeViaView(organization, project, linkType, role, userId, view))) { // does user have access to the view? val authorId = view.authorId.orEmpty() val linkTypeIds = view.allLinkTypeIds if (linkTypeIds.contains(linkType.id) && authorId.isNotEmpty()) { // does the view contain the linkType? if (hasRole(organization, project, linkType, collections, role, authorId)) { // has the view author access to the linkType? return true // grant access } } } return false } private fun hasExtendedPermissionsInLinkTypeViaView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String, view: View?): Boolean { if (view?.perspective == Perspective.Form) { val collectionId = FormConfig(view).collectionId.orEmpty() if (view.additionalLinkTypeIds.contains(linkType.id) && linkType.collectionIds.contains(collectionId)) { return when (role) { RoleType.DataContribute -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite), userId) in listOf(RoleType.DataRead, RoleType.Read) -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite, RoleType.DataRead), userId) else -> false } } } return false } fun checkRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String) { if (!hasRoleInLinkType(organization, project, linkType, role, userId)) { throw NoPermissionException(ResourceType.LINK_TYPE.toString()) } } fun checkAnyRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, roles: Set<RoleType>, userId: String) { if (!hasAnyRoleInLinkType(organization, project, linkType, roles, userId)) { throw NoPermissionException(ResourceType.LINK_TYPE.toString()) } } fun hasAnyRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, roles: Set<RoleType>, userId: String): Boolean { val linkTypeCollections = getLinkTypeCollections(linkType); return roles.any { hasRoleInLinkType(organization, project, linkType, linkTypeCollections, it, userId) } } fun hasRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String): Boolean { return hasRoleInLinkType(organization, project, linkType, getLinkTypeCollections(linkType), role, userId) } fun hasRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, role: RoleType, userId: String): Boolean { return hasRole(organization, project, linkType, collections, role, userId) } fun hasRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, userId: String): Boolean { return getUserRolesInResource(organization, project, resource, userId).contains(role) } fun hasRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, group: Group): Boolean { return getUserRolesInResource(organization, project, resource, group).contains(role) } fun hasRole(organization: Organization, project: Project?, linkType: LinkType, collection: List<Collection>, role: RoleType, userId: String): Boolean { return getUserRolesInLinkType(organization, project, linkType, collection, userId).contains(role) } fun checkFunctionRuleAccess(organization: Organization, project: Project?, js: String, role: RoleType, userId: String) { val collections = collections.value.associateBy { it.id } val collectionIds = collections.keys val linkTypes = linkTypes.value.associateBy { it.id } val linkTypeIds = linkTypes.keys val references = FunctionRuleJsParser.parseRuleFunctionJs(js, collectionIds, linkTypeIds) references.forEach { reference -> when (reference.resourceType) { ResourceType.COLLECTION -> { checkRole(organization, project, collections[reference.id]!!, role, userId) } ResourceType.LINK -> { checkRoleInLinkType(organization, project, linkTypes[reference.id]!!, role, userId) } else -> { throw NoPermissionException("Rule") } } } } fun getUser(userId: String): User { if (userCache.containsKey(userId)) { return userCache[userId]!! } val user = userDao.getUserById(userId) if (user != null) userCache[userId] = user return user ?: User(userId, userId, userId, setOf()) } fun getUsers(organizationId: String): List<User> { return usersCache.computeIfAbsent(organizationId) { userDao.getAllUsers(organizationId) } } fun getView(viewId: String): View { return viewCache.computeIfAbsent(viewId) { viewDao.getViewById(viewId) } } fun getCollection(collectionId: String): Collection { return collectionCache.computeIfAbsent(collectionId) { collectionDao.getCollectionById(collectionId) } } fun getGroups(organizationId: String): List<Group> { return groupsCache.computeIfAbsent(organizationId) { groupDao.getAllGroups(organizationId) } } }
lumeer-core/src/main/kotlin/io/lumeer/core/adapter/PermissionAdapter.kt
1378047260
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.common import com.google.common.truth.Truth.assertThat import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @OptIn(ExperimentalCoroutinesApi::class) // For `runTest`. class CountDownLatchTest { @Test fun `latch count is equal to initial count`() { val latch = CountDownLatch(10) assertThat(latch.count).isEqualTo(10) } @Test fun `countDown decrements count`() { val latch = CountDownLatch(10) latch.countDown() assertThat(latch.count).isEqualTo(9) } @Test fun `countDown is no-op when current count is zero`() { val latch = CountDownLatch(1) latch.countDown() latch.countDown() assertThat(latch.count).isEqualTo(0) } @Test fun `await suspends until count is zero`() = runTest(UnconfinedTestDispatcher()) { val latch = CountDownLatch(10) val job = launch { latch.await() } assertFalse(job.isCompleted) repeat(9) { latch.countDown() } assertThat(latch.count).isEqualTo(1) assertFalse(job.isCompleted) latch.countDown() assertThat(latch.count).isEqualTo(0) assertTrue(job.isCompleted) } @Test fun `await resumes immediately when initial count is zero`() = runTest(UnconfinedTestDispatcher()) { val latch = CountDownLatch(0) val job = launch { latch.await() } assertTrue(job.isCompleted) } @Test fun `await resumes multiple coroutines when count reaches zero`() = runTest(UnconfinedTestDispatcher()) { val latch = CountDownLatch(1) val job1 = launch { latch.await() } val job2 = launch { latch.await() } latch.countDown() assertTrue(job1.isCompleted) assertTrue(job2.isCompleted) } }
src/test/kotlin/org/wfanet/measurement/common/CountDownLatchTest.kt
4274686423
package com.cout970.magneticraft.misc.network import com.cout970.magneticraft.misc.gui.ValueAverage /** * Created by cout970 on 2017/07/01. */ abstract class SyncVariable(val id: Int) { abstract fun read(ibd: IBD) abstract fun write(ibd: IBD) } class FloatSyncVariable(id: Int, val getter: () -> Float, val setter: (Float) -> Unit) : SyncVariable(id) { override fun read(ibd: IBD) = ibd.getFloat(id, setter) override fun write(ibd: IBD) { ibd.setFloat(id, getter()) } } class IntSyncVariable(id: Int, val getter: () -> Int, val setter: (Int) -> Unit) : SyncVariable(id) { override fun read(ibd: IBD) = ibd.getInteger(id, setter) override fun write(ibd: IBD) { ibd.setInteger(id, getter()) } } class StringSyncVariable(id: Int, val getter: () -> String, val setter: (String) -> Unit) : SyncVariable(id) { override fun read(ibd: IBD) = ibd.getString(id, setter) override fun write(ibd: IBD) { ibd.setString(id, getter()) } } class AverageSyncVariable(id: Int, val valueAverage: ValueAverage) : SyncVariable(id) { override fun read(ibd: IBD) = ibd.getFloat(id) { valueAverage.storage = it } override fun write(ibd: IBD) { ibd.setFloat(id, valueAverage.average) } }
src/main/kotlin/com/cout970/magneticraft/misc/network/SyncVariable.kt
755331388
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_14_R1.pathfinding import com.github.ysl3000.bukkit.pathfinding.AbstractNavigation import net.minecraft.server.v1_14_R1.NavigationAbstract import org.bukkit.craftbukkit.v1_14_R1.entity.CraftEntity class CraftNavigation(private val navigationAbstract: NavigationAbstract, private val defaultSpeed: Double) : AbstractNavigation( doneNavigating = { navigationAbstract.n() }, pathSearchRange = { navigationAbstract.i() }, moveToPositionU = { x, y, z -> navigationAbstract.a(x, y, z, defaultSpeed) }, moveToPositionB = { x, y, z, speed -> navigationAbstract.a(x, y, z, speed) }, moveToEntityU = { entity -> navigationAbstract.a((entity as CraftEntity).handle, defaultSpeed) }, moveToentityB = { entity, speed -> navigationAbstract.a((entity as CraftEntity).handle, speed) }, speedU = { speed -> navigationAbstract.a(speed) }, clearPathEntityU = navigationAbstract::o, setCanPassDoors = navigationAbstract.q()::a, setCanOpenDoors = navigationAbstract.q()::b, setCanFloat = navigationAbstract.q()::c, canPassDoors = navigationAbstract.q()::c, canOpenDoors = navigationAbstract.q()::d, canFloat = navigationAbstract.q()::e )
Pathfinder_1_14/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_14_R1/pathfinding/CraftNavigation.kt
3439421391
@file:Suppress("MatchingDeclarationName") package reactivecircus.flowbinding.material import androidx.annotation.CheckResult import com.google.android.material.chip.ChipGroup import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.InitialValueFlow import reactivecircus.flowbinding.common.asInitialValueFlow import reactivecircus.flowbinding.common.checkMainThread /** * Create a [InitialValueFlow] of chip checked state change events on the [ChipGroup] instance * where the value emitted is the currently checked chip id, or [View#NO_ID] when selection is cleared. * * Note: Created flow keeps a strong reference to the [ChipGroup] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * chipGroup.chipCheckedChanges() * .onEach { checkedId -> * // handle checkedId * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun ChipGroup.chipCheckedChanges(): InitialValueFlow<Int> = callbackFlow { checkMainThread() val listener = ChipGroup.OnCheckedChangeListener { _, checkedId -> trySend(checkedId) } setOnCheckedChangeListener(listener) awaitClose { setOnCheckedChangeListener(null) } } .conflate() .asInitialValueFlow { checkedChipId }
flowbinding-material/src/main/java/reactivecircus/flowbinding/material/ChipGroupCheckedChangedFlow.kt
2620119790
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.processors import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettingsManager import org.rust.ide.formatter.rust fun shouldRunPunctuationProcessor(element: ASTNode): Boolean { val psi = element.psi if (!psi.isValid) return false // EA-110296, element might be invalid for some plugins return !CodeStyleSettingsManager.getInstance(psi.project).currentSettings.rust.PRESERVE_PUNCTUATION }
src/main/kotlin/org/rust/ide/formatter/processors/Util.kt
2871860716
package com.denysnovoa.nzbmanager.di.scope import javax.inject.Scope @Scope annotation class ActivityScope
app/src/main/java/com/denysnovoa/nzbmanager/di/scope/ActivityScope.kt
3432737035
package com.mrebollob.loteria.android.presentation.settings.manageticket.ui import android.content.res.Configuration import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mrebollob.loteria.android.R import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme import com.mrebollob.loteria.android.presentation.platform.ui.theme.SystemRed @Composable fun ManageTicketItemView( modifier: Modifier = Modifier, title: String, subTitle: String = "", onClick: () -> Unit ) { Surface( modifier = modifier .fillMaxWidth(), color = MaterialTheme.colors.background ) { Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Row( verticalAlignment = Alignment.Bottom ) { Text( text = title, style = MaterialTheme.typography.subtitle1, color = MaterialTheme.colors.onSurface, ) Text( modifier = Modifier .padding(start = 8.dp), color = MaterialTheme.colors.onSurface.copy(0.7f), text = subTitle, style = MaterialTheme.typography.body2 ) } Spacer(modifier = Modifier.weight(1f)) Icon( modifier = Modifier .padding(vertical = 24.dp) .clickable { onClick() } .size(24.dp), imageVector = Icons.Outlined.Delete, contentDescription = stringResource(id = R.string.manage_tickets_screen_delete_action), tint = SystemRed ) } } } @Preview("Manage ticket item") @Preview("Manage ticket item (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun PreviewManageTicketItemView() { LotteryTheme { Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier.padding(16.dp) ) { ManageTicketItemView( title = "Familia", subTitle = "00000 - 20 €", onClick = {} ) ManageTicketItemView( title = "Amigos", subTitle = "99999 - 200 €", onClick = {} ) } } } }
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/settings/manageticket/ui/ManageTicketItemView.kt
2537343004
package com.supercilex.robotscouter.core.ui import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData class StateHolder<T : Any>(state: T) { private val _liveData = MutableLiveData(state) val liveData: LiveData<T> get() = _liveData private var _value: T = state val value: T get() = _value fun update(notify: Boolean = true, block: T.() -> T) { synchronized(LOCK) { _value = block(value) if (notify) _liveData.postValue(value) } } private companion object { val LOCK = Object() } }
library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/StateHolder.kt
567675623
package util.remoter.remoterclient import android.annotation.TargetApi import android.os.Build import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import remoter.RemoterGlobalProperties import util.remoter.service.* import java.io.IOException /** * Sample service impl */ class KotlinServiceImpl : ISampleKotlinService { private val nonSuspendService = KotlinNonSuspendServiceImpl() private val nonSuspendService2 = KotlinNonSuspendServiceImpl2() companion object { const val TAG = "KotlinServiceImpl" } override fun testVarArg(vararg string: String?) : Int { var totalSize = 0 string.forEach { Log.v(TAG, "testVarArg $it") totalSize ++ } return totalSize } override suspend fun testBoolean1(a: Boolean, arrayIn: BooleanArray, arrayOut: BooleanArray, arrayInOut: BooleanArray): Boolean { Log.v(TAG, "testBoolean1 $a") arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testBoolean2(a: Boolean, arrayIn: BooleanArray?, arrayOut: BooleanArray?, arrayInOut: BooleanArray?): BooleanArray { Log.v(TAG, "testBoolean2 $a") if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } val result = booleanArrayOf(a) return result } override suspend fun testBoolean3(a: Boolean, arrayIn: BooleanArray?, arrayOut: BooleanArray?, arrayInOut: BooleanArray?): BooleanArray? { Log.v(TAG, "testBoolean3 $a") if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testByte1(a: Byte, arrayIn: ByteArray, arrayOut: ByteArray, arrayInOut: ByteArray): Byte { Log.v(TAG, "testByte1 $a") arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testByte2(a: Byte, arrayIn: ByteArray?, arrayOut: ByteArray?, arrayInOut: ByteArray?): ByteArray { val result = byteArrayOf(a) return result } override suspend fun testByte3(a: Byte, arrayIn: ByteArray?, arrayOut: ByteArray?, arrayInOut: ByteArray?): ByteArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testChar1(a: Char, arrayIn: CharArray, arrayOut: CharArray, arrayInOut: CharArray): Char { arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testChar2(a: Char, arrayIn: CharArray?, arrayOut: CharArray?, arrayInOut: CharArray?): CharArray { return charArrayOf(a) } override suspend fun testChar3(a: Char, arrayIn: CharArray?, arrayOut: CharArray?, arrayInOut: CharArray?): CharArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testInt1(a: Int, arrayIn: IntArray, arrayOut: IntArray, arrayInOut: IntArray): Int { arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testInt2(a: Int, arrayIn: IntArray?, arrayOut: IntArray?, arrayInOut: IntArray?): IntArray { return intArrayOf(a) } override suspend fun testInt3(a: Int, arrayIn: IntArray?, arrayOut: IntArray?, arrayInOut: IntArray?): IntArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testLong1(a: Long, arrayIn: LongArray, arrayOut: LongArray, arrayInOut: LongArray): Long { arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testLong2(a: Long, arrayIn: LongArray?, arrayOut: LongArray?, arrayInOut: LongArray?): LongArray { return longArrayOf(a) } override suspend fun testLong3(a: Long, arrayIn: LongArray?, arrayOut: LongArray?, arrayInOut: LongArray?): LongArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testFloat1(a: Float, arrayIn: FloatArray, arrayOut: FloatArray, arrayInOut: FloatArray): Float { arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testFloat2(a: Float, arrayIn: FloatArray?, arrayOut: FloatArray?, arrayInOut: FloatArray?): FloatArray { return floatArrayOf(a) } override suspend fun testFloat3(a: Float, arrayIn: FloatArray?, arrayOut: FloatArray?, arrayInOut: FloatArray?): FloatArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override suspend fun testDouble1(a: Double, arrayIn: DoubleArray, arrayOut: DoubleArray, arrayInOut: DoubleArray): Double { arrayInOut[0] = a arrayOut[0] = a return a } override suspend fun testDouble2(a: Double, arrayIn: DoubleArray?, arrayOut: DoubleArray?, arrayInOut: DoubleArray?): DoubleArray { return doubleArrayOf(a) } override suspend fun testDouble3(a: Double, arrayIn: DoubleArray?, arrayOut: DoubleArray?, arrayInOut: DoubleArray?): DoubleArray? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = a } return arrayIn } override fun testCharSequence1(a: CharSequence): CharSequence { return a } override suspend fun testCharSequence2(a: CharSequence?): CharSequence? { return a } override suspend fun testString1(a: String, data: Array<String>, result: Array<String>, reply: Array<String>): String { result[0] = a reply[0] = a return a } override suspend fun testString2(a: String?, data: Array<String?>?, result: Array<String?>?, reply: Array<String?>?): Array<String?>? { if (reply != null && reply.isNotEmpty()) { reply[0] = a } return data } override suspend fun testList1(inList: MutableList<String>, listOut: MutableList<String>, inOutList: MutableList<String>): MutableList<String> { inOutList[0] = inList[0] listOut.add(inList[0]) return inList } override suspend fun testList2(inList: MutableList<String?>?, listOut: MutableList<String?>?, inOutList: MutableList<String?>?): MutableList<String?>? { if (inOutList != null) { inOutList.clear() if (inList != null) { inOutList.addAll(inList) } } return inList } override suspend fun testMap1(inMap: MutableMap<String, Int>, outMap: MutableMap<String, Int>, inOutMap: MutableMap<String, Int>): MutableMap<String, Int> { outMap.clear() inOutMap.clear() outMap.putAll(inMap) inOutMap.putAll(inMap) return inMap } @TargetApi(Build.VERSION_CODES.N) override suspend fun testMap2(inMap: MutableMap<String?, Int?>?, outMap: MutableMap<String?, Int?>?, inOutMap: MutableMap<String?, Int?>?): MutableMap<String?, Int?>? { if (inOutMap != null) { inOutMap.clear() inMap?.forEach { t, u -> inOutMap[t] = u } Log.v(TAG, "testMap2 inout $inOutMap") } return inMap } override suspend fun testMap3(inMap: MutableMap<String?, Int>?, outMap: MutableMap<String, Int>?, inOutMap: MutableMap<String, Int>?): MutableMap<String, Int?>? { return mutableMapOf() } override suspend fun testParcelable1(inParcelable: FooParcelable<String>, parcelableOut: FooParcelable<String>, parcelableInOut: FooParcelable<String>): FooParcelable<String> { parcelableOut.stringValue = inParcelable.stringValue parcelableInOut.stringValue = inParcelable.stringValue return inParcelable } override suspend fun testParcelable2(inParcelable: FooParcelable<String?>?, parcelableOut: FooParcelable<String?>?, parcelableInOut: FooParcelable<String?>?): FooParcelable<String?>? { if (parcelableInOut != null) { if (inParcelable != null) { parcelableInOut.intValue = inParcelable.intValue } } return inParcelable } override suspend fun testParcelableArray1(arrayIn: Array<FooParcelable<String>>, arrayOut: Array<FooParcelable<String>>, arrayInOut: Array<FooParcelable<String>>): Array<FooParcelable<String>> { arrayOut[0] = arrayIn[0] arrayInOut[0] = arrayIn[0] return arrayIn } override suspend fun testParcelableArray2(arrayIn: Array<FooParcelable<String?>?>?, arrayOut: Array<FooParcelable<String?>?>?, arrayInOut: Array<FooParcelable<String?>?>?): Array<FooParcelable<String?>?>? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = arrayIn!![0] } return arrayIn } override suspend fun testSimpleParcelable1(inParcelable: SimpleParcelable, parcelableOut: SimpleParcelable, parcelableInOut: SimpleParcelable): SimpleParcelable { parcelableOut.stringValue = inParcelable.stringValue parcelableInOut.stringValue = inParcelable.stringValue return inParcelable } override suspend fun testSimpleParcelable2(inParcelable: SimpleParcelable?, parcelableOut: SimpleParcelable?, parcelableInOut: SimpleParcelable?): SimpleParcelable? { Log.v(TAG, "testSimpleParcelable2 $inParcelable , $parcelableOut , $parcelableInOut") if (parcelableInOut != null) { if (inParcelable != null) { parcelableInOut.intValue = inParcelable.intValue } } Log.v(TAG, "testSimpleParcelable2 returning $inParcelable $parcelableInOut") return inParcelable } override suspend fun testSimpleParcelableArray1(arrayIn: Array<SimpleParcelable>, arrayOut: Array<SimpleParcelable>, arrayInOut: Array<SimpleParcelable>): Array<SimpleParcelable> { arrayOut[0] = arrayIn[0] arrayInOut[0] = arrayIn[0] return arrayIn } override suspend fun testSimpleParcelableArray2(arrayIn: Array<SimpleParcelable?>?, arrayOut: Array<SimpleParcelable?>?, arrayInOut: Array<SimpleParcelable?>?): Array<SimpleParcelable?>? { if (arrayInOut != null && arrayInOut.isNotEmpty()) { arrayInOut[0] = arrayIn!![0] } return arrayIn } override suspend fun testParcel1(customData: CustomData, customData2: CustomData, customData3: CustomData): CustomData { return customData } override suspend fun testParcel2(customData: CustomData?, customData2: CustomData?, customData3: CustomData?): CustomData? { Log.v(TAG, "testParcel2 inout ${customData3?.data} ${customData3?.intData}") return customData } override suspend fun testParcelArray1(customData: Array<CustomData>, customData2: Array<CustomData>, customData3: Array<CustomData>): Array<CustomData> { customData2[0] = customData[0] customData3[0] = customData[0] return customData } override suspend fun testParcelArray2(customData: Array<CustomData?>?, customData2: Array<CustomData?>?, customData3: Array<CustomData?>?): Array<CustomData?>? { if (customData3?.isNotEmpty() == true && customData?.isNotEmpty() == true) { customData3[0] = customData[0] } return customData } override suspend fun testParcelList1(customData1: MutableList<CustomData>, customData2: MutableList<CustomData>, customData3: MutableList<CustomData>): MutableList<CustomData> { customData2.add(customData1[0]) customData3[0] = customData1[0] return customData1 } override suspend fun testParcelList2(customData1: MutableList<CustomData?>?, customData2: MutableList<CustomData?>?, customData3: MutableList<CustomData?>?): MutableList<CustomData?>? { if (customData3 != null) { customData3.clear() if (customData1 != null) { customData3.addAll(customData1) } } return customData1 } override suspend fun testEcho(string: String?, listener: ISampleKotlinServiceListener?): String? { listener?.onEcho(string) return string } override suspend fun testOneway0(a: Int): Int { return a } override suspend fun testOneway1(a: Int) { } override suspend fun testException(): Int { throw IOException("IOException thrown") } override suspend fun testRuntimeException(): Int { throw RuntimeException("Runtime exception") } override suspend fun getBinder1(binder1: IExtE, binderArray: Array<IExtE>): IExtE { binder1.echoLong(1) return binder1 } override suspend fun getBinder2(binder1: IExtE?, binderArray: Array<IExtE?>?): Array<IExtE?>? { return binderArray } override suspend fun getTemplateRemoter1(): ITest<String, CustomData, CustomData> { return ITest { param1, param2 -> CustomData().also { it.data = "input $param1" } } } override suspend fun getTemplateRemoter2(): ITest<String?, CustomData, CustomData?>? { return ITest { param1, param2 -> CustomData().also { it.data = "input $param1" } } } private val listeners = mutableListOf<ISampleKotlinServiceListener>() override suspend fun registerListener(listener: ISampleKotlinServiceListener?): Int { if (listener != null && !listeners.contains(listener)) { listeners.add(listener) return 1 } return 0 } override suspend fun unRegisterListener(listener: ISampleKotlinServiceListener?): Boolean { if (listener != null && listeners.contains(listener)) { listeners.remove(listener) return true } return false } override suspend fun testOnewayThrowsException(a: Int) { throw RuntimeException("Exception") } override suspend fun testSuspend() { } override suspend fun testSuspend2() = withContext(Dispatchers.IO) { 100 } override suspend fun testSuspend3(a: Int, b: String): MutableMap<Int?, CustomData?>? = withContext(Dispatchers.IO) { mutableMapOf<Int?, CustomData?>() } override suspend fun testSuspend4(a: Int, b: String): MutableMap<Int, CustomData> { return mutableMapOf<Int, CustomData>() } override fun testSuspend5(a: Int, b: String): MutableMap<Int?, CustomData?>? { return mutableMapOf() } override fun testSuspend6(a: Int, b: String): MutableMap<Int, CustomData> { return mutableMapOf() } override fun getNonSuspendInterface(): ISampleNonSuspendKotlinService { return nonSuspendService } override fun getNonSuspendInterface2(): ISampleNonSuspendKotlinService2 { return nonSuspendService2 } override fun getExtE(): IExtE { return ExtImpl() } override suspend fun getExtESuspend(): IExtE { return ExtImpl() } } class ExtImpl : IExtE { override fun echoString(s: String?): String { TODO("Not yet implemented") } override fun echoString(s: String?, s2: String?): String? { if ("GlobalKey1" == s) { //return from global properties for test val result = RemoterGlobalProperties.get(s) as String? Log.w("EXT", "Global properties $result") return result } return s + s2 } override fun echoInt(s: Int): Int { TODO("Not yet implemented") } override fun echoInt(s: Int, s2: Int): Int { TODO("Not yet implemented") } override fun echoFloat(s: Float): Float { TODO("Not yet implemented") } override fun echoFloat(s: Float, s2: Float): Float { TODO("Not yet implemented") } override fun echoLong(s: Long): Long { TODO("Not yet implemented") } override fun echoLong(s: Long, s2: Long): Long { TODO("Not yet implemented") } override fun testListParceler(customDataList: MutableList<CustomData>?) { TODO("Not yet implemented") } }
sampleclient-remoter/src/main/java/util/remoter/remoterclient/KotlinServiceImpl.kt
1840814548
package org.koin.sample.android.components.sdk class SDKService
koin-projects/examples/android-samples/src/main/java/org/koin/sample/android/components/sdk/SDKService.kt
1588953933
package com.mmartin.ghibliapi.di.module import com.mmartin.ghibliapi.App import dagger.Module import dagger.Provides /** * Created by mmartin on 10/11/17. */ @Module class ApplicationModule(internal var app: App) { @Provides fun provideApp(): App { return app } }
app/src/main/java/com/mmartin/ghibliapi/di/module/ApplicationModule.kt
3807808190
package kadet.dnd.api.service import kadet.dnd.api.model.Hero import kadet.dnd.api.model.Scene import kadet.dnd.api.model.Talent import kadet.dnd.api.model.Turn import kadet.dnd.api.repository.DayRepository import kadet.dnd.api.repository.HeroRepository import kadet.dnd.api.repository.SceneRepository import kadet.dnd.api.repository.TalentRepository import kadet.dnd.api.repository.TurnRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional fun isAvailableTalent(talent: Talent?, usedInScene: Set<String?>, usedInDay: Set<String?>): Boolean { return talent?.limitType == "Неограниченный" || (talent?.limitType == "На сцену" && !usedInScene.contains(talent.id)) || (talent?.limitType == "На день" && !usedInDay.contains(talent.id)) } @Service class SceneService(val sceneRepository: SceneRepository, val turnRepository: TurnRepository, val talentRepository: TalentRepository, val heroRepository: HeroRepository, val dayRepository: DayRepository) { /** * Start scene within a day. */ @Transactional fun startScene(dayId: String): Scene { val day = dayRepository.findOne(dayId) val scene = sceneRepository.save(Scene()) day.scenes.add(scene) dayRepository.save(day) return scene } /** * Stop scene within a day. */ @Transactional fun stopScene(sceneId: String): Scene { val scene = sceneRepository.findOne(sceneId) scene.finished = true return sceneRepository.save(scene) } /** * Add new turn to scene. (Turn is an action of hero). */ @Transactional fun makeMove(sceneId: String, turn: Turn?): Turn { val scene = sceneRepository.findOne(sceneId) val hero = heroRepository.findOne(turn?.owner?.id) val talent = talentRepository.findOne(turn?.action?.id) var newTurn = Turn() newTurn.action = talent newTurn.owner = hero newTurn = turnRepository.save(newTurn) scene.turns.add(newTurn) sceneRepository.save(scene) return newTurn } /** * Delete scene from db. */ @Transactional fun delete(sceneId: String) { sceneRepository.delete(sceneId) } /** * Fetch all talents that are still available in scene. * All day and scene talents that already used by hero can not be in list. */ fun findAvailableTalents(sceneId: String, heroId: String): Set<Talent> { val scene = sceneRepository.findOne(sceneId) val hero = heroRepository.findOne(heroId) return filterAvailableTalents(hero.talents, hero, scene) } fun filterAvailableTalents(talents: Set<Talent>, hero: Hero, scene: Scene): Set<Talent> { // TODO add custom query val usedInScene = scene.turns .filter { it.owner?.id == hero.id } .map { it.action } .filter { it?.limitType == "На сцену" } .map { it?.id } .toSet() // TODO add custom query val usedInDay = dayRepository.findAll() .filter { it.scenes.map { it.id }.contains(scene.id) } .flatMap { it.scenes } .flatMap { it.turns } .filter { it.owner?.id == hero.id } .map { it.action } .filter { it?.limitType == "На день" } .map { it?.id } .toSet() return talents .filter { isAvailableTalent(it, usedInScene, usedInDay) } .toSet() } }
api/src/main/kotlin/kadet/dnd/api/service/SceneService.kt
900847957
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.activities import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.media.RingtoneManager import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import ca.allanwang.kau.kpref.activity.CoreAttributeContract import ca.allanwang.kau.kpref.activity.KPrefActivity import ca.allanwang.kau.kpref.activity.KPrefAdapterBuilder import ca.allanwang.kau.ui.views.RippleCanvas import ca.allanwang.kau.utils.finishSlideOut import ca.allanwang.kau.utils.setMenuIcons import ca.allanwang.kau.utils.startActivityForResult import ca.allanwang.kau.utils.startLink import ca.allanwang.kau.utils.tint import ca.allanwang.kau.utils.withSceneTransitionAnimation import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import com.pitchedapps.frost.R import com.pitchedapps.frost.db.NotificationDao import com.pitchedapps.frost.facebook.FbCookie import com.pitchedapps.frost.injectors.ThemeProvider import com.pitchedapps.frost.prefs.Prefs import com.pitchedapps.frost.settings.getAppearancePrefs import com.pitchedapps.frost.settings.getBehaviourPrefs import com.pitchedapps.frost.settings.getDebugPrefs import com.pitchedapps.frost.settings.getExperimentalPrefs import com.pitchedapps.frost.settings.getFeedPrefs import com.pitchedapps.frost.settings.getNotificationPrefs import com.pitchedapps.frost.settings.getSecurityPrefs import com.pitchedapps.frost.settings.sendDebug import com.pitchedapps.frost.utils.ActivityThemer import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.REQUEST_REFRESH import com.pitchedapps.frost.utils.REQUEST_RESTART import com.pitchedapps.frost.utils.cookies import com.pitchedapps.frost.utils.frostChangelog import com.pitchedapps.frost.utils.frostNavigationBar import com.pitchedapps.frost.utils.launchNewTask import com.pitchedapps.frost.utils.loadAssets import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch /** Created by Allan Wang on 2017-06-06. */ @AndroidEntryPoint class SettingsActivity : KPrefActivity() { @Inject lateinit var fbCookie: FbCookie @Inject lateinit var prefs: Prefs @Inject lateinit var themeProvider: ThemeProvider @Inject lateinit var notifDao: NotificationDao @Inject lateinit var activityThemer: ActivityThemer private var resultFlag = Activity.RESULT_CANCELED companion object { private const val REQUEST_RINGTONE = 0b10111 shl 5 const val REQUEST_NOTIFICATION_RINGTONE = REQUEST_RINGTONE or 1 const val REQUEST_MESSAGE_RINGTONE = REQUEST_RINGTONE or 2 const val ACTIVITY_REQUEST_TABS = 29 const val ACTIVITY_REQUEST_DEBUG = 53 } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (fetchRingtone(requestCode, resultCode, data)) return when (requestCode) { ACTIVITY_REQUEST_TABS -> { if (resultCode == Activity.RESULT_OK) shouldRestartMain() return } ACTIVITY_REQUEST_DEBUG -> { val url = data?.extras?.getString(DebugActivity.RESULT_URL) if (resultCode == Activity.RESULT_OK && url?.isNotBlank() == true) sendDebug(url, data.getStringExtra(DebugActivity.RESULT_BODY)) return } } reloadList() } /** Fetch ringtone and save uri Returns [true] if consumed, [false] otherwise */ private fun fetchRingtone(requestCode: Int, resultCode: Int, data: Intent?): Boolean { if (requestCode and REQUEST_RINGTONE != REQUEST_RINGTONE || resultCode != Activity.RESULT_OK) return false val uri = data?.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) val uriString: String = uri?.toString() ?: "" if (uri != null) { try { grantUriPermission("com.android.systemui", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (e: Exception) { L.e(e) { "grantUriPermission" } } } when (requestCode) { REQUEST_NOTIFICATION_RINGTONE -> { prefs.notificationRingtone = uriString reloadByTitle(R.string.notification_ringtone) } REQUEST_MESSAGE_RINGTONE -> { prefs.messageRingtone = uriString reloadByTitle(R.string.message_ringtone) } } return true } override fun kPrefCoreAttributes(): CoreAttributeContract.() -> Unit = { textColor = { themeProvider.textColor } accentColor = { themeProvider.accentColor } } override fun onCreateKPrefs(savedInstanceState: Bundle?): KPrefAdapterBuilder.() -> Unit = { subItems(R.string.appearance, getAppearancePrefs()) { descRes = R.string.appearance_desc iicon = GoogleMaterial.Icon.gmd_palette } subItems(R.string.behaviour, getBehaviourPrefs()) { descRes = R.string.behaviour_desc iicon = GoogleMaterial.Icon.gmd_trending_up } subItems(R.string.newsfeed, getFeedPrefs()) { descRes = R.string.newsfeed_desc iicon = CommunityMaterial.Icon3.cmd_newspaper } subItems(R.string.notifications, getNotificationPrefs()) { descRes = R.string.notifications_desc iicon = GoogleMaterial.Icon.gmd_notifications } subItems(R.string.security, getSecurityPrefs()) { descRes = R.string.security_desc iicon = GoogleMaterial.Icon.gmd_lock } // subItems(R.string.network, getNetworkPrefs()) { // descRes = R.string.network_desc // iicon = GoogleMaterial.Icon.gmd_network_cell // } // todo add donation? plainText(R.string.about_frost) { descRes = R.string.about_frost_desc iicon = GoogleMaterial.Icon.gmd_info onClick = { startActivityForResult<AboutActivity>( 9, bundleBuilder = { withSceneTransitionAnimation(this@SettingsActivity) } ) } } plainText(R.string.help_translate) { descRes = R.string.help_translate_desc iicon = GoogleMaterial.Icon.gmd_translate onClick = { startLink(R.string.translation_url) } } plainText(R.string.replay_intro) { iicon = GoogleMaterial.Icon.gmd_replay onClick = { launchNewTask<IntroActivity>(cookies(), true) } } subItems(R.string.experimental, getExperimentalPrefs()) { descRes = R.string.experimental_desc iicon = CommunityMaterial.Icon2.cmd_flask_outline } subItems(R.string.debug_frost, getDebugPrefs()) { descRes = R.string.debug_frost_desc iicon = CommunityMaterial.Icon.cmd_bug visible = { prefs.debugSettings } } } fun setFrostResult(flag: Int) { resultFlag = resultFlag or flag } fun shouldRestartMain() { setFrostResult(REQUEST_RESTART) } fun shouldRefreshMain() { setFrostResult(REQUEST_REFRESH) } @SuppressLint("MissingSuperCall") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityThemer.setFrostTheme(forceTransparent = true) animate = prefs.animate themeExterior(false) } fun themeExterior(animate: Boolean = true) { if (animate) bgCanvas.fade(themeProvider.bgColor) else bgCanvas.set(themeProvider.bgColor) if (animate) toolbarCanvas.ripple(themeProvider.headerColor, RippleCanvas.MIDDLE, RippleCanvas.END) else toolbarCanvas.set(themeProvider.headerColor) frostNavigationBar(prefs, themeProvider) } override fun onBackPressed() { if (!super.backPress()) { setResult(resultFlag) launch(NonCancellable) { loadAssets(themeProvider) finishSlideOut() } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_settings, menu) toolbar.tint(themeProvider.iconColor) setMenuIcons( menu, themeProvider.iconColor, R.id.action_github to CommunityMaterial.Icon2.cmd_github, R.id.action_changelog to GoogleMaterial.Icon.gmd_info ) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_github -> startLink(R.string.github_url) R.id.action_changelog -> frostChangelog() else -> return super.onOptionsItemSelected(item) } return true } }
app/src/main/kotlin/com/pitchedapps/frost/activities/SettingsActivity.kt
3456507484
package io.jentz.winter.android.sample.quotes import io.jentz.winter.android.sample.model.Quote data class QuotesViewState( val isLoading: Boolean = false, val quotes: List<Quote> = emptyList() )
android-sample-app/src/main/java/io/jentz/winter/android/sample/quotes/QuotesViewState.kt
2040288505
package com.google.devtools.ksp.visitor import com.google.devtools.ksp.symbol.* open class KSValidateVisitor( private val predicate: (KSNode?, KSNode) -> Boolean ) : KSDefaultVisitor<KSNode?, Boolean>() { private fun validateType(type: KSType): Boolean { return !type.isError && !type.arguments.any { it.type?.accept(this, null) == false } } override fun defaultHandler(node: KSNode, data: KSNode?): Boolean { return true } override fun visitDeclaration(declaration: KSDeclaration, data: KSNode?): Boolean { if (!predicate(data, declaration)) { return true } if (declaration.typeParameters.any { !it.accept(this, declaration) }) { return false } return this.visitAnnotated(declaration, data) } override fun visitDeclarationContainer(declarationContainer: KSDeclarationContainer, data: KSNode?): Boolean { return declarationContainer.declarations.all { !predicate(declarationContainer, it) || it.accept( this, declarationContainer ) } } override fun visitTypeParameter(typeParameter: KSTypeParameter, data: KSNode?): Boolean { return !predicate(data, typeParameter) || typeParameter.bounds.all { it.accept(this, typeParameter) } } override fun visitAnnotated(annotated: KSAnnotated, data: KSNode?): Boolean { return !predicate(data, annotated) || annotated.annotations.all { it.accept(this, annotated) } } override fun visitAnnotation(annotation: KSAnnotation, data: KSNode?): Boolean { if (!predicate(data, annotation)) { return true } if (!annotation.annotationType.accept(this, annotation)) { return false } if (annotation.arguments.any { !it.accept(this, it) }) { return false } return true } override fun visitTypeReference(typeReference: KSTypeReference, data: KSNode?): Boolean { return validateType(typeReference.resolve()) } override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: KSNode?): Boolean { if (classDeclaration.asStarProjectedType().isError) { return false } if (!classDeclaration.superTypes.all { it.accept(this, classDeclaration) }) { return false } if (!this.visitDeclaration(classDeclaration, data)) { return false } if (!this.visitDeclarationContainer(classDeclaration, data)) { return false } return true } override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: KSNode?): Boolean { if (function.returnType != null && predicate(function, function.returnType!!) && !function.returnType!!.accept(this, data) ) { return false } if (!function.parameters.all { it.accept(this, function) }) { return false } if (!this.visitDeclaration(function, data)) { return false } return true } override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: KSNode?): Boolean { if (predicate(property, property.type) && !property.type.accept(this, data)) { return false } if (!this.visitDeclaration(property, data)) { return false } return true } override fun visitValueArgument(valueArgument: KSValueArgument, data: KSNode?): Boolean { fun visitValue(value: Any?): Boolean = when (value) { is KSType -> this.validateType(value) is KSAnnotation -> this.visitAnnotation(value, data) is List<*> -> value.all { visitValue(it) } else -> true } return visitValue(valueArgument.value) } override fun visitValueParameter(valueParameter: KSValueParameter, data: KSNode?): Boolean { return valueParameter.type.accept(this, valueParameter) } }
api/src/main/kotlin/com/google/devtools/ksp/visitor/KSValidateVisitor.kt
1799845201
package me.vavra.nexttram.model /** * Response to API.AI which asks for user's location. */ class LocationPermissionResponse { val data = Data() val speech = "Location" val contextOut = listOf(Context()) class Data { val google = Google() class Google { val permissions_request = PermissionsRequest() class PermissionsRequest { val opt_context = "To find nearby tram stops" val permissions = listOf("DEVICE_PRECISE_LOCATION") } } } class Context { val name = "requesting_permission" } }
webhook/src/main/kotlin/me/vavra/nexttram/model/LocationPermissionResponse.kt
1277198568
/* Copyright 2014 Christian Broomfield Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.sbg.vindinium.kindinium.model data class Position(val x: Int, val y: Int): Comparable<Position> { override fun compareTo(other: Position): Int { return if (x < other.x) 1 else if (x > other.x) -1 else if (y < other.y) 1 else if (y > other.y) 1 else 0 } override fun toString(): String = "($x, $y)" }
src/main/kotlin/com/sbg/vindinium/kindinium/model/Position.kt
3229031044
package demo val superSimpleSolvableMaze = """ #################### # # # S # # # # # # # # # # # # # # # # # # F # # # # # # # # # # # # # # # # # # # # # # # # # ####################""".removeFirstCharacter() val expectedSuperSimpleSolvableMazeWithRoute = """ #################### # # # S # # . # # . # # . # # . # # . # # . # # . # # . # # F # # # # # # # # # # # # # # # # # # # # # # # # # #################### """.removeFirstCharacter() val simpleSolvableMaze = """ ############################################ #S # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # F # # # # # # # # # # # # # # # # ############################################""".removeFirstCharacter() val mazeWithANarrowWall=""" ############################################ # # # # # # # # # # # # # # # # # # # # # # # F # # # # # # # # # # # S # # # # # # # # # # # # # # # # # # # ############################################""".removeFirstCharacter() val maze = """ ########## # S F # ##########""".removeFirstCharacter() fun String.removeFirstCharacter(): String{ return this.substring(1, this.length); }
src/test/kotlin/demo/SampleMazes.kt
522882186
/* * Copyright (c) 2017 Fabio Berta * * 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 ch.berta.fabio.popularmovies.data.themoviedb.dtos import ch.berta.fabio.popularmovies.data.dtos.Review import com.google.gson.annotations.SerializedName /** * Represents a result page of reviews obtained from TheMovieDb. */ data class ReviewsPage( val page: Int, @SerializedName("results") val reviews: List<Review>, @SerializedName("total_pages") val totalPages: Int, @SerializedName("total_results") val totalResults: Int )
app/src/main/java/ch/berta/fabio/popularmovies/data/themoviedb/dtos/ReviewsPage.kt
1162467362
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.notifications import com.intellij.ProjectTopics import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import org.rust.cargo.project.settings.RustProjectSettingsService import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.StandardLibrary import org.rust.cargo.project.workspace.cargoWorkspace import org.rust.cargo.toolchain.RustToolchain import org.rust.cargo.util.cargoProjectRoot import org.rust.lang.core.psi.isNotRustFile import org.rust.utils.pathAsPath import java.awt.Component /** * Warn user if rust toolchain or standard library is not properly configured. * * Try to fix this automatically (toolchain from PATH, standard library from the last project) * and if not successful show the actual notification to the user. */ class MissingToolchainNotificationProvider( private val project: Project, private val notifications: EditorNotifications ) : EditorNotifications.Provider<EditorNotificationPanel>() { init { project.messageBus.connect(project).apply { subscribe(RustProjectSettingsService.TOOLCHAIN_TOPIC, object : RustProjectSettingsService.ToolchainListener { override fun toolchainChanged() { notifications.updateAllNotifications() } }) subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun beforeRootsChange(event: ModuleRootEvent?) { // NOP } override fun rootsChanged(event: ModuleRootEvent?) { notifications.updateAllNotifications() } }) } } override fun getKey(): Key<EditorNotificationPanel> = PROVIDER_KEY override fun createNotificationPanel(file: VirtualFile, editor: FileEditor): EditorNotificationPanel? { if (file.isNotRustFile || isNotificationDisabled()) return null val toolchain = project.toolchain if (toolchain == null || !toolchain.looksLikeValidToolchain()) { return if (trySetupToolchainAutomatically()) null else createBadToolchainPanel() } val module = ModuleUtilCore.findModuleForFile(file, project) ?: return null if (module.cargoWorkspace?.hasStandardLibrary == false) { val rustup = module.cargoProjectRoot?.let { toolchain.rustup(it.pathAsPath) } // If rustup is not null, the WorkspaceService will use it // to add stdlib automatically. This happens asynchronously, // so we can't reliably say here if that succeeded or not. if (rustup == null) { createLibraryAttachingPanel(module) } } return null } private fun trySetupToolchainAutomatically(): Boolean { if (alreadyTriedForThisProject(TOOLCHAIN_DISCOVERY_KEY)) return false val toolchain = RustToolchain.suggest() ?: return false ApplicationManager.getApplication().invokeLater { if (project.isDisposed) return@invokeLater val oldToolchain = project.rustSettings.toolchain if (oldToolchain != null && oldToolchain.looksLikeValidToolchain()) { return@invokeLater } runWriteAction { project.rustSettings.data = project.rustSettings.data.copy(toolchain = toolchain) } project.showBalloon("Using Cargo at ${toolchain.presentableLocation}", NotificationType.INFORMATION) notifications.updateAllNotifications() } return true } private fun createBadToolchainPanel(): EditorNotificationPanel = EditorNotificationPanel().apply { setText("No Rust toolchain configured") createActionLabel("Setup toolchain") { project.rustSettings.configureToolchain() } createActionLabel("Do not show again") { disableNotification() notifications.updateAllNotifications() } } private fun createLibraryAttachingPanel(module: Module): EditorNotificationPanel = EditorNotificationPanel().apply { setText("Can not attach stdlib sources automatically without rustup.") createActionLabel("Attach manually") { val stdlib = chooseStdlibLocation(this) ?: return@createActionLabel if (StandardLibrary.fromFile(stdlib) != null) { module.project.rustSettings.explicitPathToStdlib = stdlib.path } else { project.showBalloon( "Invalid Rust standard library source path: `${stdlib.presentableUrl}`", NotificationType.ERROR ) } notifications.updateAllNotifications() } createActionLabel("Do not show again") { disableNotification() notifications.updateAllNotifications() } } private fun chooseStdlibLocation(parent: Component): VirtualFile? { val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() return FileChooser.chooseFile(descriptor, parent, project, null) } private fun disableNotification() { PropertiesComponent.getInstance(project).setValue(NOTIFICATION_STATUS_KEY, true) } private fun isNotificationDisabled(): Boolean = PropertiesComponent.getInstance(project).getBoolean(NOTIFICATION_STATUS_KEY) private fun alreadyTriedForThisProject(key: String): Boolean { val properties = PropertiesComponent.getInstance(project) val result = properties.getBoolean(key) properties.setValue(key, true) return result } companion object { private val NOTIFICATION_STATUS_KEY = "org.rust.hideToolchainNotifications" private val TOOLCHAIN_DISCOVERY_KEY = "org.rust.alreadyTriedToolchainAutoDiscovery" private val PROVIDER_KEY: Key<EditorNotificationPanel> = Key.create("Setup Rust toolchain") } }
src/main/kotlin/org/rust/ide/notifications/MissingToolchainNotificationProvider.kt
1342293172
package org.stt import java.util.* import java.util.function.Predicate object Streams { fun <T> distinctByKey(keyExtractor: (T) -> Any): Predicate<T> { val visited = HashSet<Any>() return Predicate { item -> visited.add(keyExtractor(item)) } } }
src/main/kotlin/org/stt/Streams.kt
3100214293
package com.booboot.vndbandroid.model.vnstat data class VNStatResults( var success: Boolean = false, var result: VNStatItem = VNStatItem(), var message: String? = null )
app/src/main/java/com/booboot/vndbandroid/model/vnstat/VNStatResults.kt
3204891860
/* * Copyright (c) 2016 Drimachine.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("PredefinedRules") package org.drimachine.grakmat val SEMICOLON: Parser<Char> = char(';') .withName("';'") val COLON: Parser<Char> = char(':') .withName("':'") val DOUBLE_QUOTE: Parser<Char> = char('\"') .withName("'\"'") val QUOTE: Parser<Char> = char('\'') .withName("'\\''") val ASTERISK: Parser<Char> = char('*') .withName("'*'") val LEFT_BRACKET: Parser<Char> = char('[') .withName("'['") val RIGHT_BRACKET: Parser<Char> = char(']') .withName("']'") val LEFT_BRACE: Parser<Char> = char('{') .withName("'{'") val RIGHT_BRACE: Parser<Char> = char('}') .withName("'}'") val CARET: Parser<Char> = char('^') .withName("'^'") val COMMA: Parser<Char> = char(',') .withName("','") val MINUS: Parser<Char> = char('-') .withName("'-'") val PLUS: Parser<Char> = char('+') .withName("'+'") val SLASH: Parser<Char> = char('/') .withName("'/'") val BACKSLASH: Parser<Char> = char('\\') .withName("'\\'") val GREATER_THAN_SIGN: Parser<Char> = char('>') .withName("'>'") val LESS_THAN_SIGN: Parser<Char> = char('<') .withName("'<'") val LEFT_PAREN: Parser<Char> = char('(') .withName("'('") val RIGHT_PAREN: Parser<Char> = char(')') .withName("')'") val DOT: Parser<Char> = char('.') .withName("'.'") val UNDERSCORE: Parser<Char> = char('_') .withName("'_'") val VERTICAL_BAR: Parser<Char> = char('|') .withName("'|'") val AMPERSAND: Parser<Char> = char('&') .withName("'&'") val QUESTION_MARK: Parser<Char> = char('?') .withName("'?'") val EQUALS_SIGN: Parser<Char> = char('=') .withName("'='") val EXCLAMATION_MARK: Parser<Char> = char('!') .withName("'!'") val AT_SIGN: Parser<Char> = char('@') .withName("'@'") val HASH: Parser<Char> = char('#') .withName("'#'") val DIGIT: Parser<Char> = anyOf('0'..'9') .withName("DIGIT") val NUMBER: Parser<String> = (oneOrMore(DIGIT)) .map { digits: List<Char> -> digits.joinToString("") } .withName("NUMBER") val IDENTIFIER: Parser<String> = oneOrMore(anyOf(('a'..'z') + ('A'..'Z') + ('0'..'9') + '_')) .map { it: List<Char> -> it.joinToString("") } .withName("IDENTIFIER") object Numbers { private fun <A> listOf(head: A, tail: List<A>): List<A> = arrayListOf(head).apply { addAll(tail) } private fun List<Char>.digitsToInt(): Int { val (multiplier: Int, result: Int) = this.foldRight(1 to 0) { digit: Char, (multiplier: Int, result: Int) -> (multiplier * 10) to (result + Character.getNumericValue(digit) * multiplier) } return result } // fragment zeroInteger: (Int) = '0' { ... }; private val zeroInteger: Parser<Int> = char('0') map { 0 } // POSITIVE_INTEGER: (Int) = [1-9] ([0-9])* { ... }; val POSITIVE_INTEGER: Parser<Int> = (anyOf('1'..'9') and zeroOrMore(DIGIT)) .map { (headDigit: Char, tailDigits: List<Char>) -> listOf(headDigit, tailDigits).digitsToInt() } .withName("POSITIVE INTEGER") // fragment zeroOrPositiveInteger: (Int) = zeroInteger | positiveInteger; private val zeroOrPositiveInteger: Parser<Int> = zeroInteger or POSITIVE_INTEGER // INTEGER: (Int) = ('-')? positiveInteger { ... }; val INTEGER: Parser<Int> = (optional(char('-')) and zeroOrPositiveInteger) .map { (minus: Char?, integer: Int) -> if (minus == null) integer else -integer } .withName("INTEGER") // fragment exp: (Pair<Char, Int>) = [Ee] > ([+\-])? positiveInteger { ... }; private val exp: Parser<Pair<Char, Int>> = (anyOf('E', 'e') then optional(anyOf('+', '-')) and zeroOrPositiveInteger) .map { (operator: Char?, integer: Int) -> if (operator == null) '+' to integer else operator to integer } // fragment zeroOrPositiveFloating: (Double) = INTEGER < '.' (DIGIT)+ { ... }; @Suppress("RemoveCurlyBracesFromTemplate") private val zeroOrPositiveFloating: Parser<Double> = (INTEGER before DOT and oneOrMore(DIGIT)) .map { (integer: Int, fracDigits: List<Char>) -> "${integer}.${fracDigits.joinToString("")}".toDouble() } // fragment floatingWithExp: (Number) = FLOATING (exp)? { ... }; private val floatingWithExp: Parser<Double> = (zeroOrPositiveFloating and optional(exp)) .map { (floating: Double, exp: Pair<Char, Int>?) -> if (exp != null) { val (expOperator: Char, expInt: Int) = exp if (expOperator == '+') (floating * Math.pow(10.0, expInt.toDouble())) else // expOperator will be always '-' (floating / Math.pow(10.0, expInt.toDouble())) } else { floating } } // FLOATING: (Double) = ('-')? positiveInteger { ... }; val FLOATING: Parser<Double> = (optional(char('-')) and floatingWithExp) .map { (minus: Char?, floating: Double) -> if (minus == null) floating else -floating } .withName("FLOATING") // fragment numberFromInteger: (Number) = INTEGER (exp)? { ... }; @Suppress("USELESS_CAST") private val numberFromInteger: Parser<Number> = (INTEGER and optional(exp)) .map { (integer: Int, exp: Pair<Char, Int>?) -> // Compiler implicitly casts Double and Int results to Any, so I have to use explicit cast if (exp != null) { val (expOperator: Char, expInt: Int) = exp if (expOperator == '+') (integer.toDouble() * Math.pow(10.0, expInt.toDouble())) as Number // <-- Double else // expOperator will be always '-' (integer.toDouble() / Math.pow(10.0, expInt.toDouble())) as Number // <-- Double } else { integer as Number // <-- Int } } // NUMBER: (Number) = FLOATING | numberFromInteger; val NUMBER: Parser<Number> = (FLOATING or numberFromInteger) .withName("NUMBER") }
src/main/kotlin/org/drimachine/grakmat/PredefinedRules.kt
3560918394
package com.safechat.encryption.asymmetric import com.safechat.encryption.base.KeysBase64Cipher import com.safechat.encryption.generator.newKeyPair import com.safechat.encryption.generator.newSymmetricKey import org.junit.Test import rx.observers.TestSubscriber class LongArraysRSACipherTest { val first = newKeyPair() val second = newKeyPair() @Test fun shouldEncryptAndDecrypt() { val message = KeysBase64Cipher.toBase64String(newSymmetricKey()) val subscriber = TestSubscriber<String>() RSACipher.encrypt(message.toByteArray(), first.public) .flatMap { LongArraysRSACipher.encrypt(it, second.private) } .flatMap { LongArraysRSACipher.decrypt(it, second.public) } .flatMap { RSACipher.decrypt(it, first.private) } .map { String(it) } .subscribe(subscriber) subscriber.assertValue(message) } }
encryption/src/test/java/com/safechat/encryption/asymmetric/LongArraysRSACipherTest.kt
3875502260
package com.openlattice.collections.aggregators import com.hazelcast.aggregation.Aggregator import com.openlattice.collections.CollectionTemplates import com.openlattice.collections.CollectionTemplateKey import java.util.* data class EntitySetCollectionConfigAggregator( val collectionTemplates: CollectionTemplates ) : Aggregator<Map.Entry<CollectionTemplateKey, UUID>, CollectionTemplates> { override fun accumulate(input: Map.Entry<CollectionTemplateKey, UUID>) { val entitySetCollectionId = input.key.entitySetCollectionId val templateTypeId = input.key.templateTypeId val entitySetId = input.value collectionTemplates.put(entitySetCollectionId, templateTypeId, entitySetId) } override fun combine(aggregator: Aggregator<*, *>) { if (aggregator is EntitySetCollectionConfigAggregator) { collectionTemplates.putAll(aggregator.collectionTemplates.templates) } } override fun aggregate(): CollectionTemplates { return collectionTemplates } }
src/main/kotlin/com/openlattice/collections/aggregators/EntitySetCollectionConfigAggregator.kt
2134138253
package com.safechat.conversation.symmetrickey.post import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test import rx.Observable.error import rx.Observable.just import rx.observers.TestSubscriber class PostSymmetricKeyControllerTest { val service = mock<PostSymmetricKeyService>() val repository = mock<PostSymmetricKeyRepository>() val encryptor = mock<PostSymmetricKeyEncryptor>() val controller = PostSymmetricKeyControllerImpl(encryptor, repository, service) val subscriber = TestSubscriber<Unit>() @Before fun setUp() { stubGenerator() stubRepository() stubService() } @Test fun shouldGenerateKey() { startController() verify(encryptor).generateSymmetricKey() } @Test fun shouldSaveGeneratedKey() { startController() verify(repository).saveDecryptedSymmetricKey("otherPublicKey", "newSymmetricKey") } @Test fun shouldEncryptGeneratedKey() { startController() verify(encryptor).encryptSymmetricKey("otherPublicKey", "myPrivateKey", "newSymmetricKey") } @Test fun shouldPostEncryptedKey() { startController() verify(service).postSymmetricKey("myPublicKey", "otherPublicKey", "encryptedSymmetricKey") } @Test fun shouldNotSaveKeyIfPostFails() { whenever(service.postSymmetricKey(any(), any(), any())).thenReturn(error(RuntimeException())) startController() verify(repository, never()).saveDecryptedSymmetricKey(any(), any()) } @Test fun shouldReturnErrorIfPostFails() { val runtimeException = RuntimeException() whenever(service.postSymmetricKey(any(), any(), any())).thenReturn(error(runtimeException)) startController() subscriber.assertError(runtimeException) } @Test fun shouldReturnErrorIfGenerationFails() { val runtimeException = RuntimeException() whenever(encryptor.generateSymmetricKey()).thenReturn(error(runtimeException)) startController() subscriber.assertError(runtimeException) } @Test fun shouldReturnErrorIfEncryptionFails() { val runtimeException = RuntimeException() whenever(encryptor.encryptSymmetricKey(any(), any(), any())).thenReturn(error(runtimeException)) startController() subscriber.assertError(runtimeException) } @Test fun shouldReturnUnitIfEverythingGoesRight() { startController() subscriber.assertValue(Unit) } private fun startController() { controller.postKey("otherPublicKey").subscribe(subscriber) } private fun stubGenerator() { whenever(encryptor.encryptSymmetricKey("otherPublicKey", "myPrivateKey", "newSymmetricKey")).thenReturn(just("encryptedSymmetricKey")) whenever(encryptor.generateSymmetricKey()).thenReturn(just("newSymmetricKey")) } private fun stubRepository() { whenever(repository.getPublicKeyString()).thenReturn("myPublicKey") whenever(repository.getPrivateKeyString()).thenReturn("myPrivateKey") } private fun stubService() { whenever(service.postSymmetricKey("myPublicKey", "otherPublicKey", "encryptedSymmetricKey")).thenReturn(just(Unit)) } }
exchange-symmetric-key-core/src/test/java/com/safechat/conversation/symmetrickey/post/PostSymmetricKeyControllerTest.kt
1748975700
package org.http4k.security import dev.forkhandles.result4k.Failure import dev.forkhandles.result4k.Result import dev.forkhandles.result4k.Success import dev.forkhandles.result4k.flatMap import org.http4k.core.HttpHandler import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.with import org.http4k.lens.WebForm import org.http4k.security.OAuthCallbackError.CouldNotFetchAccessToken import org.http4k.security.OAuthWebForms.clientId import org.http4k.security.OAuthWebForms.code import org.http4k.security.OAuthWebForms.grantType import org.http4k.security.OAuthWebForms.redirectUri import org.http4k.security.OAuthWebForms.requestForm class AccessTokenFetcher( private val api: HttpHandler, private val callbackUri: Uri, private val providerConfig: OAuthProviderConfig, private val accessTokenFetcherAuthenticator: AccessTokenFetcherAuthenticator, private val accessTokenExtractor: AccessTokenExtractor = ContentTypeJsonOrForm() ) { fun fetch(theCode: String): Result<AccessTokenDetails, CouldNotFetchAccessToken> = api( Request(POST, providerConfig.tokenPath) .with( requestForm of WebForm() .with( grantType of "authorization_code", redirectUri of callbackUri, clientId of providerConfig.credentials.user, code of theCode ) ) .authenticate(accessTokenFetcherAuthenticator) ).let { if (it.status != OK) Failure(CouldNotFetchAccessToken(it.status, it.bodyString())) else Success(it) }.flatMap { msg -> accessTokenExtractor(msg) } private fun Request.authenticate(accessTokenFetcherAuthenticator: AccessTokenFetcherAuthenticator): Request = accessTokenFetcherAuthenticator.authenticate(this) }
http4k-security/oauth/src/main/kotlin/org/http4k/security/AccessTokenFetcher.kt
1764885655
/* * 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.jdbi.v3.core.kotlin import org.jdbi.v3.core.Jdbi import org.jdbi.v3.core.spi.JdbiPlugin class KotlinPlugin : JdbiPlugin { override fun customizeJdbi(jdbi: Jdbi) { jdbi.registerRowMapper(KotlinMapperFactory()) } }
kotlin/src/main/kotlin/org/jdbi/v3/core/kotlin/KotlinPlugin.kt
2173280621
package com.retronicgames.lis.visual import com.badlogic.gdx.graphics.Color interface Tintable { var tint: Color? }
core/src/main/kotlin/com/retronicgames/lis/visual/Tintable.kt
2082674998
/* * Copyright (c) 2022 David Allison <[email protected]> * Copyright (c) 2022 Arthur Milchior <[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.servicelayer.scopedstorage import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.* import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.Operation import com.ichi2.compat.CompatHelper import com.ichi2.testutils.TestException import com.ichi2.testutils.createTransientDirectory import org.mockito.invocation.InvocationOnMock import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.spy import org.mockito.kotlin.whenever import timber.log.Timber import java.io.File interface OperationTest { val executionContext: MockMigrationContext /** Helper function: executes an [Operation] and all sub-operations */ fun executeAll(vararg ops: Operation) = MockExecutor(ArrayDeque(ops.toList())) { executionContext } .execute() /** * Executes an [Operation] without executing the sub-operations * @return the sub-operations returned from the execution of the operation */ fun Operation.execute(): List<Operation> = this.execute(executionContext) /** Creates an empty TMP directory to place the output files in */ fun generateDestinationDirectoryRef(): File { val createDirectory = createTransientDirectory() Timber.d("test: deleting $createDirectory") CompatHelper.compat.deleteFile(createDirectory) return createDirectory } /** * Allow to get a MoveDirectoryContent that works for at most three files and fail on the second one. * It keeps track of which files is the failed one and which are before and after; since directory can list its file in * any order, it ensure that we know which file failed. It also allows to test that move still occurs after a failure. */ class SpyMoveDirectoryContent(private val moveDirectoryContent: MoveDirectoryContent) { /** * The first file moved, before the failed file. Null if no moved occurred. */ var beforeFile: File? = null private set /** * The second file, it moves fails. Null if no moved occurred. */ var failedFile: File? = null // ensure the second file fails private set /** * The last file moved, after the failed file. Null if no moved occurred. */ var afterFile: File? = null private set var movesProcessed = 0 private set fun toMoveOperation(op: InvocationOnMock): Operation { val sourceFile = op.arguments[0] as File when (movesProcessed++) { 0 -> beforeFile = sourceFile 1 -> { failedFile = sourceFile return FailMove() } 2 -> afterFile = sourceFile else -> throw IllegalStateException("only 3 files expected") } return op.callRealMethod() as Operation } /** * The [MoveDirectoryContent] that performs the action mentioned in the class description. */ val spy: MoveDirectoryContent get() = spy(moveDirectoryContent) { doAnswer { toMoveOperation(it) }.whenever(it).toMoveOperation(any()) } } } /** A move operation which fails */ class FailMove : Operation() { override fun execute(context: MigrationContext): List<Operation> { throw TestException("should fail but not crash") } }
AnkiDroid/src/test/java/com/ichi2/anki/servicelayer/scopedstorage/OperationTest.kt
2354339057
/**************************************************************************************** * Copyright (c) 2020 arthur milchior <[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.libanki.utils import com.ichi2.libanki.Note object NoteUtils { /** * Set the set tags of currentNote to tagsList. We make no * assumption on the content of tagsList, except that its strings * are valid tags (i.e. no spaces in it). */ fun setTags(currentNote: Note, tagsList: List<String>?) { val currentTags = currentNote.tags.toTypedArray() for (tag in currentTags) { currentNote.delTag(tag) } if (tagsList != null) { val tagsSet = currentNote.col.tags.canonify(tagsList) currentNote.addTags(tagsSet) } } }
AnkiDroid/src/main/java/com/ichi2/libanki/utils/NoteUtils.kt
264234053
package com.infinum.dbinspector.domain.connection.usecases import com.infinum.dbinspector.domain.Repositories import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get import org.mockito.kotlin.any @DisplayName("CloseConnectionUseCase tests") internal class CloseConnectionUseCaseTest : BaseTest() { override fun modules(): List<Module> = listOf( module { factory { mockk<Repositories.Connection>() } } ) @Test fun `Invoking use case invokes connection close`() { val repository: Repositories.Connection = get() val useCase = CloseConnectionUseCase(repository) coEvery { repository.close(any()) } returns Unit test { useCase.invoke(any()) } coVerify(exactly = 1) { repository.close(any()) } } }
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/connection/usecases/CloseConnectionUseCaseTest.kt
2004385735
package eu.stosdev import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty public class bindFXML<T : Any> : ReadOnlyProperty<Any?, T> { private var value: T? = null public override fun getValue(thisRef: Any?, property: KProperty<*>): T { val v = value if (v == null) { throw IllegalStateException("Node was not properly injected") } return v } } public class bindOptionalFXML<T : Any> : ReadOnlyProperty<Any?, T?> { private var value: T? = null public override fun getValue(thisRef: Any?, property: KProperty<*>): T? { return value } }
src/main/kotlin/eu/stosdev/Binders.kt
1569620225
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.compositor.core.events import org.westford.compositor.core.Point class PointerMotion(val time: Int, val point: Point)
compositor/src/main/kotlin/org/westford/compositor/core/events/PointerMotion.kt
1812516586
/* * Copyright 2021 Alex Almeida Tavella * * 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 br.com.moov.moviedetails.data import br.com.moov.core.result.Result import br.com.moov.moviedetails.domain.GetMovieDetailError import br.com.moov.moviedetails.domain.MovieDetail import br.com.moov.moviedetails.testdoubles.TestMovieDetailDataSource import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class DefaultMovieDetailRepositoryTest { private val movies: List<MovieDetail> = listOf( MovieDetail( id = 123, title = "Lord of the Rings" ) ) private val repository = DefaultMovieDetailRepository(TestMovieDetailDataSource(movies)) @Test fun getMovieDetail_exists_returnsMovieDetail() = runBlocking { val actual = repository.getMovieDetail(123) assertEquals(Result.Ok(MovieDetail(123, "Lord of the Rings")), actual) } @Test fun getMovieDetail_notFound_returnsNull() = runBlocking { val actual = repository.getMovieDetail(456) assertEquals(Result.Err(GetMovieDetailError), actual) } }
feature/movie-details/impl/src/test/java/br/com/moov/moviedetails/data/DefaultMovieDetailRepositoryTest.kt
3947410693
package org.wordpress.android.fluxc.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId import org.wordpress.android.fluxc.model.order.FeeLine import org.wordpress.android.fluxc.model.order.LineItem import org.wordpress.android.fluxc.model.order.OrderAddress import org.wordpress.android.fluxc.model.order.ShippingLine import org.wordpress.android.fluxc.model.order.TaxLine import java.math.BigDecimal @Entity( tableName = "OrderEntity", indices = [Index( value = ["localSiteId", "orderId"] )], primaryKeys = ["localSiteId", "orderId"] ) data class OrderEntity( @ColumnInfo(name = "localSiteId") val localSiteId: LocalId, val orderId: Long, val number: String = "", // The, order number to display to the user val status: String = "", val currency: String = "", val orderKey: String = "", val dateCreated: String = "", // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z val dateModified: String = "", // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z val total: String = "", // Complete total, including taxes val totalTax: String = "", // The total amount of tax (from products, shipping, discounts, etc.) val shippingTotal: String = "", // The total shipping cost (excluding tax) val paymentMethod: String = "", // Payment method code e.g. 'cod' 'stripe' val paymentMethodTitle: String = "", // Displayable payment method e.g. 'Cash on delivery' 'Credit Card (Stripe)' val datePaid: String = "", val pricesIncludeTax: Boolean = false, val customerNote: String = "", // Note left by the customer during order submission val discountTotal: String = "", val discountCodes: String = "", val refundTotal: BigDecimal = BigDecimal.ZERO, // The total refund value for this order (usually a negative number) val billingFirstName: String = "", val billingLastName: String = "", val billingCompany: String = "", val billingAddress1: String = "", val billingAddress2: String = "", val billingCity: String = "", val billingState: String = "", val billingPostcode: String = "", val billingCountry: String = "", val billingEmail: String = "", val billingPhone: String = "", val shippingFirstName: String = "", val shippingLastName: String = "", val shippingCompany: String = "", val shippingAddress1: String = "", val shippingAddress2: String = "", val shippingCity: String = "", val shippingState: String = "", val shippingPostcode: String = "", val shippingCountry: String = "", val shippingPhone: String = "", val lineItems: String = "", val shippingLines: String = "", val feeLines: String = "", val taxLines: String = "", val metaData: String = "", // this is a small subset of the metadata, see OrderMetaDataEntity for full metadata @ColumnInfo(name = "paymentUrl", defaultValue = "") val paymentUrl: String = "", @ColumnInfo(name = "isEditable", defaultValue = "1") val isEditable: Boolean = true ) { companion object { private val gson by lazy { Gson() } } /** * Returns true if there are shipping details defined for this order, * which are different from the billing details. * * If no separate shipping details are defined, the billing details should be used instead, * as the shippingX properties will be empty. */ fun hasSeparateShippingDetails() = shippingCountry.isNotEmpty() /** * Returns the billing details wrapped in a [OrderAddress]. */ fun getBillingAddress() = OrderAddress.Billing(this) /** * Returns the shipping details wrapped in a [OrderAddress]. */ fun getShippingAddress() = OrderAddress.Shipping(this) /** * Deserializes the JSON contained in [lineItems] into a list of [LineItem] objects. */ fun getLineItemList(): List<LineItem> { val responseType = object : TypeToken<List<LineItem>>() {}.type return gson.fromJson(lineItems, responseType) as? List<LineItem> ?: emptyList() } /** * Returns the order subtotal (the sum of the subtotals of each line item in the order). */ fun getOrderSubtotal(): Double { return getLineItemList().sumByDouble { it.subtotal?.toDoubleOrNull() ?: 0.0 } } /** * Deserializes the JSON contained in [shippingLines] into a list of [ShippingLine] objects. */ fun getShippingLineList(): List<ShippingLine> { val responseType = object : TypeToken<List<ShippingLine>>() {}.type return gson.fromJson(shippingLines, responseType) as? List<ShippingLine> ?: emptyList() } /** * Deserializes the JSON contained in [feeLines] into a list of [FeeLine] objects. */ fun getFeeLineList(): List<FeeLine> { val responseType = object : TypeToken<List<FeeLine>>() {}.type return gson.fromJson(feeLines, responseType) as? List<FeeLine> ?: emptyList() } /** * Deserializes the JSON contained in [taxLines] into a list of [TaxLine] objects. */ fun getTaxLineList(): List<TaxLine> { val responseType = object : TypeToken<List<TaxLine>>() {}.type return gson.fromJson(taxLines, responseType) as? List<TaxLine> ?: emptyList() } /** * Deserializes the JSON contained in [metaData] into a list of [WCMetaData] objects. */ fun getMetaDataList(): List<WCMetaData> { val responseType = object : TypeToken<List<WCMetaData>>() {}.type return gson.fromJson(metaData, responseType) as? List<WCMetaData> ?: emptyList() } fun isMultiShippingLinesAvailable() = getShippingLineList().size > 1 }
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/OrderEntity.kt
1324142798
package app.youkai.data.service import app.youkai.data.models.* import app.youkai.data.remote.Client import app.youkai.util.SerializationUtils import app.youkai.util.ext.append import app.youkai.util.ext.capitalizeFirstLetter import com.github.jasminb.jsonapi.JSONAPIDocument import com.github.jasminb.jsonapi.retrofit.JSONAPIConverterFactory import io.reactivex.Observable import okhttp3.MediaType import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Response import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.jackson.JacksonConverterFactory object Api { private val JSON_API_CONTENT_TYPE = "application/vnd.api+json" val BASE = "https://kitsu.io/api/" private val CLIENT_ID = "dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd" private val CLIENT_SECRET = "54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151" /** * Lazy modifier only instantiates when the value is first used. * See: https://kotlinlang.org/docs/reference/delegated-properties.html */ private val converterFactory by lazy { val converterFactory = JSONAPIConverterFactory(ResourceConverters.mainConverter) converterFactory.setAlternativeFactory(JacksonConverterFactory.create()) converterFactory } private val service: Service by lazy { val retrofit: Retrofit = Retrofit.Builder() .client(Client) .baseUrl(BASE) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(converterFactory) .build() retrofit.create(Service::class.java) } /** * Authentication */ fun login(username: String, password: String) = service.postLogin(username, password, "password", CLIENT_ID, CLIENT_SECRET) fun refreshAuthToken(refreshToken: String) = service.refreshAuthToken(refreshToken, "refresh_token", CLIENT_ID, CLIENT_SECRET) private fun createAuthorizationParam(tokenType: String, authToken: String): String = tokenType.capitalizeFirstLetter().append(authToken, " ") /** * Anime */ private val getAllAnimeCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllAnime(m) } fun allAnime(): RequestBuilder<Observable<JSONAPIDocument<List<Anime>>>> = RequestBuilder("", getAllAnimeCall) private val getAnimeCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getAnime(id, h, m) } fun anime(id: String): RequestBuilder<Observable<JSONAPIDocument<Anime>>> = RequestBuilder(id, getAnimeCall) fun searchAnime(query: String): RequestBuilder<Observable<JSONAPIDocument<List<Anime>>>> = RequestBuilder("", getAllAnimeCall).filter("text", query) private val getAnimeLanguagesCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getAnimeLanguages(id, h, m) } fun languagesForAnime(animeId: String): RequestBuilder<Observable<List<String>>> = RequestBuilder(animeId, getAnimeLanguagesCall) private val getAnimeEpisodesCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getAnimeEpisodes(id, h, m) } fun episodesForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Episode>>>> = RequestBuilder(animeId, getAnimeEpisodesCall) private val getAnimeMediaRelationshipsCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getAnimeMediaRelationships(id, h, m) } fun mediaRelationshipsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<MediaRelationship>>>> = RequestBuilder(animeId, getAnimeMediaRelationshipsCall) /** * Manga */ private val getAllMangaCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllManga(m) } fun allManga(): RequestBuilder<Observable<JSONAPIDocument<List<Manga>>>> = RequestBuilder("", getAllMangaCall) private val getMangaCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getManga(id, h, m) } fun manga(id: String): RequestBuilder<Observable<JSONAPIDocument<Manga>>> = RequestBuilder(id, getMangaCall) fun searchManga(query: String): RequestBuilder<Observable<JSONAPIDocument<List<Manga>>>> = RequestBuilder("", getAllMangaCall).filter("text", query) private val getMangaChaptersCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getMangaChapters(id, h, m) } fun chaptersForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Chapter>>>> = RequestBuilder(mangaId, getMangaChaptersCall) private val getMangaMediaRelationshipsCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getMangaMediaRelationships(id, h, m) } /** * Not implemented on server. */ fun mediaRelationshipsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<MediaRelationship>>>> = RequestBuilder(mangaId, getMangaMediaRelationshipsCall) /** * Library */ private val getAllLibraryEntriesCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllLibraryEntries(m) } fun allLibraryEntries(): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> = RequestBuilder("", getAllLibraryEntriesCall) private val getLibraryCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getLibrary(id, h, m) } fun library(id: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> = RequestBuilder(id, getLibraryCall) private val getLibraryEntryCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getLibraryEntry(id, h, m) } fun libraryEntry(id: String): RequestBuilder<Observable<JSONAPIDocument<LibraryEntry>>> = RequestBuilder(id, getLibraryEntryCall) private fun libraryEntryForMedia(userId: String, mediaId: String, mediaType: String) : RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> { return RequestBuilder("", getAllLibraryEntriesCall) .filter("userId", userId) .filter("kind", mediaType) .filter(mediaType + "Id", mediaId) .page("limit", 1) } fun libraryEntryForAnime(userId: String, animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> = libraryEntryForMedia(userId, animeId, "anime") fun libraryEntryForManga(userId: String, mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> = libraryEntryForMedia(userId, mangaId, "manga") fun createLibraryEntry(libraryEntry: LibraryEntry, authToken: String, tokenType: String = "bearer") : Observable<Response<ResponseBody>> { libraryEntry.id = "temporary_id" var body: String = ResourceConverters .mainConverter .writeDocument(JSONAPIDocument<LibraryEntry>(libraryEntry)) .toString(Charsets.UTF_8) // remove the ID as it should not be sent (the resource has not been create yet so throws an error on the server) body = SerializationUtils.removeFirstIdFromJson(body) return service.createLibraryEntry( createAuthorizationParam(tokenType, authToken), RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body) ) } fun updateLibraryEntry(libraryEntry: LibraryEntry, authToken: String, tokenType: String = "bearer"): Observable<JSONAPIDocument<LibraryEntry>> { val body = ResourceConverters.mainConverter.writeDocument(JSONAPIDocument<LibraryEntry>(libraryEntry)) return service.updateLibraryEntry( createAuthorizationParam(tokenType, authToken), libraryEntry.id!!, RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body) ) } fun deleteLibraryEntry(id: String, authToken: String, tokenType: String = "bearer"): Observable<Response<Void>> = service.deleteLibraryEntry(createAuthorizationParam(tokenType, authToken), id) /** * Favorites */ private val getAllFavoritesCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllFavorites(h, m) } fun allFavorites(): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>> = RequestBuilder("", getAllFavoritesCall) private val getFavoriteCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getFavorite(id, h, m) } fun favorite(id: String): RequestBuilder<Observable<JSONAPIDocument<Favorite>>> = RequestBuilder(id, getFavoriteCall) private fun favoriteForMedia(userId: String, mediaId: String, mediaType: String) : RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>> { return RequestBuilder("", getAllFavoritesCall) .filter("userId", userId) .filter("itemId", mediaId) .filter("itemType", mediaType) .page("limit", 1) } fun favoriteForAnime(userId: String, animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>> = favoriteForMedia(userId, animeId, "Anime") fun favoriteForManga(userId: String, mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>> = favoriteForMedia(userId, mangaId, "Manga") // TODO: create version of method without need for full object fun createFavorite(favorite: Favorite, authToken: String, tokenType: String = "bearer"): Observable<JSONAPIDocument<Favorite>> { favorite.id = "temporary_id" var body = ResourceConverters .mainConverter .writeDocument(JSONAPIDocument<Favorite>(favorite)) .toString(Charsets.UTF_8) body = SerializationUtils.removeIdFromJson(body, favorite.id!!) return service.postFavorite( createAuthorizationParam(tokenType, authToken), RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body) ) } fun createFavorite(userId: String, mediaId: String, mediaType: JsonType, authToken: String, tokenType: String = "bearer") { //TODO: write (blocked by polymorph) } //TODO: test (need to make a test for [createFavorite] first so can test safely fun deleteFavorite(id: String): Observable<Response<Void>> { return service.deleteFavorite(id) } /** * Characters */ private val getAllCharactersCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllCharacters(h, m) } fun allCharacters(): RequestBuilder<Observable<JSONAPIDocument<List<Character>>>> = RequestBuilder("", getAllCharactersCall) private val getCharacterCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getCharacter(id, h, m) } fun character(id: String): RequestBuilder<Observable<JSONAPIDocument<Character>>> = RequestBuilder(id, getCharacterCall) private val getAnimeCharactersCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getAnimeCharacters(id, h, m) } /** * No equivalent method for Manga due to current Api limits (no filter for `mediaType` on `/characters` and `manga-characters` is unfilled. * You must use [castingsForManga] and append the following [RequestBuilder] methods: * .filter("isCharacter", "true") * .include("character", "person") */ fun charactersForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<AnimeCharacter>>>> = RequestBuilder(animeId, getAnimeCharactersCall) /** * Castings */ private val getAllCastingsCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllCastings(h, m) } fun allCastings(): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>> = RequestBuilder("", getAllCastingsCall) private val getCastingCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getCasting(id, h, m) } fun casting(id: String): RequestBuilder<Observable<JSONAPIDocument<Casting>>> = RequestBuilder(id, getCastingCall) private fun castingsForMedia(mediaId: String, mediaType: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>> = RequestBuilder("", getAllCastingsCall) .filter("mediaType", mediaType) .filter("mediaId", mediaId) fun castingsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>> = castingsForMedia(animeId, "Anime") fun castingsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>> = castingsForMedia(mangaId, "Manga") /** * Reactions */ private val getAllReactionsCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllReactions(h, m) } fun allReactions(): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>> = RequestBuilder("", getAllReactionsCall) private val getReactionCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getReaction(id, h, m) } fun reaction(id: String): RequestBuilder<Observable<JSONAPIDocument<Reaction>>> = RequestBuilder(id, getReactionCall) private fun reactionsForMedia(mediaId: String, mediaType: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>> = RequestBuilder("", getAllReactionsCall) .filter(mediaType + "Id", mediaId) fun reactionsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>> = reactionsForMedia(animeId, "anime") fun reactionsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>> = reactionsForMedia(mangaId, "manga") private val getLibraryEntryReactionCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getLibraryEntryReaction(id, h, m) } fun reactionForLibraryEntry(libraryEntryId: String): RequestBuilder<Observable<JSONAPIDocument<Reaction>>> = RequestBuilder(libraryEntryId, getLibraryEntryReactionCall) /** * Users */ private val getAllUsersCall = { _: String, h: Map<String, String>, m: Map<String, String> -> service.getAllUsers(h, m) } fun allUsers(): RequestBuilder<Observable<JSONAPIDocument<List<User>>>> = RequestBuilder("", getAllUsersCall) fun allUsersAuth(authToken: String, tokenType: String = "bearer"): RequestBuilder<Observable<JSONAPIDocument<List<User>>>> = RequestBuilder("", getAllUsersCall) .withHeader("Authorization", createAuthorizationParam(tokenType, authToken)) private val getUserCall = { id: String, h: Map<String, String>, m: Map<String, String> -> service.getUser(id, h, m) } fun user(id: String): RequestBuilder<Observable<JSONAPIDocument<User>>> = RequestBuilder(id, getUserCall) }
app/src/main/kotlin/app/youkai/data/service/Api.kt
605892976
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.testing import java.nio.file.Path import org.wfanet.measurement.common.getJarResourcePath object Schemata { private const val KINGDOM_SPANNER_RESOURCE_PREFIX = "kingdom/spanner" private fun getResourcePath(fileName: String): Path { val resourceName = "$KINGDOM_SPANNER_RESOURCE_PREFIX/$fileName" val classLoader: ClassLoader = Thread.currentThread().contextClassLoader return requireNotNull(classLoader.getJarResourcePath(resourceName)) { "Resource $resourceName not found" } } val KINGDOM_CHANGELOG_PATH: Path = getResourcePath("changelog.yaml") }
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/testing/Schemata.kt
3421476562
package io.rover.sdk.experiences.assets import android.graphics.Bitmap import org.reactivestreams.Publisher import java.net.URL /** * A pipeline step that does I/O operations of (fetch, cache, etc.) an asset. * * Stages will synchronously block the thread while waiting for I/O. * * Stages should not block to do computation-type work, however; the asset pipeline is * run on a thread pool optimized for I/O multiplexing and not computation. */ internal interface SynchronousPipelineStage<in TInput, TOutput> { fun request(input: TInput): PipelineStageResult<TOutput> } internal sealed class PipelineStageResult<TOutput> { class Successful<TOutput>(val output: TOutput) : PipelineStageResult<TOutput>() class Failed<TOutput>(val reason: Throwable, val retry: Boolean) : PipelineStageResult<TOutput>() } internal interface AssetService { /** * Subscribe to any updates for the image at URL, fully decoded and ready for display. * * It will complete after successfully yielding once. However, it will not attempt * * The Publisher will yield on the app's main UI thread. */ fun imageByUrl( url: URL ): Publisher<Bitmap> /** * Use this to request and wait for a single update to the given image asset by URI. Use this * is lieu of [imageByUrl] if you need to subscribe to a single update. */ fun getImageByUrl( url: URL ): Publisher<PipelineStageResult<Bitmap>> /** * Request a fetch. Be sure you are subscribed to [imageByUrl] to receive the updates. */ fun tryFetch( url: URL ) }
experiences/src/main/kotlin/io/rover/sdk/experiences/assets/Interfaces.kt
1176102568
package taiwan.no1.app.mvp.contracts import taiwan.no1.app.mvp.presenters.IPresenter import taiwan.no1.app.mvp.views.IActivityView import taiwan.no1.app.mvp.views.IView /** * This specifies the contract between the [IPresenter] and the [IView]. * * @author Jieyi * @since 1/15/17 */ interface VideoContract { interface Presenter: IPresenter<View> interface View: IView, IActivityView }
app/src/main/kotlin/taiwan/no1/app/mvp/contracts/VideoContract.kt
3436609351
/* * Copyright (C) 2014 Simon Vig Therkildsen * * 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 net.simonvt.cathode.api.service import net.simonvt.cathode.api.entity.SearchResult import net.simonvt.cathode.api.enumeration.Enums import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.enumeration.ItemType import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface SearchService { /** * Queries will search fields like the title and description. */ @GET("/search/{type}") fun search( @Path("type") types: Enums<ItemType>, @Query("query") query: String, @Query("limit") limit: Int = LIMIT, @Query("extended") extended: Extended? = null ): Call<List<SearchResult>> companion object { const val LIMIT = 100 } }
trakt-api/src/main/java/net/simonvt/cathode/api/service/SearchService.kt
2069733474
package com.github.k0kubun.gitstar_ranking.core data class StarsCursor( val id: Long, val stars: Long, )
worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/core/StarsCursor.kt
1412847302
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.kotlin.mybatis3.canonical import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.util.kotlin.elements.column import java.sql.JDBCType import java.util.Date object PersonDynamicSqlSupport { val person = Person() val id = person.id val firstName = person.firstName val lastName = person.lastName val birthDate = person.birthDate val employed = person.employed val occupation = person.occupation val addressId = person.addressId class Person : SqlTable("Person") { val id = column<Int>(name = "id", jdbcType = JDBCType.INTEGER) val firstName = column<String>(name = "first_name", jdbcType = JDBCType.VARCHAR) val lastName = column<LastName>( name = "last_name", jdbcType = JDBCType.VARCHAR, typeHandler = "examples.kotlin.mybatis3.canonical.LastNameTypeHandler" ) val birthDate = column<Date>(name = "birth_date", jdbcType = JDBCType.DATE) val employed = column<Boolean>( name = "employed", JDBCType.VARCHAR, typeHandler = "examples.kotlin.mybatis3.canonical.YesNoTypeHandler" ) val occupation = column<String>(name = "occupation", jdbcType = JDBCType.VARCHAR) val addressId = column<Int>(name = "address_id", jdbcType = JDBCType.INTEGER) } }
src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonDynamicSqlSupport.kt
4252249038
package voice.data.repo import voice.data.Chapter import voice.data.repo.internals.dao.ChapterDao import voice.data.runForMaxSqlVariableNumber import java.time.Instant import javax.inject.Inject import javax.inject.Singleton @Singleton class ChapterRepo @Inject constructor( private val dao: ChapterDao, ) { private val cache = mutableMapOf<Chapter.Id, Chapter?>() suspend fun get(id: Chapter.Id): Chapter? { // this does not use getOrPut because a `null` value should also be cached if (!cache.containsKey(id)) { cache[id] = dao.chapter(id) } return cache[id] } suspend fun warmup(ids: List<Chapter.Id>) { val missing = ids.filter { it !in cache } missing .runForMaxSqlVariableNumber { dao.chapters(it) } .forEach { cache[it.id] = it } } suspend fun put(chapter: Chapter) { dao.insert(chapter) cache[chapter.id] = chapter } suspend inline fun getOrPut( id: Chapter.Id, lastModified: Instant, defaultValue: () -> Chapter?, ): Chapter? { val chapter = get(id) if (chapter != null && chapter.fileLastModified == lastModified) { return chapter } return defaultValue()?.also { put(it) } } }
data/src/main/kotlin/voice/data/repo/ChapterRepo.kt
31031990
package com.polito.sismic.Presenters.Adapters import android.content.Context import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.polito.sismic.Domain.NeighboursNodeData import com.polito.sismic.Domain.PeriodData import com.polito.sismic.Domain.PillarDomainGraphPoint import com.polito.sismic.Domain.SpectrumDTO import com.polito.sismic.Extensions.inflate import com.polito.sismic.Interactors.Helpers.StatiLimite import com.polito.sismic.R import kotlinx.android.synthetic.main.close_points_layout.view.* import kotlinx.android.synthetic.main.domain_point_item.view.* import kotlinx.android.synthetic.main.limit_state_data_layout.view.* import kotlinx.android.synthetic.main.period_data_layout.view.* class NodeListAdapter(private val mContext: Context, private val mNodeData: List<NeighboursNodeData>) : RecyclerView.Adapter<NodeListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NodeListAdapter.ViewHolder? { val v = parent.inflate(R.layout.close_points_layout) return NodeListAdapter.ViewHolder(v, mContext) } override fun onBindViewHolder(holder: NodeListAdapter.ViewHolder, position: Int) { if (position == 0) holder.bindHeader() else holder.bindNodeData(mNodeData[position - 1]) } override fun getItemCount(): Int { return mNodeData.size + 1 } class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) { fun bindNodeData(neighboursNodeData: NeighboursNodeData) = with(neighboursNodeData) { itemView.node_id.text = id itemView.node_longitude.text = longitude.toString() itemView.node_latitude.text = latitude.toString() itemView.node_distance.text = String.format(mContext.resources.getText(R.string.km_format).toString(), distance) } fun bindHeader() { itemView.node_id.text = mContext.resources.getText(R.string.nodelist_id_header) itemView.node_longitude.text = mContext.resources.getText(R.string.nodelist_longitude_header) itemView.node_latitude.text = mContext.resources.getText(R.string.nodelist_latitude_header) itemView.node_distance.text = mContext.resources.getText(R.string.nodelist_distance_header) itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey)) } } } class PeriodListAdapter(private val mContext: Context, private val mPeriodDataList: List<PeriodData>) : RecyclerView.Adapter<PeriodListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PeriodListAdapter.ViewHolder? { val v = parent.inflate(R.layout.period_data_layout) return PeriodListAdapter.ViewHolder(v, mContext) } override fun onBindViewHolder(holder: PeriodListAdapter.ViewHolder, position: Int) { if (position == 0) holder.bindHeader() else holder.bindPeriodData(mPeriodDataList[position - 1]) } override fun getItemCount(): Int { return mPeriodDataList.size + 1 } class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) { fun bindPeriodData(periodData: PeriodData) = with(periodData) { itemView.year.text = years.toString() itemView.ag.text = String.format(mContext.resources.getText(R.string.params_format).toString(), ag) itemView.f0.text = String.format(mContext.resources.getText(R.string.params_format).toString(), f0) itemView.tcstar.text = String.format(mContext.resources.getText(R.string.params_format).toString(), tcstar) } fun bindHeader() { itemView.year.text = mContext.resources.getText(R.string.year_header) itemView.ag.text = mContext.resources.getText(R.string.ag_header) itemView.f0.text = mContext.resources.getText(R.string.f0_header) itemView.tcstar.text = mContext.resources.getText(R.string.tcstar_header) itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey)) } } } class LimitStateAdapter(private val mContext: Context, private val mLimitStateAdapter: List<SpectrumDTO>) : RecyclerView.Adapter<LimitStateAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LimitStateAdapter.ViewHolder? { val v = parent.inflate(R.layout.limit_state_data_layout) return LimitStateAdapter.ViewHolder(v, mContext) } override fun onBindViewHolder(holder: LimitStateAdapter.ViewHolder, position: Int) { if (position == 0) holder.bindHeader() else holder.bindPeriodData(mLimitStateAdapter[position - 1]) } override fun getItemCount(): Int { return mLimitStateAdapter.size + 1 } class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) { fun bindPeriodData(periodData: SpectrumDTO) = with(periodData) { val state = StatiLimite.values().first { it.name == name } itemView.state.text = String.format(mContext.getString(R.string.params_spectrum_state_format_old), state.name, (state.multiplier * 100).toInt(), "%") itemView.tc.text = String.format(mContext.getString(R.string.params_spectrum_format), tc) itemView.tb.text = String.format(mContext.getString(R.string.params_spectrum_format), tb) itemView.td.text = String.format(mContext.getString(R.string.params_spectrum_format), td) itemView.cc.text = String.format(mContext.getString(R.string.params_spectrum_format), ag) itemView.ss.text = String.format(mContext.getString(R.string.params_spectrum_format), f0) itemView.s.text = String.format(mContext.getString(R.string.params_spectrum_format), tcStar) } fun bindHeader() { itemView.state.text = mContext.resources.getText(R.string.state_header) itemView.tc.text = mContext.resources.getText(R.string.tc_header) itemView.tb.text = mContext.resources.getText(R.string.tb_header) itemView.td.text = mContext.resources.getText(R.string.td_header) //same layout but i show other datas itemView.cc.text = mContext.resources.getText(R.string.ag_header) itemView.ss.text = mContext.resources.getText(R.string.f0_header) itemView.s.text = mContext.resources.getText(R.string.tcstar_header) itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey)) } } } class DomainPointAdapter(private val mContext: Context, private val mDomainPointList: List<PillarDomainGraphPoint>) : RecyclerView.Adapter<DomainPointAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DomainPointAdapter.ViewHolder? { val v = parent.inflate(R.layout.domain_point_item) return DomainPointAdapter.ViewHolder(v, mContext) } override fun onBindViewHolder(holder: DomainPointAdapter.ViewHolder, position: Int) { if (position == 0) holder.bindHeader() else holder.bindPillarDomainPoint(mDomainPointList[position - 1], position) } override fun getItemCount(): Int { return mDomainPointList.size + 1 } class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) { fun bindPillarDomainPoint(domainPoint: PillarDomainGraphPoint, index: Int) = with(domainPoint) { itemView.index.text = String.format(mContext.getString(R.string.domain_point_id_value), index) itemView.n.text = String.format(mContext.getString(R.string.domain_point_value_format_high), n) itemView.m.text = String.format(mContext.getString(R.string.domain_point_value_format_high), m) } fun bindHeader() { itemView.index.text = mContext.getString(R.string.domain_point_id_label) itemView.n.text = mContext.getString(R.string.domain_point_n_label) itemView.m.text = mContext.getString(R.string.domain_point_m_label) itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey)) } } }
app/src/main/java/com/polito/sismic/Presenters/Adapters/NodeListAdapter.kt
1085782320
package com.github.ykrank.androidtools.widget.uglyfix import android.content.Context import androidx.drawerlayout.widget.DrawerLayout import android.util.AttributeSet import android.view.MotionEvent import java.lang.Exception /** * Created by ykrank on 2017/7/22. */ class FixDrawerLayout : androidx.drawerlayout.widget.DrawerLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) override fun onTouchEvent(ev: MotionEvent?): Boolean { try { return super.onTouchEvent(ev) } catch (e: Exception) { e.printStackTrace() return true } } }
library/src/main/java/com/github/ykrank/androidtools/widget/uglyfix/FixDrawerLayout.kt
1487287578
package com.lasthopesoftware.bluewater.client.connection.testing import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider import com.lasthopesoftware.bluewater.shared.StandardRequest import com.namehillsoftware.handoff.promises.Promise import com.namehillsoftware.handoff.promises.propagation.CancellationProxy import okhttp3.Response import org.slf4j.LoggerFactory import java.io.IOException object ConnectionTester : TestConnections { private val logger = LoggerFactory.getLogger(ConnectionTester::class.java) override fun promiseIsConnectionPossible(connectionProvider: IConnectionProvider): Promise<Boolean> = ConnectionPossiblePromise(connectionProvider) private class ConnectionPossiblePromise(connectionProvider: IConnectionProvider) : Promise<Boolean>() { init { val cancellationProxy = CancellationProxy() respondToCancellation(cancellationProxy) connectionProvider.promiseResponse("Alive") .also(cancellationProxy::doCancel) .then({ resolve(!cancellationProxy.isCancelled && testResponse(it)) }, { resolve(false) }) } } private fun testResponse(response: Response): Boolean { response.body?.use { body -> try { return body.byteStream().use(StandardRequest::fromInputStream)?.isStatus ?: false } catch (e: IOException) { logger.error("Error closing connection, device failure?", e) } catch (e: IllegalArgumentException) { logger.warn("Illegal argument passed in", e) } } return false } }
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/testing/ConnectionTester.kt
974103459
package za.org.grassroot2.database import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import za.org.grassroot2.model.* import za.org.grassroot2.model.enums.GrassrootEntityType import za.org.grassroot2.model.network.Syncable import za.org.grassroot2.model.request.MemberRequest import za.org.grassroot2.model.task.Meeting import za.org.grassroot2.model.task.Task /** * Created by luke on 2017/08/10. */ interface DatabaseService { fun wipeDatabase() fun loadUserProfile(): UserProfile? fun <E> load(clazz: Class<E>, uid: String): Maybe<E> fun <E> loadObjectByUid(cls: Class<E>, uid: String): E? fun loadGroup(uid: String): Group? fun <E> loadExistingObjectsWithLastChangeTime(clazz: Class<E>): Map<String, Long> fun getTasksLastChangedTimestamp(groupUid: String): Map<String, Long> fun <E> loadObjects(clazz: Class<E>): List<E> fun loadGroupsSorted(): List<Group> fun <E> loadObjectsByName(clazz: Class<E>, nameQuery: String): List<E> fun loadTasksForGroup(groupUid: String, type: GrassrootEntityType?): Single<List<Task>> fun loadMembersForGroup(groupUid: String): Single<List<Membership>> fun loadMemberLogsForGroup(groupUid: String): Single<List<MembershipLog>> fun countMembersJoinedSince(groupUid: String, cutOffDate: Long): Long // write and read methods (can only be called within an observable on background thread) fun <E> store(cls: Class<E>, `object`: E): Single<E> fun <E> storeObject(cls: Class<E>, `object`: E): E fun <E> copyOrUpdateListOfEntities(cls: Class<E>, objects: List<E>): List<E> // void executeTransaction(Realm.Transaction transaction); fun updateOrCreateUserProfile(userUid: String, userPhone: String, userDisplayName: String, email: String?, languageCode: String, userSystemRole: String?): UserProfile fun removeUserProfile() fun removeGroup(groupUid: String): Boolean fun storeGroupWithMembers(group: Group): Single<Group> // only for debugging fun <E> listAllEntitesOfType(clazz: Class<E>) fun storeMembersInvites(requests: List<MemberRequest>) fun <E : Syncable> getObjectsToSync(cls: Class<E>): Observable<List<E>> fun storeTasks(data: List<Task>) fun delete(r: MemberRequest) fun <E> delete(cls: Class<E>, item: E) fun <E> loadObjectsSortedByDate(clazz: Class<E>): List<E> fun getMemberRequestsToSync(): Observable<List<MemberRequest>> fun getAllTasksLastChangedTimestamp(): Map<String, Long> fun loadAllTasksSorted(): Maybe<List<Task>> fun <E> load(clazz: Class<E>): Maybe<List<E>> fun <E> deleteAll(cls: Class<E>) fun loadPublicMeetings(): Maybe<List<AroundEntity>> fun storePosts(meeting: Meeting, posts: List<Post>) fun getMeetings(taskUid: String): Maybe<List<Post>> }
app/src/main/java/za/org/grassroot2/database/DatabaseService.kt
2850075480
package za.org.grassroot2 import android.Manifest import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.support.v4.graphics.drawable.RoundedBitmapDrawable import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory import android.view.View import android.widget.Toast import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import com.tbruyelle.rxpermissions2.RxPermissions import io.reactivex.Observable import kotlinx.android.synthetic.main.activity_group_settings.* import timber.log.Timber import za.org.grassroot2.dagger.activity.ActivityComponent import za.org.grassroot2.model.Group import za.org.grassroot2.presenter.activity.GroupSettingsPresenter import za.org.grassroot2.view.activity.DashboardActivity import za.org.grassroot2.view.activity.GrassrootActivity import za.org.grassroot2.view.dialog.GenericSelectDialog import za.org.grassroot2.view.dialog.SelectImageDialog import javax.inject.Inject class GroupSettingsActivity : GrassrootActivity(), GroupSettingsPresenter.GroupSettingsView,SelectImageDialog.SelectImageDialogEvents { override val layoutResourceId: Int get() = R.layout.activity_group_settings @Inject lateinit var presenter: GroupSettingsPresenter @Inject lateinit var rxPermission: RxPermissions private val REQUEST_TAKE_PHOTO = 2 private val REQUEST_GALLERY = 3 private var groupUid: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) groupUid = intent.getStringExtra(EXTRA_GROUP_UID) presenter.attach(this) presenter.init(groupUid!!) initToolbar() viewMembers.setOnClickListener { presenter.loadMembers() } hideGroup.setOnClickListener { presenter.hideGroup() } leaveGroup.setOnClickListener { presenter.leaveGroup() } exportGroup.setOnClickListener{ presenter.exportMembers() } } override fun onResume() { super.onResume() presenter.loadData() } override fun render(group: Group, lastMonthCount: Long) { supportActionBar!!.title = group.name description.text = if (lastMonthCount > 0) getString(R.string.member_count_recent, group.memberCount, lastMonthCount) else getString(R.string.member_count_basic, group.memberCount) if(group.profileImageUrl != null){ loadProfilePic(group.profileImageUrl) } if(!group.permissions.contains("GROUP_PERMISSION_UPDATE_GROUP_DETAILS")){ changePhoto.visibility = View.GONE }else{ changePhoto.visibility = View.VISIBLE changePhoto.setOnClickListener { v -> val dialog:SelectImageDialog = SelectImageDialog.newInstance(R.string.select_image,false); dialog.show(supportFragmentManager,"DIALOG_TAG") } } //loadProfilePic(group.uid) viewMembers.isEnabled = group.hasMembersFetched() } override fun membersAvailable(totalMembers: Int, lastMonthCount: Long) { viewMembers.isEnabled = true description.text = if (lastMonthCount > 0) getString(R.string.member_count_recent, totalMembers, lastMonthCount) else getString(R.string.member_count_basic, totalMembers) } private fun loadProfilePic(url: String) { //val url = BuildConfig.API_BASE + "group/image/view/" + groupUid Picasso.get() .load(url) .resizeDimen(R.dimen.profile_photo_s_width, R.dimen.profile_photo_s_height) .placeholder(R.drawable.group_5) .error(R.drawable.group_5) .centerCrop() .into(groupPhoto, object : Callback { override fun onSuccess() { val imageBitmap = (groupPhoto.drawable as BitmapDrawable).bitmap val imageDrawable: RoundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, imageBitmap) imageDrawable.isCircular = true imageDrawable.cornerRadius = Math.max(imageBitmap.width, imageBitmap.height) / 2.0f groupPhoto.setImageDrawable(imageDrawable) } override fun onError(e: Exception?) { groupPhoto.setImageResource(R.drawable.user) } }) } override fun exitToHome(messageToUser: Int) { Toast.makeText(this, messageToUser, Toast.LENGTH_SHORT).show() startActivity(Intent(this, DashboardActivity::class.java)) finish() } override fun ensureWriteExteralStoragePermission(): Observable<Boolean> { return rxPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE) } private fun initToolbar() { setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp) toolbar.setNavigationOnClickListener { v -> finish() } } override fun selectFileActionDialog(fileUri: Uri) { val dialog = GenericSelectDialog.get(getString(R.string.group_export_select), intArrayOf(R.string.open_file, R.string.share_file), arrayListOf<View.OnClickListener>( View.OnClickListener { tryOpenExcel(fileUri) }, View.OnClickListener { tryShareExcel(fileUri) } )) dialog.show(supportFragmentManager, DIALOG_TAG) } private fun tryOpenExcel(fileUri: Uri) { val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(fileUri, "application/vnd.ms-excel") try { startActivity(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(this, R.string.open_file_no_app, Toast.LENGTH_SHORT).show() } } private fun tryShareExcel(fileUri: Uri) { val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_STREAM, fileUri) intent.setType("application/vnd.ms-excel") try { startActivity(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(this, R.string.share_file_no_app, Toast.LENGTH_SHORT).show() } } override fun onInject(component: ActivityComponent) { component.inject(this) } override fun openCamera() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun pickImageFromGallery() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun cameraForResult(contentProviderPath: String, s: String) { val intent:Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse(contentProviderPath)) intent.putExtra("MY_UID", s) startActivityForResult(intent,REQUEST_TAKE_PHOTO) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if(resultCode == Activity.RESULT_OK){ if(requestCode == REQUEST_TAKE_PHOTO){ presenter.cameraResult() } else if(requestCode == REQUEST_GALLERY){ val imageUri:Uri = data!!.data //presenter.setGroupImageUrl(imageUri.toString()) //setImage(imageUri.toString()) } } } companion object { private val EXTRA_GROUP_UID = "group_uid" fun start(activity: Activity, groupUid: String?) { val intent = Intent(activity, GroupSettingsActivity::class.java) intent.putExtra(EXTRA_GROUP_UID, groupUid) activity.startActivity(intent) } } }
app/src/main/java/za/org/grassroot2/GroupSettingsActivity.kt
4081251130
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.filesystem.root import com.amaze.filemanager.fileoperations.exceptions.ShellNotRunningException import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object MakeFileCommand : IRootCommand() { /** * Creates an empty file using root * * @param path path to new file */ @Throws(ShellNotRunningException::class) fun makeFile(path: String) { val mountPoint = MountPathCommand.mountPath(path, MountPathCommand.READ_WRITE) runShellCommand("touch \"${RootHelper.getCommandLineString(path)}\"") mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } } }
app/src/main/java/com/amaze/filemanager/filesystem/root/MakeFileCommand.kt
2043584857
package swak import io.github.neyb.shoulk.shouldEqual import org.junit.Test import swak.body.reader.BodyReader import swak.body.reader.provider.request.BodyReaderChooser import swak.body.reader.provider.type.BodyReaderChooserProvider import swak.http.request.Method.POST import swak.http.request.UpdatableRequest import swak.http.response.* class SwakServer_bodyReaderTest : SwakServerTest() { @Test fun body_can_be_read() { val bodyLengthReader = object : BodyReader<Int>, BodyReaderChooserProvider, BodyReaderChooser<Int> { override fun read(body: String) = body.length override fun <B> forClass(target: Class<B>) = @Suppress("UNCHECKED_CAST") if (target == Int::class.javaObjectType) this as BodyReaderChooser<B> else null override fun forRequest(request: UpdatableRequest<String>) = this } var nameLength: Int? = null swakServer { addContentReaderProvider(bodyLengthReader) on("/IAm", POST).withA<Int>() answer { request.body .doOnSuccess { nameLength = it } .map { SimpleResponse.withoutBody() } } }.start() post("/IAm", "Tony Stark") nameLength shouldEqual 10 } }
undertow/src/test/kotlin/swak/SwakServer_bodyReaderTest.kt
1911267574
package com.didichuxing.doraemonkit.kit.connect import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.IdRes import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.didichuxing.doraemonkit.R import com.didichuxing.doraemonkit.widget.titlebar.HomeTitleBar import com.didichuxing.doraemonkit.zxing.activity.CaptureActivity /** * didi Create on 2022/4/12 . * * Copyright (c) 2022/4/12 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/12 6:07 下午 * @Description 用一句话说明文件功能 */ class DoKitScanActivity : CaptureActivity() { companion object { private const val REQUEST_CODE = 200999 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) checkCameraPermission() } override fun setContentView(@IdRes layoutResID: Int) { super.setContentView(layoutResID) initTitleBar() } private fun initTitleBar() { val homeTitleBar = HomeTitleBar(this) homeTitleBar.setBackgroundColor(resources.getColor(R.color.foreground_wtf)) homeTitleBar.setIcon(R.mipmap.dk_close_icon) homeTitleBar.setListener { finish() } val params = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, resources.getDimension(R.dimen.dk_home_title_height).toInt() ) (findViewById<View>(android.R.id.content) as FrameLayout).addView(homeTitleBar, params) } private fun checkCameraPermission() { val hasCameraPermission: Int = ContextCompat.checkSelfPermission(application, Manifest.permission.CAMERA) if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CODE) { } } }
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/connect/DoKitScanActivity.kt
995158623
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.dependency /** * A Java implementation of JSON Web Token (JWT) - RFC 7519. * * [Java JWT](https://github.com/auth0/java-jwt) */ @Suppress("unused") object JavaJwt { private const val version = "3.19.1" const val lib = "com.auth0:java-jwt:${version}" }
buildSrc/src/main/kotlin/io/spine/internal/dependency/JavaJwt.kt
2700965489
package uk.co.nickthecoder.paratask.examples import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.TaskParser import uk.co.nickthecoder.paratask.parameters.IntParameter import uk.co.nickthecoder.paratask.parameters.LabelPosition import uk.co.nickthecoder.paratask.parameters.asHorizontal import uk.co.nickthecoder.paratask.parameters.compound.IntRangeParameter class IntRangeExample : AbstractTask() { val intP = IntParameter("int") val range1P = IntRangeParameter("range1") val range2P = IntRangeParameter("range2", toText = null) .asHorizontal(LabelPosition.TOP) override val taskD = TaskDescription("intRangeExample") .addParameters(intP, range1P, range2P) override fun run() { println("Range1 = from ${range1P.from} to ${range1P.to}") println("Range2 = from ${range2P.from} to ${range2P.to}") } } fun main(args: Array<String>) { TaskParser(IntRangeExample()).go(args, prompt = true) }
paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/IntRangeExample.kt
4133452080
/* * Copyright 2021 Brackeys IDE contributors. * * 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.brackeys.ui.feature.explorer.adapters import android.view.View import android.view.ViewGroup import androidx.recyclerview.selection.Selection import androidx.recyclerview.selection.SelectionTracker import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.brackeys.ui.filesystem.base.model.FileModel import com.brackeys.ui.utils.adapters.OnItemClickListener class FileAdapter( private val selectionTracker: SelectionTracker<String>, private val onItemClickListener: OnItemClickListener<FileModel>, private val viewMode: Int ) : ListAdapter<FileModel, FileAdapter.FileViewHolder>(diffCallback) { companion object { const val VIEW_MODE_COMPACT = 0 const val VIEW_MODE_DETAILED = 1 private val diffCallback = object : DiffUtil.ItemCallback<FileModel>() { override fun areItemsTheSame(oldItem: FileModel, newItem: FileModel): Boolean { return oldItem.path == newItem.path } override fun areContentsTheSame(oldItem: FileModel, newItem: FileModel): Boolean { return oldItem == newItem } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder { return when (viewMode) { VIEW_MODE_COMPACT -> CompactViewHolder.create(parent, onItemClickListener) VIEW_MODE_DETAILED -> DetailedViewHolder.create(parent, onItemClickListener) else -> CompactViewHolder.create(parent, onItemClickListener) } } override fun onBindViewHolder(holder: FileViewHolder, position: Int) { val fileModel = getItem(position) val isSelected = selectionTracker.isSelected(fileModel.path) holder.bind(fileModel, isSelected) } fun getSelectedFiles(keys: Selection<String>): List<FileModel> { val files = mutableListOf<FileModel>() currentList.forEach { fileModel -> if (keys.contains(fileModel.path)) { files.add(fileModel) } } return files } fun indexOf(path: String): Int { var position = 0 currentList.forEachIndexed { index, fileModel -> if (path == fileModel.path) { position = index } } return position } abstract class FileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind(fileModel: FileModel, isSelected: Boolean) } }
app/src/main/kotlin/com/brackeys/ui/feature/explorer/adapters/FileAdapter.kt
352682058
package com.github.pgutkowski.kgraphql.schema.directive import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper class DirectiveExecution(val function: FunctionWrapper<DirectiveResult>) : FunctionWrapper<DirectiveResult> by function
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/directive/DirectiveExecution.kt
665748715
/* * Copyright (C) 2017 Andrzej Ressel ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.domain import com.jereksel.libresubstratumlib.ThemePack interface IThemeReader { fun readThemePack(appId: String): ThemePack fun isThemeEncrypted(appId: String): Boolean }
app/src/main/kotlin/com/jereksel/libresubstratum/domain/IThemeReader.kt
180386330
package tileentity.heat import com.cout970.magneticraft.api.internal.heat.HeatContainer import com.cout970.magneticraft.misc.tileentity.ITileTrait import com.cout970.magneticraft.misc.tileentity.TraitHeat import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.util.COPPER_HEAT_CAPACITY import com.cout970.magneticraft.util.COPPER_MELTING_POINT import com.cout970.magneticraft.util.DEFAULT_CONDUCTIVITY import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister /** * Created by cout970 on 04/07/2016. */ @TileRegister("redstone_heat_pipe") class TileRedstoneHeatPipe : TileBase() { val heat = HeatContainer(dissipation = 0.0, specificHeat = COPPER_HEAT_CAPACITY * 3 / 8, maxHeat = COPPER_HEAT_CAPACITY * 3 * COPPER_MELTING_POINT / 8, conductivity = DEFAULT_CONDUCTIVITY, worldGetter = { this.world }, posGetter = { this.getPos() }) val traitHeat: TraitHeat = TraitHeat(this, listOf(heat)) override val traits: List<ITileTrait> = listOf(traitHeat) override fun onLoad() { super.onLoad() //TODO ? } }
ignore/test/tileentity/heat/TileRedstoneHeatPipe.kt
3979879073
package net.nemerosa.ontrack.extension.scm.catalog import java.time.LocalDate /** * Filter used on the SCM catalog entries */ data class SCMCatalogProjectFilter( val offset: Int = 0, val size: Int = 20, val scm: String? = null, val config: String? = null, val repository: String? = null, val project: String? = null, val link: SCMCatalogProjectFilterLink = SCMCatalogProjectFilterLink.ALL, val beforeLastActivity: LocalDate? = null, val afterLastActivity: LocalDate? = null, val beforeCreatedAt: LocalDate? = null, val afterCreatedAt: LocalDate? = null, val team: String? = null, val sortOn: SCMCatalogProjectFilterSort? = null, val sortAscending: Boolean = true )
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogProjectFilter.kt
4099770020
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.core import java.util.ArrayDeque /** * This async runner is suitable for tests, where manual simulation of * asynchronous operations is desirable. */ class ManualAsyncRunner : AsyncRunner { private val queue: ArrayDeque<Runnable> = ArrayDeque() override fun <T> postQuickTask( task: () -> T, onResult: OnResultCallback<T>?, onError: OnErrorCallback? ): Cancellable { return postTask( task = { _: OnProgressCallback<Any>, _: IsCancelled -> task.invoke() }, onResult = onResult, onError = onError, onProgress = null ) } override fun <T, P> postTask( task: TaskFunction<T, P>, onResult: OnResultCallback<T>?, onError: OnErrorCallback?, onProgress: OnProgressCallback<P>? ): Cancellable { val remove: Function1<Runnable, Boolean> = queue::remove val taskWrapper = Task( postResult = { it.run(); true }, removeFromQueue = remove, taskBody = task, onSuccess = onResult, onError = onError, onProgress = onProgress ) queue.push(taskWrapper) return taskWrapper } val size: Int get() = queue.size val isEmpty: Boolean get() = queue.size == 0 /** * Run all enqueued tasks until queue is empty. This will run also tasks * enqueued by task callbacks. * * @param maximum max number of tasks to run to avoid infinite loopss * @return number of executed tasks */ fun runAll(maximum: Int = 100): Int { var c = 0 while (queue.size > 0) { val t = queue.remove() t.run() c++ if (c > maximum) { throw IllegalStateException("Maximum number of tasks run. Are you in infinite loop?") } } return c } /** * Run one pending task * * @return true if task has been run */ fun runOne(): Boolean { val t = queue.pollFirst() t?.run() return t != null } }
app/src/main/java/com/nextcloud/client/core/ManualAsyncRunner.kt
3730507087
package com.intellij.configurationScript.providers import com.intellij.configurationScript.ConfigurationFileManager import com.intellij.configurationScript.Keys import com.intellij.configurationScript.SynchronizedClearableLazy import com.intellij.configurationScript.readObject import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.UpdateSettingsProvider import org.yaml.snakeyaml.nodes.MappingNode import org.yaml.snakeyaml.nodes.ScalarNode private class MyUpdateSettingsProvider(project: Project) : UpdateSettingsProvider { private val data = SynchronizedClearableLazy<PluginsConfiguration?> { val node = project.service<ConfigurationFileManager>().getConfigurationNode() ?: return@SynchronizedClearableLazy null readPluginsConfiguration(node) } init { project.service<ConfigurationFileManager>().registerClearableLazyValue(data) } override fun getPluginRepositories(): List<String> { return data.value?.repositories ?: emptyList() } } internal class PluginsConfiguration : BaseState() { val repositories by list<String>() } internal fun readPluginsConfiguration(rootNode: MappingNode): PluginsConfiguration? { // later we can avoid full node graph building, but for now just use simple implementation (problem is that Yaml supports references and merge - proper support of it can be tricky) // "load" under the hood uses "compose" - i.e. Yaml itself doesn't use stream API to build object model. for (tuple in rootNode.value) { val keyNode = tuple.keyNode if (keyNode is ScalarNode && keyNode.value == Keys.plugins) { val valueNode = tuple.valueNode as? MappingNode ?: continue return readObject(PluginsConfiguration(), valueNode) as PluginsConfiguration } } return null }
plugins/configuration-script/src/providers/updateSettingsProvider.kt
1444349200
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.message import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.ByteArrayOutputStream @RunWith(JUnit4::class) class SsdpRequestDelegateTest { private lateinit var delegate: SsdpMessageDelegate private lateinit var message: SsdpRequest @Before fun setUp() { delegate = mockk(relaxed = true) every { delegate.type } returns "" every { delegate.uuid } returns "" message = SsdpRequest(mockk(relaxed = true), delegate) } @Test fun getLocalAddress() { message.localAddress verify(exactly = 1) { delegate.localAddress } } @Test fun getHeader() { val name = "name" message.getHeader(name) verify(exactly = 1) { delegate.getHeader(name) } } @Test fun setHeader() { val name = "name" val value = "value" message.setHeader(name, value) verify(exactly = 1) { delegate.setHeader(name, value) } } @Test fun getUuid() { message.uuid verify(exactly = 1) { delegate.uuid } } @Test fun getType() { message.type verify(exactly = 1) { delegate.type } } @Test fun getNts() { message.nts verify(exactly = 1) { delegate.nts } } @Test fun getMaxAge() { message.maxAge verify(exactly = 1) { delegate.maxAge } } @Test fun getExpireTime() { message.expireTime verify(exactly = 1) { delegate.expireTime } } @Test fun getLocation() { message.location verify(exactly = 1) { delegate.location } } @Test fun writeData() { val os = ByteArrayOutputStream() message.writeData(os) verify(exactly = 1) { delegate.writeData(os) } } @Test fun toString_() { message.toString() } }
mmupnp/src/test/java/net/mm2d/upnp/internal/message/SsdpRequestDelegateTest.kt
3667646161
package com.omega.discord.bot.database import com.omega.discord.bot.permission.Group import com.omega.discord.bot.permission.Permission import sx.blah.discord.handle.obj.IGuild interface GroupDAO : DAO<Group> { fun findFor(guild: IGuild): List<Group> fun addPermission(entity: Group, permission: Permission) fun removePermission(entity: Group, permission: Permission) }
src/main/kotlin/com/omega/discord/bot/database/GroupDAO.kt
2557853687
package com.lunivore.montecarluni.engine import com.lunivore.montecarluni.Events import com.lunivore.montecarluni.model.* import org.junit.Assert.assertEquals import org.junit.Test import java.time.LocalDate import java.time.format.DateTimeFormatter class ForecasterTest { private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") @Test fun `should be able to provide a simple probability distribution from a weekly sample`() { // Given a completely even sample set that finishes on 25th Feb val startDate = LocalDate.of(2017, 1, 1) val distribution = Distributions(toDistribution(listOf(4, 4, 4, 4, 4, 4, 4, 4), startDate), listOf()) // And a forecaster listening for events, and to which we are listening val events = Events() val forecaster = Forecaster(events) var result : Forecast = Forecast(listOf()) events.forecastNotification.subscribe { result = it } // When we request a forecast for that distribution with a number of work items // that we should finish in exactly 8 weeks events.distributionChangeNotification.push(distribution) events.forecastRequest.push(ForecastRequest(32, null)) // Then we should be provided with a really predictable result val expectedForecast =listOf(100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0) .map {if (it == 0) "0% | 2017-04-22" else "$it% | 2017-04-23"} .joinToString(separator="\n") assertEquals(expectedForecast, result.dataPoints.map { "${it.probability}% | ${it.forecastDate.format(formatter)}" } .joinToString(separator="\n")) } @Test fun `should be able to start forecast from a given date`() { // Given a completely even sample set that finishes on 25th Feb val startDate = LocalDate.of(2017, 1, 1) val distribution = Distributions(toDistribution(listOf(4, 4, 4, 4, 4, 4, 4, 4), startDate), listOf()) // And a forecaster listening for events, and to which we are listening val events = Events() val forecaster = Forecaster(events) var result : Forecast = Forecast(listOf()) events.forecastNotification.subscribe { result = it } // When we request a forecast for that distribution with a number of tickets // that we should finish in exactly 8 weeks, but we're adding another week // (on top of the 8 weeks of distribution data) events.distributionChangeNotification.push(distribution) events.forecastRequest.push(ForecastRequest(32, LocalDate.of(2017, 3, 5))) // Then we should be provided with a really predictable result val expectedForecast =listOf(100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0) .map {if (it == 0) "0% | 2017-04-29" else "$it% | 2017-04-30"} .joinToString(separator="\n") assertEquals(expectedForecast, result.dataPoints.map { "${it.probability}% | ${it.forecastDate.format(formatter)}" } .joinToString(separator="\n")) } @Test fun `should be able to use a partial distribution`() { // Given a bimodal sample set that finishes on 25th Feb val startDate = LocalDate.of(2017, 1, 1).minusDays(7) val distribution = Distributions(toDistribution(listOf(8, 8, 4, 4, 4, 4, 4, 4, 4), startDate), listOf()) // And a forecaster listening for events, and to which we are listening val events = Events() val forecaster = Forecaster(events) var result : Forecast = Forecast(listOf()) events.forecastNotification.subscribe { result = it } // When we request a forecast for the distribution from the point the team ramped up events.distributionChangeNotification.push(distribution) events.forecastRequest.push(ForecastRequest(32, null, true, listOf(2, 3, 4, 5, 6, 7, 8))) // Then we should be provided with exactly the same distribution as before. val expectedForecast =listOf(100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0) .map {if (it == 0) "0% | 2017-04-22" else "$it% | 2017-04-23"} .joinToString(separator="\n") assertEquals(expectedForecast, result.dataPoints.map { "${it.probability}% | ${it.forecastDate.format(formatter)}" } .joinToString(separator="\n")) } @Test fun `should clear down for empty distributions`() { // Given we created a forecast val startDate = LocalDate.of(2017, 1, 1) val distribution = Distributions(toDistribution(listOf(4, 4, 4, 4, 4, 4, 4, 4), startDate), listOf()) val events = Events() val forecaster = Forecaster(events) var result : Forecast = Forecast(listOf()) events.forecastNotification.subscribe { result = it } events.distributionChangeNotification.push(distribution) events.forecastRequest.push(ForecastRequest(32, null)) // When an empty distribution comes through events.distributionChangeNotification.push(Distributions.EMPTY) // Then the forecast should be cleared assertEquals(0, result.dataPoints.size) } private fun toDistribution(numOfWorkItemsClosed: List<Int>, startDate: LocalDate): List<WorkItemsClosedInWeek> { return numOfWorkItemsClosed.mapIndexed { index, distribution -> WorkItemsClosedInWeek(DateRange(startDate.plusDays(7 * index.toLong()), startDate.plusDays((7 * index.toLong() + 7))), distribution) } } }
src/test/kotlin/com/lunivore/montecarluni/engine/ForecasterTest.kt
1762104613
package com.robyn.dayplus2.myUtils import android.content.Context import android.widget.ImageView import com.robyn.dayplus2.R import com.robyn.dayplus2.data.MyEvent import com.robyn.dayplus2.data.source.enums.EventCategory import com.robyn.dayplus2.data.source.enums.EventRepeatMode import com.robyn.dayplus2.data.source.enums.EventType import org.joda.time.DateTime import org.joda.time.Days import org.joda.time.format.DateTimeFormat import java.io.File import java.util.* fun isSinceEvent(event: MyEvent): Boolean = (event.datetime - DateTime.now().millis) <= 0 // 0,1,2,3,4,5 = cake, loving, face, social, work, no categoryCode - to match the tab position in tabLayout fun categoryCodeToFilter(eventCategoryCode: Int): EventCategory = when (eventCategoryCode) { 0 -> EventCategory.CAKE_EVENTS 1 -> EventCategory.LOVED_EVENTS 2 -> EventCategory.FACE_EVENTS 3 -> EventCategory.EXPLORE_EVENTS 4 -> EventCategory.WORK_EVENTS else -> EventCategory.WORK_EVENTS // cannot return - if the receiver method } fun eventTypeToCode(eventType: EventType): Int = when (eventType) { EventType.ALL_EVENTS -> 0 EventType.SINCE_EVENTS -> 1 EventType.UNTIL_EVENTS -> 2 EventType.STARRED_EVENTS -> 3 EventType.CATEGORY_EVENTS -> 4 } /** * 1,2,3,4,5 = cake, loving, face, social, work, no categoryCode - t * * 0 for no category. However for now try null for no category. * * Since the db doesn't store enum type, use int code instead. Is it a good practice? */ /** * According to tabs' position code in the tabLayout, get this mapping: * position / categoryCode code -> tab 'name' * 0 -> cake * 1 -> loved * 2 -> face * 3 -> explore * 4 -> work */ //@Ignore val categoryCodeMap: HashMap<EventCategory, Int> = hashMapOf( EventCategory.CAKE_EVENTS to 1, EventCategory.LOVED_EVENTS to 2, EventCategory.FACE_EVENTS to 3, EventCategory.EXPLORE_EVENTS to 4, EventCategory.WORK_EVENTS to 5 ) // repeatCode to enum //@Ignore //val repeatCodeMap: HashMap<Int, EventRepeatMode> = hashMapOf( // 1 to EventRepeatMode.EVERY_WEEK, // 2 to EventRepeatMode.EVERY_WEEK, // 3 to EventRepeatMode.EVERY_WEEK //) // enum to repeat type string //@Ignore val repeatStrMap: HashMap<EventRepeatMode, String> = hashMapOf( EventRepeatMode.EVERY_WEEK to "Never", EventRepeatMode.EVERY_MONTH to "Every Week", EventRepeatMode.EVERY_YEAR to "Every Month" ) fun MyEvent.repeatModeStr(): String { return repeatCodeToString(this.repeatMode) } fun repeatCodeToString(repeatCode: Int): String { return when (repeatCode) { 1 -> "Every Week" 2 -> "Every Month" 3 -> "Every Year" else -> "Never" } } fun MyEvent.dayCount(): Int { val nowDate = DateTime.now() val eventDate = DateTime(this.datetime) val count = Days.daysBetween( nowDate.withTimeAtStartOfDay(), eventDate.withTimeAtStartOfDay() ).days return count } fun MyEvent.dayCountAbs(): Int = Math.abs(this.dayCount()) fun MyEvent.ifSince(): Int { return if (this.dayCount() > 0) { R.string.until } else { R.string.since } } fun MyEvent.ifSinceStr(): String { return if (this.dayCount() > 0) { "Until " } else { "Since " } } // Num days since date fun MyEvent.daysSinceDateStr(): String { return "${this.dayCountAbs()} days ${ifSinceStr()} ${this.formatDateStr()}" } fun MyEvent.numDaysStr(): String { // Handle word pl. return if (this.dayCountAbs() > 1) { "${this.dayCountAbs()} days" } else { "${this.dayCountAbs()} day" } } fun MyEvent.photoFilename(): String = "IMG_${this.uuid}.jpg" // For AddEditFragment date field. fun MyEvent.formatDateStr(): String { val fmt = DateTimeFormat.forPattern("dd MMM, yyyy") return DateTime(this.datetime).toString(fmt) } fun MyEvent.formatDateStr(millis:Long): String { val fmt = DateTimeFormat.forPattern("dd MMM, yyyy") return DateTime(millis).toString(fmt) } fun MyEvent.getImageFile(context: Context): File? { with(File(context.filesDir, this.photoFilename())) { return if (this.exists()) { this } else { // retrieve or take photo? // val fileDir = context.filesDir // return File(fileDir, photoFilename) null } } } fun MyEvent.getImagePath(context: Context):String? { return getImageFile(context)?.path }
app/src/main/java/com/robyn/dayplus2/myUtils/MyEventExt.kt
2611513317