repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sandipv22/pointer_replacer | ui/magisk/src/main/java/com/afterroot/allusive2/magisk/MagiskApplyUtils.kt | 1 | 4700 | /*
* Copyright (C) 2016-2021 Sandip Vaghela
* 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.afterroot.allusive2.magisk
import android.content.Context
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.Properties
const val FRAMEWORK_APK = "/system/framework/framework-res.apk"
fun frameworkCopyApkPath(context: Context) = "${context.externalCacheDir?.path}/framework.apk"
fun frameworkExtractPath(context: Context) = "${context.externalCacheDir?.path}/framework"
fun repackedFrameworkPath(context: Context) = "${context.externalCacheDir?.path}/repacked.apk"
fun repackedMagiskModulePath(context: Context, name: String) = "${context.getExternalFilesDir(null)?.path}/$name"
fun magiskEmptyModuleZipPath(context: Context) = "${context.externalCacheDir?.path}/empty-module.zip"
fun magiskEmptyModuleExtractPath(context: Context) = "${context.externalCacheDir?.path}/empty-module"
const val POINTER_XHDPI = "/res/drawable-xhdpi-v4/pointer_spot_touch.png"
const val POINTER_MDPI = "/res/drawable-mdpi-v4/pointer_spot_touch.png"
const val POINTER_HDPI = "/res/drawable-hdpi-v4/pointer_spot_touch.png"
const val MAGISK_EMPTY_ZIP = "empty-module.zip"
const val MAGISK_PACKAGE = "com.topjohnwu.magisk"
fun copyFrameworkRes(context: Context): File {
val file = File(FRAMEWORK_APK)
val target = File(frameworkCopyApkPath(context))
if (target.exists()) target.delete()
return file.copyTo(target)
}
fun filesToReplace(context: Context): List<File> {
val targetPath = frameworkExtractPath(context)
if (!File(targetPath).exists()) return emptyList()
val list = mutableListOf<File>()
val paths = listOf(
"$targetPath$POINTER_HDPI",
"$targetPath$POINTER_MDPI",
"$targetPath$POINTER_XHDPI"
)
paths.forEach {
val file = File(it)
if (file.exists()) {
list.add(file)
}
}
return list
}
enum class Variant {
MDPI, HDPI, XHDPI
}
object VariantSizes {
const val MDPI = 33
const val HDPI = 49
const val XHDPI = 66
}
fun variantsToReplace(context: Context): List<Variant> {
val targetPath = frameworkExtractPath(context)
if (!File(targetPath).exists()) return emptyList()
val list = mutableListOf<Variant>()
if (File("$targetPath$POINTER_HDPI").exists()) list.add(Variant.HDPI)
if (File("$targetPath$POINTER_MDPI").exists()) list.add(Variant.MDPI)
if (File("$targetPath$POINTER_XHDPI").exists()) list.add(Variant.XHDPI)
return list
}
fun Bitmap.saveAs(path: String): File {
val file = File(path)
if (file.exists()) file.delete()
kotlin.runCatching {
val fos = FileOutputStream(file)
this.compress(Bitmap.CompressFormat.PNG, 100, fos)
fos.flush()
fos.close()
}
return file
}
fun copyMagiskEmptyZip(context: Context, to: String) {
val assetManager: AssetManager = context.assets
val inputStream: InputStream?
val outputStream: OutputStream?
try {
inputStream = assetManager.open(MAGISK_EMPTY_ZIP)
val outFile = File(to)
outputStream = FileOutputStream(outFile)
inputStream.copyTo(outputStream)
inputStream.close()
outputStream.flush()
outputStream.close()
} catch (e: IOException) {
Log.e("tag", "Failed to copy asset file: $MAGISK_EMPTY_ZIP", e)
}
}
fun extractMagiskZip(context: Context) {
val file = File(magiskEmptyModuleZipPath(context))
if (!file.exists()) return
file.unzip(toFolder = File(magiskEmptyModuleExtractPath(context)))
}
fun copyRepackedFrameworkResApk(context: Context): File {
val repacked = File(repackedFrameworkPath(context))
return repacked.copyTo(target = File("${magiskEmptyModuleExtractPath(context)}$FRAMEWORK_APK"), overwrite = true)
}
fun createModuleProp(context: Context) {
val properties = Properties()
properties.load(FileReader(File(magiskEmptyModuleExtractPath(context) + "/module.prop")))
properties.keys
}
| apache-2.0 | 4a9126aa1f43bc0abe656fed2241b003 | 34.338346 | 117 | 0.716383 | 3.827362 | false | false | false | false |
jwren/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/XmlReader.kt | 1 | 35934 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("XmlReader")
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ide.plugins
import com.intellij.openapi.components.ComponentConfig
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import com.intellij.util.xml.dom.NoOpXmlInterner
import com.intellij.util.xml.dom.XmlInterner
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.xml.dom.readXmlAsModel
import org.codehaus.stax2.XMLStreamReader2
import org.codehaus.stax2.typed.TypedXMLStreamException
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.io.InputStream
import java.text.ParseException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamException
import javax.xml.stream.XMLStreamReader
import javax.xml.stream.events.XMLEvent
private const val defaultXPointerValue = "xpointer(/idea-plugin/*)"
/**
* Do not use [java.io.BufferedInputStream] - buffer is used internally already.
*/
fun readModuleDescriptor(input: InputStream,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
fun readModuleDescriptor(input: ByteArray,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
internal fun readModuleDescriptor(reader: XMLStreamReader2,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?): RawPluginDescriptor {
try {
if (reader.eventType != XMLStreamConstants.START_DOCUMENT) {
throw XMLStreamException("State ${XMLStreamConstants.START_DOCUMENT} is expected, " +
"but current state is ${getEventTypeString(reader.eventType)}", reader.location)
}
val descriptor = readInto ?: RawPluginDescriptor()
@Suppress("ControlFlowWithEmptyBody")
while (reader.next() != XMLStreamConstants.START_ELEMENT) {
}
if (!reader.isStartElement) {
return descriptor
}
readRootAttributes(reader, descriptor)
reader.consumeChildElements { localName ->
readRootElementChild(reader = reader,
descriptor = descriptor,
readContext = readContext,
localName = localName,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
assert(reader.isEndElement)
}
return descriptor
}
finally {
reader.closeCompletely()
}
}
@TestOnly
fun readModuleDescriptorForTest(input: ByteArray): RawPluginDescriptor {
return readModuleDescriptor(
input = input,
readContext = object : ReadModuleContext {
override val interner = NoOpXmlInterner
override val isMissingIncludeIgnored
get() = false
},
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
dataLoader = object : DataLoader {
override val pool: ZipFilePool? = null
override fun load(path: String) = throw UnsupportedOperationException()
override fun toString() = ""
},
includeBase = null,
readInto = null,
locationSource = null,
)
}
private fun readRootAttributes(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"package" -> descriptor.`package` = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.url = getNullifiedAttributeValue(reader, i)
"use-idea-classloader" -> descriptor.isUseIdeaClassLoader = reader.getAttributeAsBoolean(i)
"allow-bundled-update" -> descriptor.isBundledUpdateAllowed = reader.getAttributeAsBoolean(i)
"implementation-detail" -> descriptor.implementationDetail = reader.getAttributeAsBoolean(i)
"require-restart" -> descriptor.isRestartRequired = reader.getAttributeAsBoolean(i)
"version" -> {
// internalVersionString - why it is not used, but just checked?
getNullifiedAttributeValue(reader, i)?.let {
try {
it.toInt()
}
catch (e: NumberFormatException) {
LOG.error("Cannot parse version: $it'", e)
}
}
}
}
}
}
/**
* Keep in sync with KotlinPluginUtil.KNOWN_KOTLIN_PLUGIN_IDS
*/
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "SSBasedInspection")
private val KNOWN_KOTLIN_PLUGIN_IDS = HashSet(Arrays.asList(
"org.jetbrains.kotlin",
"com.intellij.appcode.kmm",
"org.jetbrains.kotlin.native.appcode"
))
private fun readRootElementChild(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
localName: String,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
when (localName) {
"id" -> {
if (descriptor.id == null) {
descriptor.id = getNullifiedContent(reader)
}
else if (!KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id) && descriptor.id != "com.intellij") {
// no warn and no redefinition for kotlin - compiler.xml is a known issue
LOG.warn("id redefinition (${reader.locationInfo.location})")
descriptor.id = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"name" -> descriptor.name = getNullifiedContent(reader)
"category" -> descriptor.category = getNullifiedContent(reader)
"version" -> {
// kotlin includes compiler.xml that due to some reasons duplicates version
if (descriptor.version == null || !KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id)) {
descriptor.version = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"description" -> descriptor.description = getNullifiedContent(reader)
"change-notes" -> descriptor.changeNotes = getNullifiedContent(reader)
"resource-bundle" -> descriptor.resourceBundleBaseName = getNullifiedContent(reader)
"product-descriptor" -> readProduct(reader, descriptor)
"module" -> {
findAttributeValue(reader, "value")?.let { moduleName ->
var modules = descriptor.modules
if (modules == null) {
descriptor.modules = Collections.singletonList(PluginId.getId(moduleName))
}
else {
if (modules.size == 1) {
val singleton = modules
modules = ArrayList(4)
modules.addAll(singleton)
descriptor.modules = modules
}
modules.add(PluginId.getId(moduleName))
}
}
reader.skipElement()
}
"idea-version" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"since-build" -> descriptor.sinceBuild = getNullifiedAttributeValue(reader, i)
"until-build" -> descriptor.untilBuild = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
}
"vendor" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"email" -> descriptor.vendorEmail = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.vendorUrl = getNullifiedAttributeValue(reader, i)
}
}
descriptor.vendor = getNullifiedContent(reader)
}
"incompatible-with" -> {
getNullifiedContent(reader)?.let {
var list = descriptor.incompatibilities
if (list == null) {
list = ArrayList()
descriptor.incompatibilities = list
}
list.add(PluginId.getId(it))
}
}
"application-components" -> readComponents(reader, descriptor.appContainerDescriptor)
"project-components" -> readComponents(reader, descriptor.projectContainerDescriptor)
"module-components" -> readComponents(reader, descriptor.moduleContainerDescriptor)
"applicationListeners" -> readListeners(reader, descriptor.appContainerDescriptor)
"projectListeners" -> readListeners(reader, descriptor.projectContainerDescriptor)
"extensions" -> readExtensions(reader, descriptor, readContext.interner)
"extensionPoints" -> readExtensionPoints(reader = reader,
descriptor = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
"content" -> readContent(reader = reader,
descriptor = descriptor,
readContext = readContext)
"dependencies" -> readDependencies(reader = reader, descriptor = descriptor, readContext = readContext)
"depends" -> readOldDepends(reader, descriptor)
"actions" -> readActions(descriptor, reader, readContext)
"include" -> readInclude(reader = reader,
readInto = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = defaultXPointerValue)
"helpset" -> {
// deprecated and not used element
reader.skipElement()
}
"locale" -> {
// not used in descriptor
reader.skipElement()
}
else -> {
LOG.error("Unknown element: $localName")
reader.skipElement()
}
}
if (!reader.isEndElement) {
throw XMLStreamException("Unexpected state (" +
"expected=END_ELEMENT, " +
"actual=${getEventTypeString(reader.eventType)}, " +
"lastProcessedElement=$localName" +
")", reader.location)
}
}
private fun readActions(descriptor: RawPluginDescriptor, reader: XMLStreamReader2, readContext: ReadModuleContext) {
var actionElements = descriptor.actions
if (actionElements == null) {
actionElements = ArrayList()
descriptor.actions = actionElements
}
val resourceBundle = findAttributeValue(reader, "resource-bundle")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
actionElements.add(RawPluginDescriptor.ActionDescriptor(
name = elementName,
element = readXmlAsModel(reader = reader, rootName = elementName, interner = readContext.interner),
resourceBundle = resourceBundle,
))
}
}
private fun readOldDepends(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
var isOptional = false
var configFile: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"optional" -> isOptional = reader.getAttributeAsBoolean(i)
"config-file" -> configFile = reader.getAttributeValue(i)
}
}
val dependencyIdString = getNullifiedContent(reader) ?: return
var depends = descriptor.depends
if (depends == null) {
depends = ArrayList()
descriptor.depends = depends
}
depends.add(PluginDependency(pluginId = PluginId.getId(dependencyIdString), configFile = configFile, isOptional = isOptional))
}
private fun readExtensions(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, interner: XmlInterner) {
val ns = findAttributeValue(reader, "defaultExtensionNs")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
var implementation: String? = null
var os: ExtensionDescriptor.Os? = null
var qualifiedExtensionPointName: String? = null
var order = LoadingOrder.ANY
var orderId: String? = null
var hasExtraAttributes = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"implementation" -> implementation = reader.getAttributeValue(i)
"implementationClass" -> {
// deprecated attribute
implementation = reader.getAttributeValue(i)
}
"os" -> os = readOs(reader.getAttributeValue(i))
"id" -> orderId = getNullifiedAttributeValue(reader, i)
"order" -> order = readOrder(reader.getAttributeValue(i))
"point" -> qualifiedExtensionPointName = getNullifiedAttributeValue(reader, i)
else -> hasExtraAttributes = true
}
}
if (qualifiedExtensionPointName == null) {
qualifiedExtensionPointName = interner.name("${ns ?: reader.namespaceURI}.${elementName}")
}
val containerDescriptor: ContainerDescriptor
when (qualifiedExtensionPointName) {
"com.intellij.applicationService" -> containerDescriptor = descriptor.appContainerDescriptor
"com.intellij.projectService" -> containerDescriptor = descriptor.projectContainerDescriptor
"com.intellij.moduleService" -> containerDescriptor = descriptor.moduleContainerDescriptor
else -> {
// bean EP can use id / implementation attributes for own bean class
// - that's why we have to create XmlElement even if all attributes are common
val element = if (qualifiedExtensionPointName == "com.intellij.postStartupActivity") {
reader.skipElement()
null
}
else {
readXmlAsModel(reader = reader, rootName = null, interner = interner).takeIf {
!it.children.isEmpty() || !it.attributes.keys.isEmpty()
}
}
var map = descriptor.epNameToExtensions
if (map == null) {
map = HashMap()
descriptor.epNameToExtensions = map
}
val extensionDescriptor = ExtensionDescriptor(implementation, os, orderId, order, element, hasExtraAttributes)
val list = map.get(qualifiedExtensionPointName)
if (list == null) {
map.put(qualifiedExtensionPointName, Collections.singletonList(extensionDescriptor))
}
else if (list.size == 1) {
val l = ArrayList<ExtensionDescriptor>(4)
l.add(list.get(0))
l.add(extensionDescriptor)
map.put(qualifiedExtensionPointName, l)
}
else {
list.add(extensionDescriptor)
}
assert(reader.isEndElement)
return@consumeChildElements
}
}
containerDescriptor.addService(readServiceDescriptor(reader, os))
reader.skipElement()
}
}
private fun readOrder(orderAttr: String?): LoadingOrder {
return when (orderAttr) {
null -> LoadingOrder.ANY
LoadingOrder.FIRST_STR -> LoadingOrder.FIRST
LoadingOrder.LAST_STR -> LoadingOrder.LAST
else -> LoadingOrder(orderAttr)
}
}
private fun checkXInclude(elementName: String, reader: XMLStreamReader2): Boolean {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
LOG.error("`include` is supported only on a root level (${reader.location})")
reader.skipElement()
return true
}
return false
}
@Suppress("DuplicatedCode")
private fun readExtensionPoints(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
reader.consumeChildElements { elementName ->
if (elementName != "extensionPoint") {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
val partial = RawPluginDescriptor()
readInclude(reader = reader,
readInto = partial,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = "xpointer(/idea-plugin/extensionPoints/*)")
LOG.warn("`include` is supported only on a root level (${reader.location})")
applyPartialContainer(partial, descriptor) { it.appContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.projectContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.moduleContainerDescriptor }
}
else {
LOG.error("Unknown element: $elementName (${reader.location})")
reader.skipElement()
}
return@consumeChildElements
}
var area: String? = null
var qualifiedName: String? = null
var name: String? = null
var beanClass: String? = null
var `interface`: String? = null
var isDynamic = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"area" -> area = getNullifiedAttributeValue(reader, i)
"qualifiedName" -> qualifiedName = reader.getAttributeValue(i)
"name" -> name = getNullifiedAttributeValue(reader, i)
"beanClass" -> beanClass = getNullifiedAttributeValue(reader, i)
"interface" -> `interface` = getNullifiedAttributeValue(reader, i)
"dynamic" -> isDynamic = reader.getAttributeAsBoolean(i)
}
}
if (beanClass == null && `interface` == null) {
throw RuntimeException("Neither beanClass nor interface attribute is specified for extension point at ${reader.location}")
}
if (beanClass != null && `interface` != null) {
throw RuntimeException("Both beanClass and interface attributes are specified for extension point at ${reader.location}")
}
reader.skipElement()
val containerDescriptor = when (area) {
null -> descriptor.appContainerDescriptor
"IDEA_PROJECT" -> descriptor.projectContainerDescriptor
"IDEA_MODULE" -> descriptor.moduleContainerDescriptor
else -> {
LOG.error("Unknown area: $area")
return@consumeChildElements
}
}
var result = containerDescriptor.extensionPoints
if (result == null) {
result = ArrayList()
containerDescriptor.extensionPoints = result
}
result.add(ExtensionPointDescriptor(
name = qualifiedName ?: name ?: throw RuntimeException("`name` attribute not specified for extension point at ${reader.location}"),
isNameQualified = qualifiedName != null,
className = `interface` ?: beanClass!!,
isBean = `interface` == null,
isDynamic = isDynamic
))
}
}
private inline fun applyPartialContainer(from: RawPluginDescriptor,
to: RawPluginDescriptor,
crossinline extractor: (RawPluginDescriptor) -> ContainerDescriptor) {
extractor(from).extensionPoints?.let {
val toContainer = extractor(to)
if (toContainer.extensionPoints == null) {
toContainer.extensionPoints = it
}
else {
toContainer.extensionPoints!!.addAll(it)
}
}
}
@Suppress("DuplicatedCode")
private fun readServiceDescriptor(reader: XMLStreamReader2, os: ExtensionDescriptor.Os?): ServiceDescriptor {
var serviceInterface: String? = null
var serviceImplementation: String? = null
var testServiceImplementation: String? = null
var headlessImplementation: String? = null
var configurationSchemaKey: String? = null
var overrides = false
var preload = ServiceDescriptor.PreloadMode.FALSE
var client: ServiceDescriptor.ClientKind? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"serviceInterface" -> serviceInterface = getNullifiedAttributeValue(reader, i)
"serviceImplementation" -> serviceImplementation = getNullifiedAttributeValue(reader, i)
"testServiceImplementation" -> testServiceImplementation = getNullifiedAttributeValue(reader, i)
"headlessImplementation" -> headlessImplementation = getNullifiedAttributeValue(reader, i)
"configurationSchemaKey" -> configurationSchemaKey = reader.getAttributeValue(i)
"overrides" -> overrides = reader.getAttributeAsBoolean(i)
"preload" -> {
when (reader.getAttributeValue(i)) {
"true" -> preload = ServiceDescriptor.PreloadMode.TRUE
"await" -> preload = ServiceDescriptor.PreloadMode.AWAIT
"notHeadless" -> preload = ServiceDescriptor.PreloadMode.NOT_HEADLESS
"notLightEdit" -> preload = ServiceDescriptor.PreloadMode.NOT_LIGHT_EDIT
else -> LOG.error("Unknown preload mode value ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
"client" -> {
when (reader.getAttributeValue(i)) {
"all" -> client = ServiceDescriptor.ClientKind.ALL
"local" -> client = ServiceDescriptor.ClientKind.LOCAL
"guest" -> client = ServiceDescriptor.ClientKind.GUEST
else -> LOG.error("Unknown client value: ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
}
}
return ServiceDescriptor(serviceInterface, serviceImplementation, testServiceImplementation, headlessImplementation,
overrides, configurationSchemaKey, preload, client, os)
}
private fun readProduct(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"code" -> descriptor.productCode = getNullifiedAttributeValue(reader, i)
"release-date" -> descriptor.releaseDate = parseReleaseDate(reader.getAttributeValue(i))
"release-version" -> {
try {
descriptor.releaseVersion = reader.getAttributeAsInt(i)
}
catch (e: TypedXMLStreamException) {
descriptor.releaseVersion = 0
}
}
"optional" -> descriptor.isLicenseOptional = reader.getAttributeAsBoolean(i)
}
}
reader.skipElement()
}
private fun readComponents(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
val result = containerDescriptor.getComponentListToAdd()
reader.consumeChildElements("component") {
var isApplicableForDefaultProject = false
var interfaceClass: String? = null
var implementationClass: String? = null
var headlessImplementationClass: String? = null
var os: ExtensionDescriptor.Os? = null
var overrides = false
var options: MutableMap<String, String?>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"skipForDefaultProject" -> {
val value = reader.elementText
if (!value.isEmpty() && value.equals("false", ignoreCase = true)) {
isApplicableForDefaultProject = true
}
}
"loadForDefaultProject" -> {
val value = reader.elementText
isApplicableForDefaultProject = value.isEmpty() || value.equals("true", ignoreCase = true)
}
"interface-class" -> interfaceClass = getNullifiedContent(reader)
// empty value must be supported
"implementation-class" -> implementationClass = getNullifiedContent(reader)
// empty value must be supported
"headless-implementation-class" -> headlessImplementationClass = reader.elementText
"option" -> {
var name: String? = null
var value: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = getNullifiedAttributeValue(reader, i)
"value" -> value = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
if (name != null && value != null) {
when {
name == "os" -> os = readOs(value)
name == "overrides" -> overrides = value.toBoolean()
options == null -> {
options = Collections.singletonMap(name, value)
}
else -> {
if (options!!.size == 1) {
options = HashMap(options)
}
options!!.put(name, value)
}
}
}
}
else -> reader.skipElement()
}
assert(reader.isEndElement)
}
assert(reader.isEndElement)
result.add(ComponentConfig(interfaceClass, implementationClass, headlessImplementationClass, isApplicableForDefaultProject,
os, overrides, options))
}
}
private fun readContent(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext) {
var items = descriptor.contentModules
if (items == null) {
items = ArrayList()
descriptor.contentModules = items
}
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (name.isNullOrEmpty()) {
throw RuntimeException("Name is not specified at ${reader.location}")
}
var configFile: String? = null
val index = name.lastIndexOf('/')
if (index != -1) {
configFile = "${name.substring(0, index)}.${name.substring(index + 1)}.xml"
}
items.add(PluginContentDescriptor.ModuleItem(name = name, configFile = configFile))
}
else -> throw RuntimeException("Unknown content item type: $elementName")
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readDependencies(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, readContext: ReadModuleContext) {
var modules: MutableList<ModuleDependenciesDescriptor.ModuleReference>? = null
var plugins: MutableList<ModuleDependenciesDescriptor.PluginReference>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (modules == null) {
modules = ArrayList()
}
modules!!.add(ModuleDependenciesDescriptor.ModuleReference(name!!))
}
"plugin" -> {
var id: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"id" -> id = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (plugins == null) {
plugins = ArrayList()
}
plugins!!.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(id!!)))
}
else -> throw RuntimeException("Unknown content item type: ${elementName}")
}
reader.skipElement()
}
descriptor.dependencies = ModuleDependenciesDescriptor(modules ?: Collections.emptyList(), plugins ?: Collections.emptyList())
assert(reader.isEndElement)
}
private fun findAttributeValue(reader: XMLStreamReader2, name: String): String? {
for (i in 0 until reader.attributeCount) {
if (reader.getAttributeLocalName(i) == name) {
return getNullifiedAttributeValue(reader, i)
}
}
return null
}
private fun getNullifiedContent(reader: XMLStreamReader2): String? = reader.elementText.takeIf { !it.isEmpty() }
private fun getNullifiedAttributeValue(reader: XMLStreamReader2, i: Int) = reader.getAttributeValue(i).takeIf { !it.isEmpty() }
interface ReadModuleContext {
val interner: XmlInterner
val isMissingIncludeIgnored: Boolean
}
private fun readInclude(reader: XMLStreamReader2,
readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
allowedPointer: String) {
var path: String? = null
var pointer: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"href" -> path = getNullifiedAttributeValue(reader, i)
"xpointer" -> pointer = reader.getAttributeValue(i)?.takeIf { !it.isEmpty() && it != allowedPointer }
else -> throw RuntimeException("Unknown attribute ${reader.getAttributeLocalName(i)} (${reader.location})")
}
}
if (pointer != null) {
throw RuntimeException("Attribute `xpointer` is not supported anymore (xpointer=$pointer, location=${reader.location})")
}
if (path == null) {
throw RuntimeException("Missing `href` attribute (${reader.location})")
}
var isOptional = false
reader.consumeChildElements("fallback") {
isOptional = true
reader.skipElement()
}
var readError: IOException? = null
val read = try {
pathResolver.loadXIncludeReference(dataLoader = dataLoader,
base = includeBase,
relativePath = path,
readContext = readContext,
readInto = readInto)
}
catch (e: IOException) {
readError = e
false
}
if (read || isOptional) {
return
}
if (readContext.isMissingIncludeIgnored) {
LOG.info("$path include ignored (dataLoader=$dataLoader)", readError)
return
}
else {
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader)", readError)
}
}
private var dateTimeFormatter: DateTimeFormatter? = null
private val LOG: Logger
get() = PluginManagerCore.getLogger()
private fun parseReleaseDate(dateString: String): LocalDate? {
if (dateString.isEmpty() || dateString == "__DATE__") {
return null
}
var formatter = dateTimeFormatter
if (formatter == null) {
formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US)
dateTimeFormatter = formatter
}
try {
return LocalDate.parse(dateString, formatter)
}
catch (e: ParseException) {
LOG.error("Cannot parse release date", e)
}
return null
}
private fun readListeners(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
var result = containerDescriptor.listeners
if (result == null) {
result = ArrayList()
containerDescriptor.listeners = result
}
reader.consumeChildElements("listener") {
var os: ExtensionDescriptor.Os? = null
var listenerClassName: String? = null
var topicClassName: String? = null
var activeInTestMode = true
var activeInHeadlessMode = true
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"os" -> os = readOs(reader.getAttributeValue(i))
"class" -> listenerClassName = getNullifiedAttributeValue(reader, i)
"topic" -> topicClassName = getNullifiedAttributeValue(reader, i)
"activeInTestMode" -> activeInTestMode = reader.getAttributeAsBoolean(i)
"activeInHeadlessMode" -> activeInHeadlessMode = reader.getAttributeAsBoolean(i)
}
}
if (listenerClassName == null || topicClassName == null) {
LOG.error("Listener descriptor is not correct as ${reader.location}")
}
else {
result.add(ListenerDescriptor(os, listenerClassName, topicClassName, activeInTestMode, activeInHeadlessMode))
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readOs(value: String): ExtensionDescriptor.Os {
return when (value) {
"mac" -> ExtensionDescriptor.Os.mac
"linux" -> ExtensionDescriptor.Os.linux
"windows" -> ExtensionDescriptor.Os.windows
"unix" -> ExtensionDescriptor.Os.unix
"freebsd" -> ExtensionDescriptor.Os.freebsd
else -> throw IllegalArgumentException("Unknown OS: $value")
}
}
private inline fun XMLStreamReader.consumeChildElements(crossinline consumer: (name: String) -> Unit) {
// cursor must be at the start of parent element
assert(isStartElement)
var depth = 1
while (true) {
@Suppress("DuplicatedCode")
when (next()) {
XMLStreamConstants.START_ELEMENT -> {
depth++
consumer(localName)
assert(isEndElement)
depth--
}
XMLStreamConstants.END_ELEMENT -> {
if (depth != 1) {
throw IllegalStateException("Expected depth: 1")
}
return
}
XMLStreamConstants.CDATA,
XMLStreamConstants.SPACE,
XMLStreamConstants.CHARACTERS,
XMLStreamConstants.ENTITY_REFERENCE,
XMLStreamConstants.COMMENT,
XMLStreamConstants.PROCESSING_INSTRUCTION -> {
// ignore
}
else -> throw XMLStreamException("Unexpected state: ${getEventTypeString(eventType)}", location)
}
}
}
private inline fun XMLStreamReader2.consumeChildElements(name: String, crossinline consumer: () -> Unit) {
consumeChildElements {
if (name == it) {
consumer()
assert(isEndElement)
}
else {
skipElement()
}
}
}
private fun getEventTypeString(eventType: Int): String {
return when (eventType) {
XMLEvent.START_ELEMENT -> "START_ELEMENT"
XMLEvent.END_ELEMENT -> "END_ELEMENT"
XMLEvent.PROCESSING_INSTRUCTION -> "PROCESSING_INSTRUCTION"
XMLEvent.CHARACTERS -> "CHARACTERS"
XMLEvent.COMMENT -> "COMMENT"
XMLEvent.START_DOCUMENT -> "START_DOCUMENT"
XMLEvent.END_DOCUMENT -> "END_DOCUMENT"
XMLEvent.ENTITY_REFERENCE -> "ENTITY_REFERENCE"
XMLEvent.ATTRIBUTE -> "ATTRIBUTE"
XMLEvent.DTD -> "DTD"
XMLEvent.CDATA -> "CDATA"
XMLEvent.SPACE -> "SPACE"
else -> "UNKNOWN_EVENT_TYPE, $eventType"
}
} | apache-2.0 | 1b224accbc3552391775759cd6c5bcb0 | 36.588912 | 137 | 0.642316 | 4.94006 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinDeclarationGroupRuleProvider.kt | 2 | 1982 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.openapi.project.Project
import com.intellij.usages.PsiNamedElementUsageGroupBase
import com.intellij.usages.Usage
import com.intellij.usages.UsageGroup
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.impl.FileStructureGroupRuleProvider
import com.intellij.usages.rules.PsiElementUsage
import com.intellij.usages.rules.UsageGroupingRule
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.parents
class KotlinDeclarationGroupingRule(val level: Int = 0) : UsageGroupingRule {
override fun groupUsage(usage: Usage): UsageGroup? {
var element = (usage as? PsiElementUsage)?.element ?: return null
if (element.containingFile !is KtFile) return null
if (element is KtFile) {
val offset = (usage as? UsageInfo2UsageAdapter)?.usageInfo?.navigationOffset
if (offset != null) {
element = element.findElementAt(offset) ?: element
}
}
val parentList = element.parents.filterIsInstance<KtNamedDeclaration>().filterNot { it is KtProperty && it.isLocal }.toList()
if (parentList.size <= level) {
return null
}
return PsiNamedElementUsageGroupBase(parentList[parentList.size - level - 1])
}
}
class KotlinDeclarationGroupRuleProvider : FileStructureGroupRuleProvider {
override fun getUsageGroupingRule(project: Project): UsageGroupingRule = KotlinDeclarationGroupingRule(0)
}
class KotlinDeclarationSecondLevelGroupRuleProvider : FileStructureGroupRuleProvider {
override fun getUsageGroupingRule(project: Project): UsageGroupingRule = KotlinDeclarationGroupingRule(1)
}
| apache-2.0 | 5cff7f81aa51c4db38edefcf1832e730 | 43.044444 | 158 | 0.76337 | 4.504545 | false | false | false | false |
smmribeiro/intellij-community | jupyter/src/org/jetbrains/plugins/notebooks/jupyter/JupyterFileType.kt | 1 | 859 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.notebooks.jupyter
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import icons.PythonPsiApiIcons
import org.jetbrains.annotations.NonNls
import javax.swing.Icon
object JupyterFileType : LanguageFileType(JupyterLanguage) {
@NonNls
override fun getName() = "Jupyter"
override fun getDescription() = JupyterPsiBundle.message("filetype.jupyter.description")
override fun getDefaultExtension() = "ipynb"
override fun getIcon(): Icon = PythonPsiApiIcons.IPythonNotebook
override fun getCharset(file: VirtualFile, content: ByteArray): String = CharsetToolkit.UTF8
} | apache-2.0 | e7d2415af719afa0cb66699bcc2a1723 | 46.777778 | 158 | 0.812573 | 4.405128 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/VersionUtil.kt | 1 | 1174 | package ch.rmy.android.http_shortcuts.utils
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import javax.inject.Inject
class VersionUtil
@Inject
constructor(
private val context: Context,
) {
fun getVersionName(): String =
try {
getPackageInfo(context).versionName
} catch (e: PackageManager.NameNotFoundException) {
"???"
}
@Suppress("DEPRECATION")
fun getVersionCode(): Long =
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getPackageInfo(context).longVersionCode
} else {
getPackageInfo(context).versionCode.toLong()
}
} catch (e: PackageManager.NameNotFoundException) {
-1
}
@Suppress("DEPRECATION")
private fun getPackageInfo(context: Context) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0))
} else {
context.packageManager.getPackageInfo(context.packageName, 0)
}
}
| mit | ae52da871e6abca3c6dffdf559b4de7a | 29.102564 | 109 | 0.635434 | 4.677291 | false | false | false | false |
microg/android_packages_apps_UnifiedNlp | service/src/main/kotlin/org/microg/nlp/service/AbstractBackendHelper.kt | 1 | 3913 | /*
* SPDX-FileCopyrightText: 2014, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.nlp.service
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.IBinder
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
fun <T> Array<out T>?.isNotNullOrEmpty(): Boolean {
return this != null && this.isNotEmpty()
}
abstract class AbstractBackendHelper(private val TAG: String, private val context: Context, protected val coroutineScope: CoroutineScope, val serviceIntent: Intent, val signatureDigest: String?) : ServiceConnection {
private var bound: Boolean = false
protected abstract suspend fun close()
protected abstract fun hasBackend(): Boolean
override fun onServiceConnected(name: ComponentName, service: IBinder) {
bound = true
Log.d(TAG, "Bound to: $name")
}
override fun onServiceDisconnected(name: ComponentName) {
bound = false
Log.d(TAG, "Unbound from: $name")
}
suspend fun unbind() {
if (bound) {
if (hasBackend()) {
try {
close()
} catch (e: Exception) {
Log.w(TAG, e)
}
}
try {
Log.d(TAG, "Unbinding from: $serviceIntent")
context.unbindService(this)
} catch (e: Exception) {
Log.w(TAG, e)
}
bound = false
}
}
fun bind() {
if (!bound) {
Log.d(TAG, "Binding to: $serviceIntent sig: $signatureDigest")
if (serviceIntent.getPackage() == null) {
Log.w(TAG, "Intent is not properly resolved, can't verify signature. Aborting.")
return
}
val computedDigest = firstSignatureDigest(context, serviceIntent.getPackage(), "SHA-256")
if (signatureDigest != null && signatureDigest != computedDigest) {
Log.w(TAG, "Target signature does not match selected package ($signatureDigest != $computedDigest). Aborting.")
return
}
try {
context.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE)
} catch (e: Exception) {
Log.w(TAG, e)
}
}
}
companion object {
@Suppress("DEPRECATION")
@SuppressLint("PackageManagerGetSignatures")
fun firstSignatureDigest(context: Context, packageName: String?, algorithm: String): String? {
val packageManager = context.packageManager
val info: PackageInfo?
try {
info = packageManager.getPackageInfo(packageName!!, PackageManager.GET_SIGNATURES)
} catch (e: PackageManager.NameNotFoundException) {
return null
}
if (info?.signatures.isNotNullOrEmpty()) {
for (sig in info.signatures) {
digest(sig.toByteArray(), algorithm)?.let { return it }
}
}
return null
}
private fun digest(bytes: ByteArray, algorithm: String): String? {
try {
val md = MessageDigest.getInstance(algorithm)
val digest = md.digest(bytes)
val sb = StringBuilder(2 * digest.size)
for (b in digest) {
sb.append(String.format("%02x", b))
}
return sb.toString()
} catch (e: NoSuchAlgorithmException) {
return null
}
}
}
}
| apache-2.0 | 3d6380a8582f731516af465cb4ec3688 | 31.882353 | 216 | 0.578584 | 4.959442 | false | false | false | false |
Goyatuzo/LurkerBot | entry/discord-bot/src/main/kotlin/gameTime/ActivityExtensions.kt | 1 | 380 | package com.lurkerbot.gameTime
import dev.kord.core.entity.Activity
fun Activity?.sameActivityAs(other: Activity?): Boolean =
this != null &&
other != null &&
name == other.name &&
details == other.details &&
state == other.state &&
assets?.smallText == other.assets?.smallText &&
assets?.largeText == other.assets?.largeText
| apache-2.0 | 67a31f15e2713ac92c64c559a24fc07e | 30.666667 | 57 | 0.623684 | 4.222222 | false | false | false | false |
arora-aman/MultiThreadDownloader | multithreaddownloader/src/main/java/com/aman_arora/multi_thread_downloader/downloader/MultiThreadDownloader.kt | 1 | 8826 | package com.aman_arora.multi_thread_downloader.downloader
import android.arch.persistence.room.Room
import android.content.Context
import com.aman_arora.multi_thread_downloader.db.Download
import com.aman_arora.multi_thread_downloader.db.DownloadsDatabase
import com.aman_arora.multi_thread_downloader.file_manager.FileManager
import com.aman_arora.multi_thread_downloader.url_info.UrlDetails
import java.io.File
import java.io.IOException
import java.util.*
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
object MultiThreadDownloader : IMultiThreadDownloader {
private val NO_CONTENT_LENGTH_CONSTANT: Long = -1
private val mBlockingQueue = LinkedBlockingQueue<Runnable>()
private val mExecutor = ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Int.MAX_VALUE,
1, TimeUnit.SECONDS, mBlockingQueue)
private val downloadIdMap = HashMap<Long, DownloadInfo>()
private val listenerMap = HashMap<Long, IMultiThreadDownloader.OnDownloadEventListener>()
private var fileManager: FileManager? = null
private var database: DownloadsDatabase? = null
private var downloadFinalizer: DownloadFinalizer? = null
private var initialised = false
override fun init(context: Context, eventListener: IMultiThreadDownloader.OnDownloaderInitiatedEventListener) {
if (!initialised) {
initialised = true
mExecutor.execute {
this.fileManager = FileManager(context)
this.database = Room.databaseBuilder(context, DownloadsDatabase::class.java, "downloads-database").build()
this.downloadFinalizer = DownloadFinalizer(fileManager!!)
initDownloadMap()
eventListener.onDownloaderInitiated()
}
} else {
throw IllegalStateException()
}
}
override fun download(webAddress: String, maxThreadCount: Int, file: File?,
eventListener: IMultiThreadDownloader.OnDownloadEventListener): Long {
if (!initialised) {
throw IllegalStateException()
}
if (file != null && file.exists() && !file.canWrite()) {
throw IOException()
}
val id = UUID.randomUUID().hashCode().toLong()
mExecutor.execute {
val urlDetails = UrlDetails(webAddress)
val threads: Int = if (urlDetails.contentLength == NO_CONTENT_LENGTH_CONSTANT) 1 else maxThreadCount
val info = DownloadInfo(id, urlDetails.fileName, threads, webAddress)
info.downloadFile = file ?: fileManager!!.createFile(urlDetails.fileName)
downloadIdMap.put(id, info)
listenerMap[id] = eventListener
setDownloadState(info, IMultiThreadDownloader.DownloadState.STARTING)
val dao = database?.downloadDao()
val download = Download(id, webAddress, info.downloadFile!!.path, maxThreadCount)
dao?.addDownload(download)
addDownloadTasks(info, urlDetails, fileManager!!, true)
}
return id
}
override fun getDownloadInfo(id: Long): DownloadInfo {
if (!downloadIdMap.containsKey(id)) {
throw IllegalArgumentException()
}
return downloadIdMap[id]!!
}
override fun pause(id: Long) {
if (!downloadIdMap.containsKey(id)) {
throw IMultiThreadDownloader.InvalidDownloadException(id)
}
val downloadInfo = downloadIdMap[id]!!
val downloadTaskList = downloadInfo.downloadTaskList
for (task in downloadTaskList) {
task.stopDownload()
}
downloadTaskList.clear()
val threadList = downloadInfo.threadList
for (thread in threadList) {
thread.join()
}
threadList.clear()
setDownloadState(downloadInfo, IMultiThreadDownloader.DownloadState.PAUSED)
}
override fun resume(id: Long) {
if (!downloadIdMap.containsKey(id)) {
throw IMultiThreadDownloader.InvalidDownloadException(id)
}
val downloadInfo = downloadIdMap[id]!!
setDownloadState(downloadInfo, IMultiThreadDownloader.DownloadState.RESTARTING)
mExecutor.execute {
val urlDetails = UrlDetails(downloadInfo.webAddress)
addDownloadTasks(downloadInfo, urlDetails, fileManager!!, false)
}
}
override fun getAllDownloads(): Map<Long, DownloadInfo> {
if (!initialised) {
throw IllegalStateException()
}
return downloadIdMap.toMap()
}
override fun isDownloadLocationChangeable(id: Long): Boolean {
if (!downloadIdMap.containsKey(id)) {
throw IllegalArgumentException()
}
val state = downloadIdMap[id]!!.state
return state != IMultiThreadDownloader.DownloadState.FINALIZING ||
state != IMultiThreadDownloader.DownloadState.DOWNLOADED
}
override fun changeDownloadLocation(id: Long, newFile: File) {
if (!downloadIdMap.containsKey(id)) {
throw IllegalArgumentException()
}
if (!isDownloadLocationChangeable(id)) {
throw IllegalStateException()
}
downloadIdMap[id]!!.downloadFile = newFile
}
private fun addDownloadTasks(downloadInfo: DownloadInfo, urlDetails: UrlDetails,
fileManager: FileManager, isNewDownload: Boolean) {
val threadCount = downloadInfo.threads
val partSize = urlDetails.contentLength / downloadInfo.threads
val listener = OnPartsDownloadEventListener(downloadInfo)
var startByte = 0L
var endByte: Long? = null
if (urlDetails.contentLength != NO_CONTENT_LENGTH_CONSTANT) {
endByte = partSize - 1
}
for (i in 1..threadCount) {
val part = if (!isNewDownload) downloadInfo.partFileList[i - 1] else fileManager.createPartFile(urlDetails.fileName, i)
val task = DownloadTask(urlDetails.webUrl, i, startByte, endByte, part, listener)
if (urlDetails.contentLength != NO_CONTENT_LENGTH_CONSTANT) {
startByte = endByte!! + 1
endByte += partSize
if (i == threadCount - 1) {
endByte = urlDetails.contentLength - 1
}
}
mExecutor.execute(task)
downloadInfo.downloadTaskList.add(task)
if (isNewDownload) {
downloadInfo.partFileList.add(part)
downloadInfo.threadProgressList.add(0f)
}
}
}
private fun setDownloadState(downloadInfo: DownloadInfo, state: IMultiThreadDownloader.DownloadState) {
if (downloadInfo.state == state) {
return
}
downloadInfo.state = state
listenerMap[downloadInfo.id]!!
.onDownloadStateChanged(downloadInfo.id, state)
}
private fun setProgress(downloadInfo: DownloadInfo, thread: Int, progress: Float) {
downloadInfo.threadProgressList.add(thread, progress)
listenerMap[downloadInfo.id]!!.onDownloadProgressChanged(downloadInfo.id, thread, progress)
}
private fun initDownloadMap() {
val downloads = database?.downloadDao()?.getDownloads()
if (downloads != null) {
for (download in downloads) {
val downloadFile = File(download.file)
downloadIdMap[download.id] = DownloadInfo(download.id, downloadFile.name, download.threadCount, download.webUrl)
downloadIdMap[download.id]?.state = IMultiThreadDownloader.DownloadState.PAUSED
}
}
}
private class OnPartsDownloadEventListener(val downloadInfo: DownloadInfo) : IDownloadTask.OnDownloadTaskEventListener {
override fun onDownloadStarted(currentThread: Thread) {
downloadInfo.threadList.add(currentThread)
}
override fun onProgressUpdated(thread: Int, progress: Float) {
setProgress(downloadInfo, thread, progress)
setDownloadState(downloadInfo, IMultiThreadDownloader.DownloadState.DOWNLOADING)
}
override fun onDownloadComplete() {
downloadInfo.downloadTaskList
.filterNot { it.isDownloaded }
.forEach { return }
setDownloadState(downloadInfo, IMultiThreadDownloader.DownloadState.FINALIZING)
downloadFinalizer!!
.finalizeDownload(downloadInfo.partFileList, downloadInfo.downloadFile!!) {
setDownloadState(downloadInfo, IMultiThreadDownloader.DownloadState.DOWNLOADED)
}
}
}
} | mit | 1f5d1f28de146119c538054664537bd9 | 36.088235 | 131 | 0.648652 | 5.02906 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/PartialEvaluator.kt | 3 | 5987 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.kotlin.dsl.execution.ResidualProgram.Dynamic
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.ApplyBasePlugins
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.ApplyDefaultPluginRequests
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.ApplyPluginRequestsOf
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.CloseTargetScope
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.Eval
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction.SetupEmbeddedKotlin
import org.gradle.kotlin.dsl.execution.ResidualProgram.Static
enum class ProgramKind {
TopLevel,
ScriptPlugin
}
enum class ProgramTarget {
Project,
Settings,
Gradle
}
/**
* Reduces a [Program] into a [ResidualProgram] given its [kind][ProgramKind] and [target][ProgramTarget].
*/
internal
class PartialEvaluator(
private val programKind: ProgramKind,
private val programTarget: ProgramTarget
) {
fun reduce(program: Program): ResidualProgram = when (program) {
is Program.Empty -> reduceEmptyProgram()
is Program.PluginManagement -> stage1WithPluginManagement(program)
is Program.Buildscript -> reduceBuildscriptProgram(program)
is Program.Plugins -> stage1WithPlugins(program)
is Program.Stage1Sequence -> stage1WithPlugins(program)
is Program.Script -> reduceScriptProgram(program)
is Program.Staged -> reduceStagedProgram(program)
else -> throw IllegalArgumentException("Unsupported `$program'")
}
private
fun reduceEmptyProgram(): Static =
when (programTarget) {
ProgramTarget.Project ->
when (programKind) {
ProgramKind.TopLevel -> Static(
SetupEmbeddedKotlin,
ApplyDefaultPluginRequests,
ApplyBasePlugins
)
ProgramKind.ScriptPlugin -> Static(
CloseTargetScope,
ApplyBasePlugins
)
}
else -> Static(defaultStageTransition())
}
private
fun reduceBuildscriptProgram(program: Program.Buildscript): Static =
Static(
SetupEmbeddedKotlin,
Eval(fragmentHolderSourceFor(program)),
defaultStageTransition()
)
private
fun fragmentHolderSourceFor(program: Program.FragmentHolder): ProgramSource {
val fragment = program.fragment
val section = fragment.section
return fragment.source.map { sourceText ->
sourceText
.subText(0..section.block.last)
.preserve(section.wholeRange)
}
}
private
fun reduceScriptProgram(program: Program.Script): ResidualProgram =
when (programTarget) {
ProgramTarget.Project -> {
when (programKind) {
ProgramKind.TopLevel -> Dynamic(
Static(
SetupEmbeddedKotlin,
ApplyDefaultPluginRequests,
ApplyBasePlugins
),
program.source
)
ProgramKind.ScriptPlugin -> Static(
CloseTargetScope,
ApplyBasePlugins,
Eval(program.source)
)
}
}
else -> {
Static(
defaultStageTransition(),
Eval(program.source)
)
}
}
private
fun defaultStageTransition(): ResidualProgram.Instruction = when (programKind) {
ProgramKind.TopLevel -> ApplyDefaultPluginRequests
else -> CloseTargetScope
}
private
fun reduceStagedProgram(program: Program.Staged): Dynamic =
Dynamic(
reduceStage1Program(program.stage1),
program.stage2.source
)
private
fun reduceStage1Program(stage1: Program.Stage1): Static = when (stage1) {
is Program.Buildscript ->
when (programTarget) {
ProgramTarget.Project -> Static(
SetupEmbeddedKotlin,
Eval(fragmentHolderSourceFor(stage1)),
ApplyDefaultPluginRequests,
ApplyBasePlugins
)
else -> reduceBuildscriptProgram(stage1)
}
else -> stage1WithPlugins(stage1)
}
private
fun stage1WithPlugins(stage1: Program.Stage1): Static =
when (programTarget) {
ProgramTarget.Project -> Static(
SetupEmbeddedKotlin,
ApplyPluginRequestsOf(stage1),
ApplyBasePlugins
)
else -> Static(
SetupEmbeddedKotlin,
ApplyPluginRequestsOf(stage1)
)
}
private
fun stage1WithPluginManagement(program: Program.PluginManagement): Static {
return Static(
SetupEmbeddedKotlin,
Eval(fragmentHolderSourceFor(program)),
ApplyDefaultPluginRequests
)
}
}
| apache-2.0 | 4c37f63f2dfac6637c381229f3937afa | 28.348039 | 106 | 0.60314 | 5.564126 | false | false | false | false |
KePeng1019/SmartPaperScan | app/src/main/java/com/pengke/paper/scanner/scan/ScanActivity.kt | 1 | 6545 | package com.pengke.paper.scanner.scan
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.Display
import android.view.SurfaceView
import com.pengke.paper.scanner.R
import com.pengke.paper.scanner.base.BaseActivity
import com.pengke.paper.scanner.view.PaperRectangle
import kotlinx.android.synthetic.main.activity_scan.*
import org.opencv.android.OpenCVLoader
import org.opencv.core.Core
import org.opencv.core.CvType
import org.opencv.core.Mat
import org.opencv.core.Size
import org.opencv.imgcodecs.Imgcodecs
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
class ScanActivity : BaseActivity(), IScanView.Proxy {
private val REQUEST_CAMERA_PERMISSION = 0
private val EXIT_TIME = 2000
private lateinit var mPresenter: ScanPresenter
private var latestBackPressTime: Long = 0
override fun provideContentViewId(): Int = R.layout.activity_scan
override fun initPresenter() {
mPresenter = ScanPresenter(this, this)
}
override fun prepare() {
if (!OpenCVLoader.initDebug()) {
Log.i(TAG, "loading opencv error, exit")
finish()
}
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CAMERA_PERMISSION)
} else if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
} else if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CAMERA_PERMISSION)
}
shut.setOnClickListener {
mPresenter.shut()
}
latestBackPressTime = System.currentTimeMillis()
gallery.setOnClickListener {
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
ActivityCompat.startActivityForResult(this, gallery, 1, null);
};
}
override fun onStart() {
super.onStart()
mPresenter.start()
}
override fun onStop() {
super.onStop()
mPresenter.stop()
}
override fun exit() {
finish()
}
override fun onBackPressed() {
if (System.currentTimeMillis().minus(latestBackPressTime) > EXIT_TIME) {
showMessage(R.string.press_again_logout)
} else {
super.onBackPressed()
}
latestBackPressTime = System.currentTimeMillis()
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
val uri: Uri = data!!.data;
val iStream: InputStream = contentResolver.openInputStream(uri)
val exif = ExifInterface(iStream);
var rotation = -1
val orientation: Int = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED)
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotation = Core.ROTATE_90_CLOCKWISE
ExifInterface.ORIENTATION_ROTATE_180 -> rotation = Core.ROTATE_180
ExifInterface.ORIENTATION_ROTATE_270 -> rotation = Core.ROTATE_90_COUNTERCLOCKWISE
}
Log.i(TAG, "rotation:" + rotation)
var imageWidth = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0).toDouble()
var imageHeight = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0).toDouble()
if (rotation == Core.ROTATE_90_CLOCKWISE || rotation == Core.ROTATE_90_COUNTERCLOCKWISE) {
imageWidth = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0).toDouble()
imageHeight = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0).toDouble()
}
Log.i(TAG, "width:" + imageWidth)
Log.i(TAG, "height:" + imageHeight)
val inputData: ByteArray? = getBytes(contentResolver.openInputStream(uri))
val mat = Mat(Size(imageWidth, imageHeight), CvType.CV_8U)
mat.put(0, 0, inputData)
val pic = Imgcodecs.imdecode(mat, Imgcodecs.CV_LOAD_IMAGE_UNCHANGED)
if (rotation > -1) Core.rotate(pic, pic, rotation)
mat.release()
mPresenter.detectEdge(pic);
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == REQUEST_CAMERA_PERMISSION
&& (grantResults[permissions.indexOf(android.Manifest.permission.CAMERA)] == PackageManager.PERMISSION_GRANTED)) {
showMessage(R.string.camera_grant)
mPresenter.initCamera()
mPresenter.updateCamera()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun getDisplay(): Display = windowManager.defaultDisplay
override fun getSurfaceView(): SurfaceView = surface
override fun getPaperRect(): PaperRectangle = paper_rect
@Throws(IOException::class)
fun getBytes(inputStream: InputStream): ByteArray? {
val byteBuffer = ByteArrayOutputStream()
val bufferSize = 1024
val buffer = ByteArray(bufferSize)
var len = 0
while (inputStream.read(buffer).also { len = it } != -1) {
byteBuffer.write(buffer, 0, len)
}
return byteBuffer.toByteArray()
}
} | apache-2.0 | fe2081cd6962037a048100a041cc32fa | 39.159509 | 175 | 0.683881 | 4.715418 | false | false | false | false |
AdamLuisSean/Picasa-Gallery-Android | app/src/main/kotlin/io/shtanko/picasagallery/ui/photo/PhotoViewer.kt | 1 | 16995 | /*
* Copyright 2017 Alexey Shtanko
*
* 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.shtanko.picasagallery.ui.photo
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PixelFormat.TRANSLUCENT
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.os.Build.VERSION_CODES.M
import android.util.AttributeSet
import android.view.ActionMode
import android.view.ActionMode.Callback
import android.view.GestureDetector
import android.view.Gravity.START
import android.view.Gravity.TOP
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_POINTER_DOWN
import android.view.View
import android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
import android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
import android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
import android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
import android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
import android.view.WindowManager.LayoutParams.MATCH_PARENT
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import android.widget.Scroller
import io.shtanko.picasagallery.PicasaApplication
import io.shtanko.picasagallery.R
import io.shtanko.picasagallery.extensions.createFrame
import io.shtanko.picasagallery.vendors.utils.BackgroundDrawable
import io.shtanko.picasagallery.vendors.utils.ClippingImageView
import io.shtanko.picasagallery.ui.util.AndroidUtils
import io.shtanko.picasagallery.ui.util.AndroidUtils.statusBarHeight
class PhotoViewer : GestureDetector.OnDoubleTapListener, GestureDetector.OnGestureListener {
private var scale = 1f
private var translationX: Float = 0.toFloat()
private var translationY: Float = 0.toFloat()
private var canZoom = true
private var imageMoveAnimation: AnimatorSet? = null
private var gestureDetector: GestureDetector? = null
private var isVisible: Boolean = false
var parentActivity: Activity? = null
private lateinit var scroller: Scroller
var windowView: FrameLayout? = null
private var containerView: FrameLayoutDrawer? = null
private var lastInsets: Any? = null
private val blackPaint = Paint()
private var animatingImageView: ClippingImageView? = null
private var windowLayoutParams: WindowManager.LayoutParams? = null
private val backgroundDrawable = BackgroundDrawable(0xff000000.toInt())
private val animationValues = Array(2) { FloatArray(8) }
private var zooming: Boolean = false
private var zoomAnimation: Boolean = false
private var animateToScale: Float = 0.toFloat()
private var animateToX: Float = 0.toFloat()
private var animateToY: Float = 0.toFloat()
private var animationStartTime: Long = 0
private val interpolator = DecelerateInterpolator(1.5f)
private var animationInProgress: Int = 0
private var animationValue: Float = 0.toFloat()
private var minX: Float = 0.toFloat()
private var maxX: Float = 0.toFloat()
private var minY: Float = 0.toFloat()
private var maxY: Float = 0.toFloat()
private var switchImageAfterAnimation: Int = 0
init {
blackPaint.color = 0xff000000.toInt()
}
fun initActivity(activity: Activity) {
parentActivity = activity
scroller = Scroller(activity)
windowView = object : FrameLayout(activity) {
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean =
super.onInterceptTouchEvent(ev)
override fun onTouchEvent(event: MotionEvent?): Boolean =
isVisible && [email protected](event)
override fun drawChild(
canvas: Canvas?,
child: View?,
drawingTime: Long
): Boolean {
val result = super.drawChild(canvas, child, drawingTime)
if (SDK_INT >= LOLLIPOP && lastInsets != null) {
val insets = lastInsets as WindowInsets
canvas?.drawRect(
0f, measuredHeight.toFloat(), measuredWidth.toFloat(),
(measuredHeight + insets.systemWindowInsetBottom).toFloat(), blackPaint
)
}
return result
}
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
var widthSize = View.MeasureSpec.getSize(widthMeasureSpec)
var heightSize = View.MeasureSpec.getSize(heightMeasureSpec)
if (SDK_INT >= LOLLIPOP) {
if (lastInsets != null) {
val insets = lastInsets as WindowInsets
heightSize -= insets.systemWindowInsetBottom
widthSize -= insets.systemWindowInsetRight
}
} else {
if (heightSize > AndroidUtils.displaySize.y) {
heightSize = AndroidUtils.displaySize.y
}
}
setMeasuredDimension(widthSize, heightSize)
if (SDK_INT >= LOLLIPOP && lastInsets != null) {
widthSize -= (lastInsets as WindowInsets).systemWindowInsetLeft
}
val layoutParams = animatingImageView?.layoutParams
if (layoutParams != null) {
animatingImageView?.measure(
View.MeasureSpec.makeMeasureSpec(layoutParams.width, View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(layoutParams.height, View.MeasureSpec.AT_MOST)
)
}
containerView?.measure(
View.MeasureSpec.makeMeasureSpec(widthSize, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(heightSize, View.MeasureSpec.EXACTLY)
)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
var x = 0
if (SDK_INT >= LOLLIPOP && lastInsets != null) {
x += (lastInsets as WindowInsets).systemWindowInsetLeft
}
animatingImageView?.layout(
x, 0, x + animatingImageView!!.measuredWidth,
animatingImageView?.measuredHeight!!
)
if (changed) {
translationX = 0f
translationY = 0f
}
}
override fun startActionModeForChild(
originalView: View?,
callback: Callback?,
type: Int
): ActionMode {
if (SDK_INT >= M) {
val view = parentActivity?.findViewById<View>(android.R.id.content)
if (view is ViewGroup) {
try {
return view.startActionModeForChild(originalView, callback, type)
} catch (e: Throwable) {
}
}
}
return super.startActionModeForChild(originalView, callback, type)
}
}
windowView?.setBackgroundDrawable(backgroundDrawable)
windowView?.clipChildren = true
windowView?.isFocusable = false
animatingImageView = ClippingImageView(activity)
animatingImageView?.setAnimationValues(animationValues)
windowView?.addView(animatingImageView, createFrame(40, 40F))
containerView = FrameLayoutDrawer(activity)
containerView?.isFocusable = false
windowView?.addView(containerView, createFrame(MATCH_PARENT, MATCH_PARENT, TOP or START))
if (SDK_INT >= LOLLIPOP) {
containerView?.fitsSystemWindows = true
containerView?.setOnApplyWindowInsetsListener({ _, insets ->
lastInsets = insets
val oldInsets = lastInsets as WindowInsets
if (oldInsets.toString() != insets.toString()) {
windowView?.requestLayout()
}
insets.consumeSystemWindowInsets()
})
containerView?.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_STABLE or
SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
windowLayoutParams = WindowManager.LayoutParams()
windowLayoutParams?.height = MATCH_PARENT
windowLayoutParams?.format = TRANSLUCENT
windowLayoutParams?.width = MATCH_PARENT
windowLayoutParams?.gravity = TOP or START
windowLayoutParams?.flags = FLAG_NOT_FOCUSABLE
if (SDK_INT >= LOLLIPOP) {
windowLayoutParams?.flags = FLAG_LAYOUT_IN_SCREEN or
FLAG_LAYOUT_INSET_DECOR or
FLAG_NOT_FOCUSABLE or
FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
} else {
windowLayoutParams?.flags = FLAG_NOT_FOCUSABLE
}
gestureDetector = GestureDetector(containerView?.context, this)
gestureDetector?.setOnDoubleTapListener(this)
}
fun openPhoto() {
isVisible = true
val wm = parentActivity?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm.addView(windowView, windowLayoutParams)
animatingImageView?.visibility = VISIBLE
animatingImageView?.alpha = 1.0f
animatingImageView?.pivotX = 0.0f
animatingImageView?.pivotY = 0.0f
val bitmap = BitmapFactory.decodeResource(
parentActivity?.resources,
R.drawable.image_placeholder
)
val layoutParams = animatingImageView?.layoutParams
layoutParams?.width = bitmap.width
layoutParams?.height = bitmap.height
animatingImageView?.layoutParams = layoutParams
animatingImageView?.setImageBitmap(bitmap)
}
fun closePhoto() {
destroyPhotoViewer()
}
override fun onDoubleTap(e: MotionEvent?): Boolean {
if (!canZoom || scale == 1.0f && (translationY != 0.toFloat() || translationX != 0.toFloat())) {
return false
}
if (animationStartTime != 0.toLong() || animationInProgress != 0) {
return false
}
if (scale == 1.0f) {
val atx =
e?.x!! - getContainerViewWidth()!! / 2 - (e.x - getContainerViewWidth()!! / 2 - translationX) * (3.0f / scale)
val aty =
e.y - getContainerViewHeight() / 2 - (e.y - getContainerViewHeight() / 2 - translationY) * (3.0f / scale)
animateTo(3.0f, atx, aty, true)
}
return true
}
override fun onDoubleTapEvent(p0: MotionEvent?): Boolean = false
override fun onSingleTapConfirmed(p0: MotionEvent?): Boolean {
return true
}
override fun onShowPress(p0: MotionEvent?) {
}
override fun onSingleTapUp(p0: MotionEvent?): Boolean {
return false
}
override fun onDown(p0: MotionEvent?): Boolean {
return false
}
override fun onFling(
p0: MotionEvent?,
p1: MotionEvent?,
p2: Float,
p3: Float
): Boolean {
return false
}
override fun onScroll(
p0: MotionEvent?,
p1: MotionEvent?,
p2: Float,
p3: Float
): Boolean {
return false
}
override fun onLongPress(p0: MotionEvent?) {
println("")
}
private fun getContainerViewHeight(): Int {
var height = AndroidUtils.displaySize.y
return height
}
private fun getContainerViewWidth(): Int? {
var width = containerView?.width
return width
}
private fun onPhotoClosed() {
containerView?.post {
animatingImageView?.setImageBitmap(null)
try {
if (windowView?.parent != null) {
val wm = parentActivity?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm.removeView(windowView)
}
} catch (e: Exception) {
}
}
}
private fun destroyPhotoViewer() {
if (windowView?.parent != null) {
val wm = parentActivity?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm.removeViewImmediate(windowView)
}
windowView = null
}
private fun animateTo(
newScale: Float,
newTx: Float,
newTy: Float,
isZoom: Boolean
) {
animateTo(newScale, newTx, newTy, isZoom, 250)
}
private fun animateTo(
newScale: Float,
newTx: Float,
newTy: Float,
isZoom: Boolean,
duration: Int
) {
if (scale == newScale && translationX == newTx && translationY == newTy) {
return
}
zoomAnimation = isZoom
animateToScale = newScale
animateToX = newTx
animateToY = newTy
animationStartTime = System.currentTimeMillis()
imageMoveAnimation = AnimatorSet()
imageMoveAnimation?.playTogether(
ObjectAnimator.ofFloat(this, "animationValue", 0.toFloat(), 1.toFloat())
)
imageMoveAnimation?.interpolator = interpolator
imageMoveAnimation?.duration = duration.toLong()
imageMoveAnimation?.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
imageMoveAnimation = null
containerView?.invalidate()
}
})
imageMoveAnimation?.start()
}
private fun updateMinMax(scale: Float) {
}
private fun onTouchEvent(ev: MotionEvent?): Boolean {
if (scale == 1.0f) {
val atx =
ev?.x!! - getContainerViewWidth()!! / 2 - (ev.x - getContainerViewWidth()!! / 2 - translationX) * (3.0f / scale)
val aty =
ev.y - getContainerViewHeight() / 2 - (ev.y - getContainerViewHeight() / 2 - translationY) * (3.0f / scale)
animateTo(3.0f, atx, aty, true)
}
if (ev?.actionMasked == ACTION_DOWN || ev?.actionMasked == ACTION_POINTER_DOWN) {
} else if (ev?.actionMasked == ACTION_MOVE) {
}
if (ev?.pointerCount == 1 && gestureDetector!!.onTouchEvent(ev)) {
return true
}
return false
}
@SuppressLint("NewApi", "DrawAllocation")
private fun onDraw(canvas: Canvas?) {
if (animationInProgress == 1) {
return
}
val currentTranslationY: Float
val currentTranslationX: Float
val currentScale: Float
var aty = -1f
if (imageMoveAnimation != null) {
if (!scroller.isFinished) {
scroller.abortAnimation()
}
val ts = scale + (animateToScale - scale) * animationValue
val tx = translationX + (animateToX - translationX) * animationValue
val ty = translationY + (animateToY - translationY) * animationValue
if (animateToScale == 1f && scale == 1f && translationX == 0f) {
aty = ty
}
currentScale = ts
currentTranslationY = ty
currentTranslationX = tx
containerView?.invalidate()
} else {
if (animationStartTime != 0.toLong()) {
translationX = animateToX
translationY = animateToY
scale = animateToScale
animationStartTime = 0
updateMinMax(scale)
zoomAnimation = false
}
}
if (!scroller.isFinished) {
if (scroller.computeScrollOffset()) {
if (scroller.startX < maxX && scroller.startX > minX) {
translationX = scroller.currX.toFloat()
}
if (scroller.startY < maxY && scroller.startY > minY) {
translationY = scroller.currY.toFloat()
}
containerView?.invalidate()
}
}
if (switchImageAfterAnimation != 0) {
if (switchImageAfterAnimation == 1) {
PicasaApplication.applicationHandler
AndroidUtils.runOnUIThread(Runnable { })
}
}
}
inner class FrameLayoutDrawer : FrameLayout {
private val paint = Paint()
constructor(context: Context) : super(context)
constructor(
context: Context,
attrs: AttributeSet
) : super(context, attrs)
constructor(
context: Context,
attrs: AttributeSet,
defStyleAttr: Int
) : super(
context, attrs,
defStyleAttr
)
init {
setWillNotDraw(false)
paint.color = 0x33000000
}
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
super.onLayout(changed, left, top, right, bottom)
}
override fun onDraw(canvas: Canvas?) {
[email protected](canvas)
if (Build.VERSION.SDK_INT >= 21 && statusBarHeight != 0) {
canvas?.drawRect(
0f, 0f, measuredWidth.toFloat(), statusBarHeight.toFloat(),
paint
)
}
}
override fun drawChild(
canvas: Canvas?,
child: View?,
drawingTime: Long
): Boolean {
return super.drawChild(canvas, child, drawingTime)
}
}
} | apache-2.0 | 3e862db3429d9022a9cd2212620d10d0 | 27.709459 | 120 | 0.672374 | 4.553859 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AccessibilityCodelab/app/src/main/java/com/example/jetnews/data/posts/PostsRepository.kt | 1 | 1725 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.data.posts
import com.example.jetnews.data.posts.impl.posts
import com.example.jetnews.model.Post
import com.example.jetnews.utils.addOrRemove
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
/**
* Simplified implementation of PostsRepository that returns a hardcoded list of
* posts with resources synchronously.
*/
class PostsRepository {
// for now, keep the favorites in memory
private val favorites = MutableStateFlow<Set<String>>(setOf())
/**
* Get a specific JetNews post.
*/
fun getPost(postId: String?): Post? {
return posts.find { it.id == postId }
}
/**
* Get JetNews posts.
*/
fun getPosts(): List<Post> {
return posts
}
/**
* Observe the current favorites
*/
fun observeFavorites(): Flow<Set<String>> = favorites
/**
* Toggle a postId to be a favorite or not.
*/
fun toggleFavorite(postId: String) {
val set = favorites.value.toMutableSet()
set.addOrRemove(postId)
favorites.value = set
}
}
| apache-2.0 | 53dae6125a894008a87e02b19449ca6a | 27.75 | 80 | 0.689275 | 4.301746 | false | false | false | false |
RichoDemus/kotlin-test | src/main/kotlin/demo/async/CoroutineMain.kt | 1 | 1307 | package demo.async
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import org.slf4j.LoggerFactory
import java.lang.Thread.sleep
import java.time.Duration
import kotlin.system.measureTimeMillis
val logger = LoggerFactory.getLogger("AsyncQueue")!!
/**
* <pre>
* For best result, add some threads to the ForkJoinPool
* -Djava.util.concurrent.ForkJoinPool.common.parallelism=5000
* </pre>
*/
fun main(args: Array<String>) {
logger.info("Start")
val time = measureTimeMillis {
val deffers = (1..3000).map {
"string-$it"
}.map {
async {
val res = expensiveOperation1(it)
expensiveOperation2(res)
}
}
runBlocking {
val strings = deffers.map { it.await() }
logger.info("done converting ${strings.size} strings")
}
}
logger.info("End")
logger.info("Took ${Duration.ofMillis(time).pretty()} seconds")
}
fun expensiveOperation1(str: String): String {
sleep(1_000L)
return "$str hello"
}
fun expensiveOperation2(str: String): String {
sleep(1_000L)
return str.toUpperCase()
}
private fun Duration.pretty() = String.format("%02d:%02d", (this.seconds % 3600) / 60, (this.seconds % 60))
| apache-2.0 | 9599997f9530ee6813fbcdd40f2e8f9c | 22.339286 | 107 | 0.641163 | 3.832845 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/AdapterViewEvent.kt | 1 | 3420 | package com.github.kittinunf.reactiveandroid.widget
import android.view.View
import android.widget.AdapterView
import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate
import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription
import io.reactivex.Observable
//================================================================================
// Events
//================================================================================
data class ItemClickListener(val adapterView: AdapterView<*>, val view: View, val position: Int, val id: Long)
fun AdapterView<*>.rx_itemClick(): Observable<ItemClickListener> {
return Observable.create { subscriber ->
setOnItemClickListener { adapterView, view, position, id ->
subscriber.onNext(ItemClickListener(adapterView, view, position, id))
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnItemClickListener(null)
})
}
}
data class ItemLongClickListener(val adapterView: AdapterView<*>, val view: View, val position: Int, val id: Long)
fun AdapterView<*>.rx_itemLongClick(consumed: Boolean): Observable<ItemLongClickListener> {
return Observable.create { subscriber ->
setOnItemLongClickListener { adapterView, view, position, id ->
subscriber.onNext(ItemLongClickListener(adapterView, view, position, id))
consumed
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnItemLongClickListener(null)
})
}
}
data class ItemSelectedListener(val adapterView: AdapterView<*>?, val view: View?, val position: Int, val id: Long)
fun AdapterView<*>.rx_itemSelected(): Observable<ItemSelectedListener> {
return Observable.create { subscriber ->
_itemSelected.onItemSelected { adapterView, view, position, id ->
subscriber.onNext(ItemSelectedListener(adapterView, view, position, id))
}
subscriber.setDisposable(AndroidMainThreadSubscription {
onItemSelectedListener = null
})
}
}
fun AdapterView<*>.rx_nothingSelected(): Observable<AdapterView<*>> {
return Observable.create { subscriber ->
_itemSelected.onNothingSelected {
if (it != null) subscriber.onNext(it)
}
subscriber.setDisposable(AndroidMainThreadSubscription {
onItemSelectedListener = null
})
}
}
private val AdapterView<*>._itemSelected: _AdapterView_OnItemSelectedListener
by ExtensionFieldDelegate({ _AdapterView_OnItemSelectedListener() }, { onItemSelectedListener = it })
internal class _AdapterView_OnItemSelectedListener : AdapterView.OnItemSelectedListener {
private var onNothingSelected: ((AdapterView<*>?) -> Unit)? = null
private var onItemSelected: ((AdapterView<*>?, View?, Int, Long) -> Unit)? = null
override fun onNothingSelected(parent: AdapterView<*>?) {
onNothingSelected?.invoke(parent)
}
//proxy method
fun onNothingSelected(listener: (AdapterView<*>?) -> Unit) {
onNothingSelected = listener
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onItemSelected?.invoke(parent, view, position, id)
}
//proxy method
fun onItemSelected(listener: (AdapterView<*>?, View?, Int, Long) -> Unit) {
onItemSelected = listener
}
}
| mit | 9cb62580a3b7539c65e58a5adb7e1578 | 34.625 | 115 | 0.665789 | 5.570033 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/34.FieldDelegateExample属性代理.kt | 1 | 1385 | package com.zj.example.kotlin.basicsknowledge
import kotlin.reflect.KProperty
/**
* 属性代理
* Created by zhengjiong
* date: 2017/9/17 20:40
*/
fun main(vararg args: String) {
var d = FieldDelegateExample()
/**
* 输出:
* Delegate1 getValue value=null property=y
*/
println(d.y)
/**
* 输出:
* Delegate1 getValue value=zzz property=z
* zzz
*/
d.z = "zzz"
println(d.z)
}
class FieldDelegateExample {
val x: String by lazy {
"hello delegate"
}
//val只需要实现getValue
val y: String by Delegate1()
/**
* var需要Delegate1实现setValue,getValue方法
*/
var z: String by Delegate1()
}
/**
* 代理者需要实现相应的setValue和getValue方法
* val只需要实现getValue
*/
class Delegate1 {
//这里名字可以不叫value, 但是下面必须用getValue和setValue并且加operator
private var value: String? = null
/**
* thisRef就是FieldDelegateExample对象
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
println("Delegate1 getValue value=" + value + " property=" + property.name)
return value ?: ""
}
/**
* 需要添加value:String参数
*/
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
this.value = value
}
} | mit | 438a5a1e66d63a89342ac229ad480c4f | 17.716418 | 83 | 0.611333 | 3.663743 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/RustExplainFilter.kt | 1 | 1329 | package org.rust.cargo.runconfig
import com.intellij.execution.filters.BrowserHyperlinkInfo
import com.intellij.execution.filters.Filter
import com.intellij.execution.filters.Filter.Result
import com.intellij.openapi.project.DumbAware
import java.util.regex.Pattern
/**
* Filters output for “[--explain Exxxx]” (or other similar patterns) and links
* to the relevant documentation.
*/
class RustExplainFilter : Filter, DumbAware {
private val patterns = listOf(
Pattern.compile("--explain E(\\d{4})"),
Pattern.compile("(error|warning)\\[E(\\d{4})\\]"))
override fun applyFilter(line: String, entireLength: Int): Result? {
val matcher = patterns
.map { it.matcher(line) }
.firstOrNull { it.find() } ?: return null
val (offset, length, code) = when (matcher.groupCount()) {
1 -> Triple(0, matcher.group(0).length, matcher.group(1))
else -> Triple(matcher.group(1).length, matcher.group(2).length + 3, matcher.group(2))
}
val url = "https://doc.rust-lang.org/error-index.html#E$code"
val info = BrowserHyperlinkInfo(url)
val startOffset = entireLength - line.length + matcher.start() + offset
val endOffset = startOffset + length
return Result(startOffset, endOffset, info)
}
}
| mit | efdbec40fd58efaf9f0186d470ea3de8 | 35.805556 | 98 | 0.662642 | 4.003021 | false | false | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/Hand.kt | 1 | 8799 | package org.luxons.sevenwonders.ui.components.game
import com.palantir.blueprintjs.*
import kotlinx.css.*
import kotlinx.css.properties.*
import kotlinx.html.DIV
import org.luxons.sevenwonders.model.*
import org.luxons.sevenwonders.model.cards.CardPlayability
import org.luxons.sevenwonders.model.cards.HandCard
import org.luxons.sevenwonders.model.resources.ResourceTransactionOptions
import org.luxons.sevenwonders.model.wonders.WonderBuildability
import org.luxons.sevenwonders.ui.redux.TransactionSelectorState
import react.*
import styled.StyledDOMBuilder
import styled.css
import styled.styledDiv
import kotlin.math.absoluteValue
private enum class HandAction(
val buttonTitle: String,
val moveType: MoveType,
val icon: IconName,
) {
PLAY("PLAY", MoveType.PLAY, "play"),
PLAY_FREE("Play as this age's free card", MoveType.PLAY_FREE, "star"),
PLAY_FREE_DISCARDED("Play discarded card", MoveType.PLAY_FREE_DISCARDED, "star"),
COPY_GUILD("Copy this guild card", MoveType.COPY_GUILD, "duplicate")
}
interface HandProps : RProps {
var turnInfo: PlayerTurnInfo
var preparedMove: PlayerMove?
var prepareMove: (PlayerMove) -> Unit
var startTransactionsSelection: (TransactionSelectorState) -> Unit
}
class HandComponent(props: HandProps) : RComponent<HandProps, RState>(props) {
override fun RBuilder.render() {
val hand = props.turnInfo.cardsToPlay() ?: return
styledDiv {
css {
handStyle()
}
hand.filter { it.name != props.preparedMove?.cardName }.forEachIndexed { index, c ->
handCard(card = c) {
attrs {
key = index.toString()
}
}
}
}
}
private fun PlayerTurnInfo.cardsToPlay(): List<HandCard>? = when (action) {
Action.PLAY, Action.PLAY_2, Action.PLAY_LAST -> hand
Action.PLAY_FREE_DISCARDED -> discardedCards
Action.PICK_NEIGHBOR_GUILD -> neighbourGuildCards
Action.WAIT, Action.WATCH_SCORE, Action.SAY_READY -> null
}
private fun RBuilder.handCard(
card: HandCard,
block: StyledDOMBuilder<DIV>.() -> Unit,
) {
styledDiv {
css {
handCardStyle()
}
block()
cardImage(card) {
css {
handCardImgStyle(card.playability.isPlayable)
}
}
actionButtons(card)
}
}
private fun RBuilder.actionButtons(card: HandCard) {
styledDiv {
css {
justifyContent = JustifyContent.center
alignItems = Align.flexEnd
display = Display.none
gridRow = GridRow("1")
gridColumn = GridColumn("1")
ancestorHover(".hand-card") {
display = Display.flex
}
}
bpButtonGroup {
val action = props.turnInfo.action
when (action) {
Action.PLAY, Action.PLAY_2, Action.PLAY_LAST -> {
playCardButton(card, HandAction.PLAY)
if (props.turnInfo.getOwnBoard().canPlayAnyCardForFree) {
playCardButton(card.copy(playability = CardPlayability.SPECIAL_FREE), HandAction.PLAY_FREE)
}
}
Action.PLAY_FREE_DISCARDED -> playCardButton(card, HandAction.PLAY_FREE_DISCARDED)
Action.PICK_NEIGHBOR_GUILD -> playCardButton(card, HandAction.COPY_GUILD)
else -> error("unsupported action in hand card: $action")
}
if (action.allowsBuildingWonder()) {
upgradeWonderButton(card)
}
if (action.allowsDiscarding()) {
discardButton(card)
}
}
}
}
private fun RElementBuilder<IButtonGroupProps>.playCardButton(card: HandCard, handAction: HandAction) {
bpButton(
title = "${handAction.buttonTitle} (${cardPlayabilityInfo(card.playability)})",
large = true,
intent = Intent.SUCCESS,
disabled = !card.playability.isPlayable,
onClick = { prepareMove(handAction.moveType, card, card.playability.transactionOptions) },
) {
bpIcon(handAction.icon)
if (card.playability.isPlayable && !card.playability.isFree) {
priceInfo(card.playability.minPrice)
}
}
}
private fun RElementBuilder<IButtonGroupProps>.upgradeWonderButton(card: HandCard) {
val wonderBuildability = props.turnInfo.wonderBuildability
bpButton(
title = "UPGRADE WONDER (${wonderBuildabilityInfo(wonderBuildability)})",
large = true,
intent = Intent.PRIMARY,
disabled = !wonderBuildability.isBuildable,
onClick = { prepareMove(MoveType.UPGRADE_WONDER, card, wonderBuildability.transactionsOptions) },
) {
bpIcon("key-shift")
if (wonderBuildability.isBuildable && !wonderBuildability.isFree) {
priceInfo(wonderBuildability.minPrice)
}
}
}
private fun prepareMove(moveType: MoveType, card: HandCard, transactionOptions: ResourceTransactionOptions) {
when (transactionOptions.size) {
1 -> props.prepareMove(PlayerMove(moveType, card.name, transactionOptions.first()))
else -> props.startTransactionsSelection(TransactionSelectorState(moveType, card, transactionOptions))
}
}
private fun RElementBuilder<IButtonGroupProps>.discardButton(card: HandCard) {
bpButton(
title = "DISCARD (+3 coins)", // TODO remove hardcoded value
large = true,
intent = Intent.DANGER,
icon = "cross",
onClick = { props.prepareMove(PlayerMove(MoveType.DISCARD, card.name)) },
)
}
}
private fun cardPlayabilityInfo(playability: CardPlayability) = when (playability.isPlayable) {
true -> priceText(-playability.minPrice)
false -> playability.playabilityLevel.message
}
private fun wonderBuildabilityInfo(buildability: WonderBuildability) = when (buildability.isBuildable) {
true -> priceText(-buildability.minPrice)
false -> buildability.playabilityLevel.message
}
private fun priceText(amount: Int) = when (amount.absoluteValue) {
0 -> "free"
1 -> "${pricePrefix(amount)}$amount coin"
else -> "${pricePrefix(amount)}$amount coins"
}
private fun pricePrefix(amount: Int) = when {
amount > 0 -> "+"
else -> ""
}
private fun RElementBuilder<IButtonProps>.priceInfo(amount: Int) {
val size = 1.rem
goldIndicator(
amount = amount,
amountPosition = TokenCountPosition.OVER,
imgSize = size,
customCountStyle = {
fontFamily = "sans-serif"
fontSize = size * 0.8
},
) {
css {
position = Position.absolute
top = (-0.2).rem
left = (-0.2).rem
}
}
}
private fun CSSBuilder.handStyle() {
alignItems = Align.center
bottom = 0.px
display = Display.flex
height = 345.px
left = 50.pct
maxHeight = 25.vw
position = Position.absolute
transform {
translate(tx = (-50).pct, ty = 55.pct)
}
transition(duration = 0.5.s)
zIndex = 30
hover {
bottom = 4.rem
transform {
translate(tx = (-50).pct, ty = 0.pct)
}
}
}
private fun CSSBuilder.handCardStyle() {
classes.add("hand-card")
alignItems = Align.flexEnd
display = Display.grid
margin(all = 0.2.rem)
}
private fun CSSBuilder.handCardImgStyle(isPlayable: Boolean) {
gridRow = GridRow("1")
gridColumn = GridColumn("1")
maxWidth = 13.vw
maxHeight = 60.vh
transition(duration = 0.1.s)
width = 11.rem
ancestorHover(".hand-card") {
boxShadow(offsetX = 0.px, offsetY = 10.px, blurRadius = 40.px, color = Color.black)
width = 14.rem
maxWidth = 15.vw
maxHeight = 90.vh
}
if (!isPlayable) {
filter = "grayscale(50%) contrast(50%)"
}
}
fun RBuilder.handCards(
turnInfo: PlayerTurnInfo,
preparedMove: PlayerMove?,
prepareMove: (PlayerMove) -> Unit,
startTransactionsSelection: (TransactionSelectorState) -> Unit,
) {
child(HandComponent::class) {
attrs {
this.turnInfo = turnInfo
this.preparedMove = preparedMove
this.prepareMove = prepareMove
this.startTransactionsSelection = startTransactionsSelection
}
}
}
| mit | 79232d93818f881297abd3ccfdc51c62 | 31.710037 | 119 | 0.599841 | 4.27551 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/test/java/io/michaelrocks/lightsaber/processor/commons/CompositeVisitorVerifier.kt | 1 | 4386 | /*
* 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.commons
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.RETURNS_DEFAULTS
import org.mockito.Mockito.mock
import org.mockito.Mockito.only
import org.mockito.Mockito.verify
import java.util.ArrayList
import kotlin.reflect.KClass
private val MAX_VISITOR_COUNT = 3
private val EMPTIES_PERMUTATIONS = arrayOf(
booleanArrayOf(),
booleanArrayOf(true),
booleanArrayOf(false),
booleanArrayOf(true, true),
booleanArrayOf(false, true),
booleanArrayOf(true, false),
booleanArrayOf(false, false),
booleanArrayOf(true, true, true),
booleanArrayOf(true, true, false),
booleanArrayOf(true, false, true),
booleanArrayOf(false, true, true),
booleanArrayOf(true, false, false),
booleanArrayOf(false, false, false)
)
fun <T, V> verifyMethodInvocations(compositeVisitorClass: KClass<T>, action: V.() -> Any?)
where T : CompositeVisitor<V>, V : Any {
for (i in 0..MAX_VISITOR_COUNT) {
verifyMethodInvocation(compositeVisitorClass.java.newInstance(), action, i)
}
}
fun <T, V> verifyMethodInvocations(compositeVisitorClass: Class<T>, action: V.() -> Any?)
where T : CompositeVisitor<V>, V : Any {
for (i in 0..MAX_VISITOR_COUNT) {
verifyMethodInvocation(compositeVisitorClass.newInstance(), action, i)
}
}
private fun <T, V> verifyMethodInvocation(compositeVisitor: T, action: V.() -> Any?, visitorCount: Int)
where T : CompositeVisitor<V>, V : Any {
val visitors = ArrayList<V>(visitorCount)
for (i in 0 until visitorCount) {
@Suppress("UNCHECKED_CAST")
val visitor = mock(compositeVisitor.javaClass.superclass as Class<V>)
visitors.add(visitor)
compositeVisitor.addVisitor(visitor)
}
@Suppress("UNCHECKED_CAST")
(compositeVisitor as V).action()
for (visitor in visitors) {
verify(visitor, only()).action()
}
}
inline fun <reified T, R, V> verifyCompositeMethodInvocations(
noinline action: V.() -> R,
noinline innerAction: R.() -> Any?
)
where T : CompositeVisitor<V>, V : Any {
verifyCompositeMethodInvocations(T::class.java, action, innerAction)
}
fun <T, R, V> verifyCompositeMethodInvocations(
compositeVisitorClass: KClass<T>,
action: V.() -> R,
innerAction: R.() -> Any?
)
where T : CompositeVisitor<V>, V : Any {
verifyCompositeMethodInvocations(compositeVisitorClass.java, action, innerAction)
}
fun <T, R, V> verifyCompositeMethodInvocations(
compositeVisitorClass: Class<T>,
action: V.() -> R,
innerAction: R.() -> Any?
)
where T : CompositeVisitor<V>, V : Any {
for (empties in EMPTIES_PERMUTATIONS) {
verifyCompositeMethodInvocation(compositeVisitorClass.newInstance(), action, innerAction, empties)
}
}
private fun <T, R, V> verifyCompositeMethodInvocation(
compositeVisitor: T,
action: V.() -> R,
innerAction: R.() -> Any?,
empties: BooleanArray
)
where T : CompositeVisitor<V>, V : Any {
val visitors = ArrayList<V>(empties.size)
for (empty in empties) {
val answer = if (empty) RETURNS_DEFAULTS else RETURNS_DEEP_STUBS
@Suppress("UNCHECKED_CAST")
val visitor = mock(compositeVisitor.javaClass.superclass as Class<V>, answer)
visitors.add(visitor)
compositeVisitor.addVisitor(visitor)
}
@Suppress("UNCHECKED_CAST")
val result = (compositeVisitor as V).action()
for (visitor in visitors) {
visitor.action()
}
result?.innerAction()
var hasNonEmpty = false
for (i in empties.indices) {
val empty = empties[i]
if (!empty) {
hasNonEmpty = true
val visitor = visitors.get(i)
assertNotNull(result)
innerAction.invoke(verify(action.invoke(visitor), only()))
}
}
if (!hasNonEmpty) {
assertNull(result)
}
}
| apache-2.0 | 449a851c20a92ef805e09983b96fab5b | 29.041096 | 103 | 0.713634 | 3.745517 | false | false | false | false |
LorittaBot/Loritta | web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/WebsiteThemeUtils.kt | 1 | 1698 | package net.perfectdreams.loritta.cinnamon.showtime.frontend
import kotlinx.browser.document
import kotlinx.dom.addClass
import kotlinx.dom.removeClass
import net.perfectdreams.dokyo.WebsiteTheme
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.select
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.selectAll
import org.w3c.dom.Element
import org.w3c.dom.HTMLSpanElement
object WebsiteThemeUtils {
/**
* Sets the current active theme and stores the user's preference in a cookie
*/
fun changeWebsiteThemeTo(newTheme: WebsiteTheme) {
val body = document.body!!
val themeChangerButton = document.select<Element?>("#theme-changer-button")
WebsiteTheme.values().forEach {
body.removeClass(it.bodyClass)
}
body.addClass(newTheme.bodyClass)
CookieUtils.createCookie("userTheme", newTheme.name)
// Switch icons
val iconsInTheThemeSwitcherButton = themeChangerButton?.selectAll<HTMLSpanElement>("span")
if (iconsInTheThemeSwitcherButton != null) {
println("Icons: ${iconsInTheThemeSwitcherButton.size}")
val activeIcons = iconsInTheThemeSwitcherButton.filter { it.style.display == "" }
val inactiveIcons = iconsInTheThemeSwitcherButton.filter { it.style.display != "" }
activeIcons.forEach { it.style.display = "none" }
inactiveIcons.forEach { it.style.display = "" }
}
// Old website
if (newTheme == WebsiteTheme.DARK_THEME)
CookieUtils.createCookie("darkTheme", "true")
else
CookieUtils.eraseCookie("darkTheme")
}
} | agpl-3.0 | 6103fc77f1597811ebe1dfc5d4cb88ca | 35.934783 | 98 | 0.697291 | 4.342711 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandlerSpec.kt | 1 | 20198 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.natpryce.hamkrest.allElements
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.hasElement
import com.natpryce.hamkrest.isEmpty
import com.natpryce.hamkrest.should.shouldMatch
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.StageStarted
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.model.Task
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionNotFoundException
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.orca.time.fixedClock
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object StartStageHandlerSpec : SubjectSpek<StartStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
subject {
StartStageHandler(
queue,
repository,
listOf(
singleTaskStage,
multiTaskStage,
stageWithSyntheticBefore,
stageWithSyntheticAfter,
stageWithParallelBranches,
rollingPushStage,
zeroTaskStage,
stageWithSyntheticAfterAndNoTasks
),
publisher,
clock,
ContextParameterProcessor()
)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("starting a stage") {
context("with a single initial task") {
val pipeline = pipeline {
application = "foo"
stage {
type = singleTaskStage.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual RUNNING
it.getStartTime() shouldEqual clock.millis()
})
}
it("attaches tasks to the stage") {
verify(repository).storeStage(check {
it.getTasks().size shouldEqual 1
it.getTasks().first().apply {
id shouldEqual "1"
name shouldEqual "dummy"
implementingClass shouldEqual DummyTask::class.java.name
isStageStart shouldEqual true
isStageEnd shouldEqual true
}
})
}
it("starts the first task") {
verify(queue).push(StartTask(message, "1"))
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageStarted> {
it.executionType shouldEqual pipeline.javaClass
it.executionId shouldEqual pipeline.id
it.stageId shouldEqual message.stageId
})
}
}
context("with no tasks") {
and("no after stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = zeroTaskStage.type
}
}
val message = StartStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual RUNNING
it.getStartTime() shouldEqual clock.millis()
})
}
it("immediately completes the stage") {
verify(queue).push(CompleteStage(message, SUCCEEDED))
verifyNoMoreInteractions(queue)
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageStarted> {
it.executionType shouldEqual pipeline.javaClass
it.executionId shouldEqual pipeline.id
it.stageId shouldEqual message.stageId
})
}
}
and("at least one after stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticAfterAndNoTasks.type
}
}
val message = StartStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage status") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual RUNNING
it.getStartTime() shouldEqual clock.millis()
})
}
it("immediately starts the first after stage") {
verify(queue).push(StartStage(pipeline.stageByRef("1>1")))
verifyNoMoreInteractions(queue)
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageStarted> {
it.executionType shouldEqual pipeline.javaClass
it.executionId shouldEqual pipeline.id
it.stageId shouldEqual message.stageId
})
}
}
}
context("with several linear tasks") {
val pipeline = pipeline {
application = "foo"
stage {
type = multiTaskStage.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
action("the handler receives a message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("attaches tasks to the stage") {
verify(repository).storeStage(check {
it.getTasks().size shouldEqual 3
it.getTasks()[0].apply {
id shouldEqual "1"
name shouldEqual "dummy1"
implementingClass shouldEqual DummyTask::class.java.name
isStageStart shouldEqual true
isStageEnd shouldEqual false
}
it.getTasks()[1].apply {
id shouldEqual "2"
name shouldEqual "dummy2"
implementingClass shouldEqual DummyTask::class.java.name
isStageStart shouldEqual false
isStageEnd shouldEqual false
}
it.getTasks()[2].apply {
id shouldEqual "3"
name shouldEqual "dummy3"
implementingClass shouldEqual DummyTask::class.java.name
isStageStart shouldEqual false
isStageEnd shouldEqual true
}
})
}
it("starts the first task") {
verify(queue).push(StartTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
"1"
))
}
}
context("with synthetic stages") {
context("before the main stage") {
val pipeline = pipeline {
application = "foo"
stage {
type = stageWithSyntheticBefore.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
action("the handler receives a message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("attaches the synthetic stage to the pipeline") {
argumentCaptor<Stage<Pipeline>>().apply {
verify(repository, times(2)).addStage(capture())
allValues.map { it.id } shouldEqual listOf("${message.stageId}-1-pre1", "${message.stageId}-2-pre2")
}
}
it("raises an event to indicate the synthetic stage is starting") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.first().id
))
}
}
context("after the main stage") {
val pipeline = pipeline {
application = "foo"
stage {
type = stageWithSyntheticAfter.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("attaches the synthetic stage to the pipeline") {
argumentCaptor<Stage<Pipeline>>().apply {
verify(repository, times(2)).addStage(capture())
allValues.map { it.id } shouldEqual listOf("${message.stageId}-2-post2", "${message.stageId}-1-post1")
}
}
it("raises an event to indicate the first task is starting") {
verify(queue).push(StartTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
"1"
))
}
}
}
context("with other upstream stages that are incomplete") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
status = SUCCEEDED
type = singleTaskStage.type
}
stage {
refId = "2"
status = RUNNING
type = singleTaskStage.type
}
stage {
refId = "3"
requisiteStageRefIds = setOf("1", "2")
type = singleTaskStage.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stageByRef("3").id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("doesn't build its tasks") {
pipeline.stageByRef("3").tasks shouldMatch isEmpty
}
it("waits for the other upstream stage to complete") {
verify(queue, never()).push(isA<StartTask>())
}
it("does not publish an event") {
verifyZeroInteractions(publisher)
}
}
context("with an execution window") {
val pipeline = pipeline {
application = "foo"
stage {
type = stageWithSyntheticBefore.type
context["restrictExecutionDuringTimeWindow"] = true
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("injects a 'wait for execution window' stage before any other synthetic stages") {
argumentCaptor<Stage<Pipeline>>().apply {
verify(repository, times(3)).addStage(capture())
firstValue.type shouldEqual RestrictExecutionDuringTimeWindow.TYPE
firstValue.parentStageId shouldEqual message.stageId
firstValue.syntheticStageOwner shouldEqual STAGE_BEFORE
}
}
it("starts the 'wait for execution window' stage") {
verify(queue).push(check<StartStage> {
it.stageId shouldEqual pipeline.stages.find { it.type == RestrictExecutionDuringTimeWindow.TYPE }!!.id
})
}
}
}
describe("running a branching stage") {
context("when the stage starts") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stageByRef("1").id)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("builds tasks for the main branch") {
val stage = pipeline.stageById(message.stageId)
stage.tasks.map(Task::getName) shouldEqual listOf("post-branch")
}
it("builds synthetic stages for each parallel branch") {
pipeline.stages.size shouldEqual 4
assertThat(
pipeline.stages.map { it.type },
allElements(equalTo(stageWithParallelBranches.type))
)
// TODO: contexts, etc.
}
it("renames the primary branch") {
pipeline.stageByRef("1").name shouldEqual "is parallel"
}
it("renames each parallel branch") {
val stage = pipeline.stageByRef("1")
pipeline.stages.filter { it.parentStageId == stage.id }.map { it.name } shouldEqual listOf("run in us-east-1", "run in us-west-2", "run in eu-west-1")
}
it("runs the parallel stages") {
verify(queue, times(3)).push(check<StartStage> {
pipeline.stageById(it.stageId).parentStageId shouldEqual message.stageId
})
}
}
context("when one branch starts") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildSyntheticStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages[0].id)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("builds tasks for the branch") {
val stage = pipeline.stageById(message.stageId)
assertThat(stage.tasks, !isEmpty)
stage.tasks.map(Task::getName) shouldEqual listOf("in-branch")
}
it("does not build more synthetic stages") {
val stage = pipeline.stageById(message.stageId)
pipeline.stages.map(Stage<Pipeline>::getParentStageId) shouldMatch !hasElement(stage.id)
}
}
}
describe("running a rolling push stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = rollingPushStage.type
}
}
context("when the stage starts") {
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stageByRef("1").id)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("builds tasks for the main branch") {
pipeline.stageById(message.stageId).let { stage ->
stage.tasks.size shouldEqual 5
stage.tasks[0].isLoopStart shouldEqual false
stage.tasks[1].isLoopStart shouldEqual true
stage.tasks[2].isLoopStart shouldEqual false
stage.tasks[3].isLoopStart shouldEqual false
stage.tasks[4].isLoopStart shouldEqual false
stage.tasks[0].isLoopEnd shouldEqual false
stage.tasks[1].isLoopEnd shouldEqual false
stage.tasks[2].isLoopEnd shouldEqual false
stage.tasks[3].isLoopEnd shouldEqual true
stage.tasks[4].isLoopEnd shouldEqual false
}
}
it("runs the parallel stages") {
verify(queue).push(check<StartTask> {
it.taskId shouldEqual "1"
})
}
}
}
describe("running an optional stage") {
context("if the stage should be run") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "true"
)
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("proceeds with the first synthetic stage as normal") {
verify(queue).push(any<StartStage>())
}
}
context("if the stage should be skipped") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "false"
)
}
}
val message = StartStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("skips the stage") {
verify(queue).push(check<CompleteStage> {
it.status shouldEqual SKIPPED
})
}
it("doesn't build any tasks") {
pipeline.stageById(message.stageId).tasks shouldMatch isEmpty
}
it("doesn't build any synthetic stages") {
pipeline.stages.filter { it.parentStageId == message.stageId } shouldMatch isEmpty
}
}
}
describe("invalid commands") {
val message = StartStage(Pipeline::class.java, "1", "foo", "1")
describe("no such execution") {
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doThrow ExecutionNotFoundException("No Pipeline found for ${message.executionId}")
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("emits an error event") {
verify(queue).push(isA<InvalidExecutionId>())
}
}
describe("no such stage") {
val pipeline = pipeline {
id = message.executionId
application = "foo"
}
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("emits an error event") {
verify(queue).push(isA<InvalidStageId>())
}
}
}
})
| apache-2.0 | 4bf522cde87e01a583ad6ab41ff4b9ef | 29.146269 | 158 | 0.614071 | 4.892926 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/PipelineActivityartifacts.kt | 1 | 1143 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param name
* @param propertySize
* @param url
* @param propertyClass
*/
data class PipelineActivityartifacts(
@Schema(example = "null", description = "")
@field:JsonProperty("name") val name: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("size") val propertySize: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("url") val url: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
| mit | 044ad75bb4d7df377d9827ebccdb424a | 28.307692 | 74 | 0.748031 | 4.082143 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/ksp/types.kt | 1 | 1958 | package se.ansman.kotshi.ksp
import com.google.devtools.ksp.getConstructors
import com.google.devtools.ksp.isLocal
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.ksp.TypeParameterResolver
import com.squareup.kotlinpoet.ksp.toTypeParameterResolver
import com.squareup.kotlinpoet.ksp.toTypeVariableName
fun KSClassDeclaration.getAllConstructors(): Sequence<KSFunctionDeclaration> =
(primaryConstructor?.let { sequenceOf(it) } ?: emptySequence()) + getConstructors()
fun KSClassDeclaration.superClass(): KSType? =
superTypes.firstNotNullOfOrNull { superType ->
superType.resolve().takeIf { (it.declaration as? KSClassDeclaration)?.classKind == ClassKind.CLASS }
}
fun KSDeclaration.toTypeParameterResolver(): TypeParameterResolver {
val typeParameters = (this as? KSClassDeclaration)?.typeParameters ?: emptyList()
return typeParameters.toTypeParameterResolver(
parentDeclaration?.toTypeParameterResolver(),
qualifiedName?.asString() ?: "<unknown>"
)
}
internal fun KSClassDeclaration.asTypeName(
typeParameterResolver: TypeParameterResolver = toTypeParameterResolver(),
actualTypeArgs: List<TypeName> = typeParameters.map { it.toTypeVariableName(typeParameterResolver) },
): TypeName {
val className = asClassName()
return if (typeParameters.isNotEmpty()) {
className.parameterizedBy(actualTypeArgs)
} else {
className
}
}
internal fun KSClassDeclaration.asClassName(): ClassName {
require(!isLocal()) {
"Local/anonymous classes are not supported!"
}
val pkgName = packageName.asString()
val typesString = qualifiedName!!.asString().removePrefix("$pkgName.")
val simpleNames = typesString
.split(".")
return ClassName(pkgName, simpleNames)
} | apache-2.0 | da1465fffec059bc07392d79e92ee495 | 37.411765 | 108 | 0.760981 | 5.085714 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/scrapers/tgdb/TGDBScrapper.kt | 1 | 11412 | package com.github.emulio.scrapers.tgdb
import com.github.emulio.exceptions.ScrapperException
import com.github.emulio.scrapers.tgdb.model.*
import khttp.get
import khttp.responses.Response
import mu.KotlinLogging
import org.json.JSONArray
import org.json.JSONObject
import java.nio.charset.Charset
import java.util.*
object TGDBScrapper {
private const val baseUrl = "https://api.thegamesdb.net/v1"
val logger = KotlinLogging.logger { }
fun getGamesUpdates(gameId: Int,
time: Int?,
page: Int): List<Game> {
val params = if (time != null) {
mapOf(
"apikey" to key,
"id" to gameId.toString(),
"time" to time.toString(), // TODO time can be null
"page" to page.toString())
} else {
mapOf(
"apikey" to key,
"id" to gameId.toString(),
"page" to page.toString())
}
return tgdbGet(
url = "$baseUrl/Games/ByGameID",
params = params,
filterName = "games",
converter = ::gameConverter
)
}
fun getGamesImages(gameId: Int,
filter: GameImageFields = GameImageFields(),
page: Int): List<Game> {
return tgdbGet(
url = "$baseUrl/Games/Images",
params = mapOf(
"apikey" to key,
"id" to gameId.toString(),
"filter" to filter.fields(),
"page" to page.toString()),
filterName = "games",
converter = ::gameConverter
)
}
fun getGamesByPlatformID(platformId: Int,
fields: GameFields = GameFields(),
include: GameInclude = GameInclude(),
page: Int = 0): List<Game> {
return tgdbGet(
url = "$baseUrl/Games/ByPlatformID",
params = mapOf(
"apikey" to key,
"id" to platformId.toString(),
"fields" to fields.fields(),
"include" to include.fields(),
"page" to page.toString()),
filterName = "games",
converter = ::gameConverter
)
}
fun getGamesByName(name: String,
fields: GameFields = GameFields(),
include: GameInclude = GameInclude(),
filterPlatformIds: List<Int> = emptyList(),
page: Int): List<Game> {
return tgdbGet(
url = "$baseUrl/Games/ByGameName",
params = mapOf(
"apikey" to key,
"id" to name,
"fields" to fields.fields(),
"include" to include.fields(),
"filter" to filterPlatformIds.joinToString(separator = ","),
"page" to page.toString()),
filterName = "games",
converter = ::gameConverter
)
}
fun getGamesByID(gameId: Int,
fields: GameFields = GameFields(),
include: GameInclude = GameInclude(),
page: Int): List<Game> {
return tgdbGet(
url = "$baseUrl/Games/ByGameID",
params = mapOf(
"apikey" to key,
"id" to gameId.toString(),
"fields" to fields.fields(),
"include" to include.fields(),
"page" to page.toString()),
filterName = "games",
converter = ::gameConverter
)
}
fun getPlatformsImages(platformId: Int,
fields: PlatformImageFields = PlatformImageFields()): List<Platform> {
return tgdbGet(
url = "$baseUrl/Platforms/Images",
params = mapOf(
"apikey" to key,
"platforms_id" to platformId.toString(),
"fields" to fields.fields()),
filterName = "platforms",
converter = ::platformConverter
)
}
fun getPlatformsByName(platformName: String,
fields: PlatformFields = PlatformFields()): List<Platform> {
return tgdbGet(
url = "$baseUrl/Platforms/ByPlatformName",
params = mapOf(
"apikey" to key,
"name" to platformName,
"fields" to fields.fields()),
filterName = "platforms",
converter = ::platformConverter
)
}
fun getPlatformsByID(platformId: Int,
fields: PlatformFields = PlatformFields()): List<Platform> {
return tgdbGet(
url = "$baseUrl/Platforms/ByPlatformID",
params = mapOf(
"apikey" to key,
"id" to platformId.toString(),
"fields" to fields.fields()),
filterName = "platforms",
converter = ::platformConverter
)
}
fun getPlatforms(): List<Platform> {
return tgdbGet(
url = "$baseUrl/Platforms",
filterName = "platforms",
converter = ::platformConverter
)
}
private fun <T> tgdbGet(url: String,
params: Map<String, String> = mapOf("apikey" to key),
converter: (JSONObject) -> T,
filterName: String): List<T> {
return try {
logger.info { "requesting url: $url; $params" }
val response = get(url, params = params)
logger.debug { "url: $url; responseData: ${response.text};"}
val responseJson = response.jsonObject
if (!responseJson.has("data")) {
return emptyList()
}
val data = responseJson["data"] as JSONObject
if (data.getInt("count") == 0) {
return emptyList()
}
val list: List<JSONObject> = when (val jsonData = data[filterName]) {
is JSONArray -> jsonData.toList().map { it as JSONObject }
is JSONObject -> jsonData.keySet().map { jsonData[it] as JSONObject }
else -> throw ScrapperException("unsupported type of object $jsonData")
}
list.map { platform ->
converter(platform)
}
} catch (ex: Exception) {
throw ScrapperException("There was a problem obtaining list", ex)
}
}
fun getGenres(): List<Genre> {
return tgdbGet(
url = "$baseUrl/Genres",
filterName = "genres",
converter = { genre ->
Genre(name = genre.getString("name"),
id = genre.getInt("id"))
}
)
}
fun getDevelopers(): List<Developer> {
return tgdbGet(
url = "$baseUrl/Developers",
filterName = "developers",
converter = { developer ->
Developer(
name = developer.getString("name"),
id = developer.getInt("id")
)
}
)
}
fun getPublishers(): List<Publisher> {
return tgdbGet(
url = "$baseUrl/Publishers",
filterName = "publishers",
converter = { publisher ->
Publisher(
name = publisher.getString("name"),
id = publisher.getInt("id")
)
}
)
}
private fun JSONObject.getNullableInt(key: String): Int? {
return if (this.has(key)) {
if (this[key] != JSONObject.NULL) {
this.getInt(key)
} else {
null
}
} else {
null
}
}
private fun JSONObject.getNullableString(key: String): String? {
return if (this.has(key)) {
if (!this.isNull(key)) {
this.getString(key)
} else {
null
}
} else {
null
}
}
private fun convertPlatforms(response: Response): List<Platform> {
println("jsonObject: ${response.jsonObject}")
val data = response.jsonObject["data"] as JSONObject
if (data.getInt("count") == 0) {
return emptyList()
}
val list: List<JSONObject> = when (val platformsJson = data["platforms"]) {
is JSONArray -> platformsJson.toList().map { it as JSONObject }
is JSONObject -> platformsJson.keySet().map { platformsJson[key] as JSONObject }
else -> throw ScrapperException("platforms is in a unsupported type of object")
}
return list.map(::platformConverter)
}
private fun gameConverter(jsonObject: JSONObject): Game {
return Game(id = jsonObject.getInt("id"))
}
private fun platformConverter(platform: JSONObject): Platform {
return Platform(
name = platform.getString("name"),
alias = platform.getNullableString("alias"),
icon = platform.getNullableString("icon"),
console = platform.getNullableString("console"),
controller = platform.getNullableString("controller"),
developer = platform.getNullableString("developer"),
manufacturer = platform.getNullableString("manufacturer"),
media = platform.getNullableString("media"),
cpu = platform.getNullableString("cpu"),
memory = platform.getNullableString("memory"),
graphics = platform.getNullableString("graphics"),
sound = platform.getNullableString("sound"),
maxcontrollers = platform.getNullableInt("maxcontrollers"),
display = platform.getNullableString("display"),
overview = platform.getNullableString("overview"),
youtube = platform.getNullableString("youtube"),
id = platform.getInt("id"))
}
private val key =
String(Base64.getDecoder().decode("==QZmNWZyIDM1kjMkZzM4IGMzQWYlNzM0UTNiNDZyUjNhVzN2YTMxkDOlhDMhNTM5MGZ1IzYkZWZxMjZmNDN0gDZ".reversed()), Charset.forName("UTF-8"))
}
fun main() {
// println(key)
// println(getPublishers())
// println(getDevelopers())
// println(getGenres())
// println(getPlatforms().map { it.id to it.name })
// println(getPlatformsByID(-1))
// println(getPlatformsByID(4970))
// println(getPlatformsByID(4970, PlatformFields(youtube = true, console = true)))
// println(getPlatformsByID(4971, PlatformFields(icon = true, console = true)))
// println(getPlatformsByName("Nintendo Switch"))
// println(getPlatformsByName("Switch"))
// println(getPlatformsByName("A"))
// println(getPlatformsByName("Takeda"))
println(TGDBScrapper.getPlatforms())
println(TGDBScrapper.getGamesByPlatformID(20, page = 20))
}
| gpl-3.0 | c0b321d24efdadca8e748a9e77801759 | 34.774295 | 175 | 0.503768 | 4.88946 | false | false | false | false |
vmmaldonadoz/android-reddit-example | Reddit/app/src/main/java/com/thirdmono/reddit/domain/utils/CircleTransformation.kt | 1 | 1015 | package com.thirdmono.reddit.domain.utils
import android.graphics.*
import com.squareup.picasso.Transformation
import kotlin.math.min
class CircleTransformation : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squaredBitmap != source) {
source.recycle()
}
val bitmap = Bitmap.createBitmap(size, size, source.config)
val canvas = Canvas(bitmap)
val paint = Paint()
val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val r = size / 2f
canvas.drawCircle(r, r, r, paint)
squaredBitmap.recycle()
return bitmap
}
override fun key(): String {
return "circle"
}
}
| apache-2.0 | 2bcf0083925bcb5fa3257489e1e6a69e | 25.710526 | 94 | 0.627586 | 4.211618 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/CompBookRenderer.kt | 2 | 6598 | package com.cout970.magneticraft.systems.gui.components
import com.cout970.magneticraft.Debug
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.logError
import com.cout970.magneticraft.misc.resource
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.contains
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.gui.render.DrawableBox
import com.cout970.magneticraft.systems.gui.render.IComponent
import com.cout970.magneticraft.systems.gui.render.IGui
import com.cout970.magneticraft.systems.manual.*
import net.minecraft.client.renderer.GlStateManager
import java.util.*
/**
* Created by cout970 on 2017/08/03.
*/
class CompBookRenderer : IComponent {
companion object {
val backgroundTexture = resource("textures/gui/guide/book_alt.png")
val backgroundSize: IVector2 = vec2Of(280, 180)
val scale get() = Config.guideBookScale
var book: Book = loadBook()
var currentSection: String = "index"
var pageIndex = 0
val sectionHistory = ArrayDeque<String>()
val undoHistory = ArrayDeque<String>()
}
override val pos: IVector2 = Vec2d.ZERO
override val size: IVector2 = vec2Of(280, 186) * scale
override lateinit var gui: IGui
// Processed pages to be rendered
var pages: List<Page> = emptyList()
// Offset form the left-top corner
val textOffset get() = vec2Of(14, 14) * scale
// Size of bounding box of the page, text cannot be placed outside this box
val pageSize get() = vec2Of(250 * scale, scale * 148)
override fun init() {
openSection()
}
fun openPage(section: String, page: Int) {
currentSection = section
pageIndex = page
openSection()
}
fun goBack() {
if (sectionHistory.size <= 1) return
undoHistory.push(sectionHistory.pop())
currentSection = sectionHistory.peek()
pageIndex = 0
loadPages()
}
fun goForward() {
if (undoHistory.isEmpty()) return
currentSection = undoHistory.pop()
sectionHistory.push(currentSection)
pageIndex = 0
loadPages()
}
fun openSection() {
sectionHistory.push(currentSection)
undoHistory.clear()
loadPages()
}
fun loadPages() {
val doc = book.sections[currentSection]?.document ?: errorDocument()
pages = MdRenderer.render(doc, pageSize, gui.fontHelper.FONT_HEIGHT, gui.fontHelper::getStringWidth)
}
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
GlStateManager.color(1f, 1f, 1f)
gui.bindTexture(backgroundTexture)
gui.drawTexture(gui.pos, size, Vec2d.ZERO, backgroundSize, vec2Of(512))
if (currentSection != "index") {
renderArrow(Arrow.INDEX, mouse in arrowHitbox(Arrow.INDEX))
}
if (pageIndex >= 1) {
renderArrow(Arrow.LEFT, mouse in arrowHitbox(Arrow.LEFT))
}
if (pageIndex + 1 in pages.indices) {
renderArrow(Arrow.RIGHT, mouse in arrowHitbox(Arrow.RIGHT))
}
if (pageIndex in pages.indices) {
renderPage(pages[pageIndex], mouse, gui.pos + textOffset)
}
}
override fun onMouseClick(mouse: Vec2d, mouseButton: Int): Boolean {
if (pageIndex - 1 in pages.indices && mouse in arrowHitbox(Arrow.LEFT)) {
pageIndex--
return true
}
if (pageIndex + 1 in pages.indices && mouse in arrowHitbox(Arrow.RIGHT)) {
pageIndex++
return true
}
if (currentSection != "index" && mouse in arrowHitbox(Arrow.INDEX)) {
sectionHistory.clear()
openPage("index", 0)
}
if (pageIndex in pages.indices) {
val link = checkLinkClick(pages[pageIndex], mouse, gui.pos + textOffset)
if (link != null) {
if (link.linkSection in book.sections) {
openPage(link.linkSection, link.linkPage)
} else {
logError("Unable to open page: {}", link.linkSection)
}
}
}
return false
}
override fun onKeyTyped(typedChar: Char, keyCode: Int): Boolean {
when (keyCode) {
14 -> goBack()
28 -> goForward()
205 -> if (pageIndex + 1 in pages.indices) pageIndex++ // Right
203 -> if (pageIndex - 1 in pages.indices) pageIndex-- // Left
19 -> {
book = loadBook()
loadPages()
}
else -> return false
}
return true
}
fun checkLinkClick(page: Page, mouse: Vec2d, offset: IVector2): LinkTextBox? {
page.links.forEach {
if (it.contains(mouse, gui, offset)) {
return it
}
}
return null
}
fun renderArrow(it: Arrow, hover: Boolean) {
val uv = if (hover) it.hoverUv to it.uvSize else it.uvPos to it.uvSize
val (pos, size) = arrowHitbox(it)
gui.drawTexture(DrawableBox(pos, size, uv.first, uv.second, vec2Of(512)))
}
fun renderPage(page: Page, mouse: IVector2, pos: IVector2) {
page.text.forEach {
renderTextBox(it, pos, 0x303030)
}
page.links.forEach { link ->
val color = if (link.contains(mouse, gui, pos)) 0x0b99ff else 0x1d3fee
link.words.forEach { renderTextBox(it, pos, color) }
}
}
fun renderTextBox(it: TextBox, pos: IVector2, color: Int) {
gui.drawShadelessString(
text = it.txt,
pos = pos + it.pos,
color = color
)
}
fun arrowHitbox(arrow: Arrow): Pair<IVector2, IVector2> {
val pos = when (arrow) {
Arrow.LEFT -> vec2Of(20 * scale, 178 * scale)
Arrow.RIGHT -> vec2Of(242 * scale, 178 * scale)
Arrow.INDEX -> vec2Of(130 * scale, 178 * scale)
}
return (pos + gui.pos) to (arrow.size * scale)
}
enum class Arrow(val size: IVector2 = vec2Of(18, 26),
val uvSize: IVector2 = vec2Of(18, 26),
val uvPos: IVector2,
val hoverUv: IVector2) {
LEFT(uvPos = vec2Of(40, 180), hoverUv = vec2Of(60, 180)),
RIGHT(uvPos = vec2Of(80, 180), hoverUv = vec2Of(100, 180)),
INDEX(uvPos = vec2Of(0, 180), hoverUv = vec2Of(20, 180));
}
} | gpl-2.0 | ce5f490240b422ec21f06552682eae65 | 31.033981 | 108 | 0.595635 | 4.003641 | false | false | false | false |
owncloud/android | owncloudData/src/androidTest/java/com/owncloud/android/data/authentication/datasources/implementation/OCLocalAuthenticationDataSourceTest.kt | 1 | 17187 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.data.authentication.datasources.implementation
import android.accounts.Account
import android.accounts.AccountManager
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.filters.MediumTest
import androidx.test.platform.app.InstrumentationRegistry
import com.owncloud.android.data.authentication.KEY_CLIENT_REGISTRATION_CLIENT_EXPIRATION_DATE
import com.owncloud.android.data.authentication.KEY_CLIENT_REGISTRATION_CLIENT_ID
import com.owncloud.android.data.authentication.KEY_CLIENT_REGISTRATION_CLIENT_SECRET
import com.owncloud.android.data.authentication.KEY_OAUTH2_REFRESH_TOKEN
import com.owncloud.android.data.authentication.KEY_OAUTH2_SCOPE
import com.owncloud.android.data.authentication.SELECTED_ACCOUNT
import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider
import com.owncloud.android.domain.authentication.oauth.model.ClientRegistrationInfo
import com.owncloud.android.domain.exceptions.AccountNotFoundException
import com.owncloud.android.domain.exceptions.AccountNotNewException
import com.owncloud.android.domain.exceptions.AccountNotTheSameException
import com.owncloud.android.domain.server.model.ServerInfo
import com.owncloud.android.domain.user.model.UserInfo
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.ACCOUNT_VERSION
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_DISPLAY_NAME
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_VERSION
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_SUPPORTS_OAUTH2
import com.owncloud.android.testutil.OC_ACCESS_TOKEN
import com.owncloud.android.testutil.OC_ACCOUNT
import com.owncloud.android.testutil.OC_ACCOUNT_ID
import com.owncloud.android.testutil.OC_ACCOUNT_NAME
import com.owncloud.android.testutil.OC_AUTH_TOKEN_TYPE
import com.owncloud.android.testutil.OC_BASE_URL
import com.owncloud.android.testutil.OC_BASIC_USERNAME
import com.owncloud.android.testutil.OC_OAUTH_SUPPORTED_TRUE
import com.owncloud.android.testutil.OC_REDIRECTION_PATH
import com.owncloud.android.testutil.OC_REFRESH_TOKEN
import com.owncloud.android.testutil.OC_SCOPE
import com.owncloud.android.testutil.OC_SERVER_INFO
import com.owncloud.android.testutil.OC_USER_INFO
import com.owncloud.android.testutil.oauth.OC_CLIENT_REGISTRATION
import io.mockk.every
import io.mockk.mockkClass
import io.mockk.spyk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@MediumTest
class OCLocalAuthenticationDataSourceTest {
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var ocLocalAuthenticationDataSource: OCLocalAuthenticationDataSource
private val accountManager = mockkClass(AccountManager::class)
private val preferencesProvider = spyk<SharedPreferencesProvider>()
@Before
fun init() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
ocLocalAuthenticationDataSource = OCLocalAuthenticationDataSource(
context,
accountManager,
preferencesProvider,
OC_ACCOUNT.type
)
}
@Test
fun addBasicAccountOk() {
mockRegularAccountCreationFlow()
mockSelectedAccountNameInPreferences()
val newAccountName = ocLocalAuthenticationDataSource.addBasicAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
"password",
OC_SERVER_INFO,
OC_USER_INFO,
null
)
val newAccount = Account(OC_ACCOUNT_NAME, "owncloud")
// One for checking if the account exists and another one for getting the new account
verifyAccountsByTypeAreGot(newAccount.type, 2)
verifyAccountIsExplicitlyAdded(newAccount, "password", 1)
verifyAccountInfoIsUpdated(newAccount, OC_SERVER_INFO, OC_USER_INFO, 1)
assertEquals(newAccount.name, newAccountName)
}
@Test(expected = AccountNotNewException::class)
fun addBasicAccountAlreadyExistsNoUpdate() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT) // The account is already there
ocLocalAuthenticationDataSource.addBasicAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
"password",
OC_SERVER_INFO,
OC_USER_INFO.copy(id = OC_ACCOUNT_ID),
null
)
}
@Test
fun addBasicAccountAlreadyExistsUpdateSameUsername() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT) // The account is already there
every {
accountManager.setPassword(any(), any())
} returns Unit
every {
accountManager.setUserData(any(), any(), any())
} returns Unit
mockSelectedAccountNameInPreferences()
ocLocalAuthenticationDataSource.addBasicAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
"password",
OC_SERVER_INFO,
OC_USER_INFO.copy(id = OC_ACCOUNT_ID),
OC_ACCOUNT_NAME
)
// One for getting account to update
verifyAccountsByTypeAreGot(OC_ACCOUNT.type, 1)
// The account already exists so do not create it
verifyAccountIsExplicitlyAdded(OC_ACCOUNT, "password", 0)
// The account already exists, so update it
verifyAccountInfoIsUpdated(OC_ACCOUNT, OC_SERVER_INFO, OC_USER_INFO, 1)
}
@Test
fun addBasicAccountAlreadyExistsUpdateDifferentUsername() {
every {
accountManager.setUserData(any(), any(), any())
} returns Unit
mockSelectedAccountNameInPreferences()
try {
ocLocalAuthenticationDataSource.addBasicAccount(
OC_BASIC_USERNAME,
OC_REDIRECTION_PATH.lastPermanentLocation,
"password",
OC_SERVER_INFO,
OC_USER_INFO,
"NotTheSameAccount"
)
} catch (exception: Exception) {
assertTrue(exception is AccountNotTheSameException)
} finally {
// The account already exists so do not create a new one
verifyAccountIsExplicitlyAdded(OC_ACCOUNT, "password", 0)
// The account is not the same, so no update needed
verifyAccountInfoIsUpdated(OC_ACCOUNT, OC_SERVER_INFO, OC_USER_INFO, 0)
}
}
@Test
fun addOAuthAccountOk() {
mockRegularAccountCreationFlow()
mockSelectedAccountNameInPreferences()
every {
accountManager.setAuthToken(any(), any(), any())
} returns Unit
val newAccountName = ocLocalAuthenticationDataSource.addOAuthAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
OC_AUTH_TOKEN_TYPE,
OC_ACCESS_TOKEN,
OC_SERVER_INFO,
OC_USER_INFO,
OC_REFRESH_TOKEN,
OC_SCOPE,
null,
OC_CLIENT_REGISTRATION
)
val newAccount = Account(OC_ACCOUNT_NAME, "owncloud")
// One for checking if the account exists and another one for getting the new account
verifyAccountsByTypeAreGot(newAccount.type, 2)
verifyAccountIsExplicitlyAdded(newAccount, "", 1)
verifyAccountInfoIsUpdated(newAccount, OC_SERVER_INFO, OC_USER_INFO, 1)
// OAuth params are updated
verifyOAuthParamsAreUpdated(newAccount, OC_ACCESS_TOKEN, OC_OAUTH_SUPPORTED_TRUE, OC_REFRESH_TOKEN, OC_SCOPE, OC_CLIENT_REGISTRATION, 1)
assertEquals(newAccount.name, newAccountName)
}
@Test(expected = AccountNotNewException::class)
fun addOAuthAccountAlreadyExistsNoUpdate() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT) // The account is already there
ocLocalAuthenticationDataSource.addOAuthAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
OC_AUTH_TOKEN_TYPE,
OC_ACCESS_TOKEN,
OC_SERVER_INFO,
OC_USER_INFO.copy(id = OC_ACCOUNT_ID),
OC_REFRESH_TOKEN,
OC_SCOPE,
null,
OC_CLIENT_REGISTRATION
)
}
@Test
fun addOAuthAccountAlreadyExistsUpdateSameUsername() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT) // The account is already there
every {
accountManager.setUserData(any(), any(), any())
} returns Unit
every {
accountManager.setAuthToken(any(), any(), any())
} returns Unit
mockSelectedAccountNameInPreferences()
ocLocalAuthenticationDataSource.addOAuthAccount(
OC_ACCOUNT_ID,
OC_REDIRECTION_PATH.lastPermanentLocation,
OC_AUTH_TOKEN_TYPE,
OC_ACCESS_TOKEN,
OC_SERVER_INFO,
OC_USER_INFO.copy(id = OC_ACCOUNT_ID),
OC_REFRESH_TOKEN,
OC_SCOPE,
OC_ACCOUNT_NAME,
OC_CLIENT_REGISTRATION
)
// One for getting account to update
verifyAccountsByTypeAreGot(OC_ACCOUNT.type, 1)
// The account already exists so do not create it
verifyAccountIsExplicitlyAdded(OC_ACCOUNT, "password", 0)
// The account already exists, so update it
verifyAccountInfoIsUpdated(OC_ACCOUNT, OC_SERVER_INFO, OC_USER_INFO, 1)
verifyOAuthParamsAreUpdated(OC_ACCOUNT, OC_ACCESS_TOKEN, OC_OAUTH_SUPPORTED_TRUE, OC_REFRESH_TOKEN, OC_SCOPE, OC_CLIENT_REGISTRATION, 1)
}
@Test
fun addOAuthAccountAlreadyExistsUpdateDifferentUsername() {
every {
accountManager.setUserData(any(), any(), any())
} returns Unit
every {
accountManager.setAuthToken(any(), any(), any())
} returns Unit
mockSelectedAccountNameInPreferences()
try {
ocLocalAuthenticationDataSource.addOAuthAccount(
OC_BASIC_USERNAME,
OC_REDIRECTION_PATH.lastPermanentLocation,
OC_AUTH_TOKEN_TYPE,
OC_ACCESS_TOKEN,
OC_SERVER_INFO,
OC_USER_INFO,
OC_REFRESH_TOKEN,
OC_SCOPE,
"AccountNotTheSame",
OC_CLIENT_REGISTRATION
)
} catch (exception: Exception) {
assertTrue(exception is AccountNotTheSameException)
} finally {
// The account already exists so do not create it
verifyAccountIsExplicitlyAdded(OC_ACCOUNT, "password", 0)
// The account already exists, so update it
verifyAccountInfoIsUpdated(OC_ACCOUNT, OC_SERVER_INFO, OC_USER_INFO, 0)
verifyOAuthParamsAreUpdated(
OC_ACCOUNT,
OC_ACCESS_TOKEN,
OC_OAUTH_SUPPORTED_TRUE,
OC_REFRESH_TOKEN,
OC_SCOPE,
OC_CLIENT_REGISTRATION,
0
)
}
}
@Test
fun supportsOAuthOk() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT)
every {
accountManager.getUserData(OC_ACCOUNT, KEY_SUPPORTS_OAUTH2)
} returns OC_OAUTH_SUPPORTED_TRUE
val supportsOAuth2 = ocLocalAuthenticationDataSource.supportsOAuth2(OC_ACCOUNT.name)
verifyAccountsByTypeAreGot(OC_ACCOUNT.type, 1)
verifyUserDataIsGot(OC_ACCOUNT, KEY_SUPPORTS_OAUTH2, 1)
assertEquals(true, supportsOAuth2)
}
@Test(expected = AccountNotFoundException::class)
fun supportsOAuthAccountNotFound() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf() // That account does not exist
ocLocalAuthenticationDataSource.supportsOAuth2(OC_ACCOUNT.name)
}
@Test
fun getBaseUrlOk() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf(OC_ACCOUNT)
every {
accountManager.getUserData(OC_ACCOUNT, KEY_OC_BASE_URL)
} returns OC_BASE_URL
val baseUrl = ocLocalAuthenticationDataSource.getBaseUrl(OC_ACCOUNT.name)
verifyAccountsByTypeAreGot(OC_ACCOUNT.type, 1)
verifyUserDataIsGot(OC_ACCOUNT, KEY_OC_BASE_URL, 1)
assertEquals(OC_BASE_URL, baseUrl)
}
@Test(expected = AccountNotFoundException::class)
fun getBaseUrlAccountNotFound() {
every {
accountManager.getAccountsByType(OC_ACCOUNT.type)
} returns arrayOf() // That account does not exist
ocLocalAuthenticationDataSource.getBaseUrl(OC_ACCOUNT.name)
}
private fun mockSelectedAccountNameInPreferences(
selectedAccountName: String = OC_ACCOUNT.name
) {
every {
preferencesProvider.getString(SELECTED_ACCOUNT, any())
} returns selectedAccountName
every {
preferencesProvider.putString(any(), any())
} returns Unit
}
private fun mockRegularAccountCreationFlow() {
// Step 1: Get accounts to know if the current account exists
every {
accountManager.getAccountsByType("owncloud")
} returns arrayOf() // There's no accounts yet
// Step 2: Add new account
every {
accountManager.addAccountExplicitly(any(), any(), any())
} returns true
// Step 3: Update just created account
every {
accountManager.setUserData(any(), any(), any())
} returns Unit
}
private fun verifyAccountsByTypeAreGot(accountType: String, exactly: Int) {
verify(exactly = exactly) {
accountManager.getAccountsByType(accountType)
}
}
private fun verifyAccountIsExplicitlyAdded(
account: Account,
password: String,
exactly: Int
) {
verify(exactly = exactly) {
accountManager.addAccountExplicitly(
account,
password,
null
)
}
}
private fun verifyAccountInfoIsUpdated(
account: Account,
serverInfo: ServerInfo,
userInfo: UserInfo,
exactly: Int
) {
verify(exactly = exactly) {
// The account info is updated
accountManager.setUserData(account, KEY_OC_ACCOUNT_VERSION, ACCOUNT_VERSION.toString())
accountManager.setUserData(account, KEY_OC_VERSION, serverInfo.ownCloudVersion)
accountManager.setUserData(account, KEY_OC_BASE_URL, serverInfo.baseUrl)
accountManager.setUserData(account, KEY_DISPLAY_NAME, userInfo.displayName)
}
}
private fun verifyOAuthParamsAreUpdated(
account: Account,
accessToken: String,
supportsOAuth2: String,
refreshToken: String,
scope: String,
clientInfo: ClientRegistrationInfo,
exactly: Int
) {
verify(exactly = exactly) {
accountManager.setAuthToken(account, OC_AUTH_TOKEN_TYPE, accessToken)
accountManager.setUserData(account, KEY_SUPPORTS_OAUTH2, supportsOAuth2)
accountManager.setUserData(account, KEY_OAUTH2_REFRESH_TOKEN, refreshToken)
accountManager.setUserData(account, KEY_OAUTH2_SCOPE, scope)
accountManager.setUserData(account, KEY_CLIENT_REGISTRATION_CLIENT_SECRET, clientInfo.clientSecret)
accountManager.setUserData(account, KEY_CLIENT_REGISTRATION_CLIENT_ID, clientInfo.clientId)
accountManager.setUserData(account, KEY_CLIENT_REGISTRATION_CLIENT_EXPIRATION_DATE, clientInfo.clientSecretExpiration.toString())
}
}
private fun verifyUserDataIsGot(account: Account, key: String, exactly: Int) {
verify(exactly = exactly) {
accountManager.getUserData(account, key)
}
}
}
| gpl-2.0 | 68d1d6933fe3d5ec11b0d1bccd68d940 | 34.72973 | 144 | 0.666473 | 4.607507 | false | true | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/matrix/Matrix4I.kt | 1 | 6657 | package hr.caellian.math.matrix
import hr.caellian.math.vector.VectorI
import kotlin.math.roundToInt
import kotlin.math.tan
/**
* Utility object containing initializers for basic 4x4 matrices.
* These functions should be used instead of any provided by [MatrixI] wherever possible as they generally perform faster.
*
* @author Caellian
*/
object Matrix4I {
/**
* Initializes perspective transformation matrix.
*
* @param fov field of view.
* @param aspectRatio aspect ration.
* @param clipNear front clipping position.
* @param clipFar back clipping position.
* @return perspective transformation matrix.
*/
@JvmStatic
fun initPerspectiveMatrix(fov: Float, aspectRatio: Float, clipNear: Float, clipFar: Float): MatrixI {
val fowAngle: Float = tan(fov / 2)
val clipRange = clipNear - clipFar
return MatrixI(Array(4) { row ->
Array(4) { column ->
when {
row == 0 && column == 0 -> (1f / (fowAngle * aspectRatio)).roundToInt()
row == 1 && column == 1 -> (1 / fowAngle).roundToInt()
row == 2 && column == 2 -> ((-clipNear - clipFar) / clipRange).roundToInt()
row == 2 && column == 3 -> (2 * clipFar * clipNear / clipRange).roundToInt()
row == 3 && column == 2 -> 1
else -> 0
}
}
})
}
/**
* Initializes orthographic transformation matrix.
*
* @param left left clipping position.
* @param right right clipping position.
* @param bottom bottom clipping position.
* @param top top clipping position.
* @param clipNear front clipping position.
* @param clipFar back clipping position.
* @return orthographic transformation matrix
*/
@JvmStatic
fun initOrthographicMatrix(left: Float, right: Float, bottom: Float, top: Float, clipNear: Float, clipFar: Float): MatrixI {
val width = right - left
val height = top - bottom
val depth = clipFar - clipNear
return MatrixI(Array(4) { row ->
Array(4) { column ->
when {
row == 0 && column == 0 -> (2 / width).roundToInt()
row == 0 && column == 3 -> (-(right + left) / width).roundToInt()
row == 1 && column == 1 -> (2 / height).roundToInt()
row == 1 && column == 3 -> (-(top + bottom) / height).roundToInt()
row == 2 && column == 2 -> (-2 / depth).roundToInt()
row == 2 && column == 3 -> (-(clipFar + clipNear) / depth).roundToInt()
row == 3 && column == 3 -> 1
else -> 0
}
}
})
}
/**
* Initializes rotation matrix using forward and up vector by calculating
* right vector.
*
* @param forward forward 3i vector.
* @param up up 3i vector.
* @return rotation matrix.
*/
@JvmStatic
fun initRotationMatrix(forward: VectorI, up: VectorI): MatrixI {
require(forward.size == 3) { "Invalid forward vector size (${forward.size}), expected size of 3!" }
require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" }
val f = forward.normalized()
val r = up.normalized().cross(f)
val u = f.cross(r)
return Matrix4I.initRotationMatrix(f, u, r)
}
/**
* Initializes rotation matrix using a rotation quaternion.
*
* @param quaternion quaternion to use for initialization.
* @return rotation matrix.
*/
@JvmStatic
fun initRotationMatrix(quaternion: VectorI): MatrixI {
val forward = VectorI(2 * (quaternion[0] * quaternion[2] - quaternion[3] * quaternion[1]),
2 * (quaternion[1] * quaternion[2] + quaternion[3] * quaternion[0]),
1 - 2 * (quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1]))
val up = VectorI(2 * (quaternion[0] * quaternion[1] + quaternion[3] * quaternion[2]),
1 - 2 * (quaternion[0] * quaternion[0] + quaternion[2] * quaternion[2]),
2 * (quaternion[1] * quaternion[2] - quaternion[3] * quaternion[0]))
val right = VectorI(1 - 2 * (quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2]),
2 * (quaternion[0] * quaternion[1] - quaternion[3] * quaternion[2]),
2 * (quaternion[0] * quaternion[2] + quaternion[3] * quaternion[1]))
return Matrix4I.initRotationMatrix(forward, up, right)
}
/**
* Initializes rotation matrix using forward, up and right vector.
*
* @param forward forward 3i vector.
* @param up up 3i vector.
* @param right right 3i vector.
* @return rotation matrix.
*/
@JvmStatic
fun initRotationMatrix(forward: VectorI, up: VectorI, right: VectorI): MatrixI {
require(forward.size == 3) { "Invalid forward vector size (${forward.size}), expected size of 3!" }
require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" }
require(right.size == 3) { "Invalid right vector size (${right.size}), expected size of 3!" }
return MatrixI(Array(4) { row ->
Array(4) { column ->
when {
row == 0 && column != 3 -> right[column]
row == 1 && column != 3 -> up[column]
row == 2 && column != 3 -> forward[column]
row == 3 && column == 3 -> 1
else -> 0
}
}
})
}
/**
* Utility method that combines translation and rotation directly and returns world transformation matrix.
*
* @since 3.0.0
*
* @param eye camera position 3i vector.
* @param center position to look at.
* @param up up 3i vector.
* @return world transformation matrix.
*/
@JvmStatic
fun lookAt(eye: VectorI, center: VectorI, up: VectorI): MatrixI {
require(eye.size == 3) { "Invalid eye position vector size (${eye.size}), expected size of 3!" }
require(center.size == 3) { "Invalid center position vector size (${center.size}), expected size of 3!" }
require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" }
val forward = (eye - center).normalized()
return MatrixI.initTranslationMatrix(eye - center) * initRotationMatrix(forward, up)
}
}
| mit | 4fc07c1504dff9574488a52b18fbebe2 | 40.347826 | 128 | 0.549647 | 4.308738 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/HeadlessWidgetsManager.kt | 1 | 3987 | package app.lawnchair
import android.annotation.SuppressLint
import android.appwidget.AppWidgetHost
import android.appwidget.AppWidgetHostView
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.core.content.edit
import com.android.launcher3.Utilities
import com.android.launcher3.util.MainThreadInitializedObject
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.plus
class HeadlessWidgetsManager(private val context: Context) {
private val scope = MainScope() + CoroutineName("HeadlessWidgetsManager")
private val prefs = Utilities.getDevicePrefs(context)
private val widgetManager = AppWidgetManager.getInstance(context)
private val host = HeadlessAppWidgetHost(context)
private val widgetsMap = mutableMapOf<String, Widget>()
init {
host.startListening()
}
fun getWidget(info: AppWidgetProviderInfo, prefKey: String): Widget {
val widget = widgetsMap.getOrPut(prefKey) { Widget(info, prefKey) }
if (info.provider != widget.info.provider) {
throw IllegalStateException("widget $prefKey was created with a different provider")
}
return widget
}
fun subscribeUpdates(info: AppWidgetProviderInfo, prefKey: String): Flow<AppWidgetHostView> {
val widget = getWidget(info, prefKey)
if (!widget.isBound) {
return emptyFlow()
}
return widget.updates
}
private class HeadlessAppWidgetHost(context: Context) : AppWidgetHost(context, 1028) {
override fun onCreateView(
context: Context,
appWidgetId: Int,
appWidget: AppWidgetProviderInfo?
): AppWidgetHostView {
return HeadlessAppWidgetHostView(context)
}
}
@SuppressLint("ViewConstructor")
private class HeadlessAppWidgetHostView(context: Context) :
AppWidgetHostView(context) {
var updateCallback: ((view: AppWidgetHostView) -> Unit)? = null
override fun updateAppWidget(remoteViews: RemoteViews?) {
super.updateAppWidget(remoteViews)
updateCallback?.invoke(this)
}
}
inner class Widget internal constructor(val info: AppWidgetProviderInfo, private val prefKey: String) {
private var widgetId = prefs.getInt(prefKey, -1)
val isBound: Boolean
get() = widgetManager.getAppWidgetInfo(widgetId)?.provider == info.provider
val updates = callbackFlow {
val view = host.createView(context, widgetId, info) as HeadlessAppWidgetHostView
trySend(view)
view.updateCallback = { trySend(it) }
awaitClose()
}
.onStart { if (!isBound) throw WidgetNotBoundException() }
.shareIn(
scope,
SharingStarted.WhileSubscribed(),
replay = 1
)
init {
bind()
}
fun bind() {
if (!isBound) {
if (widgetId > -1) {
host.deleteAppWidgetId(widgetId)
}
widgetId = host.allocateAppWidgetId()
widgetManager.bindAppWidgetIdIfAllowed(
widgetId, info.profile, info.provider, null)
}
prefs.edit { putInt(prefKey, widgetId) }
}
fun getBindIntent() = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
}
private class WidgetNotBoundException : RuntimeException()
companion object {
val INSTANCE = MainThreadInitializedObject(::HeadlessWidgetsManager)
}
}
| gpl-3.0 | 18fe36b65e668299c63ace0ca7dfebd5 | 32.504202 | 107 | 0.663406 | 5.177922 | false | false | false | false |
Doctoror/FuckOffMusicPlayer | presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/appwidget/SingleRowAppWidgetPresenter.kt | 2 | 4590 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.presentation.appwidget
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.doctoror.fuckoffmusicplayer.R
import com.doctoror.fuckoffmusicplayer.domain.media.AlbumThumbHolder
import com.doctoror.fuckoffmusicplayer.domain.media.CurrentMediaProvider
import com.doctoror.fuckoffmusicplayer.domain.playback.PlaybackState
import com.doctoror.fuckoffmusicplayer.presentation.Henson
import com.doctoror.fuckoffmusicplayer.presentation.home.HomeActivity
import com.doctoror.fuckoffmusicplayer.presentation.playback.PlaybackServiceIntentFactory
class SingleRowAppWidgetPresenter(
private val albumThumbHolder: AlbumThumbHolder,
private val currentMediaProvider: CurrentMediaProvider,
private val viewModel: SingleRowAppWidgetViewModel) {
fun bindState(context: Context, state: PlaybackState) {
bindAppearance(context, state)
bindClickActions(context)
}
private fun bindAppearance(context: Context, state: PlaybackState) {
val media = currentMediaProvider.currentMedia
var artist: CharSequence? = media?.artist
var title: CharSequence? = media?.title
if (TextUtils.isEmpty(artist)) {
artist = context.getText(R.string.Unknown_artist)
}
if (TextUtils.isEmpty(title)) {
title = context.getText(R.string.Untitled)
}
viewModel.artistText = artist
viewModel.titleText = title
viewModel.albumThumb = albumThumbHolder.albumThumb
viewModel.playPauseResId = if (state == PlaybackState.STATE_PLAYING)
R.drawable.ic_pause_white_24dp
else
R.drawable.ic_play_arrow_white_24dp
}
private fun bindClickActions(context: Context) {
val hasMedia = currentMediaProvider.currentMedia != null
if (hasMedia) {
setPlayPauseButtonAction(context)
setPrevButtonAction(context)
setNextButtonAction(context)
} else {
val playAnything = generatePlayAnythingIntent(context)
viewModel.playPauseAction = playAnything
viewModel.prevAction = playAnything
viewModel.nextAction = playAnything
}
setCoverAction(context, hasMedia)
}
private fun setPlayPauseButtonAction(context: Context) {
val intent = PlaybackServiceIntentFactory.intentPlayPause(context)
val action = serviceIntent(context, intent)
viewModel.playPauseAction = action
}
private fun setPrevButtonAction(context: Context) {
val intent = PlaybackServiceIntentFactory.intentPrev(context)
val action = serviceIntent(context, intent)
viewModel.prevAction = action
}
private fun setNextButtonAction(context: Context) {
val intent = PlaybackServiceIntentFactory.intentNext(context)
val action = serviceIntent(context, intent)
viewModel.nextAction = action
}
private fun setCoverAction(context: Context, hasMedia: Boolean) {
val coverIntent = if (hasMedia) {
Henson.with(context)
.gotoNowPlayingActivity()
.hasCoverTransition(true)
.hasListViewTransition(false)
.build()
} else {
Intent(context, HomeActivity::class.java)
}
viewModel.coverAction = PendingIntent.getActivity(
context, 0, coverIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun generatePlayAnythingIntent(context: Context): PendingIntent {
val intent = PlaybackServiceIntentFactory.intentPlayAnything(context)
return serviceIntent(context, intent)
}
private fun serviceIntent(context: Context, intent: Intent): PendingIntent {
return PendingIntent.getService(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
| apache-2.0 | d03dd7a5d5973e72f03a3ea9f935d8ee | 36.622951 | 89 | 0.701743 | 4.946121 | false | false | false | false |
canou/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/helpers/AlphanumericComparator.kt | 1 | 2449 | package com.simplemobiletools.commons.helpers
// taken from https://gist.github.com/MichaelRocks/1b94bb44c7804e999dbf31dac86955ec
// make IMG_5.jpg come before IMG_10.jpg
class AlphanumComparator {
fun compare(string1: String, string2: String): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = string1.length
val s2Length = string2.length
while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(string1, s1Length, thisMarker)
thisMarker += thisChunk.length
val thatChunk = getChunk(string2, s2Length, thatMarker)
thatMarker += thatChunk.length
// If both chunks contain numeric characters, sort them numerically.
var result: Int
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0..thisChunkLength - 1) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) {
return result
}
}
}
} else {
result = thisChunk.compareTo(thatChunk)
}
if (result != 0) {
return result
}
}
return s1Length - s2Length
}
private fun getChunk(string: String, length: Int, marker: Int): String {
var current = marker
val chunk = StringBuilder()
var c = string[current]
chunk.append(c)
current++
if (isDigit(c)) {
while (current < length) {
c = string[current]
if (!isDigit(c)) {
break
}
chunk.append(c)
current++
}
} else {
while (current < length) {
c = string[current]
if (isDigit(c)) {
break
}
chunk.append(c)
current++
}
}
return chunk.toString()
}
private fun isDigit(ch: Char): Boolean {
return ch in '0'..'9'
}
}
| apache-2.0 | 6755a7445ca3fbffcddd43b64716974a | 30.805195 | 83 | 0.485913 | 4.620755 | false | false | false | false |
TheFallOfRapture/Morph | src/main/kotlin/com/morph/engine/newgui/Element.kt | 2 | 1951 | package com.morph.engine.newgui
import com.morph.engine.graphics.components.RenderData
import com.morph.engine.math.Vector2f
import com.morph.engine.physics.components.Transform2D
import com.morph.engine.script.debug.Console
import com.morph.engine.util.State
import com.morph.engine.util.StateMachine
import kotlin.properties.Delegates
/**
* Created by Fernando on 10/12/2016.
*/
abstract class Element(
val name: String,
val transform: Transform2D,
open val renderData: RenderData,
var depth: Int = 0
) {
private val enabled: Boolean = false
private var onIdle: () -> Unit = { Console.out.println("Idle : " + this) }
private var onClick: () -> Unit by Delegates.observable({ Console.out.println("Click : " + this) }) {
_, _, newValue -> state.addTransition("*", "CLICK", newValue)
}
private var onHover: () -> Unit by Delegates.observable({ Console.out.println("Hover : " + this) }) {
_, _, newValue -> state.addTransition("*", "HOVER", newValue)
}
private val state: StateMachine = StateMachine(State("IDLE"))
init {
state.addPossibilities("IDLE", "HOVER", "CLICK")
state.addTransition("*", "IDLE", onIdle)
state.addTransition("*", "HOVER", onHover)
state.addTransition("*", "CLICK", onClick)
transform.init()
renderData.init()
}
operator fun contains(point: Vector2f): Boolean {
val p0 = transform.position - (transform.scale * 0.5f)
val p1 = p0 + (transform.scale)
return (p0.x < point.x
&& point.x < p1.x
&& p0.y < point.y
&& point.y < p1.y)
}
fun onHover(onHover: () -> Unit) {
this.onHover = onHover
}
fun onClick(onClick: () -> Unit) {
this.onClick = onClick
}
fun setState(stateName: String) = state.changeState(stateName)
fun getState(): String = state.currentStateName
}
| mit | 3660cd101e900460f285ee4d16c4b869 | 29.015385 | 105 | 0.619682 | 3.90982 | false | false | false | false |
kvnxiao/kommandant | kommandant-configurable/src/main/kotlin/com/github/kvnxiao/kommandant/configurable/CommandConfig.kt | 2 | 4582 | /*
* Copyright 2017 Ze Hao Xiao
*
* 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.github.kvnxiao.kommandant.configurable
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.afterburner.AfterburnerModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.kvnxiao.kommandant.Kommandant.Companion.LOGGER
import com.github.kvnxiao.kommandant.command.CommandProperties
import com.github.kvnxiao.kommandant.command.ICommand
import java.io.IOException
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Paths
/**
* An object class containing default constants and methods for getting, loading, and saving command configs.
*/
object CommandConfig {
/**
* The default folder location where all command configuration files will be found. Defaults to "kommandant"
*/
@JvmField
var CONFIG_FOLDER = "kommandant"
/**
* Default Jackson object mapper instance for serializing and deserializing JSON
*/
@JvmField
val OBJECT_MAPPER: ObjectMapper = ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT)
.enable(JsonParser.Feature.ALLOW_COMMENTS)
.registerModule(AfterburnerModule())
.registerModule(KotlinModule())
/**
* Default method to get configuration files for a command and all of its subcommands.
*/
@JvmStatic
fun getConfigs(command: ICommand<*>, currentPath: String, configMap: MutableMap<String, ByteArray?> = mutableMapOf()): Map<String, ByteArray?> {
val path = Paths.get("$currentPath/${command.props.uniqueName}.json")
// Read json file as byte array
try {
val file = Files.readAllBytes(path)
configMap.put("$currentPath/${command.props.uniqueName}", file)
} catch (e: NoSuchFileException) {
configMap.put("$currentPath/${command.props.uniqueName}", null)
}
if (command.hasSubcommands()) {
command.subCommands.forEach {
getConfigs(it, "$currentPath/${command.props.uniqueName}", configMap)
}
}
return configMap.toMap()
}
/**
* Default method to load configuration files for a command and all of its subcommands.
*/
@JvmStatic
fun loadConfigs(command: ICommand<*>, currentPath: String, configMap: Map<String, ByteArray?>) {
val path = "$currentPath/${command.props.uniqueName}"
val configByteArr = configMap[path]
if (configByteArr !== null) {
// Read the byte array and set new properties for command
val loadedProps: CommandProperties = OBJECT_MAPPER.readValue(configByteArr)
command.props = loadedProps
}
if (command.hasSubcommands()) {
command.subCommands.forEach {
loadConfigs(it, "$currentPath/${command.props.uniqueName}", configMap)
}
}
}
/**
* Default method to write configuration file sfor a command and all of its subcommands.
*/
@JvmStatic
fun writeConfigs(command: ICommand<*>, currentPath: String) {
val path = Paths.get("$currentPath/${command.props.uniqueName}.json")
val configJson = OBJECT_MAPPER.writeValueAsBytes(command.props)
// Create file and directories if they do not exist
try {
if (Files.notExists(path)) {
Files.createDirectories(path.parent)
Files.createFile(path)
Files.write(path, configJson)
}
} catch (e: IOException) {
LOGGER.error("An IO error occurred in writing configuration files for $path")
}
if (command.hasSubcommands()) {
command.subCommands.forEach {
writeConfigs(it, "$currentPath/${command.props.uniqueName}")
}
}
}
}
| apache-2.0 | e9936a64b37d6b2a7e6d8746b91c243c | 36.252033 | 148 | 0.670231 | 4.704312 | false | true | false | false |
AM5800/polyglot | app/src/main/kotlin/com/am5800/polyglot/app/sentenceGeneration/GeneratorRuleSet.kt | 1 | 2550 | package com.am5800.polyglot.app.sentenceGeneration
enum class Head {
IsLeft,
IsRight
}
interface RuleNode {
fun <TUp, TDown> visit(visitor: GeneratorRuleSetVisitor<TUp, TDown>, data: TDown): TUp
}
class LeafRuleNode(val tag: GeneratorTag) : RuleNode {
override fun <TUp, TDown> visit(visitor: GeneratorRuleSetVisitor<TUp, TDown>, data: TDown): TUp {
return visitor.visitLeaf(this, data)
}
}
class BinaryNode(val left: RuleNode, val right: RuleNode, val format: String, val head: Head) : RuleNode {
override fun <TUp, TDown> visit(visitor: GeneratorRuleSetVisitor<TUp, TDown>, data: TDown): TUp {
return visitor.visitBinaryNode(this, data)
}
}
class GeneratorRuleSet(private val rootNode: RuleNode) {
class RuleSetDefinition {
private class DefinitionNode(val left: GeneratorTag, val right: GeneratorTag, val format: String, val head: Head)
private class Link(val name: String) : GeneratorTag
private val nodes = mutableMapOf<String, DefinitionNode>()
fun rootRule(format: String, left: GeneratorTag, right: GeneratorTag, head: Head) {
nodes.put("S", DefinitionNode(left, right, format, head))
}
fun rootRule(format: String, left: GeneratorTag, right: String, head: Head) {
nodes.put("S", DefinitionNode(left, Link(right), format, head))
}
fun rule(nonTerminalName: String, format: String, left: GeneratorTag, right: GeneratorTag, head: Head) {
nodes.put(nonTerminalName, DefinitionNode(left, right, format, head))
}
private fun buildRecursive(nodeName: String): RuleNode {
val node = nodes[nodeName]!!
nodes.remove(nodeName)
val head = node.left
val dependent = node.right
val headNode = if (head is Link) buildRecursive(head.name) else LeafRuleNode(head)
val dependentNode = if (dependent is Link) buildRecursive(dependent.name) else LeafRuleNode(dependent)
return BinaryNode(headNode, dependentNode, node.format, node.head)
}
fun build(): RuleNode {
val result = buildRecursive("S")
if (!nodes.isEmpty()) throw Exception("Unreachable non terminal(s) found: " + nodes.map { it.key }.joinToString(", "))
return result
}
}
companion object {
fun create(init: RuleSetDefinition.() -> Unit): GeneratorRuleSet {
val definition = RuleSetDefinition()
init(definition)
return GeneratorRuleSet(definition.build())
}
}
fun <TUp, TDown> visit(visitor: GeneratorRuleSetVisitor<TUp, TDown>, data: TDown): TUp {
return rootNode.visit(visitor, data)
}
} | gpl-3.0 | c6868381a5501ab3bd2f9896112a552e | 33.013333 | 124 | 0.700784 | 3.772189 | false | false | false | false |
msebire/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/highlighting.kt | 1 | 3526 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.type
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.util.toArray
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.createSignature
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
fun HighlightSink.highlightUnknownArgs(highlightElement: PsiElement) {
registerProblem(highlightElement, ProblemHighlightType.WEAK_WARNING, message("cannot.infer.argument.types"))
}
fun HighlightSink.highlightCannotApplyError(invokedText: String, typesString: String, highlightElement: PsiElement) {
registerError(highlightElement, message("cannot.apply.method.or.closure", invokedText, typesString))
}
fun HighlightSink.highlightAmbiguousMethod(highlightElement: PsiElement) {
registerError(highlightElement, message("constructor.call.is.ambiguous"))
}
fun HighlightSink.highlightInapplicableMethod(result: GroovyMethodResult,
arguments: List<Argument>,
argumentList: GrArgumentList?,
highlightElement: PsiElement) {
val method = result.element
val containingClass = if (method is GrGdkMethod) method.staticMethod.containingClass else method.containingClass
val argumentString = argumentsString(arguments)
val methodName = method.name
if (containingClass == null) {
highlightCannotApplyError(methodName, argumentString, highlightElement)
return
}
val message: String
if (method is DefaultConstructor) {
message = message("cannot.apply.default.constructor", methodName)
}
else {
val factory = JavaPsiFacade.getElementFactory(method.project)
val containingType = factory.createType(containingClass, result.substitutor)
val canonicalText = containingType.internalCanonicalText
if (method.isConstructor) {
message = message("cannot.apply.constructor", methodName, canonicalText, argumentString)
}
else {
message = message("cannot.apply.method1", methodName, canonicalText, argumentString)
}
}
val fixes = generateCastFixes(result, arguments, argumentList)
registerProblem(highlightElement, ProblemHighlightType.GENERIC_ERROR, message, *fixes)
}
private fun argumentsString(arguments: List<Argument>): String {
return arguments.joinToString(", ", "(", ")") {
it.type?.internalCanonicalText ?: "?"
}
}
private fun generateCastFixes(result: GroovyMethodResult, arguments: Arguments, argumentList: GrArgumentList?): Array<out LocalQuickFix> {
val signature = createSignature(result.element, result.substitutor)
return GroovyTypeCheckVisitorHelper.genCastFixes(signature, arguments.map(Argument::type).toArray(PsiType.EMPTY_ARRAY), argumentList)
}
| apache-2.0 | af4441cd30f6a8044bb2c199f3b7fd75 | 47.30137 | 140 | 0.776234 | 4.810368 | false | false | false | false |
bric3/mockito | subprojects/androidTest/src/test/java/org/mockitousage/androidtest/SharedJUnitTests.kt | 3 | 2464 | package org.mockitousage.androidtest
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
class SharedJUnitTests(
private val mockedViaAnnotationBasicOpenClass: BasicOpenClass,
private val mockedViaAnnotationBasicClosedClass: BasicClosedClass,
private val mockedViaAnnotationBasicInterface: BasicInterface,
)
{
fun mockAndUseBasicOpenClassUsingAnnotatedMock() {
val basicClass = BasicOpenClassReceiver(mockedViaAnnotationBasicOpenClass)
basicClass.callDependencyMethod()
}
fun mockAndUseBasicOpenClassUsingLocalMock() {
val basicOpenClass = mock(BasicOpenClass::class.java)
val basicReceiver = BasicOpenClassReceiver(basicOpenClass)
basicReceiver.callDependencyMethod()
}
fun mockAndUseBasicOpenClassWithVerify() {
val basicClass = BasicOpenClassReceiver(mockedViaAnnotationBasicOpenClass)
basicClass.callDependencyMethod()
verify(mockedViaAnnotationBasicOpenClass).emptyMethod()
}
//Closed class
fun mockAndUseBasicClosedClassUsingAnnotatedMock() {
val basicReceiver = BasicClosedClassReceiver(mockedViaAnnotationBasicClosedClass)
basicReceiver.callDependencyMethod()
}
fun mockAndUseBasicClosedClassUsingLocalMock() {
val basicClosedClass = mock(BasicClosedClass::class.java)
val basicReceiver = BasicClosedClassReceiver(basicClosedClass)
basicReceiver.callDependencyMethod()
}
fun mockAndUseBasicClosedClassWithVerify() {
val basicReceiver = BasicClosedClassReceiver(mockedViaAnnotationBasicClosedClass)
basicReceiver.callDependencyMethod()
verify(mockedViaAnnotationBasicClosedClass).emptyMethod()
}
//Interface
fun mockAndUseBasicInterfaceUsingAnnotatedMock() {
val receiver = BasicInterfaceReceiver(mockedViaAnnotationBasicInterface)
receiver.callInterfaceMethod()
verify(mockedViaAnnotationBasicInterface).interfaceMethod()
}
fun mockAndUseBasicInterfaceUsingLocalMock() {
val basicInterface = mock(BasicInterface::class.java)
val receiver = BasicInterfaceReceiver(basicInterface)
receiver.callInterfaceMethod()
}
fun mockAndUseBasicInterfaceAndVerify() {
val basicInterface = mock(BasicInterface::class.java)
val receiver = BasicInterfaceReceiver(basicInterface)
receiver.callInterfaceMethod()
verify(basicInterface).interfaceMethod()
}
}
| mit | 99aae95c42586c981d24ac7b9c3a0982 | 35.235294 | 89 | 0.761769 | 4.859961 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/scopedstorage/migrateuserdata/UserDataMigrationPreferences.kt | 1 | 3017 | /*
* 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.migrateuserdata
import android.content.SharedPreferences
import com.ichi2.anki.servicelayer.ScopedStorageService.PREF_MIGRATION_DESTINATION
import com.ichi2.anki.servicelayer.ScopedStorageService.PREF_MIGRATION_SOURCE
import java.io.File
/**
* Preferences relating to whether a user data scoped storage migration is taking place
* This refers to the [MigrateUserData] operation of copying media which can take a long time.
*
* @param source The path of the source directory. Check [migrationInProgress] before use.
* @param destination The path of the destination directory. Check [migrationInProgress] before use.
*/
class UserDataMigrationPreferences private constructor(val source: String, val destination: String) {
/** Whether a scoped storage migration is in progress */
val migrationInProgress = source.isNotEmpty()
val sourceFile get() = File(source)
val destinationFile get() = File(destination)
// Throws if migration can't occur as expected.
fun check() {
// ensure that both are set, or both are empty
if (source.isEmpty() != destination.isEmpty()) {
// throw if there's a mismatch + list the key -> value pairs
val message =
"'$PREF_MIGRATION_SOURCE': '$source'; " +
"'$PREF_MIGRATION_DESTINATION': '$destination'"
throw IllegalStateException("Expected either all or no migration directories set. $message")
}
}
companion object {
/**
* @throws IllegalStateException If either [PREF_MIGRATION_SOURCE] or [PREF_MIGRATION_DESTINATION] is set (but not both)
* It is a logic bug if only one is set
*/
fun createInstance(preferences: SharedPreferences): UserDataMigrationPreferences {
fun getValue(key: String) = preferences.getString(key, "")!!
return createInstance(
source = getValue(PREF_MIGRATION_SOURCE),
destination = getValue(PREF_MIGRATION_DESTINATION)
)
}
fun createInstance(source: String, destination: String) = UserDataMigrationPreferences(source, destination).also { it.check() }
}
}
| gpl-3.0 | 7623769859ff0b4ea27901abcf483e2e | 45.415385 | 135 | 0.700696 | 4.634409 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/store/ActivityLogStoreTest.kt | 1 | 20601 | package org.wordpress.android.fluxc.store
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import com.yarolegovich.wellsql.SelectQuery
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.ActivityLogAction
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.generated.ActivityLogActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.activity.ActivityLogModel
import org.wordpress.android.fluxc.model.activity.BackupDownloadStatusModel
import org.wordpress.android.fluxc.model.activity.RewindStatusModel
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient
import org.wordpress.android.fluxc.persistence.ActivityLogSqlUtils
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadResultPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadResultPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindResultPayload
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
@RunWith(MockitoJUnitRunner::class)
class ActivityLogStoreTest {
@Mock private lateinit var activityLogRestClient: ActivityLogRestClient
@Mock private lateinit var activityLogSqlUtils: ActivityLogSqlUtils
@Mock private lateinit var dispatcher: Dispatcher
@Mock private lateinit var siteModel: SiteModel
private lateinit var activityLogStore: ActivityLogStore
@Before
fun setUp() {
activityLogStore = ActivityLogStore(activityLogRestClient, activityLogSqlUtils,
initCoroutineEngine(), dispatcher)
}
@Test
fun onFetchActivityLogFirstPageActionCleanupDbAndCallRestClient() = test {
val payload = FetchActivityLogPayload(siteModel)
whenever(activityLogRestClient.fetchActivity(eq(payload), any(), any())).thenReturn(
FetchedActivityLogPayload(
listOf(),
siteModel,
0,
0,
0
)
)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivity(payload, PAGE_SIZE, OFFSET)
}
@Test
fun onFetchActivityLogNextActionReadCurrentDataAndCallRestClient() = test {
val payload = FetchActivityLogPayload(siteModel, loadMore = true)
whenever(activityLogRestClient.fetchActivity(eq(payload), any(), any())).thenReturn(
FetchedActivityLogPayload(
listOf(),
siteModel,
0,
0,
0
)
)
val existingActivities = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getActivitiesForSite(siteModel, SelectQuery.ORDER_ASCENDING))
.thenReturn(existingActivities)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivity(payload, PAGE_SIZE, existingActivities.size)
}
@Test
fun onFetchRewindStatusActionCallRestClient() = test {
val payload = FetchRewindStatePayload(siteModel)
whenever(activityLogRestClient.fetchActivityRewind(siteModel)).thenReturn(
FetchedRewindStatePayload(
null,
siteModel
)
)
val action = ActivityLogActionBuilder.newFetchRewindStateAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivityRewind(siteModel)
}
@Test
fun onRewindActionCallRestClient() = test {
whenever(activityLogRestClient.rewind(eq(siteModel), any(), anyOrNull())).thenReturn(
RewindResultPayload(
"rewindId",
null,
siteModel
)
)
val rewindId = "rewindId"
val payload = RewindPayload(siteModel, rewindId, null)
val action = ActivityLogActionBuilder.newRewindAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).rewind(siteModel, rewindId)
}
@Test
fun storeFetchedActivityLogToDbAndSetsLoadMoreToFalse() = test {
val rowsAffected = 1
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected)
activityLogStore.onAction(action)
verify(activityLogSqlUtils).insertOrUpdateActivities(siteModel, activityModels)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(rowsAffected,
false,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
verify(activityLogSqlUtils).deleteActivityLog(siteModel)
}
@Test
fun cannotLoadMoreWhenResponseEmpty() = test {
val rowsAffected = 0
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected)
activityLogStore.onAction(action)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(0,
false,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun setsLoadMoreToTrueOnMoreItems() = test {
val rowsAffected = 1
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected, totalItems = 500)
whenever(activityLogSqlUtils.insertOrUpdateActivities(any(), any())).thenReturn(rowsAffected)
activityLogStore.onAction(action)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(rowsAffected,
true,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnActivitiesFromDb() {
val activityModels = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING))
.thenReturn(activityModels)
val activityModelsFromDb = activityLogStore.getActivityLogForSite(
site = siteModel,
ascending = false,
rewindableOnly = false
)
verify(activityLogSqlUtils).getActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING)
assertEquals(activityModels, activityModelsFromDb)
}
@Test
fun returnRewindableOnlyActivitiesFromDb() {
val rewindableActivityModels = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getRewindableActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING))
.thenReturn(rewindableActivityModels)
val activityModelsFromDb = activityLogStore.getActivityLogForSite(
site = siteModel,
ascending = false,
rewindableOnly = true
)
verify(activityLogSqlUtils).getRewindableActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING)
assertEquals(rewindableActivityModels, activityModelsFromDb)
}
@Test
fun storeFetchedRewindStatusToDb() = test {
val rewindStatusModel = mock<RewindStatusModel>()
val payload = FetchedRewindStatePayload(rewindStatusModel, siteModel)
whenever(activityLogRestClient.fetchActivityRewind(siteModel)).thenReturn(payload)
val fetchAction = ActivityLogActionBuilder.newFetchRewindStateAction(FetchRewindStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).replaceRewindStatus(siteModel, rewindStatusModel)
val expectedChangeEvent = ActivityLogStore.OnRewindStatusFetched(ActivityLogAction.FETCH_REWIND_STATE)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnRewindStatusFromDb() {
val rewindStatusModel = mock<RewindStatusModel>()
whenever(activityLogSqlUtils.getRewindStatusForSite(siteModel))
.thenReturn(rewindStatusModel)
val rewindStatusFromDb = activityLogStore.getRewindStatusForSite(siteModel)
verify(activityLogSqlUtils).getRewindStatusForSite(siteModel)
assertEquals(rewindStatusModel, rewindStatusFromDb)
}
@Test
fun emitsRewindResult() = test {
val rewindId = "rewindId"
val restoreId = 10L
val payload = RewindResultPayload(rewindId, restoreId, siteModel)
whenever(activityLogRestClient.rewind(siteModel, rewindId)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newRewindAction(RewindPayload(
siteModel,
rewindId,
null)))
val expectedChangeEvent = ActivityLogStore.OnRewind(rewindId, restoreId, ActivityLogAction.REWIND)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnsActivityLogItemFromDbByRewindId() {
val rewindId = "rewindId"
val activityLogModel = mock<ActivityLogModel>()
whenever(activityLogSqlUtils.getActivityByRewindId(rewindId)).thenReturn(activityLogModel)
val returnedItem = activityLogStore.getActivityLogItemByRewindId(rewindId)
assertEquals(activityLogModel, returnedItem)
verify(activityLogSqlUtils).getActivityByRewindId(rewindId)
}
@Test
fun returnsActivityLogItemFromDbByActivityId() {
val rewindId = "activityId"
val activityLogModel = mock<ActivityLogModel>()
whenever(activityLogSqlUtils.getActivityByActivityId(rewindId)).thenReturn(activityLogModel)
val returnedItem = activityLogStore.getActivityLogItemByActivityId(rewindId)
assertEquals(activityLogModel, returnedItem)
verify(activityLogSqlUtils).getActivityByActivityId(rewindId)
}
@Test
fun onRewindActionWithTypesCallRestClient() = test {
whenever(activityLogRestClient.rewind(eq(siteModel), any(), any())).thenReturn(
RewindResultPayload(
"rewindId",
null,
siteModel
)
)
val rewindId = "rewindId"
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = RewindPayload(siteModel, rewindId, types)
val action = ActivityLogActionBuilder.newRewindAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).rewind(siteModel, rewindId, types)
}
@Test
fun emitsRewindResultWhenSendingTypes() = test {
val rewindId = "rewindId"
val restoreId = 10L
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = RewindResultPayload(rewindId, restoreId, siteModel)
whenever(activityLogRestClient.rewind(siteModel, rewindId, types)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newRewindAction(RewindPayload(siteModel, rewindId, types)))
val expectedChangeEvent = ActivityLogStore.OnRewind(rewindId, restoreId, ActivityLogAction.REWIND)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun onBackupDownloadActionCallRestClient() = test {
whenever(activityLogRestClient.backupDownload(eq(siteModel), any(), any())).thenReturn(
BackupDownloadResultPayload(
"rewindId",
10L,
"backupPoint",
"startedAt",
50,
siteModel
)
)
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val rewindId = "rewindId"
val payload = BackupDownloadPayload(siteModel, rewindId, types)
val action = ActivityLogActionBuilder.newBackupDownloadAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).backupDownload(siteModel, rewindId, types)
}
@Test
fun emitsBackupDownloadResult() = test {
val rewindId = "rewindId"
val downloadId = 10L
val backupPoint = "backup_point"
val startedAt = "started_at"
val progress = 50
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = BackupDownloadResultPayload(
rewindId,
downloadId,
backupPoint,
startedAt,
progress,
siteModel)
whenever(activityLogRestClient.backupDownload(siteModel, rewindId, types)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newBackupDownloadAction(BackupDownloadPayload(
siteModel,
rewindId,
types)))
val expectedChangeEvent = ActivityLogStore.OnBackupDownload(
rewindId,
downloadId,
backupPoint,
startedAt,
progress,
ActivityLogAction.BACKUP_DOWNLOAD)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun onFetchBackupDownloadStatusActionCallRestClient() = test {
val payload = FetchBackupDownloadStatePayload(siteModel)
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel)).thenReturn(
FetchedBackupDownloadStatePayload(
null,
siteModel
)
)
val action = ActivityLogActionBuilder.newFetchBackupDownloadStateAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchBackupDownloadState(siteModel)
}
@Test
fun storeFetchedBackupDownloadStatusToDb() = test {
val backupDownloadStatusModel = mock<BackupDownloadStatusModel>()
val payload = FetchedBackupDownloadStatePayload(backupDownloadStatusModel, siteModel)
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel)).thenReturn(payload)
val fetchAction =
ActivityLogActionBuilder.newFetchBackupDownloadStateAction(FetchBackupDownloadStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).replaceBackupDownloadStatus(siteModel, backupDownloadStatusModel)
val expectedChangeEvent =
ActivityLogStore.OnBackupDownloadStatusFetched(ActivityLogAction.FETCH_BACKUP_DOWNLOAD_STATE)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnBackupDownloadStatusFromDb() {
val backupDownloadStatusModel = mock<BackupDownloadStatusModel>()
whenever(activityLogSqlUtils.getBackupDownloadStatusForSite(siteModel))
.thenReturn(backupDownloadStatusModel)
val backDownloadStatusFromDb = activityLogStore.getBackupDownloadStatusForSite(siteModel)
verify(activityLogSqlUtils).getBackupDownloadStatusForSite(siteModel)
assertEquals(backupDownloadStatusModel, backDownloadStatusFromDb)
}
@Test
fun storeFetchedEmptyRewindStatusRemoveFromDb() = test {
whenever(activityLogRestClient.fetchActivityRewind(siteModel))
.thenReturn(FetchedRewindStatePayload(null, siteModel))
val fetchAction = ActivityLogActionBuilder.newFetchRewindStateAction(FetchRewindStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).deleteRewindStatus(siteModel)
}
@Test
fun storeFetchedEmptyBackupDownloadStatusRemoveFromDb() = test {
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel))
.thenReturn(FetchedBackupDownloadStatePayload(null, siteModel))
val fetchAction =
ActivityLogActionBuilder.newFetchBackupDownloadStateAction(FetchBackupDownloadStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).deleteBackupDownloadStatus(siteModel)
}
@Test
fun onDismissBackupDownloadActionCallRestClient() = test {
whenever(activityLogRestClient.dismissBackupDownload(eq(siteModel), any())).thenReturn(
DismissBackupDownloadResultPayload(
100L,
10L,
true
)
)
val downloadId = 10L
val payload = DismissBackupDownloadPayload(siteModel, downloadId)
val action = ActivityLogActionBuilder.newDismissBackupDownloadAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).dismissBackupDownload(siteModel, downloadId)
}
@Test
fun emitsDismissBackupDownloadResult() = test {
val downloadId = 10L
val isDismissed = true
val payload = DismissBackupDownloadResultPayload(
siteModel.siteId,
downloadId,
isDismissed)
whenever(activityLogRestClient.dismissBackupDownload(siteModel, downloadId)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newDismissBackupDownloadAction(DismissBackupDownloadPayload(
siteModel,
downloadId)))
val expectedChangeEvent = ActivityLogStore.OnDismissBackupDownload(
downloadId,
isDismissed,
ActivityLogAction.DISMISS_BACKUP_DOWNLOAD)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
private suspend fun initRestClient(
activityModels: List<ActivityLogModel>,
rowsAffected: Int,
offset: Int = OFFSET,
number: Int = PAGE_SIZE,
totalItems: Int = PAGE_SIZE
): Action<*> {
val requestPayload = FetchActivityLogPayload(siteModel)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(requestPayload)
val payload = FetchedActivityLogPayload(activityModels, siteModel, totalItems, number, offset)
whenever(activityLogRestClient.fetchActivity(requestPayload, number, offset)).thenReturn(payload)
whenever(activityLogSqlUtils.insertOrUpdateActivities(any(), any())).thenReturn(rowsAffected)
return action
}
companion object {
private const val OFFSET = 0
private const val PAGE_SIZE = 100
}
}
| gpl-2.0 | 0d05171b8740a669fb22fb7595aea9cb | 39.079767 | 119 | 0.688704 | 5.743239 | false | true | false | false |
android/topeka | base/src/main/java/com/google/samples/apps/topeka/adapter/AvatarAdapter.kt | 1 | 1844 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.google.samples.apps.topeka.base.R
import com.google.samples.apps.topeka.model.Avatar
import com.google.samples.apps.topeka.widget.AvatarView
/**
* Adapter to display [Avatar] icons.
*/
class AvatarAdapter(context: Context) : BaseAdapter() {
private val layoutInflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return ((convertView ?:
layoutInflater.inflate(R.layout.item_avatar, parent, false)) as AvatarView)
.also { setAvatar(it, avatars[position]) }
}
private fun setAvatar(view: AvatarView, avatar: Avatar) {
with(view) {
setAvatar(avatar.drawableId)
contentDescription = avatar.nameForAccessibility
}
}
override fun getCount() = avatars.size
override fun getItem(position: Int) = avatars[position]
override fun getItemId(position: Int) = position.toLong()
companion object {
private val avatars = Avatar.values()
}
}
| apache-2.0 | 53e03b7f0f31e574f64c91d8fab90b28 | 30.254237 | 91 | 0.713666 | 4.288372 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/world/WeakWorldReference.kt | 1 | 2759 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.world
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.util.ToStringHelper
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.api.world.Location
import org.lanternpowered.api.world.World
import org.lanternpowered.api.world.WorldManager
import org.lanternpowered.api.world.fix
import org.spongepowered.math.vector.Vector3d
import org.spongepowered.math.vector.Vector3i
import java.lang.ref.WeakReference
import org.spongepowered.api.world.World as SpongeWorld
/**
* Represents a weak reference to a [World].
*/
class WeakWorldReference {
private var reference: WeakReference<World>? = null
/**
* The unique id of the world of this reference.
*/
val key: NamespacedKey
/**
* Creates a new weak world reference.
*
* @param world The world
*/
constructor(world: SpongeWorld<*>) {
world.fix()
this.reference = WeakReference(world)
this.key = world.key
}
/**
* Creates a new weak world reference with the key of the world.
*
* @param key The key
*/
constructor(key: NamespacedKey) {
this.key = key
}
/**
* Gets the world of this reference, this world may be
* `null` if it couldn't be found.
*
* @return The world if present, otherwise `null`
*/
val world: World? get() {
val reference = this.reference
var world = reference?.get()
if (world != null)
return world
world = WorldManager.getWorld(this.key).orNull()
if (world != null) {
this.reference = WeakReference(world)
return world
}
return null
}
fun toLocation(position: Vector3i): Location =
this.world?.let { world -> LanternLocation(world, position) } ?: LanternLocation(this.key, position)
fun toLocation(position: Vector3d): Location =
this.world?.let { world -> LanternLocation(world, position) } ?: LanternLocation(this.key, position)
override fun toString(): String = ToStringHelper(this)
.omitNullValues()
.add("key", this.key)
.toString()
override fun equals(other: Any?): Boolean {
if (other !is WeakWorldReference)
return false
return other.key == this.key
}
override fun hashCode(): Int = this.key.hashCode()
}
| mit | 7e929ba893831a76982add2fee857e32 | 28.351064 | 112 | 0.649873 | 4.167674 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/duchy/deploy/gcloud/spanner/computation/GcpSpannerComputationsDatabaseReaderTest.kt | 1 | 17330 | // 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.duchy.deploy.gcloud.spanner.computation
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import com.google.protobuf.kotlin.toByteStringUtf8
import java.time.Instant
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.wfanet.measurement.duchy.db.computation.ComputationProtocolStageDetails
import org.wfanet.measurement.duchy.db.computation.ComputationProtocolStages
import org.wfanet.measurement.duchy.db.computation.ComputationTypes
import org.wfanet.measurement.duchy.deploy.gcloud.spanner.testing.Schemata
import org.wfanet.measurement.duchy.service.internal.computations.newEmptyOutputBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.newInputBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.newOutputBlobMetadata
import org.wfanet.measurement.duchy.toProtocolStage
import org.wfanet.measurement.gcloud.common.toGcloudTimestamp
import org.wfanet.measurement.gcloud.spanner.testing.UsingSpannerEmulator
import org.wfanet.measurement.internal.duchy.ComputationBlobDependency
import org.wfanet.measurement.internal.duchy.ComputationDetails
import org.wfanet.measurement.internal.duchy.ComputationStage
import org.wfanet.measurement.internal.duchy.ComputationToken
import org.wfanet.measurement.internal.duchy.ComputationTypeEnum.ComputationType
import org.wfanet.measurement.internal.duchy.RequisitionDetails
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig
import org.wfanet.measurement.internal.duchy.externalRequisitionKey
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2.Stage
@RunWith(JUnit4::class)
class GcpSpannerComputationsDatabaseReaderTest :
UsingSpannerEmulator(Schemata.DUCHY_CHANGELOG_PATH) {
companion object {
val DETAILS_WHEN_NON_AGGREGATOR: ComputationDetails =
ComputationDetails.newBuilder()
.apply {
liquidLegionsV2Builder.apply {
role = LiquidLegionsV2SetupConfig.RoleInComputation.NON_AGGREGATOR
}
}
.build()
val DETAILS_WHEN_AGGREGATOR: ComputationDetails =
ComputationDetails.newBuilder()
.apply {
liquidLegionsV2Builder.apply {
role = LiquidLegionsV2SetupConfig.RoleInComputation.AGGREGATOR
addParticipantBuilder().apply { duchyId = "non_aggregator_1" }
addParticipantBuilder().apply { duchyId = "non_aggregator_2" }
addParticipantBuilder().apply { duchyId = "aggregator" }
}
}
.build()
}
private val computationMutations =
ComputationMutations(
ComputationTypes,
ComputationProtocolStages,
ComputationProtocolStageDetails
)
private lateinit var liquidLegionsSketchAggregationSpannerReader:
GcpSpannerComputationsDatabaseReader
@Before
fun initDatabase() {
liquidLegionsSketchAggregationSpannerReader =
GcpSpannerComputationsDatabaseReader(databaseClient, ComputationProtocolStages)
}
@Test
fun `readComputationToken wait_sketches`() = runBlocking {
val globalId = "777"
val localId = 0xABCDEFL
val lastUpdated = Instant.ofEpochMilli(12345678910L)
val computationRow =
computationMutations.insertComputation(
localId = localId,
updateTime = lastUpdated.toGcloudTimestamp(),
globalId = globalId,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
details = DETAILS_WHEN_AGGREGATOR
)
val waitSetupPhaseInputComputationStageRow =
computationMutations.insertComputationStage(
localId = localId,
stage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
nextAttempt = 2,
creationTime = lastUpdated.minusSeconds(2).toGcloudTimestamp(),
endTime = lastUpdated.minusMillis(200).toGcloudTimestamp(),
details =
computationMutations.detailsFor(
Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
DETAILS_WHEN_AGGREGATOR
)
)
val outputBlob1ForWaitSetupPhaseInputComputationStageRow =
computationMutations.insertComputationBlobReference(
localId = localId,
stage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
blobId = 0L,
dependencyType = ComputationBlobDependency.OUTPUT
)
val outputBlob2ForWaitSetupPhaseInputComputationStageRow =
computationMutations.insertComputationBlobReference(
localId = localId,
stage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
blobId = 1L,
dependencyType = ComputationBlobDependency.OUTPUT
)
databaseClient.write(
listOf(
computationRow,
waitSetupPhaseInputComputationStageRow,
outputBlob1ForWaitSetupPhaseInputComputationStageRow,
outputBlob2ForWaitSetupPhaseInputComputationStageRow
)
)
val expectedToken =
ComputationToken.newBuilder()
.apply {
globalComputationId = globalId
localComputationId = localId
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
computationDetails = DETAILS_WHEN_AGGREGATOR
attempt = 1
version = lastUpdated.toEpochMilli()
stageSpecificDetails =
computationMutations.detailsFor(
Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
DETAILS_WHEN_AGGREGATOR
)
addBlobs(newEmptyOutputBlobMetadata(0L))
addBlobs(newEmptyOutputBlobMetadata(1L))
}
.build()
assertThat(liquidLegionsSketchAggregationSpannerReader.readComputationToken(globalId))
.isEqualTo(expectedToken)
}
@Test
fun readComputationToken() = runBlocking {
val globalId = "998877665555"
val localId = 100L
val lastUpdated = Instant.ofEpochMilli(12345678910L)
val requisition1Key = externalRequisitionKey {
externalRequisitionId = "111"
requisitionFingerprint = "A".toByteStringUtf8()
}
val requisition2Key = externalRequisitionKey {
externalRequisitionId = "222"
requisitionFingerprint = "B".toByteStringUtf8()
}
val requisition3Key = externalRequisitionKey {
externalRequisitionId = "333"
requisitionFingerprint = "B".toByteStringUtf8()
}
val computationRow =
computationMutations.insertComputation(
localId = localId,
updateTime = lastUpdated.toGcloudTimestamp(),
globalId = globalId,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
details = DETAILS_WHEN_NON_AGGREGATOR
)
val setupPhaseComputationStageRow =
computationMutations.insertComputationStage(
localId = localId,
stage = Stage.SETUP_PHASE.toProtocolStage(),
nextAttempt = 45,
creationTime = lastUpdated.minusSeconds(2).toGcloudTimestamp(),
endTime = lastUpdated.minusMillis(200).toGcloudTimestamp(),
details =
computationMutations.detailsFor(
Stage.SETUP_PHASE.toProtocolStage(),
DETAILS_WHEN_NON_AGGREGATOR
)
)
val outputBlobForToSetupPhaseComputationStageRow =
computationMutations.insertComputationBlobReference(
localId = localId,
stage = Stage.SETUP_PHASE.toProtocolStage(),
blobId = 0L,
dependencyType = ComputationBlobDependency.OUTPUT,
pathToBlob = "blob-key"
)
val waitExecutionPhaseOneInputStageRow =
computationMutations.insertComputationStage(
localId = localId,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
nextAttempt = 2,
creationTime = lastUpdated.toGcloudTimestamp(),
details =
computationMutations.detailsFor(
Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
DETAILS_WHEN_NON_AGGREGATOR
)
)
val inputBlobForWaitExecutionPhaseOneInputStageRow =
computationMutations.insertComputationBlobReference(
localId = localId,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
blobId = 33L,
dependencyType = ComputationBlobDependency.INPUT,
pathToBlob = "blob-key"
)
val outputBlobForWaitExecutionPhaseOneInputStageRow =
computationMutations.insertComputationBlobReference(
localId = localId,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
blobId = 44L,
dependencyType = ComputationBlobDependency.OUTPUT
)
val fulfilledRequisitionRowOne =
computationMutations.insertRequisition(
localComputationId = localId,
requisitionId = 1L,
externalRequisitionId = requisition1Key.externalRequisitionId,
requisitionFingerprint = requisition1Key.requisitionFingerprint,
pathToBlob = "foo/111"
)
val fulfilledRequisitionRowTwo =
computationMutations.insertRequisition(
localComputationId = localId,
requisitionId = 2L,
externalRequisitionId = requisition2Key.externalRequisitionId,
requisitionFingerprint = requisition3Key.requisitionFingerprint,
pathToBlob = "foo/222"
)
val unfulfilledRequisitionRowOne =
computationMutations.insertRequisition(
localComputationId = localId,
requisitionId = 3L,
externalRequisitionId = requisition3Key.externalRequisitionId,
requisitionFingerprint = requisition3Key.requisitionFingerprint,
)
databaseClient.write(
listOf(
computationRow,
setupPhaseComputationStageRow,
outputBlobForToSetupPhaseComputationStageRow,
waitExecutionPhaseOneInputStageRow,
inputBlobForWaitExecutionPhaseOneInputStageRow,
outputBlobForWaitExecutionPhaseOneInputStageRow,
fulfilledRequisitionRowOne,
fulfilledRequisitionRowTwo,
unfulfilledRequisitionRowOne
)
)
val expectedTokenWhenOutputNotWritten =
ComputationToken.newBuilder()
.apply {
globalComputationId = globalId
localComputationId = localId
computationStage =
ComputationStage.newBuilder()
.setLiquidLegionsSketchAggregationV2(Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS)
.build()
computationDetails = DETAILS_WHEN_NON_AGGREGATOR
attempt = 1
version = lastUpdated.toEpochMilli()
stageSpecificDetails =
computationMutations.detailsFor(
Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
DETAILS_WHEN_NON_AGGREGATOR
)
addBlobs(newInputBlobMetadata(33L, "blob-key"))
addBlobs(newEmptyOutputBlobMetadata(44L))
addRequisitionsBuilder().apply {
externalKey = requisition1Key
path = "foo/111"
details = RequisitionDetails.getDefaultInstance()
}
addRequisitionsBuilder().apply {
externalKey = requisition2Key
path = "foo/222"
details = RequisitionDetails.getDefaultInstance()
}
addRequisitionsBuilder().apply {
externalKey = requisition3Key
path = ""
details = RequisitionDetails.getDefaultInstance()
}
}
.build()
assertThat(liquidLegionsSketchAggregationSpannerReader.readComputationToken(globalId))
.isEqualTo(expectedTokenWhenOutputNotWritten)
assertThat(liquidLegionsSketchAggregationSpannerReader.readComputationToken(requisition1Key))
.isEqualTo(expectedTokenWhenOutputNotWritten)
val writenOutputBlobForWaitExecutionPhaseOneStageRow =
computationMutations.updateComputationBlobReference(
localId = localId,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
blobId = 44L,
pathToBlob = "written-output-key"
)
databaseClient.write(listOf(writenOutputBlobForWaitExecutionPhaseOneStageRow))
assertThat(liquidLegionsSketchAggregationSpannerReader.readComputationToken(globalId))
.isEqualTo(
expectedTokenWhenOutputNotWritten
.toBuilder()
.clearBlobs()
.addBlobs(newInputBlobMetadata(33L, "blob-key"))
.addBlobs(newOutputBlobMetadata(44L, "written-output-key"))
.build()
)
}
@Test
fun `readComputationToken no references`() = runBlocking {
val globalId = "998877665555"
val localId = 100L
val lastUpdated = Instant.ofEpochMilli(12345678910L)
val computationRow =
computationMutations.insertComputation(
localId = localId,
updateTime = lastUpdated.toGcloudTimestamp(),
globalId = globalId,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
details = DETAILS_WHEN_NON_AGGREGATOR
)
val waitExecutionPhaseOneInputRow =
computationMutations.insertComputationStage(
localId = localId,
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
nextAttempt = 2,
creationTime = lastUpdated.toGcloudTimestamp(),
details =
computationMutations.detailsFor(
Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
DETAILS_WHEN_NON_AGGREGATOR
)
)
databaseClient.write(listOf(computationRow, waitExecutionPhaseOneInputRow))
val expectedTokenWhenOutputNotWritten =
ComputationToken.newBuilder()
.apply {
globalComputationId = globalId
localComputationId = localId
computationStage =
ComputationStage.newBuilder()
.setLiquidLegionsSketchAggregationV2(Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS)
.build()
computationDetails = DETAILS_WHEN_NON_AGGREGATOR
attempt = 1
version = lastUpdated.toEpochMilli()
stageSpecificDetails =
computationMutations.detailsFor(
Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage(),
DETAILS_WHEN_NON_AGGREGATOR
)
}
.build()
assertThat(liquidLegionsSketchAggregationSpannerReader.readComputationToken(globalId))
.isEqualTo(expectedTokenWhenOutputNotWritten)
}
@Test
fun `readGlobalComputationIds by stage`() =
runBlocking<Unit> {
val lastUpdatedTimeStamp = Instant.ofEpochMilli(12345678910L).toGcloudTimestamp()
val nonAggregatorSetupPhaseRow =
computationMutations.insertComputation(
localId = 123,
updateTime = lastUpdatedTimeStamp,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.SETUP_PHASE.toProtocolStage(),
globalId = "A",
details = DETAILS_WHEN_NON_AGGREGATOR
)
val nonAggregatorExecutionPhaseOneRow =
computationMutations.insertComputation(
localId = 234,
updateTime = lastUpdatedTimeStamp,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
globalId = "B",
details = DETAILS_WHEN_NON_AGGREGATOR
)
val aggregatorSetupPhaseRow =
computationMutations.insertComputation(
localId = 345,
updateTime = lastUpdatedTimeStamp,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.SETUP_PHASE.toProtocolStage(),
globalId = "C",
details = DETAILS_WHEN_AGGREGATOR
)
val aggregatorCompletedRow =
computationMutations.insertComputation(
localId = 456,
updateTime = lastUpdatedTimeStamp,
protocol = ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
stage = Stage.COMPLETE.toProtocolStage(),
globalId = "D",
details = DETAILS_WHEN_AGGREGATOR
)
databaseClient.write(
listOf(
nonAggregatorSetupPhaseRow,
nonAggregatorExecutionPhaseOneRow,
aggregatorSetupPhaseRow,
aggregatorCompletedRow
)
)
assertThat(
liquidLegionsSketchAggregationSpannerReader.readGlobalComputationIds(
setOf(Stage.SETUP_PHASE.toProtocolStage())
)
)
.containsExactly("A", "C")
}
}
| apache-2.0 | 5ee5f0d2d518c13be826b3442c43fe01 | 38.297052 | 97 | 0.700519 | 4.944365 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/DatabaseInteractor.kt | 1 | 14525 | package com.polito.sismic.Interactors
import android.content.Context
import android.os.Build
import android.os.Environment
import android.support.annotation.RequiresApi
import com.polito.sismic.Domain.Database.*
import com.polito.sismic.Domain.Report
import com.polito.sismic.Domain.ReportDetails
import com.polito.sismic.Domain.ReportItemHistory
import com.polito.sismic.Extensions.*
import com.polito.sismic.Interactors.Helpers.LoginSharedPreferences
import org.jetbrains.anko.db.SqlOrderDirection
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.select
import java.io.File
import java.util.*
import kotlin.collections.HashMap
/**
* Created by Matteo on 13/08/2017.
*/
class DatabaseInteractor(private val reportDatabaseHelper: ReportDatabaseHelper = ReportDatabaseHelper.instance,
private val dataMapper: DatabaseDataMapper = DatabaseDataMapper()) {
//Creates the entry in the db for the current (new) report
fun createReportDetailsForUser(userID: String,
title: String = "",
date: Date = Date()): ReportDetails = reportDatabaseHelper.use {
//so it creates a new valid id
insert(ReportTable.NAME,
ReportTable.USERID to userID,
ReportTable.TITLE to title,
ReportTable.DATE to date.toFormattedString(),
ReportTable.PDF to " ",
ReportTable.COMMITTED to -1)
val reportRequest = "${ReportTable.USERID} = ? AND ${ReportTable.COMMITTED} = ?"
//last invalid inserted value.. its this
val databaseReportDetails = select(ReportTable.NAME)
.whereSimple(reportRequest, userID, "-1")
.orderBy(ReportTable.USERID, SqlOrderDirection.DESC)
.limit(1)
.parseOpt { DatabaseReportDetails(HashMap(it)) }
//returns new entry
databaseReportDetails!!.let { dataMapper.convertReportDetailsToDomain(it) }
}
//read from the db tables into databaseclasses maps that will be converted into domain classes
fun getReportForId(reportID: String, userID: String): Report? = reportDatabaseHelper.use {
val reportDetailRequest = "${ReportTable.USERID} = ? AND ${ReportTable.ID} = ?"
val databaseReportDetails = select(ReportTable.NAME)
.whereSimple(reportDetailRequest, userID, reportID)
.parseOpt { DatabaseReportDetails(HashMap(it)) }
//They have just a unique reference to the report ID
val mediaSectionRequest = "${ReportMediaTable.REPORT_ID} = ?"
val databaseMediaInfo = select(ReportMediaTable.NAME)
.whereSimple(mediaSectionRequest, reportID)
.parseList { DatabaseReportMedia(HashMap(it)) }
val databaseLocalizationInfo = select(LocalizationInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseLocalizationSection(HashMap(it)) }
val databaseCatastoInfo = select(CatastoInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseCatastoSection(HashMap(it)) }
val datiSismoGeneticiInfo = select(DatiSismogeneticiInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseDatiSismogenetici(HashMap(it)) }
val parametriSismiciInfo = select(ParametriSismiciInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseParametriSismici(HashMap(it)) }
val spettriDiProgettoInfo = select(SpettriDiProgettoInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseParametriSpettri(HashMap(it)) }
val caratteristicheGeneraliInfo = select(CaratteristicheGeneraliInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseCaratteristicheGenerali(HashMap(it)) }
val datiStrutturaliInfo = select(DatiStrutturaliInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseDatiStrutturali(HashMap(it)) }
val caratteristichePilastriInfo = select(CaratteristichePilastriInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseCaratteristichePilastri(HashMap(it)) }
val rilieviInfo = select(RilieviInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseRilievi(HashMap(it)) }
val magliaStrutt = select(MagliaStrutturaleInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseMagliaStrutturale(HashMap(it)) }
val results = select(ResultsInfoTable.NAME)
.byReportId(reportID)
.parseOpt { DatabaseResults(HashMap(it)) }
val sectionList = listOf(databaseLocalizationInfo,
databaseCatastoInfo,
datiSismoGeneticiInfo,
parametriSismiciInfo,
spettriDiProgettoInfo,
caratteristicheGeneraliInfo,
datiStrutturaliInfo,
caratteristichePilastriInfo,
rilieviInfo,
magliaStrutt,
results)
databaseReportDetails?.let {
dataMapper.convertReportToDomain(
DatabaseReport(it, databaseMediaInfo, sectionList.filterNotNull())
)
}
}
fun cleanDatabase() = reportDatabaseHelper.use {
clear(ReportTable.NAME)
clear(ReportMediaTable.NAME)
clear(LocalizationInfoTable.NAME)
clear(CatastoInfoTable.NAME)
clear(DatiSismogeneticiInfoTable.NAME)
clear(ParametriSismiciInfoTable.NAME)
clear(SpettriDiProgettoInfoTable.NAME)
clear(CaratteristicheGeneraliInfoTable.NAME)
clear(RilieviInfoTable.NAME)
clear(DatiStrutturaliInfoTable.NAME)
clear(CaratteristichePilastriInfoTable.NAME)
clear(MagliaStrutturaleInfoTable.NAME)
clear(ResultsInfoTable.NAME)
}
//maps domain classes into db classes with map for save into db
fun save(report: Report, editing: Boolean, pdfFileName: String?) = reportDatabaseHelper.use {
//delete if exists (in the case I'm editing I delete the old one)
delete(report.reportDetails, editing)
with(dataMapper.convertReportFromDomain(report, pdfFileName))
{
insert(ReportTable.NAME, *reportDetails.map.toVarargArray())
insertEachSectionIntoCorrectTable(sections)
mediaList.forEach { (map) -> insert(ReportMediaTable.NAME, *map.toVarargArray()) }
}
}
fun delete(reportDetails: ReportDetails, editing: Boolean) {
if (editing)
//Meaning the old one is not valid anymore
delete(reportDetails.id)
else {
//Delete just the uncommitted details
reportDatabaseHelper.use {
delete(ReportTable.NAME, "${ReportTable.ID} = ?", arrayOf(reportDetails.id.toString()))
}
}
}
fun delete(_id: Int) = reportDatabaseHelper.use {
delete(ReportTable.NAME, "${ReportTable.ID} = ?", arrayOf(_id.toString()))
delete(ReportMediaTable.NAME, "${ReportMediaTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(LocalizationInfoTable.NAME, "${LocalizationInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(CatastoInfoTable.NAME, "${CatastoInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(DatiSismogeneticiInfoTable.NAME, "${DatiSismogeneticiInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(ParametriSismiciInfoTable.NAME, "${ParametriSismiciInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(CaratteristicheGeneraliInfoTable.NAME, "${CaratteristicheGeneraliInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(SpettriDiProgettoInfoTable.NAME, "${SpettriDiProgettoInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(DatiStrutturaliInfoTable.NAME, "${DatiStrutturaliInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(RilieviInfoTable.NAME, "${RilieviInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(CaratteristichePilastriInfoTable.NAME, "${CaratteristichePilastriInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(MagliaStrutturaleInfoTable.NAME, "${MagliaStrutturaleInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
delete(ResultsInfoTable.NAME, "${ResultsInfoTable.REPORT_ID} = ?", arrayOf(_id.toString()))
}
//no need for visitor with pattern matching
private fun insertEachSectionIntoCorrectTable(sections: List<DatabaseSection>) = reportDatabaseHelper.use {
sections.forEach { section ->
when (section) {
is DatabaseLocalizationSection -> {
insert(LocalizationInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseCatastoSection -> {
insert(CatastoInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseDatiSismogenetici -> {
insert(DatiSismogeneticiInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseParametriSismici -> {
insert(ParametriSismiciInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseParametriSpettri -> {
insert(SpettriDiProgettoInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseCaratteristicheGenerali -> {
insert(CaratteristicheGeneraliInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseRilievi -> {
insert(RilieviInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseDatiStrutturali -> {
insert(DatiStrutturaliInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseMagliaStrutturale -> {
insert(MagliaStrutturaleInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseCaratteristichePilastri -> {
insert(CaratteristichePilastriInfoTable.NAME, *section.map.toVarargArray())
}
is DatabaseResults -> {
insert(ResultsInfoTable.NAME, *section.map.toVarargArray())
}
}
}
}
//maps to dto for history
fun getDetailsForHistory(userID: String): MutableList<ReportItemHistory> = reportDatabaseHelper.use {
val validReportsDetailsRequest = "${ReportTable.USERID} = ? AND ${ReportTable.COMMITTED} = 1"
val reports = select(ReportTable.NAME)
.whereSimple(validReportsDetailsRequest, userID)
.orderBy(ReportTable.ID)
.parseList { DatabaseReportDetails(HashMap(it)) }
val results = select(ResultsInfoTable.NAME)
.orderBy(ResultsInfoTable.ID)
.parseList { DatabaseResults(HashMap(it)) }
reports.map { dataMapper.convertReportDataForHistory(it, results) }.toMutableList()
}
//deletes invalid report (after crashes for example)
fun deleteNotCommittedReports(context: Context) = reportDatabaseHelper.use {
val invalidReportsDetailsRequest = "${ReportTable.COMMITTED} = -1"
val invalidReportsDetails = select(ReportTable.NAME)
.whereSimple(invalidReportsDetailsRequest)
.parseList { DatabaseReportDetails(HashMap(it)) }
//Delete uncommitted reports
invalidReportsDetails.forEach { delete(it._id) }
val validReportsDetailsRequest = "${ReportTable.COMMITTED} = 1"
val validReportsDetails = select(ReportTable.NAME)
.whereSimple(validReportsDetailsRequest)
.parseList { DatabaseReportDetails(HashMap(it)) }
//gets all valid media and pdf file paths saved into db
val savedFilePaths = mutableListOf<String>()
val pdfSavedFilePaths = mutableListOf<String>()
validReportsDetails.forEach { reports ->
val validReportMediaDetails = select(ReportMediaTable.NAME)
.byReportId(reports._id.toString())
.parseList { DatabaseReportMedia(HashMap(it)) }
pdfSavedFilePaths.add(reports.pdf_uri)
validReportMediaDetails.forEach { media -> savedFilePaths.add(media.filepath) }
}
val storageDirs = listOf(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
context.getExternalFilesDir(Environment.DIRECTORY_MOVIES),
context.getExternalFilesDir(Environment.DIRECTORY_MUSIC))
//Add all valid files read from dirs
val listValidFiles = mutableListOf<File>()
storageDirs.filterNotNull()
.forEach { dir ->
dir.listFiles().filter { file -> file.isFile }
.forEach { file -> listValidFiles.add(file) }
}
//Delete every files that has not been saved into db (checking its name in the saved paths)
listValidFiles
.filter { file ->
!savedFilePaths
.any { it.contains(file.name) }
}
.forEach { invalidFile -> invalidFile.delete() }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
deleteInvalidPdfFiles(context, pdfSavedFilePaths)
}
}
//deletes uncommitted pdf
@RequiresApi(Build.VERSION_CODES.KITKAT)
private fun deleteInvalidPdfFiles(context: Context, pdfValidFilePathsList: List<String>) {
val pdfFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
pdfFilesDir?.let { dir ->
dir.listFiles()
.filter { file -> file.isFile } //all files
.filter { file -> file.extension == "pdf" } //all pdfs
.filter { file ->
!pdfValidFilePathsList.any {
//all pdf of directory documents that are not saved into db list
it.contains(file.name)
}
}
.forEach { file ->
//delete them!
file.delete()
}
}
}
} | mit | c8884301cd8f5e3a13e4b2ff3c8fbdaf | 44.252336 | 131 | 0.625955 | 4.520697 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/utils/AvatarUtils.kt | 1 | 978 | package com.quickblox.sample.conference.kotlin.presentation.utils
import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import androidx.core.content.ContextCompat
import com.quickblox.sample.conference.kotlin.R
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
object AvatarUtils {
private const val RANDOM_COLOR_END_RANGE = 9L
fun getDrawableAvatar(context: Context, colorPosition: Int): Drawable {
val drawable = ContextCompat.getDrawable(context, R.drawable.shape_circle) as GradientDrawable
val colorPosition1 = colorPosition % RANDOM_COLOR_END_RANGE.toInt()
val colorIdName = String.format("randomColor%d", colorPosition1 + 1)
val colorId = context.resources.getIdentifier(colorIdName, "color", context.packageName)
drawable.setColor(ContextCompat.getColor(context, colorId))
return drawable
}
} | bsd-3-clause | e139079a0f9ec95a0998d23ed84247ab | 39.75 | 102 | 0.763562 | 4.361607 | false | false | false | false |
perseacado/aquasketch | aquasketch-frontend/src/main/java/com/github/perseacado/aquasketch/frontend/sketch/Sketch.kt | 1 | 1055 | package com.github.perseacado.aquasketch.frontend.sketch
import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
/**
* @author Marco Eigletsberger, 09.07.16.
*/
@Document
class Sketch {
@Id var id: String? = UUID.randomUUID().toString()
var name: String? = null
@JsonIgnore var userId: String? = null
var activeLayer: Long? = null
var showGrid: Boolean? = true
var layers: MutableList<Layer>? = mutableListOf()
var tools: Tools = Tools()
}
class Layer {
val id: Long? = 0
var name: String? = ""
var visible: Boolean? = true
var lines: MutableList<Line>? = mutableListOf()
var data: MutableList<String>? = mutableListOf()
}
class Line {
var points: MutableList<Array<Int>>? = mutableListOf()
var tools: Tools = Tools()
}
class Tools {
var pen: MutableMap<String, Object> = mutableMapOf()
}
class SketchInfo {
var id: String? = null
var name: String? = null
} | mit | 2dcd14410fc7a9f9fbab5b0a41b1e167 | 24.142857 | 61 | 0.687204 | 3.701754 | false | false | false | false |
jraska/github-client | plugins/src/main/java/com/jraska/github/client/release/data/RetrofitGitHubApi.kt | 1 | 3010 | package com.jraska.github.client.release.data
import com.google.gson.annotations.SerializedName
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
interface RetrofitGitHubApi {
@POST("milestones")
fun createMilestone(@Body dto: MilestoneDto): Call<CreateMilestoneResponseDto>
@PATCH("milestones/{milestoneNumber}")
fun updateMilestone(@Path("milestoneNumber") milestoneNumber: Int, @Body dto: UpdateMilestoneDto): Call<ResponseBody>
@POST("issues/{prNumber}/comments")
fun sendComment(@Path("prNumber") prNumber: Int, @Body commentRequestDto: CommentRequestDto): Call<ResponseBody>
@GET("releases/tags/{tag}")
fun getRelease(@Path("tag") tag: String): Call<ReleaseDto>
@PATCH("releases/{release_id}")
fun setReleaseBody(@Path("release_id") id: Int, @Body releaseBody: ReleaseBodyDto): Call<ResponseBody>
@PATCH("issues/{issue_number}")
fun assignMilestone(@Path("issue_number") prNumber: Int, @Body dto: AssignMilestoneDto): Call<ResponseBody>
@GET("pulls?state=closed&base=master&per_page=100")
fun getPulls(@Query("page") page: Int = 1): Call<List<PullRequestDto>>
@POST("releases")
fun createRelease(@Body dto: CreateReleaseDto): Call<ResponseBody>
@GET("pulls/{pr_number}/commits")
fun commits(@Path("pr_number") prNumber: Int): Call<List<CommitItemDto>>
}
class PullRequestDto {
@SerializedName("number")
var number: Int = 0
@SerializedName("title")
var title: String = ""
@SerializedName("milestone")
var milestone: MilestoneDto? = null
@SerializedName("merged_at")
var mergedAt: String? = null
}
class ReleaseBodyDto(
@SerializedName("body")
val body: String
)
class ReleaseDto {
@SerializedName("id")
var id: Int = 0
}
class CreateReleaseDto(
@SerializedName("tag_name")
val tagName: String,
@SerializedName("target_commitish")
val targetCommitish: String = "master",
@SerializedName("name")
val name: String = tagName
)
class AssignMilestoneDto(
@SerializedName("milestone")
val milestoneNumber: Int
)
class MilestoneDto(
@SerializedName("title")
val title: String,
@SerializedName("state")
val state: String = "closed"
)
class UpdateMilestoneDto(
@SerializedName("description")
val body: String,
)
class CreateMilestoneResponseDto {
@SerializedName("number")
var number: Int = 0
}
class CommentRequestDto(val body: String)
class CommitItemDto {
@SerializedName("sha")
lateinit var sha: String
@SerializedName("commit")
lateinit var commit: CommitDto
@SerializedName("author")
lateinit var author: UserDto
}
class CommitDto {
@SerializedName("author")
lateinit var author: AuthorDto
@SerializedName("message")
lateinit var message: String
}
class AuthorDto {
@SerializedName("date")
lateinit var dateString: String
}
class UserDto {
@SerializedName("login")
lateinit var login: String
}
| apache-2.0 | 94b72b577f356346d74b7dae5b4d6a69 | 22.333333 | 119 | 0.737874 | 3.819797 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/utils/extensions/CommandClientBuilder.kt | 1 | 1586 | package gg.octave.bot.utils.extensions
import me.devoxin.flight.api.CommandClientBuilder
import me.devoxin.flight.api.entities.Invite
import me.devoxin.flight.internal.parsers.*
fun CommandClientBuilder.registerAlmostAllParsers(): CommandClientBuilder {
val booleanParser = BooleanParser()
addCustomParser(Boolean::class.java, booleanParser)
addCustomParser(java.lang.Boolean::class.java, booleanParser)
val doubleParser = DoubleParser()
addCustomParser(Double::class.java, doubleParser)
addCustomParser(java.lang.Double::class.java, doubleParser)
val floatParser = FloatParser()
addCustomParser(Float::class.java, floatParser)
addCustomParser(java.lang.Float::class.java, floatParser)
val intParser = IntParser()
addCustomParser(Int::class.java, intParser)
addCustomParser(java.lang.Integer::class.java, intParser)
val longParser = LongParser()
addCustomParser(Long::class.java, longParser)
addCustomParser(java.lang.Long::class.java, longParser)
// JDA entities
val inviteParser = InviteParser()
addCustomParser(Invite::class.java, inviteParser)
addCustomParser(net.dv8tion.jda.api.entities.Invite::class.java, inviteParser)
//addCustomParser(MemberParser())
addCustomParser(UserParser())
addCustomParser(RoleParser())
addCustomParser(TextChannelParser())
addCustomParser(VoiceChannelParser())
// Custom entities
addCustomParser(EmojiParser())
addCustomParser(StringParser())
addCustomParser(SnowflakeParser())
addCustomParser(UrlParser())
return this
}
| mit | b38873674a4268bda2c936d06b02c09c | 33.478261 | 82 | 0.760404 | 4.229333 | false | false | false | false |
general-mobile/kotlin-architecture-components-notes-demo | app/src/main/kotlin/com/generalmobile/app/gmnotes/ui/main/NoteAdapter.kt | 1 | 1339 | package com.generalmobile.app.gmnotes.ui.main
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.generalmobile.app.gmnotes.Application
import com.generalmobile.app.gmnotes.R
import com.generalmobile.app.gmnotes.databinding.ItemNoteBinding
import com.generalmobile.app.gmnotes.db.entities.Note
class NoteAdapter(private var noteList: List<Note>, var application: Application) : RecyclerView.Adapter<NoteAdapter.ViewHolder>() {
override fun getItemCount() = noteList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.binding.viewModel.note = noteList[position]
holder.binding.executePendingBindings()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val postBinding = DataBindingUtil.inflate<ItemNoteBinding>(LayoutInflater.from(parent.context), R.layout.item_note, parent, false)
val viewModel = NoteAdapterViewModel(application)
postBinding.viewModel = viewModel
return ViewHolder(postBinding)
}
fun addItems(notes: List<Note>) {
noteList = notes
notifyDataSetChanged()
}
class ViewHolder(var binding: ItemNoteBinding) : RecyclerView.ViewHolder(binding.root)
} | mit | 1c16c32c6272d0869f9b557311bf3e1d | 38.411765 | 138 | 0.769231 | 4.419142 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/fragment/BoardItemListFragment.kt | 1 | 33451 | package com.emogoth.android.phone.mimi.fragment
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.webkit.WebView
import android.widget.*
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.emogoth.android.phone.mimi.BuildConfig
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.activity.MimiActivity
import com.emogoth.android.phone.mimi.adapter.BoardListAdapter
import com.emogoth.android.phone.mimi.adapter.BoardListAdapter.OnBoardClickListener
import com.emogoth.android.phone.mimi.app.MimiApplication
import com.emogoth.android.phone.mimi.db.ArchivedPostTableConnection
import com.emogoth.android.phone.mimi.db.BoardTableConnection.convertBoardDbModelsToChanBoards
import com.emogoth.android.phone.mimi.db.BoardTableConnection.fetchBoard
import com.emogoth.android.phone.mimi.db.BoardTableConnection.fetchBoards
import com.emogoth.android.phone.mimi.db.BoardTableConnection.incrementAccessCount
import com.emogoth.android.phone.mimi.db.BoardTableConnection.observeBoards
import com.emogoth.android.phone.mimi.db.BoardTableConnection.saveBoards
import com.emogoth.android.phone.mimi.db.BoardTableConnection.setBoardVisibility
import com.emogoth.android.phone.mimi.db.DatabaseUtils.applySchedulers
import com.emogoth.android.phone.mimi.db.DatabaseUtils.applySingleSchedulers
import com.emogoth.android.phone.mimi.db.MimiDatabase.Companion.getInstance
import com.emogoth.android.phone.mimi.db.PostTableConnection
import com.emogoth.android.phone.mimi.db.models.Board
import com.emogoth.android.phone.mimi.fourchan.FourChanConnector
import com.emogoth.android.phone.mimi.interfaces.BoardItemClickListener
import com.emogoth.android.phone.mimi.interfaces.ContentInterface
import com.emogoth.android.phone.mimi.interfaces.IToolbarContainer
import com.emogoth.android.phone.mimi.interfaces.TabInterface
import com.emogoth.android.phone.mimi.util.*
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.mimireader.chanlib.ChanConnector
import com.mimireader.chanlib.models.ChanBoard
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import java.util.*
/**
* A list fragment representing a list of PostItems. This fragment
* also supports tablet devices by allowing list items to be given an
* 'activated' state upon selection. This helps indicate which item is
* currently being viewed in a [ThreadPagerFragment].
*
*
* Activities containing this fragment MUST implement the [com.emogoth.android.phone.mimi.interfaces.BoardItemClickListener]
* interface.
*/
class BoardItemListFragment
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
: MimiFragmentBase(), OnBoardClickListener, TabInterface, ContentInterface {
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private var mCallbacks: BoardItemClickListener? = null
private var activateOnItemClick = false
/**
* The current activated item position. Only used on tablets.
*/
private val mActivatedPosition = ListView.INVALID_POSITION
private var boardsList: RecyclerView? = null
private var boardListAdapter: BoardListAdapter? = null
private var rootView: View? = null
private var boardOrderContainer: ViewGroup? = null
private var showContentButton: TextView? = null
private var boardOrderText: TextView? = null
private var orderTypeList: ViewGroup? = null
private var orderByFavorites: TextView? = null
private var orderByName: TextView? = null
private var orderByTitle: TextView? = null
private var orderByAccess: TextView? = null
private var orderByLast: TextView? = null
private var orderByPost: TextView? = null
private var orderbyCustom: TextView? = null
private var boardOrderBackground: ViewGroup? = null
private var toolbarSpinner: Spinner? = null
private var errorView: View? = null
private var errorSwitcher: BetterViewAnimator? = null
private var revealListAnimation: Animation? = null
private var showBoardOrderBackground: Animation? = null
private var hideListAnimation: Animation? = null
private var hideBoardOrderBackground: Animation? = null
private var orderByNames: Array<String> = arrayOf("")
private var boardOrderListVisible = false
private var editMode = false
private var toolbar: Toolbar? = null
private var chanConnector: ChanConnector? = null
private var itemTouchHelper: ItemTouchHelper? = null
private var actionModeCallback: ActionMode.Callback? = null
private var boardInfoSubscription: Disposable? = null
private var fetchBoardsSubscription: Disposable? = null
private var watchDatabaseSubscription: Disposable? = null
private var boardFetchDisposable: Disposable? = null
private var initDatabaseDisposable: Disposable? = null
private var manageBoardsMenuItem: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = false
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val userAgent = PreferenceManager.getDefaultSharedPreferences(activity).getString(getString(R.string.user_agent_pref), null)
if (userAgent != null) {
RequestQueueUtil.getInstance().userAgent = userAgent
} else {
try {
val webView = WebView(activity as Context)
val webViewAgent = webView.settings.userAgentString
PreferenceManager.getDefaultSharedPreferences(activity).edit().putString(getString(R.string.user_agent_pref), webViewAgent).apply()
webView.destroy()
} catch (e: Exception) {
Log.e(LOG_TAG, "Caught exception", e)
if (PreferenceManager.getDefaultSharedPreferences(activity).getString(getString(R.string.user_agent_pref), null) == null) {
val defaultAgent = System.getProperty("http.agent")
PreferenceManager.getDefaultSharedPreferences(activity).edit().putString(getString(R.string.user_agent_pref), defaultAgent).apply()
}
}
}
if (activity is MimiActivity) {
toolbar = (activity as MimiActivity).toolbar
}
rootView = inflater.inflate(R.layout.fragment_boards_list, container, false)
errorSwitcher = rootView?.findViewById(R.id.error_switcher)
boardListAdapter = BoardListAdapter(activity as Context, ArrayList())
val layoutManager = LinearLayoutManager(activity)
boardsList = rootView?.findViewById(R.id.boards_list)
boardsList?.addItemDecoration(DividerItemDecoration(boardsList?.context, RecyclerView.VERTICAL))
boardsList?.layoutManager = layoutManager
boardsList?.adapter = boardListAdapter
boardListAdapter?.setDragListener(object : BoardListAdapter.OnStartDragListener {
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder?) {
if (viewHolder != null) {
itemTouchHelper?.startDrag(viewHolder)
}
}
})
boardListAdapter?.itemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
if (activity != null) {
activity?.startActionMode(actionMode)
}
true
}
return rootView
}
private val actionMode: ActionMode.Callback
get() {
editMode = true
boardListAdapter?.editMode(true)
if (actionModeCallback == null) {
val callback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
if (activity !is MimiActivity) {
return false
}
val act = activity as MimiActivity
val inflater = mode.menuInflater
inflater.inflate(R.menu.edit_boards, menu)
if (act.drawerLayout != null) {
act.drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
toolbar?.visibility = View.GONE
boardOrderContainer?.visibility = View.GONE
boardsList?.isClickable = false
boardListAdapter?.boardClickListener = null
mode.setTitle(R.string.manage_boards)
return act.onCreateActionMode(mode, menu)
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (item.itemId == R.id.add_board) {
showAddBoardDialog()
}
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
if (activity == null || activity !is MimiActivity) {
return
}
val act = activity as MimiActivity
editMode = false
act.drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
toolbar?.visibility = View.VISIBLE
boardListAdapter?.editMode(false)
boardsList?.isClickable = true
boardListAdapter?.boardClickListener = this@BoardItemListFragment
boardOrderContainer?.visibility = View.VISIBLE
val order = MimiUtil.getBoardOrder()
if (boardOrderText != null) {
val bo = boardOrderText as TextView
bo.text = orderByNames[order]
}
act.onDestroyActionMode(mode)
}
}
actionModeCallback = callback
return callback
} else {
return actionModeCallback as ActionMode.Callback
}
}
private fun showAddBoardDialog() {
if (activity == null) {
return
}
val alertBuilder = MaterialAlertDialogBuilder(activity as Context)
val input = EditText(activity)
input.setHint(R.string.board_name_input_hint)
input.setSingleLine()
input.imeOptions = EditorInfo.IME_ACTION_DONE
alertBuilder.setView(input)
alertBuilder.setPositiveButton(R.string.add) { _: DialogInterface?, _: Int -> addBoard(input.text.toString()) }
alertBuilder.setTitle(R.string.add_board)
val d = alertBuilder.create()
d.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
d.show()
input.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
addBoard(input.text.toString())
d.dismiss()
}
true
}
}
private fun addBoard(rawBoardName: String) {
if (TextUtils.isEmpty(rawBoardName)) {
return
}
if (errorSwitcher != null) {
val switcher = errorSwitcher as BetterViewAnimator
switcher.displayedChildId = boardsList?.id ?: 0
}
RxUtil.safeUnsubscribe(boardInfoSubscription)
val boardName = rawBoardName.replace("/".toRegex(), "").toLowerCase().trim { it <= ' ' }
boardInfoSubscription = fetchBoard(boardName)
.flatMap { chanBoard: ChanBoard -> setBoardVisibility(chanBoard, true) }
.flatMap { _ ->
val orderId = MimiUtil.getBoardOrder()
fetchBoards(orderId)
}
.flatMap { boards: List<Board> -> Single.just(convertBoardDbModelsToChanBoards(boards)) }
.onErrorReturn { Collections.emptyList() }
.compose(applySingleSchedulers())
.subscribe { boards: List<ChanBoard> ->
if (boards.isNotEmpty()) {
boardListAdapter?.boards = ArrayList(boards)
if (manageBoardsMenuItem != null) {
manageBoardsMenuItem?.isEnabled = true
}
} else {
showError()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (activity == null) {
return
}
setupHeader(view)
if (userVisibleHint) {
initMenu()
}
setupTouchListeners()
val preferences = PreferenceManager.getDefaultSharedPreferences(activity)
val lastVersion = preferences.getInt(getString(R.string.last_version_code_pref), 0)
if (BuildConfig.VERSION_CODE > lastVersion) {
showChangeLog()
// TODO: Remove the removeAllThreads() calls
Single.defer {
val timer = System.currentTimeMillis()
Log.d(LOG_TAG, "Starting clearing cache...")
MimiUtil.deleteRecursive(activity?.cacheDir, true)
Log.d(LOG_TAG, "Cache cleared in " + (System.currentTimeMillis() - timer) + " ms")
Single.just(true)
}
.flatMap { PostTableConnection.removeAllThreads() }
.flatMap { ArchivedPostTableConnection.removeAllThreads() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn { throwable: Throwable ->
Log.e(LOG_TAG, "Cache could not be cleared on app upgrade", throwable)
false
}
.subscribe()
preferences.edit().putInt(getString(R.string.last_version_code_pref), BuildConfig.VERSION_CODE).apply()
}
chanConnector = FourChanConnector.Builder()
.setCacheDirectory(MimiUtil.getInstance().cacheDir)
.setEndpoint(FourChanConnector.getDefaultEndpoint())
.setClient(HttpClientFactory.getInstance().client)
.setPostEndpoint(FourChanConnector.getDefaultPostEndpoint())
.build<ChanConnector>()
boardListAdapter?.boardClickListener = this
initDatabase()
getInstance()?.boards()?.getVisibleBoards()?.subscribe(object : Subscriber<List<Board>> {
override fun onSubscribe(s: Subscription) {}
override fun onNext(boards: List<Board>) {
for ((_, _, name) in boards) {
Log.d(LOG_TAG, "Board: $name")
}
}
override fun onError(t: Throwable) {
Log.e(LOG_TAG, "Error fetching boards using Room", t)
}
override fun onComplete() {
Log.d(LOG_TAG, "Finished fetching boards")
}
})
}
private fun initDatabase() {
if (chanConnector == null) {
return
}
val connector = chanConnector as ChanConnector
RxUtil.safeUnsubscribe(initDatabaseDisposable)
initDatabaseDisposable = fetchBoards(MimiUtil.getBoardOrder())
.map { b: List<Board> -> convertBoardDbModelsToChanBoards(b) }
.flatMap {
if (it.isEmpty()) {
Log.d(LOG_TAG, "Fetching all boards for debug version")
connector.fetchBoards()
.observeOn(Schedulers.io())
.doOnSuccess(saveBoards())
.toFlowable()
.flatMapIterable { list -> list }
.doOnNext { chanBoard: ChanBoard -> Log.d(LOG_TAG, "Setting visibility for " + chanBoard.title) }
.flatMap { chanBoard: ChanBoard -> setBoardVisibility(chanBoard, if (BuildConfig.SHOW_ALL_BOARDS) true else isDefaultBoard(chanBoard.name)).toFlowable() }
.toList()
} else {
Single.just(it)
}
}
.compose(applySingleSchedulers())
.subscribe({ chanBoards: List<ChanBoard> ->
Log.d(LOG_TAG, "Fetching boards was a success; starting database watch: boards=" + chanBoards.size)
watchDatabase()
if (chanBoards.isNotEmpty()) {
loadBoards()
} else {
showError()
}
}) { throwable: Throwable? ->
Log.e(LOG_TAG, "Error while initializing database with boards", throwable)
watchDatabase()
showError()
}
}
private fun isDefaultBoard(boardName: String): Boolean {
val boards = MimiApplication.instance.resources.getStringArray(R.array.boards)
for (board in boards) {
if (board == boardName) {
return true
}
}
return false
}
private fun loadBoards() {
if (chanConnector == null) {
return
}
val connector = chanConnector as ChanConnector
RxUtil.safeUnsubscribe(boardFetchDisposable)
boardFetchDisposable = connector.fetchBoards()
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn { throwable: Throwable? ->
Log.e(LOG_TAG, "Error while fetching list of boards from the network", throwable)
showError()
emptyList()
}
.observeOn(Schedulers.io())
.doOnSuccess(saveBoards())
.compose(applySingleSchedulers())
.subscribe()
}
private fun watchDatabase() {
errorSwitcher?.displayedChildId = boardsList?.id ?: 0
RxUtil.safeUnsubscribe(watchDatabaseSubscription)
watchDatabaseSubscription = observeBoards(MimiUtil.getBoardOrder())
.first(emptyList())
.compose(applySingleSchedulers())
.subscribe { chanBoards: List<ChanBoard> ->
if (chanBoards.isEmpty() || TextUtils.isEmpty(chanBoards[0].title)) {
return@subscribe
}
if (manageBoardsMenuItem != null) {
manageBoardsMenuItem?.isEnabled = true
}
if (boardsList != null) {
boardOrderContainer?.visibility = View.VISIBLE
boardListAdapter?.boards = ArrayList(chanBoards)
errorSwitcher?.displayedChildId = boardsList?.id ?: 0
}
}
}
private fun showError() {
if (manageBoardsMenuItem != null) {
manageBoardsMenuItem?.isEnabled = false
}
if (errorView != null) {
errorSwitcher?.displayedChildId = errorView?.id ?: 0
return
}
val errorStub = rootView?.findViewById<ViewStub>(R.id.error_container)
errorStub?.setOnInflateListener { _: ViewStub?, view: View ->
view.findViewById<View>(R.id.retry_button).setOnClickListener { loadBoards() }
errorSwitcher?.displayedChildId = view.id
errorView = view
}
errorStub?.inflate()
}
private fun setupTouchListeners() {
val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
var mCurrentTarget: RecyclerView.ViewHolder? = null
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
if (boardListAdapter?.IsEditMode() == true) {
mCurrentTarget = target
boardListAdapter?.onItemMove(viewHolder.absoluteAdapterPosition, target.absoluteAdapterPosition)
return true
}
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
boardListAdapter?.onDismiss(viewHolder.absoluteAdapterPosition)
}
override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return if (boardListAdapter?.IsEditMode() == true) super.getSwipeDirs(recyclerView, viewHolder) else 0
}
override fun getDragDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return if (boardListAdapter?.IsEditMode() == true) super.getDragDirs(recyclerView, viewHolder) else 0
}
}
itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper?.attachToRecyclerView(boardsList)
}
override fun onBoardClick(board: ChanBoard) {
incrementAccessCount(board.name)
.compose(applySingleSchedulers())
.subscribe()
mCallbacks?.onBoardItemClick(board, true)
}
override fun initMenu() {
super.initMenu()
if (toolbar != null) {
setupToolBar()
if (activity != null) {
activity?.invalidateOptionsMenu()
}
}
}
override fun onPause() {
super.onPause()
RxUtil.safeUnsubscribe(initDatabaseDisposable)
RxUtil.safeUnsubscribe(fetchBoardsSubscription)
RxUtil.safeUnsubscribe(watchDatabaseSubscription)
RxUtil.safeUnsubscribe(boardInfoSubscription)
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Activities containing this fragment must implement its callbacks.
check(context is BoardItemClickListener) { "Activity must implement fragment's callbacks." }
mCallbacks = context
}
private fun showManageBoardsTutorial() {
if (activity == null) {
return
}
val inflater = LayoutInflater.from(activity)
val dialogBuilder = MaterialAlertDialogBuilder(activity as Context)
val dialogView = inflater.inflate(R.layout.dialog_manage_boards_tutorial, null, false)
val dontShow = dialogView.findViewById<CheckBox>(R.id.manage_boards_dont_show)
dialogBuilder.setTitle(R.string.manage_boards)
.setView(dialogView)
.setPositiveButton(R.string.ok) { dialog: DialogInterface?, which: Int ->
if (activity != null) {
val pref = PreferenceManager.getDefaultSharedPreferences(activity)
pref.edit().putBoolean(getString(R.string.show_manage_boards_tutorial), !dontShow.isChecked).apply()
}
}
.show()
}
private fun showChangeLog() {
if (isAdded) {
LicensesFragment.displayLicensesFragment(activity?.supportFragmentManager, R.raw.changelog, "ChangeLog")
}
}
private fun setupHeader(rootView: View) {
showContentButton = rootView.findViewById(R.id.board_header_show_content)
boardOrderText = rootView.findViewById(R.id.board_order_subtitle)
orderTypeList = rootView.findViewById(R.id.board_order_content)
orderByFavorites = rootView.findViewById(R.id.board_order_type_favorite)
orderByName = rootView.findViewById(R.id.board_order_type_name)
orderByTitle = rootView.findViewById(R.id.board_order_type_title)
orderByAccess = rootView.findViewById(R.id.board_order_type_access_count)
orderByLast = rootView.findViewById(R.id.board_order_type_last_access)
orderByPost = rootView.findViewById(R.id.board_order_type_post_count)
orderbyCustom = rootView.findViewById(R.id.board_order_type_custom)
val orderBackground = rootView.findViewById<ViewGroup>(R.id.board_order_background)
if (orderBackground != null) {
orderBackground.setOnClickListener { v: View? -> hideList(NO_ORDER_SELECTED) }
boardOrderBackground = orderBackground
}
orderByNames = resources.getStringArray(R.array.orderbyName)
val boardOrder = MimiUtil.getBoardOrder()
showBoardOrderBackground = AlphaAnimation(0f, 1f)
showBoardOrderBackground?.duration = 400
revealListAnimation = AnimationUtils.loadAnimation(activity, R.anim.board_order_slide_down)
hideListAnimation = AnimationUtils.loadAnimation(activity, R.anim.board_order_slide_up)
hideBoardOrderBackground = AlphaAnimation(1f, 0f)
hideBoardOrderBackground?.duration = 400
revealListAnimation?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
orderTypeList?.setVisibility(View.VISIBLE)
}
override fun onAnimationEnd(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
})
showBoardOrderBackground?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
boardOrderBackground?.setVisibility(View.VISIBLE)
}
override fun onAnimationEnd(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
})
hideListAnimation?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
orderTypeList?.setVisibility(View.GONE)
}
override fun onAnimationRepeat(animation: Animation) {}
})
hideBoardOrderBackground?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
boardOrderBackground?.setVisibility(View.GONE)
}
override fun onAnimationRepeat(animation: Animation) {}
})
boardOrderContainer = rootView.findViewById(R.id.board_order_container)
boardOrderText?.text = orderByNames[boardOrder]
orderByFavorites?.setOnClickListener { hideList(6) }
orderByName?.setOnClickListener { hideList(2) }
orderByTitle?.setOnClickListener { hideList(1) }
orderByAccess?.setOnClickListener { hideList(3) }
orderByLast?.setOnClickListener { hideList(5) }
orderByPost?.setOnClickListener { hideList(4) }
orderbyCustom?.setOnClickListener { hideList(7) }
boardOrderContainer?.setOnClickListener {
if (orderTypeList?.visibility == View.VISIBLE) {
hideList(NO_ORDER_SELECTED)
} else {
showList()
}
}
}
private fun showList() {
boardOrderListVisible = true
orderTypeList?.startAnimation(revealListAnimation)
boardOrderBackground?.startAnimation(showBoardOrderBackground)
showContentButton?.setText(R.string.ic_content_shown)
}
private fun hideList(index: Int) {
boardOrderListVisible = false
if (index >= 0) {
orderList(index)
boardOrderText?.text = orderByNames[index]
}
orderTypeList?.startAnimation(hideListAnimation)
boardOrderBackground?.startAnimation(hideBoardOrderBackground)
showContentButton?.setText(R.string.ic_content_hidden)
}
private fun orderList(orderType: Int) {
if (activity != null) {
MimiUtil.setBoardOrder(activity, orderType)
errorSwitcher?.displayedChildId = boardsList?.id ?: 0
RxUtil.safeUnsubscribe(fetchBoardsSubscription)
fetchBoardsSubscription = fetchBoards(orderType)
.flatMap { boards: List<Board> -> Single.just<List<ChanBoard>>(convertBoardDbModelsToChanBoards(boards)) }
.compose(applySingleSchedulers())
.subscribe { orderedBoards: List<ChanBoard> ->
if (orderedBoards.isNotEmpty()) {
updateBoardsAdapter(orderedBoards)
}
}
}
}
private fun updateBoardsAdapter(updatedBoards: List<ChanBoard>) {
if (boardListAdapter != null) {
boardListAdapter?.boards = ArrayList(updatedBoards)
} else if (activity is MimiActivity) {
val act = activity as MimiActivity
boardListAdapter = BoardListAdapter(act, ArrayList(updatedBoards))
}
if (manageBoardsMenuItem != null) {
manageBoardsMenuItem?.isEnabled = true
}
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
if (activity is IToolbarContainer) {
val toolbarContainer = activity as IToolbarContainer?
toolbarContainer?.setExpandedToolbar(true, true)
}
}
}
override fun onBackPressed(): Boolean {
if (boardOrderListVisible) {
hideList(NO_ORDER_SELECTED)
return true
}
return super.onBackPressed()
}
private fun setupToolBar() {
if (activity is MimiActivity) {
val activity = activity as MimiActivity?
activity?.supportActionBar?.setTitle(R.string.app_name)
activity?.supportActionBar?.subtitle = null
}
toolbarSpinner = toolbar?.findViewById(R.id.board_spinner)
if (toolbarSpinner != null) {
toolbarSpinner?.visibility = View.GONE
}
}
override fun getMenuRes(): Int {
return R.menu.board_list
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(menuRes, menu)
manageBoardsMenuItem = menu.findItem(R.id.manage_boards_menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.manage_boards_menu && activity != null) {
activity?.startActionMode(actionMode)
}
return true
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition)
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
fun setActivateOnItemClick(activateOnItemClick: Boolean) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
this.activateOnItemClick = activateOnItemClick
}
override fun showFab(): Boolean {
return true
}
override fun getTitle(): String {
return ""
}
override fun getSubtitle(): String {
return ""
}
override fun getPageName(): String {
return "board_list"
}
override fun getTabId(): Int {
return TAB_ID
}
override fun addContent() {
showAddBoardDialog()
}
companion object {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private const val STATE_ACTIVATED_POSITION = "activated_position"
private val LOG_TAG = BoardItemListFragment::class.java.simpleName
private const val NO_ORDER_SELECTED = -1
const val TAB_ID = 100
}
} | apache-2.0 | c172bee7a8eb4284531af6ad9c4ef13a | 42.50065 | 202 | 0.623569 | 5.229987 | false | false | false | false |
thatJavaNerd/JRAW | lib/src/main/kotlin/net/dean/jraw/pagination/ModLogPaginator.kt | 1 | 2133 | package net.dean.jraw.pagination
import net.dean.jraw.JrawUtils
import net.dean.jraw.RedditClient
import net.dean.jraw.http.HttpRequest
import net.dean.jraw.models.ModAction
class ModLogPaginator private constructor(
reddit: RedditClient,
val subreddit: String,
baseUrl: String,
limit: Int,
val actionType: String? = null,
val moderatorName: String? = null
) : BarebonesPaginator<ModAction>(reddit, baseUrl, limit, ModAction::class.java) {
override fun createNextRequest(): HttpRequest.Builder {
val builder = super.createNextRequest()
val extraQueryArgs = mutableMapOf<String, String>()
if (actionType != null)
extraQueryArgs["type"] = actionType
if (moderatorName != null)
extraQueryArgs["mod"] = moderatorName
return builder.query(extraQueryArgs)
}
class Builder(reddit: RedditClient, val subreddit: String) : Paginator.Builder<ModAction>(
reddit = reddit,
baseUrl = "/r/${JrawUtils.urlEncode(subreddit)}/about/log",
clazz = ModAction::class.java
) {
private var limit: Int = Paginator.DEFAULT_LIMIT
private var actionType: String? = null
private var moderatorName: String? = null
/**
* The maximum amount of items per page. Unlike most other paginated endpoints, this one allows up to 500 items
* per page instead of the regular 100.
*/
fun limit(limit: Int): Builder { this.limit = limit; return this }
/** What kind of action to filter by. A null value will remove the filter */
fun actionType(actionType: String?): Builder { this.actionType = actionType; return this }
/**
* The username (not fullname) of a moderator. Only actions performed by this user will be returned. A value of
* null removes the filter
*/
fun moderatorName(moderatorName: String?): Builder { this.moderatorName = moderatorName; return this }
override fun build(): ModLogPaginator =
ModLogPaginator(reddit, subreddit, baseUrl, limit, actionType, moderatorName)
}
}
| mit | f195fb4f41695a6368f7763bf35b30f0 | 37.089286 | 119 | 0.667604 | 4.528662 | false | false | false | false |
is00hcw/anko | dsl/testData/functional/recyclerview-v7/LayoutsTest.kt | 2 | 2259 | private val defaultInit: Any.() -> Unit = {}
public open class _RecyclerView(ctx: Context): android.support.v7.widget.RecyclerView(ctx) {
public fun <T: View> T.lparams(
c: android.content.Context?,
attrs: android.util.AttributeSet?,
init: android.support.v7.widget.RecyclerView.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.RecyclerView.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
public fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: android.support.v7.widget.RecyclerView.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.RecyclerView.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
public fun <T: View> T.lparams(
source: android.view.ViewGroup.MarginLayoutParams?,
init: android.support.v7.widget.RecyclerView.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.RecyclerView.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
public fun <T: View> T.lparams(
source: android.view.ViewGroup.LayoutParams?,
init: android.support.v7.widget.RecyclerView.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.RecyclerView.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
public fun <T: View> T.lparams(
source: android.support.v7.widget.RecyclerView.LayoutParams?,
init: android.support.v7.widget.RecyclerView.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.RecyclerView.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
} | apache-2.0 | 3575ed551010d4d1945a8e33674587f4 | 39.357143 | 94 | 0.652501 | 4.482143 | false | false | false | false |
mix-it/mixit | src/main/kotlin/mixit/util/validator/UrlValidator.kt | 1 | 670 | package mixit.util.validator
import org.springframework.stereotype.Component
import java.net.MalformedURLException
import java.net.URL
/**
* @author Dev-Mind <[email protected]>
* @since 11/02/18.
*/
@Component
class UrlValidator {
fun isValid(value: String?): Boolean {
if (value == null || value.isEmpty()) {
return true
}
val url: URL
try {
url = URL(value)
} catch (e: MalformedURLException) {
return false
}
if ("http" != url.protocol && "https" != url.protocol) {
return false
}
return url.port == 80 || url.port == -1
}
}
| apache-2.0 | ef67b2c61dd8205d5cca7928bef90cc4 | 19.9375 | 64 | 0.559701 | 3.941176 | false | false | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/query/QueryType.kt | 1 | 1703 | /*
* Copyright (C) 2017 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.query
data class QueryType(val mimeType: String, val defaultExtensions: List<String>, val builder: QueryBuilder)
val XQUERY: QueryType = QueryType("application/xquery", listOf("xq", "xqy", "xquery", "xql", "xqu"), XQueryBuilder)
val JAVA_SCRIPT: QueryType = QueryType("application/javascript", listOf("js", "sjs"), JavaScriptBuilder)
val SQL: QueryType = QueryType("application/sql", listOf("sql"), SQLBuilder)
val SPARQL_QUERY: QueryType = QueryType("application/sparql-query", listOf("sparql", "rq"), SPARQLQueryBuilder)
val SPARQL_UPDATE: QueryType = QueryType("application/sparql-update", listOf("ru"), SPARQLUpdateBuilder)
val XSLT: QueryType = QueryType("application/xml", listOf("xsl", "xslt"), XSLTBuilder)
val QUERY_TYPES = listOf(
XQUERY,
JAVA_SCRIPT,
SQL,
SPARQL_QUERY,
SPARQL_UPDATE,
XSLT)
val QUERY_EXTENSIONS get(): List<String> =
// XSLT is not fully supported, so exclude from the list of supported extensions.
QUERY_TYPES.filter { type -> type !== XSLT }.flatMap { type -> type.defaultExtensions }
| apache-2.0 | 6521d3aa7e1da91d2044e1f9a98d15f6 | 39.547619 | 115 | 0.730476 | 3.978972 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/operators/IndexOperator.kt | 2 | 799 | package me.ztiany.operators
data class Point2(val x: Int, val y: Int)
operator fun Point2.get(index: Int): Int {
return when (index) {
0 -> x
1 -> y
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
data class MutablePoint(var x: Int, var y: Int)
operator fun MutablePoint.set(index: Int, value: Int) {
when(index) {
0 -> x = value
1 -> y = value
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
fun main(args: Array<String>) {
println("-------------------------------------------")
val p = Point2(10, 20)
println(p[1])
println("-------------------------------------------")
val mp = MutablePoint(10, 20)
mp[1] = 42
println(p)
}
| apache-2.0 | 95a39eb1079a974daf52f8a7686e129c | 21.828571 | 72 | 0.510638 | 3.916667 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/Binding.kt | 1 | 8389 | @file:Suppress("UNCHECKED_CAST", "CAST_NEVER_SUCCEEDS")
package tornadofx
import javafx.beans.binding.Bindings
import javafx.beans.binding.BooleanBinding
import javafx.beans.binding.BooleanExpression
import javafx.beans.property.Property
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.StringProperty
import javafx.beans.value.ChangeListener
import javafx.beans.value.ObservableValue
import javafx.beans.value.WritableValue
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.scene.control.*
import javafx.scene.paint.Color
import javafx.scene.text.Text
import javafx.util.StringConverter
import javafx.util.converter.*
import java.math.BigDecimal
import java.math.BigInteger
import java.text.Format
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.*
import java.util.concurrent.Callable
private fun <T> Property<T>.internalBind(property: ObservableValue<T>, readonly: Boolean) {
ViewModel.register(this, property)
if (readonly || (property !is Property<*>)) bind(property) else bindBidirectional(property as Property<T>)
}
fun <T> ComboBoxBase<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) =
valueProperty().internalBind(property, readonly)
fun ColorPicker.bind(property: ObservableValue<Color>, readonly: Boolean = false) =
valueProperty().internalBind(property, readonly)
fun DatePicker.bind(property: ObservableValue<LocalDate>, readonly: Boolean = false) =
valueProperty().internalBind(property, readonly)
fun ProgressIndicator.bind(property: ObservableValue<Number>, readonly: Boolean = false) =
progressProperty().internalBind(property, readonly)
fun <T> ChoiceBox<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) =
valueProperty().internalBind(property, readonly)
fun CheckBox.bind(property: ObservableValue<Boolean>, readonly: Boolean = false) =
selectedProperty().internalBind(property, readonly)
fun CheckMenuItem.bind(property: ObservableValue<Boolean>, readonly: Boolean = false) =
selectedProperty().internalBind(property, readonly)
fun Slider.bind(property: ObservableValue<Number>, readonly: Boolean = false) =
valueProperty().internalBind(property, readonly)
fun <T> Spinner<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) =
valueFactory.valueProperty().internalBind(property, readonly)
inline fun <reified S : T, reified T : Any> Labeled.bind(
property: ObservableValue<S>,
readonly: Boolean = false,
converter: StringConverter<T>? = null,
format: Format? = null
) {
bindStringProperty(textProperty(), converter, format, property, readonly)
}
inline fun <reified S : T, reified T : Any> TitledPane.bind(
property: ObservableValue<S>,
readonly: Boolean = false,
converter: StringConverter<T>? = null,
format: Format? = null
) = bindStringProperty(textProperty(), converter, format, property, readonly)
inline fun <reified S : T, reified T : Any> Text.bind(
property: ObservableValue<S>,
readonly: Boolean = false,
converter: StringConverter<T>? = null,
format: Format? = null
) = bindStringProperty(textProperty(), converter, format, property, readonly)
inline fun <reified S : T, reified T : Any> TextInputControl.bind(
property: ObservableValue<S>,
readonly: Boolean = false,
converter: StringConverter<T>? = null,
format: Format? = null
) = bindStringProperty(textProperty(), converter, format, property, readonly)
inline fun <reified S : T, reified T : Any> bindStringProperty(
stringProperty: StringProperty,
converter: StringConverter<T>?,
format: Format?,
property: ObservableValue<S>,
readonly: Boolean
) {
if (stringProperty.isBound) stringProperty.unbind()
val effectiveReadonly = readonly || property !is Property<S> || S::class != T::class
ViewModel.register(stringProperty, property)
if (S::class == String::class) when {
effectiveReadonly -> stringProperty.bind(property as ObservableValue<String>)
else -> stringProperty.bindBidirectional(property as Property<String>)
} else {
val effectiveConverter = if (format != null) null else converter ?: getDefaultConverter<S>()
if (effectiveReadonly) {
val toStringConverter = Callable {
when {
converter != null -> converter.toString(property.value)
format != null -> format.format(property.value)
else -> property.value?.toString()
}
}
val stringBinding = Bindings.createStringBinding(toStringConverter, property)
stringProperty.bind(stringBinding)
} else when {
effectiveConverter != null -> stringProperty.bindBidirectional(property as Property<S>, effectiveConverter as StringConverter<S>)
format != null -> stringProperty.bindBidirectional(property as Property<S>, format)
else -> throw IllegalArgumentException("Cannot convert from ${S::class} to String without an explicit converter or format")
}
}
}
inline fun <reified T : Any> getDefaultConverter() = when (T::class.javaPrimitiveType ?: T::class) {
Int::class.javaPrimitiveType -> IntegerStringConverter()
Long::class.javaPrimitiveType -> LongStringConverter()
Double::class.javaPrimitiveType -> DoubleStringConverter()
Float::class.javaPrimitiveType -> FloatStringConverter()
Date::class -> DateStringConverter()
BigDecimal::class -> BigDecimalStringConverter()
BigInteger::class -> BigIntegerStringConverter()
Number::class -> NumberStringConverter()
LocalDate::class -> LocalDateStringConverter()
LocalTime::class -> LocalTimeStringConverter()
LocalDateTime::class -> LocalDateTimeStringConverter()
Boolean::class.javaPrimitiveType -> BooleanStringConverter()
else -> null
} as StringConverter<T>?
fun ObservableValue<Boolean>.toBinding() = object : BooleanBinding() {
init {
super.bind(this@toBinding)
}
override fun dispose() {
super.unbind(this@toBinding)
}
override fun computeValue() = [email protected]
override fun getDependencies(): ObservableList<*> = FXCollections.singletonObservableList(this@toBinding)
}
fun <T, N> ObservableValue<T>.select(nested: (T) -> ObservableValue<N>): Property<N> {
fun extractNested(): ObservableValue<N>? = value?.let(nested)
var currentNested: ObservableValue<N>? = extractNested()
return object : SimpleObjectProperty<N>() {
val changeListener = ChangeListener<Any?> { _, _, _ ->
invalidated()
fireValueChangedEvent()
}
init {
currentNested?.addListener(changeListener)
[email protected](changeListener)
}
override fun invalidated() {
currentNested?.removeListener(changeListener)
currentNested = extractNested()
currentNested?.addListener(changeListener)
}
override fun get() = currentNested?.value
override fun set(v: N?) {
(currentNested as? WritableValue<N>)?.value = v
super.set(v)
}
}
}
fun <T> ObservableValue<T>.selectBoolean(nested: (T) -> BooleanExpression): BooleanExpression {
fun extractNested() = nested(value)
val dis = this
var currentNested = extractNested()
return object : SimpleBooleanProperty() {
val changeListener = ChangeListener<Boolean> { _, _, _ ->
currentNested = extractNested()
fireValueChangedEvent()
}
init {
dis.onChange {
fireValueChangedEvent()
invalidated()
}
}
override fun invalidated() {
currentNested.removeListener(changeListener)
currentNested = extractNested()
currentNested.addListener(changeListener)
}
override fun getValue() = currentNested.value
override fun setValue(v: Boolean?) {
(currentNested as? WritableValue<*>)?.value = v
super.setValue(v)
}
}
}
| apache-2.0 | 8679449da6b9d6aa436c10b2b3b21883 | 35.633188 | 141 | 0.685421 | 4.810206 | false | false | false | false |
eviltak/adb-nmap | src/test/kotlin/net/eviltak/adbnmap/net/protocol/AdbServicesProtocolTest.kt | 1 | 3778 | /*
* adb-nmap: An ADB network device discovery and connection library
* Copyright (C) 2017-present Arav Singhal and adb-nmap contributors
*
* 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.
*
* The full license can be found in LICENSE.md.
*/
package net.eviltak.adbnmap.net.protocol
import com.nhaarman.mockito_kotlin.*
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
import java.io.*
import java.net.Socket
import java.net.SocketTimeoutException
@RunWith(Enclosed::class)
class AdbServicesProtocolTest {
class SendTestMessage {
@Test
fun sendTestMessageTest() {
val byteArrayOutputStream = ByteArrayOutputStream()
val mockedSocket = mock<Socket> {
on { getOutputStream() } doReturn byteArrayOutputStream
}
val servicesProtocol = AdbServicesProtocol(mockedSocket)
servicesProtocol.sendTestMessage()
assertTrue("Wrong command \"${String(byteArrayOutputStream.toByteArray(),
Charsets.US_ASCII)}\" written to socket",
byteArrayOutputStream.toByteArray().contentEquals(
"000Chost:version".toByteArray(Charsets.US_ASCII))
)
}
}
class HostUsesProtocol {
@Test
fun hostDoesUseProtocolTest() {
val byteArrayInputStream = ByteArrayInputStream("OKAY0000".toByteArray(Charsets.US_ASCII))
val byteArrayOutputStream = ByteArrayOutputStream()
val mockedSocket = mock<Socket> {
on { getInputStream() } doReturn byteArrayInputStream
on { getOutputStream() } doReturn byteArrayOutputStream
}
val servicesProtocol = AdbServicesProtocol(mockedSocket)
assertTrue("hostUsesProtocol returned false", servicesProtocol.hostUsesProtocol())
}
@Test
fun invalidDataReceivedTest() {
val byteArrayInputStream = ByteArrayInputStream("FAIL0000".toByteArray(Charsets.US_ASCII))
val byteArrayOutputStream = ByteArrayOutputStream()
val mockedSocket = mock<Socket> {
on { getInputStream() } doReturn byteArrayInputStream
on { getOutputStream() } doReturn byteArrayOutputStream
}
val servicesProtocol = AdbServicesProtocol(mockedSocket)
assertFalse("hostUsesProtocol returned true", servicesProtocol.hostUsesProtocol())
}
@Test
fun dataReceiveTimeoutTest() {
val blockingInputStream = mock<InputStream> {
on { read(any()) } doAnswer doAnswer@ {
throw SocketTimeoutException()
}
}
val byteArrayOutputStream = ByteArrayOutputStream()
val mockedSocket = mock<Socket> {
on { getInputStream() } doReturn blockingInputStream
on { getOutputStream() } doReturn byteArrayOutputStream
}
val servicesProtocol = AdbServicesProtocol(mockedSocket)
assertFalse("hostUsesProtocol returned true", servicesProtocol.hostUsesProtocol())
}
}
}
| gpl-3.0 | 52531900428a92bf5f35a0972c627d2c | 35.679612 | 102 | 0.652726 | 5.428161 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/statuses/StatusesSearchFragment.kt | 1 | 3368 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.statuses
import android.content.Context
import android.os.Bundle
import android.support.v4.content.Loader
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.fragment.ParcelableStatusesFragment
import de.vanita5.twittnuker.loader.statuses.TweetSearchLoader
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.util.Utils
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.util.*
open class StatusesSearchFragment : ParcelableStatusesFragment() {
override val savedStatusesFileArgs: Array<String>?
get() {
val accountKey = Utils.getAccountKey(context, arguments)
val query = arguments.getString(EXTRA_QUERY)
val local = arguments.getBoolean(EXTRA_LOCAL)
val result = ArrayList<String>()
result.add(AUTHORITY_SEARCH_TWEETS)
result.add("account=$accountKey")
result.add("query=$query")
if (local) {
result.add("local")
}
return result.toTypedArray()
}
override val readPositionTagWithArguments: String?
get() {
val tabPosition = arguments.getInt(EXTRA_TAB_POSITION, -1)
val sb = StringBuilder("search_")
if (tabPosition < 0) return null
val query = arguments.getString(EXTRA_QUERY) ?: return null
val encodedQuery: String
try {
encodedQuery = URLEncoder.encode(query, "UTF-8").replace("[^\\w\\d]".toRegex(), "_")
} catch (e: UnsupportedEncodingException) {
return null
}
sb.append(encodedQuery)
return sb.toString()
}
override fun onCreateStatusesLoader(context: Context, args: Bundle, fromUser: Boolean):
Loader<List<ParcelableStatus>?> {
refreshing = true
val accountKey = Utils.getAccountKey(context, args)
val query = arguments.getString(EXTRA_QUERY)
val local = arguments.getBoolean(EXTRA_LOCAL, false)
val tabPosition = arguments.getInt(EXTRA_TAB_POSITION, -1)
val makeGap = args.getBoolean(EXTRA_MAKE_GAP, true)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
return TweetSearchLoader(activity, accountKey, query, adapterData, savedStatusesFileArgs,
tabPosition, fromUser, makeGap, local, loadingMore)
}
} | gpl-3.0 | e4bc6d731122593de647382d4c937818 | 39.107143 | 100 | 0.680819 | 4.502674 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/fragments/AbsenceCheckFragment.kt | 1 | 2471 | package com.sapuseven.untis.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.sapuseven.untis.R
import com.sapuseven.untis.adapters.AbsenceCheckAdapter
import com.sapuseven.untis.adapters.AbsenceCheckAdapterItem
import com.sapuseven.untis.viewmodels.PeriodDataViewModel
import java.text.Collator
class AbsenceCheckFragment : Fragment() {
private val viewModel: PeriodDataViewModel by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = activity?.layoutInflater?.inflate(R.layout.fragment_timetable_absence_check, container, false) as ViewGroup
val rvAbsenceCheck = rootView.findViewById<RecyclerView>(R.id.recyclerview_absence_check)
val adapter = AbsenceCheckAdapter {
if (it.absence is PeriodDataViewModel.PendingAbsence) return@AbsenceCheckAdapter
if (it.absence.untisAbsence == null)
viewModel.createAbsence(it.student)
else
viewModel.deleteAbsence(it.student, it.absence.untisAbsence)
}
rvAbsenceCheck.layoutManager = LinearLayoutManager(context)
rvAbsenceCheck.adapter = adapter
viewModel.absenceData().observe(viewLifecycleOwner, Observer { absenceList ->
rootView.findViewById<ProgressBar>(R.id.progressbar_absencecheck_loading).visibility = View.GONE
adapter.clear()
adapter.addItems(absenceList.map { AbsenceCheckAdapterItem(it.key, it.value) }.sortedWith(Comparator { s1, s2 ->
Collator.getInstance().compare(s1.student.fullName(), s2.student.fullName())
}))
adapter.notifyDataSetChanged()
})
rootView.findViewById<FloatingActionButton>(R.id.fab_absencecheck_save).setOnClickListener {
viewModel.submitAbsencesChecked(
onSuccess = {
parentFragmentManager.popBackStack()
Snackbar.make(rootView, "Absences checked.", Snackbar.LENGTH_SHORT).show()
},
onFailure = {
Snackbar.make(rootView, "Network error: ${it.message}", Snackbar.LENGTH_SHORT).show()
}
)
}
return rootView
}
}
| gpl-3.0 | 6e22007da8f6e98f595bdec530051599 | 38.854839 | 124 | 0.795629 | 4.202381 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/com/congwiny/basic/ControlFlow.kt | 1 | 5876 | package com.congwiny.basic
/**
* Created by congwiny on 2017/6/12.
*/
fun main(args: Array<String>) {
//在 Kotlin 中,if是⼀个表达式,即它会返回⼀个值。
// 因此就不需要三元运算符(条件 ? 然后 : 否则),因为普通的 if 就能胜任这个⻆⾊。
// 传统⽤法
val a = 1
val b = 3
var max1 = a
if (a < b) max1 = b
// With else
var max2: Int
if (a > b) {
max2 = a
} else {
max2 = b
}
/**作为表达式
*
* 如果你使⽤ if 作为表达式⽽不是语句(例如:返回它的值或者 把它赋给变量),
* 该表达式需要有 else 分⽀。
*/
val max = if (a > b) a else b
//if的分⽀可以是代码块,最后的表达式作为该块的值:
val max3 = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
//when表达式
//when取代了类C语言的switch操作符,最简单形式如下
when(max){
1 -> println("max==1")
3 -> println("max==3")
else ->{
println ("neither 1 nor 3")
}
}
//如果很多分⽀需要⽤相同的⽅式处理,则可以把多个分⽀条件放在⼀起,⽤逗号分隔:
when (max) {
0, 1 -> println("x == 0 or x == 1")
else -> println("otherwise")
}
//我们可以⽤任意表达式(⽽不只是常量)作为分⽀条件
when (max) {
parseInt("3") -> println("s encodes x")
else -> println("s does not encode x")
}
//我们也可以检测⼀个值在(in)或者不在(!in)⼀个区间或者集合中:
val validNumbers = arrayOf(1,2,3)
when (max) {
in 4..10 -> println("x is in the range")
in validNumbers -> println("x is valid")
!in 10..20 -> println("x is outside the range")
else -> println("none of the above")
}
println(hasPrefix("prefix_abc"))
/**
* when 也可以⽤来取代 if-else if链。
* 如果不提供参数,所有的分⽀条件都是简单的布尔表达式,
* ⽽当⼀个分⽀的条件为真时则执⾏该分⽀:
*/
val str = "abc"
when {
str.startsWith("a") -> print("aaa")
str.startsWith("b") -> print("bbb")
else -> print("str is funny")
}
//For循环(For Loops)
/**
* for 循环可以对任何提供迭代器(iterator)的对象进⾏遍历,语法如下:
* for (item in collection) print(item)
*
* 循环体可以是⼀个代码块。
for (item: Int in ints) {
// ……
}
*/
/**
*对数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。
*如果你想要通过索引遍历⼀个数组或者⼀个 list,你可以这么做:
*/
val array = arrayOf(1,2,3)
//注意这种“在区间上遍历”会编译成优化的实现⽽不会创建额外对象。
for (i in array.indices) {
print(array[i])
}
println()
//库函数with index...牛逼哄哄啊
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
//while和do...while 和java一样
//break和continue也与java一样
//返回和跳转
//Kotlin 有三种结构化跳转表达式:
/**
* return。默认从最直接包围它的函数或者匿名函
* break。终⽌最直接包围它的循环。
* continue。继续下⼀次最直接包围它的循环。
*/
//所有这些表达式都可以⽤作更⼤表达式的⼀部分:
//TODO 这不知道啥意思。。。
val s = "abc"?:return
//return at labels (return又多了那么多玩法。。。)
/**
* Kotlin 有函数字⾯量、局部函数和对象表达式。
* 因此 Kotlin 的函数可以被嵌套。
* 标签限制的 return 允许我们从外层函数返回。
* 最重要的⼀个⽤途就是从lambda 表达式中返回
*/
foo2()
/**
*如果我们需要从 lambda 表达式中返回,我们必须给它加标签并⽤以限制 return。
*/
foo3()
/**
* 通常情况下使⽤隐式标签更⽅便。
* 该标签与接受该 lambda 的函数同名。
*/
foo4()
/**
* 我们⽤⼀个匿名函数替代 lambda 表达式。
* 匿名函数内部的 return 语句将从该匿名函数⾃⾝返回
*/
foo5()
/**
* Note:
* 当要返⼀个回值的时候,解析器优先选⽤【标签限制的】return,即
return@a 1
意为“从标签 @a 返回 1”,⽽不是“返回⼀个标签标注的表达式 (@a 1) ”。
*/
}
fun foo5(){
val ints = arrayOf(1,2,0,3)
ints.forEach(fun(value:Int){
if (value==0) return
println("funfun"+value)
})
}
fun foo4(){
val ints = arrayOf(1,2,0,3)
ints.forEach{
if (it==2) return@forEach
println("lit@"+it)
}
}
/**
* lit@1
* lit@0
* lit@3
*/
fun foo3(){
val ints = arrayOf(1,2,0,3)
ints.forEach lit@ {
if (it==2) return@lit
println("lit@"+it)
}
}
fun foo2() {
val ints = arrayOf(1,2,0,3)
ints.forEach {
if (it == 0)
/**
* 这个 return 表达式从最直接包围它的函数即 foo 中返回。
* 注意,这种【⾮局部的返回】只⽀持传给【内联函数的】 lambda 表达式。
*/
return
println(it)
}
}
/**
* 另⼀种可能性是检测⼀个值是(is)或者不是(!is)⼀个特定类型的值。
* 注意:由于智能转换,你可以访问该类型的⽅法和属性⽽⽆需 任何额外的检测。
*/
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
} | apache-2.0 | 519ac0fac0e4e774bb3885fd1d39ff83 | 18.046083 | 55 | 0.507018 | 2.371986 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/payments/StripeBrowserLauncherViewModel.kt | 1 | 4778 | package com.stripe.android.payments
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewmodel.CreationExtras
import com.stripe.android.PaymentConfiguration
import com.stripe.android.R
import com.stripe.android.auth.PaymentBrowserAuthContract
import com.stripe.android.core.browser.BrowserCapabilities
import com.stripe.android.core.browser.BrowserCapabilitiesSupplier
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor
import com.stripe.android.networking.PaymentAnalyticsEvent
import com.stripe.android.networking.PaymentAnalyticsRequestFactory
import com.stripe.android.utils.requireApplication
import kotlin.properties.Delegates
internal class StripeBrowserLauncherViewModel(
private val analyticsRequestExecutor: AnalyticsRequestExecutor,
private val paymentAnalyticsRequestFactory: PaymentAnalyticsRequestFactory,
private val browserCapabilities: BrowserCapabilities,
private val intentChooserTitle: String,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
var hasLaunched: Boolean by Delegates.observable(
savedStateHandle.contains(KEY_HAS_LAUNCHED)
) { _, _, newValue ->
savedStateHandle.set(KEY_HAS_LAUNCHED, true)
}
fun createLaunchIntent(
args: PaymentBrowserAuthContract.Args
): Intent {
val shouldUseCustomTabs = browserCapabilities == BrowserCapabilities.CustomTabs
logCapabilities(shouldUseCustomTabs)
val url = Uri.parse(args.url)
return if (shouldUseCustomTabs) {
val customTabColorSchemeParams = args.statusBarColor?.let { statusBarColor ->
CustomTabColorSchemeParams.Builder()
.setToolbarColor(statusBarColor)
.build()
}
// use Custom Tabs
val customTabsIntent = CustomTabsIntent.Builder()
.setShareState(CustomTabsIntent.SHARE_STATE_OFF)
.also {
if (customTabColorSchemeParams != null) {
it.setDefaultColorSchemeParams(customTabColorSchemeParams)
}
}
.build()
customTabsIntent.intent.data = url
Intent.createChooser(
customTabsIntent.intent,
intentChooserTitle
)
} else {
// use default device browser
Intent.createChooser(
Intent(Intent.ACTION_VIEW, url),
intentChooserTitle
)
}
}
fun getResultIntent(args: PaymentBrowserAuthContract.Args): Intent {
val url = Uri.parse(args.url)
return Intent().putExtras(
PaymentFlowResult.Unvalidated(
clientSecret = args.clientSecret,
sourceId = url.lastPathSegment.orEmpty(),
stripeAccountId = args.stripeAccountId,
canCancelSource = args.shouldCancelSource
).toBundle()
)
}
fun logCapabilities(
shouldUseCustomTabs: Boolean
) {
analyticsRequestExecutor.executeAsync(
paymentAnalyticsRequestFactory.createRequest(
when (shouldUseCustomTabs) {
true -> PaymentAnalyticsEvent.AuthWithCustomTabs
false -> PaymentAnalyticsEvent.AuthWithDefaultBrowser
}
)
)
}
class Factory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val application = extras.requireApplication()
val savedStateHandle = extras.createSavedStateHandle()
val config = PaymentConfiguration.getInstance(application)
val browserCapabilitiesSupplier = BrowserCapabilitiesSupplier(application)
return StripeBrowserLauncherViewModel(
DefaultAnalyticsRequestExecutor(),
PaymentAnalyticsRequestFactory(
application,
config.publishableKey
),
browserCapabilitiesSupplier.get(),
application.getString(R.string.stripe_verify_your_payment),
savedStateHandle
) as T
}
}
internal companion object {
const val KEY_HAS_LAUNCHED = "has_launched"
}
}
| mit | e4ca2c5a1d997beefd3b1791ef04ae08 | 36.622047 | 94 | 0.666597 | 5.798544 | false | false | false | false |
stripe/stripe-android | financial-connections/src/main/java/com/stripe/android/financialconnections/FinancialConnectionsSheetState.kt | 1 | 2181 | package com.stripe.android.financialconnections
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.PersistState
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetActivityArgs
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetActivityResult
import com.stripe.android.financialconnections.model.FinancialConnectionsSessionManifest
/**
* Class containing all of the data needed to represent the screen.
*/
internal data class FinancialConnectionsSheetState(
val initialArgs: FinancialConnectionsSheetActivityArgs = emptyArgs(),
val activityRecreated: Boolean = false,
@PersistState val manifest: FinancialConnectionsSessionManifest? = null,
@PersistState val authFlowActive: Boolean = false,
val viewEffect: FinancialConnectionsSheetViewEffect? = null
) : MavericksState {
val sessionSecret: String
get() = initialArgs.configuration.financialConnectionsSessionClientSecret
/**
* Constructor used by Mavericks to build the initial state.
*/
constructor(args: FinancialConnectionsSheetActivityArgs) : this(
initialArgs = args
)
private companion object {
fun emptyArgs(): FinancialConnectionsSheetActivityArgs {
return FinancialConnectionsSheetActivityArgs.ForData(
FinancialConnectionsSheet.Configuration(
financialConnectionsSessionClientSecret = "",
publishableKey = ""
)
)
}
}
}
/**
* Class containing all side effects intended to be run by the view.
*
* Mostly one-off actions to be executed by the view will be instances of ViewEffect.
*/
internal sealed class FinancialConnectionsSheetViewEffect {
/**
* Open the AuthFlow.
*/
data class OpenAuthFlowWithUrl(
val url: String
) : FinancialConnectionsSheetViewEffect()
/**
* Finish [FinancialConnectionsSheetActivity] with a given [FinancialConnectionsSheetActivityResult]
*/
data class FinishWithResult(
val result: FinancialConnectionsSheetActivityResult
) : FinancialConnectionsSheetViewEffect()
}
| mit | 5c7d8392ac3125e47361eca6155ee56a | 34.177419 | 104 | 0.735901 | 5.650259 | false | false | false | false |
AndroidX/androidx | datastore/datastore-sampleapp/src/main/java/com/example/datastoresampleapp/PreferencesDataStoreActivity.kt | 3 | 3431 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.datastoresampleapp
import android.content.Context
import android.os.Bundle
import android.os.StrictMode
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.io.IOException
val Context.prefsDs by preferencesDataStore("datastore_test_app")
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class PreferencesDataStoreActivity : AppCompatActivity() {
private val TAG = "PreferencesActivity"
private val PREFERENCE_STORE_FILE_NAME = "datastore_test_app"
private val COUNTER_KEY = intPreferencesKey("counter")
override fun onCreate(savedInstanceState: Bundle?) {
// Strict mode allows us to check that no writes or reads are blocking the UI thread.
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.penaltyDeath()
.build()
)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpPreferenceStoreUi()
}
private fun setUpPreferenceStoreUi() {
// Using preferenceStore:
findViewById<Button>(R.id.counter_dec).setOnClickListener {
lifecycleScope.launch {
prefsDs.edit { prefs ->
prefs[COUNTER_KEY] = (prefs[COUNTER_KEY] ?: 0) - 1
}
}
}
findViewById<Button>(R.id.counter_inc).setOnClickListener {
lifecycleScope.launch {
prefsDs.edit { prefs ->
prefs[COUNTER_KEY] = (prefs[COUNTER_KEY] ?: 0) + 1
}
}
}
lifecycleScope.launch {
prefsDs.data
.catch { e ->
if (e is IOException) {
Log.e(TAG, "Error reading preferences.", e)
emit(emptyPreferences())
} else {
throw e
}
}
.map { it[COUNTER_KEY] ?: 0 }
.distinctUntilChanged()
.collect { counterValue ->
findViewById<TextView>(R.id.counter_text_view).text = counterValue.toString()
}
}
}
} | apache-2.0 | 2383027ca92c82ff1e28ece9906629d4 | 34.020408 | 97 | 0.64471 | 4.887464 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/OnnxInvokeParams.kt | 1 | 2486 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.linalg.api.buffer.DataType
import org.nd4j.linalg.api.ops.custom.Invoke.InvokeParams
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRGraph
class OnnxInputTensors(op: SameDiffOp,sd: SameDiff,importedBody: OnnxIRGraph) {
val op: SameDiffOp = op
val sd: SameDiff = sd
val importedBody = importedBody
fun toInputTensors(): List<SDVariable> {
val inputTensors = ArrayList<SDVariable>()
val currIteration = sd.constant(0).castTo(DataType.INT64)
//loop has 2 to N dependencies: the termination iterations and the custom condition
//note when not specified we just loop the maximum number of iterations and let the user specify the termination condition
val terminationIterations: SDVariable? = if(op.inputsToOp.size > 0 && op.inputsToOp[0] != "") sd.getVariable(op.inputsToOp[0]) else sd.constant(Long.MAX_VALUE)
val cond: SDVariable? = if(op.inputsToOp.size > 1 && op.inputsToOp[1] != "") sd.getVariable(op.inputsToOp[1]) else sd.constant(true)
inputTensors.add(currIteration)
if(terminationIterations != null)
inputTensors.add(terminationIterations)
if(cond != null)
inputTensors.add(cond)
for(i in 2 until importedBody.inputList.size) {
inputTensors.add(sd.getVariable(op.inputsToOp[i]))
}
return inputTensors
}
}
| apache-2.0 | d1931e7d3ea89e32e89e24098f1b2916 | 43.392857 | 167 | 0.668544 | 3.939778 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/PublishJob.kt | 1 | 974 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Entity
import java.util.Date
/**
* A representation of the status of any attempts to upload/post a video to a
* third-party social network at a specific time.
*
* @param firstPublishDate The time in ISO 8601 format when the user first attempted to publish a clip to third-party
* social networks.
* @param destinations Contains information about upload/post status on all third party social networks.
* @param resourceKey The resource key string of the PublishJob.
*/
@JsonClass(generateAdapter = true)
data class PublishJob(
@Json(name = "first_publish_date")
val firstPublishDate: Date? = null,
@Json(name = "destinations")
val destinations: PublishJobDestinations? = null,
@Json(name = "resource_key")
val resourceKey: String? = null
) : Entity {
override val identifier: String? = resourceKey
}
| mit | a38c401c0e37b5b5a49ccf6821fa6b3c | 30.419355 | 117 | 0.746407 | 4.024793 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/albedo/src/test/kotlin/com/teamwizardry/librarianlib/albedo/test/shaders/TestFlatLineBevels.kt | 1 | 7610 | package com.teamwizardry.librarianlib.albedo.test.shaders
import com.mojang.blaze3d.platform.GlStateManager
import com.mojang.blaze3d.systems.RenderSystem
import com.teamwizardry.librarianlib.albedo.base.buffer.FlatColorRenderBuffer
import com.teamwizardry.librarianlib.albedo.base.buffer.FlatLinesRenderBuffer
import com.teamwizardry.librarianlib.albedo.buffer.Primitive
import com.teamwizardry.librarianlib.albedo.test.ShaderTest
import com.teamwizardry.librarianlib.core.util.Client
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.math.*
import net.minecraft.client.gui.screen.Screen
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.util.math.Vec3d
import java.awt.Color
import kotlin.math.*
internal object TestFlatLineBevels : ShaderTest(220, 220) {
override fun doDraw(stack: MatrixStack, matrix: Matrix4d, mousePos: Vec2d) {
val center = vec(width / 2, height / 2, 0)
// val direction = (vec(mousePos.x, mousePos.y, 0) - center).normalize()
val directionAngle = Client.time.seconds * 2 * PI / 5
val direction = vec(sin(directionAngle), cos(directionAngle), 0)
val inset = -30f
val outset = -5f
val length = 65
val radius = 110
val startDelta = vec(-length, 0, 0)
val startNormal = vec(0, 1, 0) / Client.scaleFactor
val endDelta = direction * length
val endNormal = vec(-direction.y, direction.x, 0) / Client.scaleFactor
val tipDelta = vec(-length / 2, 0, 0)
val tipNormal = vec(0, -1, 0) / Client.scaleFactor
run {
val rb = FlatColorRenderBuffer.SHARED
rb.pos(stack, center).color(0.2f, 0.2f, 0.2f, 1f).endVertex()
val steps = 50
val stepSize = 2 * PI / steps
for (i in 0..steps) {
val angle = i * stepSize
rb.pos(stack, center + vec(sin(angle), cos(angle), 0) * radius).color(0.2f, 0.2f, 0.2f, 1f).endVertex()
}
rb.draw(Primitive.TRIANGLE_FAN)
}
run {
val rb = FlatLinesRenderBuffer.SHARED
var color = Color(0.78f, 0.33f, 0.07f, 1f)
rb.pos(stack, center + startDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + startDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta).inset(inset).outset(outset).color(color).endVertex()
rb.draw(Primitive.LINE_STRIP_ADJACENCY)
color = Color(0.23f, 0.57f, 0.04f, 1f)
rb.pos(stack, center + startDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta + tipDelta).inset(inset).outset(outset).color(color).endVertex()
rb.draw(Primitive.LINE_STRIP_ADJACENCY)
color = Color(0.05f, 0.51f, 0.67f, 1f)
rb.pos(stack, center).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta + tipDelta).inset(inset).outset(outset).color(color).endVertex()
rb.pos(stack, center + endDelta + tipDelta).inset(inset).outset(outset).color(color).endVertex()
rb.draw(Primitive.LINE_STRIP_ADJACENCY)
}
if(!Screen.hasShiftDown()) {
val rb = FlatColorRenderBuffer.SHARED
rb.pos(stack, center + startDelta).color(0f, 0f, 0f, 1f).endVertex()
rb.pos(stack, center).color(0f, 0f, 0f, 1f).endVertex()
rb.pos(stack, center).color(0f, 0f, 0f, 1f).endVertex()
rb.pos(stack, center + endDelta).color(0f, 0f, 0f, 1f).endVertex()
rb.pos(stack, center + endDelta).color(0f, 0f, 0f, 1f).endVertex()
rb.pos(stack, center + endDelta + tipDelta).color(0f, 0f, 0f, 1f).endVertex()
fun line(offset: Vec3d, color: Color) {
val intercept = vec(offset.y, -offset.x, offset.z).normalize() * (sqrt(1 - offset.lengthSquared() / (radius * radius)) * radius)
rb.pos(stack, center + offset + intercept).color(color).endVertex()
rb.pos(stack, center + offset - intercept).color(color).endVertex()
}
val red = Color(1f, 0f, 0f, 0.5f)
val green = Color(0f, 0.75f, 0f, 0.5f)
line(startNormal * outset, red)
line(startNormal * inset, red)
line(endNormal * outset, red)
line(endNormal * inset, red)
line(vec(0, endDelta.y, 0) + tipNormal * outset, red)
line(vec(0, endDelta.y, 0) + tipNormal * inset, red)
val bevelCoefficient = 1.5
run {
val insetBevel = inset * bevelCoefficient / Client.scaleFactor
val outsetBevel = outset * bevelCoefficient / Client.scaleFactor
val cornerNormal = (vec(startDelta.y, -startDelta.x, startDelta.z).normalize() +
vec(-endDelta.y, endDelta.x, endDelta.z).normalize()).normalize()
val cornerPerpendicular = vec(cornerNormal.y, -cornerNormal.x, cornerNormal.z)
rb.pos(stack, center + cornerNormal * insetBevel).color(green).endVertex()
rb.pos(stack, center + cornerNormal * outsetBevel).color(green).endVertex()
rb.pos(stack, center + cornerNormal * insetBevel - cornerPerpendicular * inset).color(green)
.endVertex()
rb.pos(stack, center + cornerNormal * insetBevel + cornerPerpendicular * inset).color(green)
.endVertex()
rb.pos(stack, center + cornerNormal * outsetBevel - cornerPerpendicular * outset).color(green)
.endVertex()
rb.pos(stack, center + cornerNormal * outsetBevel + cornerPerpendicular * outset).color(green)
.endVertex()
}
run {
val insetBevel = inset * bevelCoefficient / Client.scaleFactor
val outsetBevel = outset * bevelCoefficient / Client.scaleFactor
val cornerNormal = (vec(-tipDelta.y, tipDelta.x, tipDelta.z).normalize() +
vec(-endDelta.y, endDelta.x, endDelta.z).normalize()).normalize()
val cornerPerpendicular = vec(cornerNormal.y, -cornerNormal.x, cornerNormal.z)
rb.pos(stack, center + endDelta + cornerNormal * insetBevel).color(green).endVertex()
rb.pos(stack, center + endDelta + cornerNormal * outsetBevel).color(green).endVertex()
rb.pos(stack, center + endDelta + cornerNormal * insetBevel - cornerPerpendicular * inset).color(green)
.endVertex()
rb.pos(stack, center + endDelta + cornerNormal * insetBevel + cornerPerpendicular * inset).color(green)
.endVertex()
rb.pos(stack, center + endDelta + cornerNormal * outsetBevel - cornerPerpendicular * outset).color(green)
.endVertex()
rb.pos(stack, center + endDelta + cornerNormal * outsetBevel + cornerPerpendicular * outset).color(green)
.endVertex()
}
rb.draw(Primitive.LINES)
}
}
} | lgpl-3.0 | fb05c31783e3c4643b347840a3c8ae31 | 46.56875 | 144 | 0.612746 | 3.808809 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/invitations/GuildInvite.kt | 2 | 383 | package com.habitrpg.android.habitica.models.invitations
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class GuildInvite : RealmObject(), GenericInvitation {
override var id: String? = null
override var inviter: String? = null
override var name: String? = null
var publicGuild: Boolean? = null
}
| gpl-3.0 | 2655141c6cdbb233e8e30508607fc3ec | 27.461538 | 59 | 0.72846 | 4.208791 | false | false | false | false |
androidx/androidx | fragment/fragment-ktx/src/main/java/androidx/fragment/app/FragmentViewModelLazy.kt | 3 | 7937 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import androidx.annotation.MainThread
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.Factory
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.CreationExtras
import kotlin.reflect.KClass
/**
* Returns a property delegate to access [ViewModel] by **default** scoped to this [Fragment]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels()
* }
* ```
*
* Custom [ViewModelProvider.Factory] can be defined via [factoryProducer] parameter,
* factory returned by it will be used to create [ViewModel]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels { myFactory }
* }
* ```
*
* Default scope may be overridden with parameter [ownerProducer]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels ({requireParentFragment()})
* }
* ```
*
* This property can be accessed only after this Fragment is attached i.e., after
* [Fragment.onAttach()], and access prior to that will result in IllegalArgumentException.
*/
@Deprecated(
"Superseded by viewModels that takes a CreationExtras producer",
level = DeprecationLevel.HIDDEN
)
@MainThread
public inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val owner by lazy(LazyThreadSafetyMode.NONE) { ownerProducer() }
return createViewModelLazy(
VM::class,
{ owner.viewModelStore },
{
(owner as? HasDefaultViewModelProviderFactory)?.defaultViewModelCreationExtras
?: CreationExtras.Empty
},
factoryProducer ?: {
(owner as? HasDefaultViewModelProviderFactory)?.defaultViewModelProviderFactory
?: defaultViewModelProviderFactory
})
}
/**
* Returns a property delegate to access [ViewModel] by **default** scoped to this [Fragment]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels()
* }
* ```
*
* Custom [ViewModelProvider.Factory] can be defined via [factoryProducer] parameter,
* factory returned by it will be used to create [ViewModel]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels { myFactory }
* }
* ```
*
* Default scope may be overridden with parameter [ownerProducer]:
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by viewmodels ({requireParentFragment()})
* }
* ```
*
* This property can be accessed only after this Fragment is attached i.e., after
* [Fragment.onAttach()], and access prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val owner by lazy(LazyThreadSafetyMode.NONE) { ownerProducer() }
return createViewModelLazy(
VM::class,
{ owner.viewModelStore },
{
extrasProducer?.invoke()
?: (owner as? HasDefaultViewModelProviderFactory)?.defaultViewModelCreationExtras
?: CreationExtras.Empty
},
factoryProducer ?: {
(owner as? HasDefaultViewModelProviderFactory)?.defaultViewModelProviderFactory
?: defaultViewModelProviderFactory
})
}
/**
* Returns a property delegate to access parent activity's [ViewModel],
* if [factoryProducer] is specified then [ViewModelProvider.Factory]
* returned by it will be used to create [ViewModel] first time. Otherwise, the activity's
* [androidx.activity.ComponentActivity.getDefaultViewModelProviderFactory](default factory)
* will be used.
*
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by activityViewModels()
* }
* ```
*
* This property can be accessed only after this Fragment is attached i.e., after
* [Fragment.onAttach()], and access prior to that will result in IllegalArgumentException.
*/
@Deprecated(
"Superseded by activityViewModels that takes a CreationExtras producer",
level = DeprecationLevel.HIDDEN
)
@MainThread
public inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> = createViewModelLazy(
VM::class, { requireActivity().viewModelStore },
{ requireActivity().defaultViewModelCreationExtras },
factoryProducer ?: { requireActivity().defaultViewModelProviderFactory }
)
/**
* Returns a property delegate to access parent activity's [ViewModel],
* if [factoryProducer] is specified then [ViewModelProvider.Factory]
* returned by it will be used to create [ViewModel] first time. Otherwise, the activity's
* [androidx.activity.ComponentActivity.getDefaultViewModelProviderFactory](default factory)
* will be used.
*
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by activityViewModels()
* }
* ```
*
* This property can be accessed only after this Fragment is attached i.e., after
* [Fragment.onAttach()], and access prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> = createViewModelLazy(
VM::class, { requireActivity().viewModelStore },
{ extrasProducer?.invoke() ?: requireActivity().defaultViewModelCreationExtras },
factoryProducer ?: { requireActivity().defaultViewModelProviderFactory }
)
/**
* Helper method for creation of [ViewModelLazy], that resolves `null` passed as [factoryProducer]
* to default factory.
*/
@Deprecated(
"Superseded by createViewModelLazy that takes a CreationExtras producer",
level = DeprecationLevel.HIDDEN
)
@MainThread
public fun <VM : ViewModel> Fragment.createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
factoryProducer: (() -> Factory)? = null
): Lazy<VM> = createViewModelLazy(
viewModelClass,
storeProducer,
{ defaultViewModelCreationExtras },
factoryProducer
)
/**
* Helper method for creation of [ViewModelLazy], that resolves `null` passed as [factoryProducer]
* to default factory.
*
* This method also takes an [CreationExtras] produces that provides default extras to the created
* view model.
*/
@MainThread
public fun <VM : ViewModel> Fragment.createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
extrasProducer: () -> CreationExtras = { defaultViewModelCreationExtras },
factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(viewModelClass, storeProducer, factoryPromise, extrasProducer)
}
| apache-2.0 | 23271cde8578c85fbc5a31845e72be6d | 34.914027 | 98 | 0.715006 | 4.724405 | false | false | false | false |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/parsed/ActiveTopicItemParsed.kt | 1 | 1091 | package com.sedsoftware.yaptalker.data.parsed
import pl.droidsonroids.jspoon.annotation.Selector
class ActiveTopicItemParsed {
@Selector(value = "a.subtitle", defValue = "Unknown")
lateinit var title: String
@Selector(value = "a.subtitle", attr = "href", defValue = "")
lateinit var link: String
@Selector(value = "img[src*=pinned]", attr = "src", defValue = "")
lateinit var isPinned: String
@Selector(value = "img[src*=closed]", attr = "src", defValue = "")
lateinit var isClosed: String
@Selector(value = "td[class~=row(2|4)] > a", defValue = "Unknown")
lateinit var forumTitle: String
@Selector(value = "td[class~=row(2|4)] > a", attr = "href", defValue = "")
lateinit var forumLink: String
@Selector(value = "div.rating-short-value", regex = "([-\\d]+)", defValue = "0")
lateinit var rating: String
@Selector(value = "td.row4:matchesOwn(\\d+)", defValue = "0")
lateinit var answers: String
@Selector(value = "span.desc", regex = "([0-9\\.]+ - [0-9:]+)", defValue = "Unknown")
lateinit var lastPostDate: String
}
| apache-2.0 | ff3c074b06c987753b2685b6d6a02b32 | 44.458333 | 89 | 0.643446 | 3.577049 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/input/MoveCursorCommandTest.kt | 3 | 5212 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.input
import androidx.compose.ui.text.TextRange
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
@SmallTest
@RunWith(AndroidJUnit4::class)
class MoveCursorCommandTest {
private val CH1 = "\uD83D\uDE00" // U+1F600
private val CH2 = "\uD83D\uDE01" // U+1F601
private val CH3 = "\uD83D\uDE02" // U+1F602
private val CH4 = "\uD83D\uDE03" // U+1F603
private val CH5 = "\uD83D\uDE04" // U+1F604
// U+1F468 U+200D U+1F469 U+200D U+1F467 U+200D U+1F466
private val FAMILY = "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66"
@Test
fun test_left() {
val eb = EditingBuffer("ABCDE", TextRange(3))
MoveCursorCommand(-1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(2)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_left_multiple() {
val eb = EditingBuffer("ABCDE", TextRange(3))
MoveCursorCommand(-2).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(1)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_left_from_offset0() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
MoveCursorCommand(-1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_right() {
val eb = EditingBuffer("ABCDE", TextRange(3))
MoveCursorCommand(1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(4)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_right_multiple() {
val eb = EditingBuffer("ABCDE", TextRange(3))
MoveCursorCommand(2).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(5)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_right_from_offset_length() {
val eb = EditingBuffer("ABCDE", TextRange(5))
MoveCursorCommand(1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(5)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_left_surrogate_pair() {
val eb = EditingBuffer("$CH1$CH2$CH3$CH4$CH5", TextRange(6))
MoveCursorCommand(-1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$CH1$CH2$CH3$CH4$CH5")
assertThat(eb.cursor).isEqualTo(4)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_left_multiple_surrogate_pair() {
val eb = EditingBuffer("$CH1$CH2$CH3$CH4$CH5", TextRange(6))
MoveCursorCommand(-2).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$CH1$CH2$CH3$CH4$CH5")
assertThat(eb.cursor).isEqualTo(2)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_right_surrogate_pair() {
val eb = EditingBuffer("$CH1$CH2$CH3$CH4$CH5", TextRange(6))
MoveCursorCommand(1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$CH1$CH2$CH3$CH4$CH5")
assertThat(eb.cursor).isEqualTo(8)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_right_multiple_surrogate_pair() {
val eb = EditingBuffer("$CH1$CH2$CH3$CH4$CH5", TextRange(6))
MoveCursorCommand(2).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$CH1$CH2$CH3$CH4$CH5")
assertThat(eb.cursor).isEqualTo(10)
assertThat(eb.hasComposition()).isFalse()
}
@Test
@SdkSuppress(minSdkVersion = 26)
fun test_left_emoji() {
val eb = EditingBuffer("$FAMILY$FAMILY", TextRange(FAMILY.length))
MoveCursorCommand(-1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$FAMILY$FAMILY")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isFalse()
}
@Test
@SdkSuppress(minSdkVersion = 26)
fun test_right_emoji() {
val eb = EditingBuffer("$FAMILY$FAMILY", TextRange(FAMILY.length))
MoveCursorCommand(1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("$FAMILY$FAMILY")
assertThat(eb.cursor).isEqualTo(2 * FAMILY.length)
assertThat(eb.hasComposition()).isFalse()
}
} | apache-2.0 | 111ca17a01cceeef40262cd1c8fd787b | 29.30814 | 93 | 0.653684 | 3.70697 | false | true | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/checker/CheckTimelines.kt | 1 | 4956 | /*
* Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.data.checker
import android.database.Cursor
import org.andstatus.app.data.MyQuery
import org.andstatus.app.database.table.TimelineTable
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.timeline.meta.TimelineSaver
import org.andstatus.app.util.MyLog
import java.util.*
import java.util.function.Consumer
/**
* @author [email protected]
*/
internal class CheckTimelines : DataChecker() {
override fun fixInternal(): Long {
return deleteInvalidTimelines() + addDefaultTimelines() + removeDuplicatedTimelines()
}
private fun deleteInvalidTimelines(): Long {
logger.logProgress("Checking if invalid timelines are present")
val size1 = myContext.timelines.values().size.toLong()
val toDelete: MutableSet<Timeline> = HashSet()
var deletedCount: Long = 0
try {
MyQuery[myContext, "SELECT * FROM " + TimelineTable.TABLE_NAME,
{ cursor: Cursor -> Timeline.fromCursor(myContext, cursor) }]
.forEach(Consumer { timeline: Timeline ->
if (!timeline.isValid()) {
logger.logProgress("Invalid timeline: $timeline")
pauseToShowCount(this, 0)
toDelete.add(timeline)
}
})
deletedCount = toDelete.size.toLong()
if (!countOnly) {
toDelete.forEach(Consumer { timeline: Timeline -> myContext.timelines.delete(timeline) })
}
} catch (e: Exception) {
val logMsg = "Error: " + e.message
logger.logProgress(logMsg)
pauseToShowCount(this, 1)
MyLog.e(this, logMsg, e)
}
myContext.timelines.saveChanged()
logger.logProgress(if (deletedCount == 0L) "No invalid timelines found"
else (if (countOnly) "To delete " else "Deleted ") + deletedCount + " invalid timelines. Valid timelines: " + size1)
pauseToShowCount(this, deletedCount)
return deletedCount
}
private fun addDefaultTimelines(): Long {
logger.logProgress("Checking if all default timelines are present")
val size1 = myContext.timelines.values().size.toLong()
try {
TimelineSaver().addDefaultCombined(myContext)
for (myAccount in myContext.accounts.get()) {
TimelineSaver().addDefaultForMyAccount(myContext, myAccount)
}
} catch (e: Exception) {
val logMsg = "Error: " + e.message
logger.logProgress(logMsg)
MyLog.e(this, logMsg, e)
}
myContext.timelines.saveChanged()
val size2 = myContext.timelines.values().size
val addedCount = size2 - size1
logger.logProgress(if (addedCount == 0L) "No new timelines were added. $size2 timelines" else "Added $addedCount of $size2 timelines")
pauseToShowCount(this, addedCount)
return addedCount
}
private fun removeDuplicatedTimelines(): Long {
logger.logProgress("Checking if duplicated timelines are present")
val size1 = myContext.timelines.values().size.toLong()
val toDelete: MutableSet<Timeline> = HashSet()
try {
for (timeline1 in myContext.timelines.values()) {
for (timeline2 in myContext.timelines.values()) {
if (timeline2.duplicates(timeline1)) toDelete.add(timeline2)
}
}
if (!countOnly) {
toDelete.forEach(Consumer { timeline: Timeline -> myContext.timelines.delete(timeline) })
}
} catch (e: Exception) {
val logMsg = "Error: " + e.message
logger.logProgress(logMsg)
MyLog.e(this, logMsg, e)
}
myContext.timelines.saveChanged()
val size2 = myContext.timelines.values().size
val deletedCount = if (countOnly) toDelete.size else size1 - size2
logger.logProgress(
if (deletedCount == 0L) "No duplicated timelines found. $size2 timelines"
else (if (countOnly) "To delete " else "Deleted ") + deletedCount +
" duplicates of " + size1 + " timelines"
)
pauseToShowCount(this, deletedCount)
return deletedCount.toLong()
}
}
| apache-2.0 | 0ef5fe2f1f348d454d827697fee5f384 | 41.358974 | 142 | 0.628128 | 4.513661 | false | false | false | false |
why168/AndroidProjects | KotlinLearning/app/src/main/java/com/github/why168/kotlinlearn/api/RxSubscriber.kt | 1 | 2662 | package com.github.why168.kotlinlearn.api
import android.text.TextUtils
import com.github.why168.kotlinlearn.Constants
import com.github.why168.kotlinlearn.event.TokenEvent
import io.reactivex.subscribers.DefaultSubscriber
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
/**
* RxSubscriber
*
* @author Edwin.Wu
* @version 2018/2/23 下午3:30
* @since JDK1.8
*/
public abstract class RxSubscriber<T : HttpResult<*>> : DefaultSubscriber<T>() {
override fun onComplete() {
// DialogHelper.stopProgressDlg()
}
override fun onError(e: Throwable) {
e.printStackTrace()
// DialogHelper.stopProgressDlg()
val errorMsg: String
if (e is SocketTimeoutException
|| e is ConnectException
|| e is UnknownHostException) {
errorMsg = Constants.ERROR_NETWORK_2
} else if (e is HttpException) {
val code = e.code()
when (code) {
401 -> {
}
403 -> {
}
404 -> {
}
405 -> {
}
500 -> {
}
}
errorMsg = e.message!!
} else {
errorMsg = e.message!!
}
onFailure(errorMsg)
}
override fun onNext(t: T) {
var msg = t.msg
if (TextUtils.isEmpty(msg))
msg = "请求失败"
when (t.status) {
Constants.HTTP_STATUS_0// 成功
-> onResponse(t)
Constants.HTTP_STATUS_1// 验证签名超时
-> onFailure(msg)
Constants.HTTP_STATUS_2// 验证签名失败
-> onFailure(msg)
Constants.HTTP_STATUS_3// 请求错误
-> onFailure(msg)
Constants.HTTP_STATUS_4// token过期
-> EventBus.getDefault().post(TokenEvent.OUT_DATA)
Constants.HTTP_STATUS_5// 登录失败
-> onFailure(msg)
Constants.HTTP_STATUS_6// 验证码发送失败
-> onFailure(msg)
Constants.HTTP_STATUS_7// 验证码发送过于频繁,1分钟同一个手机只能发一次
-> onFailure(msg)
Constants.HTTP_STATUS_8// 参数参数验证不通过
-> onFailure(msg)
Constants.HTTP_STATUS_9// 发现在其他设备登录
-> EventBus.getDefault().post(TokenEvent.OTHER_DEVICE)
}
}
abstract fun onResponse(t: T)
abstract fun onFailure(msg: String?)
} | mit | 8ec915cb06809c767d02f291edde1b0e | 28.197674 | 80 | 0.55259 | 4.14876 | false | false | false | false |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/activity/MainActivity.kt | 1 | 17656 | package org.xdty.callerinfo.activity
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog.Builder
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Canvas
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.OnClickListener
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.SearchView.OnQueryTextListener
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.MenuItemCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.Theme
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.Callback
import org.xdty.callerinfo.R
import org.xdty.callerinfo.application.Application
import org.xdty.callerinfo.contract.MainContract
import org.xdty.callerinfo.di.DaggerMainComponent
import org.xdty.callerinfo.di.modules.AppModule
import org.xdty.callerinfo.di.modules.MainModule
import org.xdty.callerinfo.fragment.MainBottomSheetFragment
import org.xdty.callerinfo.model.db.Caller
import org.xdty.callerinfo.model.db.InCall
import org.xdty.callerinfo.model.permission.Permission
import org.xdty.callerinfo.model.setting.Setting
import org.xdty.callerinfo.service.FloatWindow
import org.xdty.callerinfo.utils.Window
import org.xdty.callerinfo.view.CallerAdapter
import org.xdty.phone.number.model.INumber
import org.xdty.phone.number.model.caller.Status
import javax.inject.Inject
class MainActivity : BaseActivity(), MainContract.View {
@Inject
internal lateinit var mPresenter: MainContract.Presenter
@Inject
internal lateinit var mPermission: Permission
@Inject
internal lateinit var mSetting: Setting
@Inject
internal lateinit var mWindow: Window
private lateinit var mToolbar: Toolbar
private var mScreenWidth = 0
private lateinit var mEmptyText: TextView
private lateinit var mRecyclerView: RecyclerView
private lateinit var mCallerAdapter: CallerAdapter
private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
private lateinit var mMainLayout: FrameLayout
private var mLastSearchTime: Long = 0
private var mUpdateDataDialog: MaterialDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerMainComponent.builder()
.appModule(AppModule(Application.application))
.mainModule(MainModule(this))
.build()
.inject(this)
mToolbar = findViewById(R.id.toolbar)
setSupportActionBar(mToolbar)
mPresenter.checkEula()
mScreenWidth = mSetting.screenWidth
mMainLayout = findViewById(R.id.main_layout)
mEmptyText = findViewById(R.id.empty_text)
mRecyclerView = findViewById(R.id.history_list)
mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout)
val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
mRecyclerView.layoutManager = layoutManager
mCallerAdapter = CallerAdapter(mPresenter)
mRecyclerView.adapter = mCallerAdapter
mRecyclerView.addOnScrollListener(object : OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> mPresenter.invalidateDataUpdate(false)
RecyclerView.SCROLL_STATE_DRAGGING,
RecyclerView.SCROLL_STATE_SETTLING -> mPresenter.invalidateDataUpdate(true)
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
// can scroll up and disable refresh
mSwipeRefreshLayout.isEnabled = !recyclerView.canScrollVertically(-1)
}
})
val itemTouchHelper = ItemTouchHelper(object : SimpleCallback(0,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: ViewHolder,
target: ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: ViewHolder, direction: Int) {
val inCall = mCallerAdapter.getItem(viewHolder.adapterPosition)
mPresenter.removeInCallFromList(inCall)
mCallerAdapter.notifyDataSetChanged()
val snackbar = Snackbar.make(mToolbar, R.string.deleted,
Snackbar.LENGTH_LONG)
snackbar.setAction(getString(R.string.undo)) {
snackbar.dismiss()
mPresenter.loadInCallList()
}
snackbar.setCallback(object : Callback() {
@SuppressLint("SwitchIntDef")
override fun onDismissed(snackbar: Snackbar, event: Int) {
when (event) {
DISMISS_EVENT_MANUAL,
DISMISS_EVENT_ACTION -> {
}
DISMISS_EVENT_CONSECUTIVE,
DISMISS_EVENT_SWIPE,
DISMISS_EVENT_TIMEOUT -> mPresenter.removeInCall(inCall)
else -> mPresenter.removeInCall(inCall)
}
super.onDismissed(snackbar, event)
}
})
snackbar.show()
}
override fun onSelectedChanged(viewHolder: ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
val swiping = actionState == ItemTouchHelper.ACTION_STATE_SWIPE
mSwipeRefreshLayout.isEnabled = !swiping
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView,
viewHolder: ViewHolder,
dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState,
isCurrentlyActive)
(viewHolder as CallerAdapter.ViewHolder).setAlpha(1 - Math.abs(dX) / mScreenWidth * 1.2f)
}
})
itemTouchHelper.attachToRecyclerView(mRecyclerView)
mSwipeRefreshLayout.setOnRefreshListener { mPresenter.loadCallerMap() }
}
override val layoutId: Int
get() = R.layout.activity_main
override val titleId: Int
get() = R.string.app_name
override fun onResume() {
super.onResume()
mPresenter.start()
}
@SuppressLint("InlinedApi")
override fun onStart() {
super.onStart()
if (!mPresenter.canDrawOverlays()) {
mPermission.requestDrawOverlays(this, REQUEST_CODE_OVERLAY_PERMISSION)
}
var res = mPresenter.checkPermission(Manifest.permission.READ_PHONE_STATE)
if (res != PackageManager.PERMISSION_GRANTED) {
mPermission.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE),
REQUEST_CODE_ASK_PERMISSIONS)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
res = mPresenter.checkPermission(Manifest.permission.READ_CALL_LOG)
if (res != PackageManager.PERMISSION_GRANTED) {
mPermission.requestPermissions(this, arrayOf(Manifest.permission.READ_CALL_LOG),
REQUEST_CODE_ASK_CALL_LOG_PERMISSIONS)
}
}
}
override fun onStop() {
if (FloatWindow.status() != FloatWindow.STATUS_CLOSE) { // FixME: window in other ui may close because async
mWindow.closeWindow()
}
mPresenter.clearSearch()
if (mUpdateDataDialog != null && mUpdateDataDialog?.isShowing!!) {
mUpdateDataDialog?.cancel()
}
super.onStop()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_OVERLAY_PERMISSION) {
if (!mPresenter.canDrawOverlays()) {
Log.e(TAG, "SYSTEM_ALERT_WINDOW permission not granted...")
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onBackPressed() {
if (FloatWindow.status() != FloatWindow.STATUS_CLOSE) {
mWindow.closeWindow()
} else {
super.onBackPressed()
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_CODE_ASK_PERMISSIONS, REQUEST_CODE_ASK_CALL_LOG_PERMISSIONS -> {
if (grantResults.isEmpty()) {
Log.e(TAG, "grantResults is empty!")
return
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this@MainActivity, "Permission Denied", Toast.LENGTH_SHORT)
.show()
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val floatWindowMenu = menu.findItem(R.id.action_float_window)
if (FloatWindow.status() != FloatWindow.STATUS_CLOSE) {
floatWindowMenu.setTitle(R.string.close_window)
} else {
floatWindowMenu.setTitle(R.string.action_float_window)
}
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
val searchView = MenuItemCompat.getActionView(
menu.findItem(R.id.action_search)) as SearchView
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.maxWidth = mScreenWidth
searchView.inputType = InputType.TYPE_CLASS_PHONE
searchView.queryHint = getString(R.string.search_hint)
searchView.setOnQueryTextListener(object : OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
Log.d(TAG, "onQueryTextSubmit: $query")
if (System.currentTimeMillis() - mLastSearchTime > 1000) {
mPresenter.search(query)
mRecyclerView.visibility = View.INVISIBLE
mMainLayout.setBackgroundColor(ContextCompat.getColor(this@MainActivity,
R.color.dark))
mLastSearchTime = System.currentTimeMillis()
}
return false
}
override fun onQueryTextChange(newText: String): Boolean {
mWindow.closeWindow()
mRecyclerView.visibility = View.VISIBLE
mMainLayout.setBackgroundColor(ContextCompat.getColor(this@MainActivity,
R.color.transparent))
return false
}
})
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
R.id.action_settings -> startActivity(Intent(this, SettingsActivity::class.java))
R.id.action_float_window -> if (FloatWindow.status() == FloatWindow.STATUS_CLOSE) {
mWindow.showTextWindow(R.string.float_window_hint, Window.Type.POSITION)
} else {
mWindow.closeWindow()
}
R.id.action_clear_history -> clearHistory()
R.id.action_clear_cache -> clearCache()
}
return true
}
private fun clearHistory() {
val builder = Builder(this)
builder.setTitle(getString(R.string.action_clear_history))
builder.setMessage(getString(R.string.clear_history_message))
builder.setCancelable(true)
builder.setPositiveButton(getString(R.string.ok)) { _, _ -> mPresenter.clearAll() }
builder.setNegativeButton(getString(R.string.cancel), null)
builder.show()
}
private fun clearCache() {
val builder = Builder(this)
builder.setTitle(getString(R.string.action_clear_cache))
builder.setMessage(getString(R.string.clear_cache_confirm_message))
builder.setCancelable(true)
builder.setPositiveButton(getString(R.string.ok)) { _, _ ->
mPresenter.clearCache()
Snackbar.make(mToolbar, R.string.clear_cache_message, Snackbar.LENGTH_LONG)
.setAction(getString(R.string.ok), null)
.show()
}
builder.setNegativeButton(getString(R.string.cancel), null)
builder.show()
}
override fun showNoCallLog(show: Boolean) {
mEmptyText.visibility = if (show) View.VISIBLE else View.GONE
}
override fun showLoading(active: Boolean) {
mSwipeRefreshLayout.isRefreshing = active
}
override fun showCallLogs(inCalls: List<InCall>) {
mCallerAdapter.replaceData(inCalls)
}
override fun showEula() {
val builder = Builder(this)
builder.setTitle(getString(R.string.eula_title))
builder.setMessage(getString(R.string.eula_message))
builder.setCancelable(false)
builder.setPositiveButton(getString(R.string.agree)) { _, _ -> mPresenter.setEula() }
builder.setNegativeButton(getString(R.string.disagree)) { _, _ -> finish() }
builder.show()
}
override fun showSearchResult(number: INumber) {
Log.d(TAG, "showSearchResult: " + number.number)
mWindow.showWindow(number, Window.Type.SEARCH)
}
override fun showSearching() {
Log.d(TAG, "showSearching")
mWindow.showTextWindow(R.string.searching, Window.Type.SEARCH)
}
override fun showSearchFailed(isOnline: Boolean) {
Log.d(TAG, "showSearchFailed: isOnline=$isOnline")
if (isOnline) {
mWindow.sendData(FloatWindow.WINDOW_ERROR, R.string.online_failed, Window.Type.SEARCH)
} else {
mWindow.showTextWindow(R.string.offline_failed, Window.Type.SEARCH)
}
}
override val context: Context
get() = this.applicationContext
override fun notifyUpdateData(status: Status) {
val snackbar = Snackbar.make(mToolbar, R.string.new_offline_data,
Snackbar.LENGTH_INDEFINITE)
snackbar.setAction(getString(R.string.update), object : OnClickListener {
override fun onClick(v: View) {
snackbar.dismiss()
mPresenter.dispatchUpdate(status)
}
})
snackbar.show()
}
override fun showUpdateData(status: Status) {
if (mUpdateDataDialog != null && mUpdateDataDialog?.isShowing!!) {
mUpdateDataDialog?.dismiss()
mUpdateDataDialog = null
}
mUpdateDataDialog = MaterialDialog.Builder(this)
.cancelable(true)
.theme(Theme.LIGHT)
.title(R.string.offline_data_update)
.content(getString(R.string.offline_data_status))
.progress(true, 0).build()
mUpdateDataDialog?.show()
}
override fun updateDataFinished(result: Boolean) {
if (mUpdateDataDialog != null && mUpdateDataDialog?.isShowing!!) {
mUpdateDataDialog?.dismiss()
}
val message = if (result) R.string.offline_data_success else R.string.offline_data_failed
val snackbar = Snackbar.make(mToolbar, message, Snackbar.LENGTH_LONG)
snackbar.setAction(getString(R.string.ok), object : OnClickListener {
override fun onClick(v: View) {
snackbar.dismiss()
}
})
snackbar.show()
}
override fun showBottomSheet(inCall: InCall) { // show bottom sheet dialog
MainBottomSheetFragment.newInstance(inCall).show(supportFragmentManager, "dialog")
}
override fun attachCallerMap(callerMap: Map<String, Caller>) {
mPresenter.loadInCallList()
}
override fun setPresenter(presenter: MainContract.Presenter) {
mPresenter = presenter
}
companion object {
const val REQUEST_CODE_OVERLAY_PERMISSION = 1001
const val REQUEST_CODE_ASK_PERMISSIONS = 1002
const val REQUEST_CODE_ASK_CALL_LOG_PERMISSIONS = 1003
private val TAG = MainActivity::class.java.simpleName
}
} | gpl-3.0 | e8d9f4abcba52873e9b02129d742d265 | 40.448357 | 116 | 0.642218 | 4.983347 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/lang/validation/XpmSyntaxValidator.kt | 1 | 2145 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpm.lang.validation
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionPointName
import org.jetbrains.annotations.TestOnly
import uk.co.reecedunn.intellij.plugin.core.extensions.PluginDescriptorProvider
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtension
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtensionPointBean
interface XpmSyntaxValidator {
companion object {
val EP_NAME: ExtensionPointName<XpmSyntaxValidatorBean> = ExtensionPointName.create(
"uk.co.reecedunn.intellij.syntaxValidator"
)
val validators: Sequence<XpmSyntaxValidator>
get() = EP_NAME.extensionList.asSequence().map { it.getInstance() }
@TestOnly
@Suppress("UsePropertyAccessSyntax")
fun register(plugin: PluginDescriptorProvider, factory: XpmSyntaxValidator, fieldName: String = "INSTANCE") {
val bean = XpmSyntaxValidatorBean()
bean.implementationClass = factory.javaClass.name
bean.fieldName = fieldName
bean.setPluginDescriptor(plugin.pluginDescriptor)
val app = ApplicationManager.getApplication()
app.registerExtensionPointBean(EP_NAME, XpmSyntaxValidatorBean::class.java, plugin.pluginDisposable)
app.registerExtension(EP_NAME, bean, plugin.pluginDisposable)
}
}
fun validate(element: XpmSyntaxValidationElement, reporter: XpmSyntaxErrorReporter)
}
| apache-2.0 | 48c85ed123ae4cf97950034f680571b6 | 42.77551 | 117 | 0.744988 | 4.875 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/social/AchievementProfileAdapter.kt | 1 | 3211 | package com.habitrpg.android.habitica.ui.adapter.social
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ProfileAchievementItemBinding
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.Achievement
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.android.habitica.ui.viewHolders.SectionViewHolder
import com.habitrpg.android.habitica.ui.views.dialogs.AchievementDetailDialog
class AchievementProfileAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var itemType: String? = null
var activity: MainActivity? = null
private var itemList: List<Any> = emptyList()
fun setItemList(itemList: List<Any>) {
this.itemList = itemList
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 0) {
SectionViewHolder(parent.inflate(R.layout.profile_achievement_category))
} else {
AchievementViewHolder(parent.inflate(R.layout.profile_achievement_item))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val obj = this.itemList[position]
if (obj.javaClass == String::class.java) {
(holder as? SectionViewHolder)?.bind(obj as String)
} else {
(holder as? AchievementViewHolder)?.bind(itemList[position] as Achievement)
}
}
override fun getItemViewType(position: Int): Int {
if (itemList.size <= position) return 0
return if (this.itemList[position].javaClass == String::class.java) {
0
} else {
1
}
}
override fun getItemCount(): Int {
return itemList.size
}
internal class AchievementViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = ProfileAchievementItemBinding.bind(itemView)
private var achievement: Achievement? = null
init {
itemView.isClickable = true
itemView.setOnClickListener(this)
}
fun bind(item: Achievement) {
binding.achievementDrawee.loadImage((if (!item.earned) "achievement-unearned" else item.icon) + "2x")
this.achievement = item
binding.achievementText.text = item.title
if (item.optionalCount == null || item.optionalCount == 0) {
binding.achievementCountLabel.visibility = View.GONE
} else {
binding.achievementCountLabel.visibility = View.VISIBLE
binding.achievementCountLabel.text = item.optionalCount.toString()
}
}
override fun onClick(view: View) {
achievement?.let {
AchievementDetailDialog(it, itemView.context).show()
}
}
}
}
| gpl-3.0 | 0f40405c9cd8b3bce0428981c04e7678 | 35.776471 | 116 | 0.656493 | 4.806886 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsMainController.kt | 1 | 3023 | package eu.kanade.tachiyomi.ui.setting
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.util.getResourceColor
class SettingsMainController : SettingsController() {
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.label_settings
val tintColor = context.getResourceColor(R.attr.colorAccent)
preference {
iconRes = R.drawable.ic_tune_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_general
onClick { navigateTo(SettingsGeneralController()) }
}
preference {
iconRes = R.drawable.ic_chrome_reader_mode_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_reader
onClick { navigateTo(SettingsReaderController()) }
}
preference {
iconRes = R.drawable.ic_file_download_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_downloads
onClick { navigateTo(SettingsDownloadController()) }
}
preference {
iconRes = R.drawable.ic_sync_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_tracking
onClick { navigateTo(SettingsTrackingController()) }
}
preference {
iconRes = R.drawable.ic_backup_black_24dp
iconTint = tintColor
titleRes = R.string.backup
onClick { navigateTo(SettingsBackupController()) }
}
preference {
iconRes = R.drawable.eh_ic_ehlogo_red_24dp
iconTint = tintColor
titleRes = R.string.pref_category_eh
onClick { navigateTo(SettingsEhController()) }
}
preference {
iconRes = R.drawable.eh_ic_nhlogo_color
iconTint = tintColor
titleRes = R.string.pref_category_nh
onClick { navigateTo(SettingsNhController()) }
}
preference {
iconRes = R.drawable.eh_ic_hllogo
iconTint = tintColor
titleRes = R.string.pref_category_hl
onClick { navigateTo(SettingsHlController()) }
}
preference {
iconRes = R.drawable.ic_code_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_advanced
onClick { navigateTo(SettingsAdvancedController()) }
}
preference {
iconRes = R.drawable.ic_help_black_24dp
iconTint = tintColor
titleRes = R.string.pref_category_about
onClick { navigateTo(SettingsAboutController()) }
}
}
private fun navigateTo(controller: SettingsController) {
router.pushController(controller.withFadeTransaction())
}
} | apache-2.0 | 1d86fff494059ac182ede6d4d7d26477 | 36.291139 | 81 | 0.597751 | 4.915447 | false | false | false | false |
deltaDNA/android-sdk | library/src/test/java/com/deltadna/android/sdk/net/RequestTest.kt | 1 | 4120 | /*
* Copyright (c) 2016 deltaDNA Ltd. 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
*
* 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.deltadna.android.sdk.net
import com.google.common.truth.Truth.assertThat
import com.squareup.okhttp.mockwebserver.MockResponse
import com.squareup.okhttp.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.net.ConnectException
@RunWith(JUnit4::class)
class RequestTest {
private var server: MockWebServer? = null
@Before
fun before() {
server = MockWebServer()
server!!.start()
}
@After
fun after() {
server!!.shutdown()
server = null
}
@Test(expected = IllegalArgumentException::class)
fun malformedUrl() {
Request.Builder<Void>().url("fail")
}
@Test
fun get() {
server!!.enqueue(MockResponse().setResponseCode(200))
val response = Request.Builder<Void>()
.get()
.url(server!!.url("/get").toString())
.build()
.call()
with(server!!.takeRequest()) {
assertThat(method).isEqualTo("GET")
assertThat(path).isEqualTo("/get")
assertThat(bodySize).isEqualTo(0)
}
assertThat(response).isEqualTo(Response(
200,
false,
byteArrayOf(),
null,
null))
}
@Test
fun post() {
val responseBody = "response"
server!!.enqueue(MockResponse()
.setResponseCode(200)
.setBody(responseBody)
.addHeader("Content-Type", "text/plain"))
val response = Request.Builder<String>()
.post(RequestBody("text/plain", "request".toByteArray()))
.header("Accept", "text/plain")
.url(server!!.url("/post").toString())
.build()
.setConverter(ResponseBodyConverter.STRING)
.call()
with(server!!.takeRequest()) {
assertThat(method).isEqualTo("POST")
assertThat(path).isEqualTo("/post")
assertThat(body.readUtf8()).isEqualTo("request")
assertThat(getHeader("Content-Type")).isEqualTo("text/plain")
assertThat(getHeader("Accept")).isEqualTo("text/plain")
}
assertThat(response).isEqualTo(Response(
200,
false,
responseBody.toByteArray(),
responseBody,
null))
}
@Test
fun httpError() {
val responseBody = "not found"
server!!.enqueue(MockResponse()
.setResponseCode(404)
.setBody(responseBody))
val response = Request.Builder<Void>()
.get()
.url(server!!.url("/fail").toString())
.build()
.call()
server!!.takeRequest()
assertThat(response).isEqualTo(Response<Void>(
404,
false,
responseBody.toByteArray(),
null,
responseBody))
}
@Test(expected = ConnectException::class)
fun failure() {
server!!.shutdown()
Request.Builder<Void>()
.get()
.url(server!!.url("/fail").toString())
.build()
.call()
}
}
| apache-2.0 | 3c3e239b8e572a329b74d858b5960afa | 28.428571 | 75 | 0.543204 | 5.01827 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/bean/info/TrendingResults.kt | 1 | 1737 | package com.gkzxhn.mygithub.bean.info
import android.os.Parcel
import android.os.Parcelable
/**
* Created by 方 on 2017/11/9.
*/
data class TrendingResults(
val count: Int, //3
val items: List<ItemBean>,
val msg: String //suc
)
data class Items(
val count: Int, //25
val items: List<ItemBean>,
val msg: String //done
)
data class
ItemBean(
val added_stars: String, //124 stars today
val avatars: List<String>,
val desc: String, //A secret manager for AWS
val forks: String, //7
val lang: String, //Java
val repo: String, //schibsted/strongbox
val repo_link: String, //https://github.com/schibsted/strongbox
val stars: String //134
) : Parcelable {
constructor(source: Parcel) : this(
source.readString(),
source.createStringArrayList(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(added_stars)
writeStringList(avatars)
writeString(desc)
writeString(forks)
writeString(lang)
writeString(repo)
writeString(repo_link)
writeString(stars)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<ItemBean> = object : Parcelable.Creator<ItemBean> {
override fun createFromParcel(source: Parcel): ItemBean = ItemBean(source)
override fun newArray(size: Int): Array<ItemBean?> = arrayOfNulls(size)
}
}
}
| gpl-3.0 | d8199beb8524d23892b4cbff96664b3f | 25.692308 | 91 | 0.610951 | 4.273399 | false | true | false | false |
Sulion/marco-paolo | src/main/kotlin/org/logout/notifications/telegram/bot/commands/StaImaGetNextEventCommand.kt | 1 | 1187 | package org.logout.notifications.telegram.bot.commands
import org.logout.notifications.telegram.bot.processor.StaImaNextEventProcessor
import org.telegram.telegrambots.api.methods.send.SendMessage
import org.telegram.telegrambots.api.objects.Chat
import org.telegram.telegrambots.api.objects.User
import org.telegram.telegrambots.bots.AbsSender
import org.telegram.telegrambots.bots.commands.BotCommand
import org.telegram.telegrambots.exceptions.TelegramApiException
import org.telegram.telegrambots.logging.BotLogger
val COMMAND_NAME = "staima"
val COMMAND_DESCRIPTION = """Gets the next event
""".trimIndent()
val LOGTAG = "STAIMACOMMAND"
class StaImaGetNextEventCommand(val processor: StaImaNextEventProcessor) : BotCommand(COMMAND_NAME, COMMAND_DESCRIPTION) {
override fun execute(absSender: AbsSender, user: User?, chat: Chat, arguments: Array<String>?) {
try {
absSender.sendMessage(SendMessage().apply {
chatId = chat.id.toString()
text = processor.onMessage(arguments).joinToString(separator = "\n")
})
} catch (e: TelegramApiException) {
BotLogger.error(LOGTAG, e)
}
}
} | apache-2.0 | 0f21233a63ea90e50046478e5ac185b3 | 36.125 | 122 | 0.74305 | 3.996633 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt | 1 | 4645 | package eu.kanade.tachiyomi.extension.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.LoadResult
import eu.kanade.tachiyomi.util.lang.launchNow
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import logcat.LogPriority
/**
* Broadcast receiver that listens for the system's packages installed, updated or removed, and only
* notifies the given [listener] when the package is an extension.
*
* @param listener The listener that should be notified of extension installation events.
*/
internal class ExtensionInstallReceiver(private val listener: Listener) :
BroadcastReceiver() {
/**
* Registers this broadcast receiver
*/
fun register(context: Context) {
context.registerReceiver(this, filter)
}
/**
* Returns the intent filter this receiver should subscribe to.
*/
private val filter
get() = IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package")
}
/**
* Called when one of the events of the [filter] is received. When the package is an extension,
* it's loaded in background and it notifies the [listener] when finished.
*/
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null) return
when (intent.action) {
Intent.ACTION_PACKAGE_ADDED -> {
if (!isReplacing(intent)) {
launchNow {
when (val result = getExtensionFromIntent(context, intent)) {
is LoadResult.Success -> listener.onExtensionInstalled(result.extension)
is LoadResult.Untrusted -> listener.onExtensionUntrusted(result.extension)
else -> {}
}
}
}
}
Intent.ACTION_PACKAGE_REPLACED -> {
launchNow {
when (val result = getExtensionFromIntent(context, intent)) {
is LoadResult.Success -> listener.onExtensionUpdated(result.extension)
// Not needed as a package can't be upgraded if the signature is different
// is LoadResult.Untrusted -> {}
else -> {}
}
}
}
Intent.ACTION_PACKAGE_REMOVED -> {
if (!isReplacing(intent)) {
val pkgName = getPackageNameFromIntent(intent)
if (pkgName != null) {
listener.onPackageUninstalled(pkgName)
}
}
}
}
}
/**
* Returns true if this package is performing an update.
*
* @param intent The intent that triggered the event.
*/
private fun isReplacing(intent: Intent): Boolean {
return intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)
}
/**
* Returns the extension triggered by the given intent.
*
* @param context The application context.
* @param intent The intent containing the package name of the extension.
*/
private suspend fun getExtensionFromIntent(context: Context, intent: Intent?): LoadResult {
val pkgName = getPackageNameFromIntent(intent)
if (pkgName == null) {
logcat(LogPriority.WARN) { "Package name not found" }
return LoadResult.Error
}
return GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) { ExtensionLoader.loadExtensionFromPkgName(context, pkgName) }.await()
}
/**
* Returns the package name of the installed, updated or removed application.
*/
private fun getPackageNameFromIntent(intent: Intent?): String? {
return intent?.data?.encodedSchemeSpecificPart ?: return null
}
/**
* Listener that receives extension installation events.
*/
interface Listener {
fun onExtensionInstalled(extension: Extension.Installed)
fun onExtensionUpdated(extension: Extension.Installed)
fun onExtensionUntrusted(extension: Extension.Untrusted)
fun onPackageUninstalled(pkgName: String)
}
}
| apache-2.0 | 2e78b5a8f2588e7c9f3233d3b829423b | 36.459677 | 148 | 0.624973 | 5.219101 | false | false | false | false |
zlyne0/colonization | core/src/net/sf/freecol/common/model/ai/missions/PlayerMissionsContainer.kt | 1 | 2792 | package net.sf.freecol.common.model.ai.missions
fun PlayerMissionsContainer.hasMission(missionId: String): Boolean {
return missions.containsId(missionId)
}
@Suppress("UNCHECKED_CAST")
inline fun <T : AbstractMission> PlayerMissionsContainer.hasMissionKt(
missionClass: Class<T>,
predicate: (T) -> Boolean
): Boolean {
for (playerMission in this.missions.entities()) {
if (playerMission.`is`(missionClass) && predicate(playerMission as T)) {
return true
}
}
return false
}
@Suppress("UNCHECKED_CAST")
inline fun <T : AbstractMission> PlayerMissionsContainer.foreachMission(
missionClass: Class<T>,
consumer: (T) -> Unit
) {
for (playerMission in this.missions.entities()) {
if (playerMission.`is`(missionClass)) {
consumer(playerMission as T)
}
}
}
@Suppress("UNCHECKED_CAST")
inline fun <T : AbstractMission> PlayerMissionsContainer.findMissions(
missionClass: Class<T>,
predicate: (T) -> Boolean
): List<T> {
var result : MutableList<T>? = null
for (playerMission in this.missions.entities()) {
if (playerMission.`is`(missionClass) && predicate(playerMission as T)) {
if (result == null) {
result = mutableListOf<T>()
}
result.add(playerMission)
}
}
if (result == null) {
return emptyList()
}
return result
}
fun PlayerMissionsContainer.findDeepDependMissions(mission: AbstractMission): List<AbstractMission> {
val result: MutableList<AbstractMission> = mutableListOf()
val buf: MutableList<AbstractMission> = mutableListOf(mission)
while (buf.isNotEmpty()) {
val m = buf.removeAt(0)
if (m.notEqualsId(mission)) {
result.add(m)
}
for (dependMissionId in m.dependMissions2) {
val dependMission = this.missions.getByIdOrNull(dependMissionId)
if (dependMission != null) {
buf.add(dependMission)
}
}
}
return result
}
fun PlayerMissionsContainer.findMissionToExecute(parentMission: AbstractMission): List<AbstractMission> {
val dependMissions = findDeepDependMissions(parentMission)
if (dependMissions.isEmpty()) {
return emptyList()
}
var result = mutableListOf<AbstractMission>()
for (dependMission in dependMissions) {
if (dependMission.hasDependMission() || dependMission.isDone) {
continue
}
result.add(dependMission)
}
return result
}
fun PlayerMissionsContainer.findParentMission(childMission: AbstractMission): AbstractMission? {
if (childMission.parentMissionId == null) {
return null
}
return this.missions.getByIdOrNull(childMission.parentMissionId)
}
| gpl-2.0 | a9d2b658477479cd9d1868f6c9b1a4c7 | 28.702128 | 105 | 0.655086 | 4.282209 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt | 1 | 3400 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.content.Context
import android.graphics.Typeface
import android.text.format.DateFormat
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.interfaces.ResourceHelper
import java.util.*
class InputTime(private val rh: ResourceHelper, private val dateUtil: DateUtil) : Element() {
var value: Int = getMinSinceMidnight(dateUtil.now())
override fun addToLayout(root: LinearLayout) {
root.addView(
LinearLayout(root.context).apply {
orientation = LinearLayout.HORIZONTAL
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addView(
TextView(root.context).apply {
text = rh.gs(R.string.atspecifiedtime, "")
setTypeface(typeface, Typeface.BOLD)
})
addView(
TextView(root.context).apply {
text = dateUtil.timeString(toMills(value))
val px = rh.dpToPx(10)
setPadding(px, px, px, px)
setOnClickListener {
getFragmentManager(root.context)?.let { fm ->
val cal = Calendar.getInstance().apply { timeInMillis = toMills(value) }
val clockFormat = if (DateFormat.is24HourFormat(context)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H
val timePicker = MaterialTimePicker.Builder()
.setTimeFormat(clockFormat)
.setHour(cal.get(Calendar.HOUR_OF_DAY))
.setMinute(cal.get(Calendar.MINUTE))
.build()
timePicker.addOnPositiveButtonClickListener {
value = 60 * timePicker.hour + timePicker.minute
text = dateUtil.timeString(toMills(value))
}
timePicker.show(fm, "input_time_picker")
}
}
})
})
}
private fun toMills(minutesSinceMidnight: Int): Long = MidnightTime.calcPlusMinutes(minutesSinceMidnight)
private fun getMinSinceMidnight(time: Long): Int = Profile.secondsFromMidnight(time) / 60
private fun getFragmentManager(context: Context?): FragmentManager? {
return when (context) {
is AppCompatActivity -> context.supportFragmentManager
is ContextThemeWrapper -> getFragmentManager(context.baseContext)
else -> null
}
}
}
| agpl-3.0 | ae1bd9c899be17d9a0a77a8d6ec594d1 | 46.887324 | 136 | 0.598824 | 5.592105 | false | false | false | false |
redutan/nbase-arc-monitoring | src/main/kotlin/io/redutan/nbasearc/monitoring/Application.kt | 1 | 3306 | package io.redutan.nbasearc.monitoring
import io.redutan.nbasearc.monitoring.collector.ArcCliLogPublisherFactory
import io.redutan.nbasearc.monitoring.collector.ClusterId
import io.redutan.nbasearc.monitoring.collector.LatencyType
import io.redutan.nbasearc.monitoring.collector.StatType
import kotlinx.coroutines.experimental.channels.consumeEach
import org.jetbrains.ktor.application.Application
import org.jetbrains.ktor.application.ApplicationCallPipeline
import org.jetbrains.ktor.application.call
import org.jetbrains.ktor.application.install
import org.jetbrains.ktor.content.defaultResource
import org.jetbrains.ktor.content.resources
import org.jetbrains.ktor.content.static
import org.jetbrains.ktor.features.DefaultHeaders
import org.jetbrains.ktor.logging.CallLogging
import org.jetbrains.ktor.routing.Routing
import org.jetbrains.ktor.sessions.session
import org.jetbrains.ktor.sessions.sessionOrNull
import org.jetbrains.ktor.sessions.withCookieByValue
import org.jetbrains.ktor.sessions.withSessions
import org.jetbrains.ktor.util.nextNonce
import org.jetbrains.ktor.websocket.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.time.Duration
private val logPersistence = DefaultLogPersistence
private val server = LogServer(ArcCliLogPublisherFactory, logPersistence)
/**
*
* @author myeongju.jung
*/
fun Application.main() {
val log by logger()
install(DefaultHeaders)
install(CallLogging)
install(WebSockets) {
pingPeriod = Duration.ofMinutes(1)
}
install(Routing) {
withSessions<LogSession> {
withCookieByValue()
}
intercept(ApplicationCallPipeline.Infrastructure) {
if (call.sessionOrNull<LogSession>() == null) {
call.session(LogSession(nextNonce()))
}
}
webSocket("/logs") {
val session = call.sessionOrNull<LogSession>()
if (session == null) {
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "No session"))
return@webSocket
}
log.debug("parameters = {}", call.parameters)
val zkAddress = call.parameters["zkAddress"]!!
val cluster = call.parameters["cluster"]!!
val clusterId = ClusterId(zkAddress = zkAddress, cluster = cluster)
log.debug("clusterId = {}", clusterId)
server.openSocket(session, clusterId, this)
try {
incoming.consumeEach { frame ->
if (frame is Frame.Text) {
receivedMessage(session, this, frame.readText())
}
}
} finally {
server.closeSocket(session, this)
}
}
static {
defaultResource("index.html", "web")
resources("web")
}
}
}
data class LogSession(val id: String)
suspend private fun receivedMessage(session: LogSession, socket: WebSocketSession, command: String) {
when {
command.startsWith("/latencies") -> server.publish(session, socket, LatencyType)
command.startsWith("/stats") -> server.publish(session, socket, StatType)
}
}
fun <R : Any> R.logger(): Lazy<Logger> {
return lazy { LoggerFactory.getLogger(this::class.java) }
} | apache-2.0 | ca9f9c4573a0421405cfaf9e49927bd8 | 33.447917 | 101 | 0.679976 | 4.437584 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrames.kt | 2 | 5453 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.data
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ReadAction
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.sun.jdi.Location
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinVariableNameFinder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeCoroutineStackFrameProxy
import org.jetbrains.kotlin.idea.debugger.safeLocation
import org.jetbrains.kotlin.idea.debugger.stackFrame.InlineStackTraceCalculator
import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame
/**
* Coroutine exit frame represented by a stack frames
* invokeSuspend():-1
* resumeWith()
*
*/
class CoroutinePreflightFrame(
val coroutineInfoData: CoroutineInfoData,
val frame: StackFrameProxyImpl,
val threadPreCoroutineFrames: List<StackFrameProxyImpl>,
val mode: SuspendExitMode,
firstFrameVariables: List<JavaValue>
) : CoroutineStackFrame(frame, null, firstFrameVariables) {
override fun isInLibraryContent() = false
override fun isSynthetic() = false
}
class CreationCoroutineStackFrame(
frame: StackFrameProxyImpl,
sourcePosition: XSourcePosition?,
val first: Boolean,
location: Location? = frame.safeLocation()
) : CoroutineStackFrame(frame, sourcePosition, emptyList(), false, location), XDebuggerFramesList.ItemWithSeparatorAbove {
override fun getCaptionAboveOf() =
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace")
override fun hasSeparatorAbove() =
first
}
open class CoroutineStackFrame(
frame: StackFrameProxyImpl,
private val position: XSourcePosition?,
private val spilledVariables: List<JavaValue> = emptyList(),
private val includeFrameVariables: Boolean = true,
location: Location? = frame.safeLocation(),
) : KotlinStackFrame(
safeCoroutineStackFrameProxy(location, spilledVariables, frame),
if (spilledVariables.isEmpty() || includeFrameVariables) {
InlineStackTraceCalculator.calculateVisibleVariables(frame)
} else {
listOf()
}
) {
init {
descriptor.updateRepresentation(null, DescriptorLabelListener.DUMMY_LISTENER)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val frame = other as? JavaStackFrame ?: return false
return descriptor.frameProxy == frame.descriptor.frameProxy
}
override fun hashCode(): Int {
return descriptor.frameProxy.hashCode()
}
override fun buildVariablesThreadAction(debuggerContext: DebuggerContextImpl, children: XValueChildrenList, node: XCompositeNode) {
if (includeFrameVariables || spilledVariables.isEmpty()) {
super.buildVariablesThreadAction(debuggerContext, children, node)
val debugProcess = debuggerContext.debugProcess ?: return
addOptimisedVariables(debugProcess, children)
} else {
// ignore original frame variables
for (variable in spilledVariables) {
children.add(variable)
}
}
}
private fun addOptimisedVariables(debugProcess: DebugProcessImpl, children: XValueChildrenList) {
val visibleVariableNames by lazy { children.getUniqueNames() }
for (variable in spilledVariables) {
val name = variable.name
if (name !in visibleVariableNames) {
children.add(variable)
visibleVariableNames.add(name)
}
}
val declaredVariableNames = findVisibleVariableNames(debugProcess)
for (name in declaredVariableNames) {
if (name !in visibleVariableNames) {
children.add(createOptimisedVariableMessageNode(name))
}
}
}
private fun createOptimisedVariableMessageNode(name: String) =
createMessageNode(
KotlinDebuggerCoroutinesBundle.message("optimised.variable.message", "\'$name\'"),
AllIcons.General.Information
)
private fun XValueChildrenList.getUniqueNames(): MutableSet<String> {
val names = mutableSetOf<String>()
for (i in 0 until size()) {
names.add(getName(i))
}
return names
}
private fun findVisibleVariableNames(debugProcess: DebugProcessImpl): List<String> {
val location = stackFrameProxy.safeLocation() ?: return emptyList()
return ReadAction.nonBlocking<List<String>> {
KotlinVariableNameFinder(debugProcess)
.findVisibleVariableNames(location)
}.executeSynchronously()
}
override fun getSourcePosition() =
position ?: super.getSourcePosition()
}
| apache-2.0 | 0fd4ab18ac30c2ed00cce251d8dfa3a6 | 36.606897 | 158 | 0.725656 | 5.263514 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/service/RuntimeService.kt | 1 | 1048 | package com.bajdcc.LALR1.grammar.runtime.service
import com.bajdcc.LALR1.grammar.runtime.RuntimeProcess
/**
* 【运行时】运行时服务
*
* @author bajdcc
*/
class RuntimeService(private val process: RuntimeProcess) : IRuntimeService {
private val pipe: RuntimePipeService = RuntimePipeService(this)
private val share: RuntimeShareService = RuntimeShareService(this)
private val file: RuntimeFileService = RuntimeFileService(this)
private val dialog: RuntimeDialogService = RuntimeDialogService(this)
private val user: RuntimeUserService = RuntimeUserService(this)
override val pipeService: IRuntimePipeService
get() = pipe
override val shareService: IRuntimeShareService
get() = share
override val processService: IRuntimeProcessService
get() = process
override val fileService: IRuntimeFileService
get() = file
override val dialogService: IRuntimeDialogService
get() = dialog
override val userService: IRuntimeUserService
get() = user
}
| mit | 911a3d2970ff43265cf8db55d8d93ec7 | 29.235294 | 77 | 0.7393 | 4.715596 | false | false | false | false |
RedMadRobot/input-mask-android | inputmask/src/main/kotlin/com/redmadrobot/inputmask/helper/Mask.kt | 1 | 12184 | package com.redmadrobot.inputmask.helper
import com.redmadrobot.inputmask.model.CaretString
import com.redmadrobot.inputmask.model.Next
import com.redmadrobot.inputmask.model.Notation
import com.redmadrobot.inputmask.model.State
import com.redmadrobot.inputmask.model.state.*
import java.util.*
/**
* ### Mask
*
* Iterates over user input. Creates formatted strings from it. Extracts value specified by mask
* format.
*
* Provided mask format string is translated by the ```Compiler``` class into a set of states, which
* define the formatting and value extraction.
*
* @see ```Compiler```, ```State``` and ```CaretString``` classes.
*
* @author taflanidi
*/
open class Mask(format: String, protected val customNotations: List<Notation>) {
/**
* Convenience constructor.
*/
constructor(format: String) : this(format, emptyList())
/**
* ### Result
*
* The end result of mask application to the user input string.
*/
data class Result(
/**
* Formatted text with updated caret position.
*/
val formattedText: CaretString,
/**
* Value, extracted from formatted text according to mask format.
*/
val extractedValue: String,
/**
* Calculated absolute affinity value between the mask format and input text.
*/
val affinity: Int,
/**
* User input is complete.
*/
val complete: Boolean
) {
fun reversed() =
Result(
this.formattedText.reversed(),
this.extractedValue.reversed(),
this.affinity,
this.complete
)
}
companion object Factory {
private val cache: MutableMap<String, Mask> = HashMap()
/**
* Factory constructor.
*
* Operates over own ```Mask``` cache where initialized ```Mask``` objects are stored under
* corresponding format key:
* ```[format : mask]```
*
* @returns Previously cached ```Mask``` object for requested format string. If such it
* doesn't exist in cache, the object is constructed, cached and returned.
*/
fun getOrCreate(format: String, customNotations: List<Notation>): Mask {
var cachedMask: Mask? = cache[format]
if (null == cachedMask) {
cachedMask = Mask(format, customNotations)
cache[format] = cachedMask
}
return cachedMask
}
/**
* Check your mask format is valid.
*
* @param format mask format.
* @param customNotations a list of custom rules to compile square bracket ```[]``` groups of format symbols.
*
* @returns ```true``` if this format coupled with custom notations will compile into a working ```Mask``` object.
* Otherwise ```false```.
*/
fun isValid(format: String, customNotations: List<Notation>): Boolean {
return try {
Mask(format, customNotations)
true
} catch (e: Compiler.FormatError) {
false
}
}
}
private val initialState: State = Compiler(this.customNotations).compile(format)
/**
* Apply mask to the user input string.
*
* @param text user input string with current cursor position
*
* @returns Formatted text with extracted value an adjusted cursor position.
*/
open fun apply(text: CaretString): Result {
val iterator = this.makeIterator(text)
var affinity = 0
var extractedValue = ""
var modifiedString = ""
var modifiedCaretPosition: Int = text.caretPosition
var state: State = this.initialState
val autocompletionStack = AutocompletionStack()
var insertionAffectsCaret: Boolean = iterator.insertionAffectsCaret()
var deletionAffectsCaret: Boolean = iterator.deletionAffectsCaret()
var character: Char? = iterator.next()
while (null != character) {
val next: Next? = state.accept(character)
if (null != next) {
if (deletionAffectsCaret) autocompletionStack.push(state.autocomplete())
state = next.state
modifiedString += next.insert ?: ""
extractedValue += next.value ?: ""
if (next.pass) {
insertionAffectsCaret = iterator.insertionAffectsCaret()
deletionAffectsCaret = iterator.deletionAffectsCaret()
character = iterator.next()
affinity += 1
} else {
if (insertionAffectsCaret && null != next.insert) {
modifiedCaretPosition += 1
}
affinity -= 1
}
} else {
if (deletionAffectsCaret) {
modifiedCaretPosition -= 1
}
insertionAffectsCaret = iterator.insertionAffectsCaret()
deletionAffectsCaret = iterator.deletionAffectsCaret()
character = iterator.next()
affinity -= 1
}
}
while (text.caretGravity.autocomplete && insertionAffectsCaret) {
val next: Next = state.autocomplete() ?: break
state = next.state
modifiedString += next.insert ?: ""
extractedValue += next.value ?: ""
if (null != next.insert) {
modifiedCaretPosition += 1
}
}
while (text.caretGravity.autoskip && !autocompletionStack.empty()) {
val skip: Next = autocompletionStack.pop()
if (modifiedString.length == modifiedCaretPosition) {
if (null != skip.insert && skip.insert == modifiedString.last()) {
modifiedString = modifiedString.dropLast(1)
modifiedCaretPosition -= 1
}
if (null != skip.value && skip.value == extractedValue.last()) {
extractedValue = extractedValue.dropLast(1)
}
} else {
if (null != skip.insert) {
modifiedCaretPosition -= 1
}
}
}
return Result(
CaretString(
modifiedString,
modifiedCaretPosition,
text.caretGravity
),
extractedValue,
affinity,
this.noMandatoryCharactersLeftAfterState(state)
)
}
open fun makeIterator(text: CaretString) = CaretStringIterator(text)
/**
* Generate placeholder.
*
* @return Placeholder string.
*/
fun placeholder(): String = this.appendPlaceholder(this.initialState, "")
/**
* Minimal length of the text inside the field to fill all mandatory characters in the mask.
*
* @return Minimal satisfying count of characters inside the text field.
*/
fun acceptableTextLength(): Int {
var state: State? = this.initialState
var length = 0
while (null != state && state !is EOLState) {
if (state is FixedState || state is FreeState || state is ValueState) {
length += 1
}
state = state.child
}
return length
}
/**
* Maximal length of the text inside the field.
*
* @return Total available count of mandatory and optional characters inside the text field.
*/
fun totalTextLength(): Int {
var state: State? = this.initialState
var length = 0
while (null != state && state !is EOLState) {
if (state is FixedState || state is FreeState || state is ValueState || state is OptionalValueState) {
length += 1
}
state = state.child
}
return length
}
/**
* Minimal length of the extracted value with all mandatory characters filled.\
*
* @return Minimal satisfying count of characters in extracted value.
*/
fun acceptableValueLength(): Int {
var state: State? = this.initialState
var length = 0
while (null != state && state !is EOLState) {
if (state is FixedState || state is ValueState) {
length += 1
}
state = state.child
}
return length
}
/**
* Maximal length of the extracted value.
*
* @return Total available count of mandatory and optional characters for extracted value.
*/
fun totalValueLength(): Int {
var state: State? = this.initialState
var length = 0
while (null != state && state !is EOLState) {
if (state is FixedState || state is ValueState || state is OptionalValueState) {
length += 1
}
state = state.child
}
return length
}
private fun appendPlaceholder(state: State?, placeholder: String): String {
if (null == state) {
return placeholder
}
if (state is EOLState) {
return placeholder
}
if (state is FixedState) {
return this.appendPlaceholder(state.child, placeholder + state.ownCharacter)
}
if (state is FreeState) {
return this.appendPlaceholder(state.child, placeholder + state.ownCharacter)
}
if (state is OptionalValueState) {
return when (state.type) {
is OptionalValueState.StateType.AlphaNumeric -> {
this.appendPlaceholder(state.child, placeholder + "-")
}
is OptionalValueState.StateType.Literal -> {
this.appendPlaceholder(state.child, placeholder + "a")
}
is OptionalValueState.StateType.Numeric -> {
this.appendPlaceholder(state.child, placeholder + "0")
}
is OptionalValueState.StateType.Custom -> {
this.appendPlaceholder(state.child, placeholder + state.type.character)
}
}
}
if (state is ValueState) {
return when (state.type) {
is ValueState.StateType.AlphaNumeric -> {
this.appendPlaceholder(state.child, placeholder + "-")
}
is ValueState.StateType.Literal -> {
this.appendPlaceholder(state.child, placeholder + "a")
}
is ValueState.StateType.Numeric -> {
this.appendPlaceholder(state.child, placeholder + "0")
}
is ValueState.StateType.Ellipsis -> placeholder
is ValueState.StateType.Custom -> {
this.appendPlaceholder(state.child, placeholder + state.type.character)
}
}
}
return placeholder
}
private fun noMandatoryCharactersLeftAfterState(state: State): Boolean {
return when (state) {
is EOLState -> { true }
is ValueState -> { return state.isElliptical }
is FixedState -> { false }
else -> { this.noMandatoryCharactersLeftAfterState(state.nextState()) }
}
}
/**
* While scanning through the input string in the `.apply(…)` method, the mask builds a graph of
* autocompletion steps.
*
* This graph accumulates the results of `.autocomplete()` calls for each consecutive `State`,
* acting as a `stack` of `Next` object instances.
*
* Each time the `State` returns `null` for its `.autocomplete()`, the graph resets empty.
*/
private class AutocompletionStack : Stack<Next>() {
override fun push(item: Next?): Next? {
return if (null != item) {
super.push(item)
} else {
this.removeAllElements()
null
}
}
}
}
| mit | c15649687fca08e2cf4f624295d56bab | 31.924324 | 122 | 0.55032 | 5.019365 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/domainregistration/DomainRegistrationSource.kt | 1 | 5096 | package org.wordpress.android.ui.mysite.cards.domainregistration
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.SiteActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.SiteStore.OnPlansFetched
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.mysite.MySiteSource.MySiteRefreshSource
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.DomainCreditAvailable
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.plans.isDomainCreditAvailable
import org.wordpress.android.util.AppLog.T.DOMAIN_REGISTRATION
import org.wordpress.android.util.SiteUtilsWrapper
import javax.inject.Inject
import javax.inject.Named
import kotlin.coroutines.resume
class DomainRegistrationSource @Inject constructor(
@param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val dispatcher: Dispatcher,
private val selectedSiteRepository: SelectedSiteRepository,
private val appLogWrapper: AppLogWrapper,
private val siteUtils: SiteUtilsWrapper
) : MySiteRefreshSource<DomainCreditAvailable> {
override val refresh = MutableLiveData(false)
private val continuations = mutableMapOf<Int, CancellableContinuation<OnPlansFetched>?>()
init {
dispatcher.register(this)
}
fun clear() {
dispatcher.unregister(this)
}
override fun build(coroutineScope: CoroutineScope, siteLocalId: Int): LiveData<DomainCreditAvailable> {
val data = MediatorLiveData<DomainCreditAvailable>()
data.addSource(refresh) { data.refreshData(coroutineScope, siteLocalId, refresh.value) }
refresh()
return data
}
private fun MediatorLiveData<DomainCreditAvailable>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int,
isRefresh: Boolean? = null
) {
val selectedSite = selectedSiteRepository.getSelectedSite()
when (isRefresh) {
null, true -> refreshData(coroutineScope, siteLocalId, selectedSite)
false -> Unit // Do nothing
}
}
private fun MediatorLiveData<DomainCreditAvailable>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int,
selectedSite: SiteModel?
) {
if (selectedSite == null || selectedSite.id != siteLocalId || !shouldFetchPlans(selectedSite)) {
postState(DomainCreditAvailable(false))
} else {
fetchPlansAndRefreshData(coroutineScope, siteLocalId, selectedSite)
}
}
private fun MediatorLiveData<DomainCreditAvailable>.fetchPlansAndRefreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int,
selectedSite: SiteModel
) {
if (continuations[siteLocalId] == null) {
coroutineScope.launch(bgDispatcher) { fetchPlans(siteLocalId, selectedSite) }
} else {
appLogWrapper.d(DOMAIN_REGISTRATION, "A request is already running for $siteLocalId")
}
}
@Suppress("SwallowedException")
private suspend fun MediatorLiveData<DomainCreditAvailable>.fetchPlans(siteLocalId: Int, selectedSite: SiteModel) {
try {
val event = suspendCancellableCoroutine<OnPlansFetched> { cancellableContinuation ->
continuations[siteLocalId] = cancellableContinuation
dispatchFetchPlans(selectedSite)
}
when {
event.isError -> {
val message = "An error occurred while fetching plans :${event.error.message}"
appLogWrapper.e(DOMAIN_REGISTRATION, message)
postState(DomainCreditAvailable(false))
}
siteLocalId == event.site.id -> {
postState(DomainCreditAvailable(isDomainCreditAvailable(event.plans)))
}
else -> {
postState(DomainCreditAvailable(false))
}
}
} catch (e: CancellationException) {
postState(DomainCreditAvailable(false))
}
}
private fun shouldFetchPlans(site: SiteModel) = !siteUtils.onFreePlan(site)
private fun dispatchFetchPlans(site: SiteModel) = dispatcher.dispatch(SiteActionBuilder.newFetchPlansAction(site))
@Subscribe(threadMode = ThreadMode.MAIN)
fun onPlansFetched(event: OnPlansFetched) {
continuations[event.site.id]?.resume(event)
continuations[event.site.id] = null
}
}
| gpl-2.0 | 937430102812ab7941be0b8f0d3a43ff | 39.444444 | 119 | 0.715856 | 5.232033 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/helpers/Trainer.kt | 1 | 7349 | /* Copyright 2019-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.helpers
import com.kotlinnlp.simplednn.core.optimizer.ParamsOptimizer
import com.kotlinnlp.utils.progressindicator.ProgressIndicatorBar
import com.kotlinnlp.utils.*
/**
* The trainer of a neural model.
*
* @param modelFilename the name of the file in which to save the serialized model
* @param optimizers the parameters optimizers
* @param examples the training examples
* @param epochs the number of training epochs
* @param batchSize the size of each batch (default 1)
* @param evaluator the helper for the evaluation (default null)
* @param shuffler shuffle the examples before each epoch, converting the sequence to a list
* @param verbose whether to print info about the training progress and timing (default = true)
*/
abstract class Trainer<ExampleType : Any>(
protected val modelFilename: String,
protected val optimizers: List<ParamsOptimizer>,
private val examples: Iterable<ExampleType>,
private val epochs: Int,
protected val batchSize: Int = 1,
private val evaluator: Evaluator<ExampleType, *>? = null,
private val shuffler: Shuffler? = Shuffler(),
protected val verbose: Boolean = true
) {
/**
* An iterator of shuffled examples.
*
* @param examples the examples list
*/
private inner class ShuffledExamplesIterator(private val examples: List<ExampleType>) : Iterator<ExampleType> {
/**
* The iterator of shuffled examples indices.
*/
private val indicesIterator = ShuffledIndices(this.examples.size, shuffler = shuffler!!).iterator()
override fun next(): ExampleType = this.examples[indicesIterator.next()]
override fun hasNext(): Boolean = indicesIterator.hasNext()
}
/**
* Counter of values used during the training (accuracy, loss, etc..).
*/
private val counter = Counter()
/**
* A timer to track the elapsed time.
*/
private val timer = Timer()
/**
* The best accuracy reached.
*/
val bestAccuracy get() = this.counter.bestAccuracy
/**
* Check requirements.
*/
init {
require(this.epochs > 0)
require(this.batchSize > 0)
}
/**
* Train the model over the specified number of epochs, grouping the examples in batches, eventually shuffled before.
* If the [evaluator] is not null, the neural model is tested with validation examples after each epoch.
*/
fun train() {
this.counter.reset()
(0 until this.epochs).forEach { i ->
this.logTrainingStart(epochIndex = i)
this.newEpoch()
this.trainEpoch()
this.logTrainingEnd()
this.validateAndSaveModel()
}
}
/**
* Learn from an example (forward + backward).
*
* @param example an example to train the model with
*/
protected abstract fun learnFromExample(example: ExampleType)
/**
* Accumulate the errors of the model resulting after the call of [learnFromExample].
*/
protected abstract fun accumulateErrors()
/**
* Dump the model to file.
*/
protected abstract fun dumpModel()
/**
* Train the model over an epoch, grouping examples in batches, shuffling them before with the given shuffler.
*/
protected open fun trainEpoch() {
val examplesIterator: Iterator<ExampleType> = this.buildExamplesIterator()
val progress: ProgressIndicatorBar? =
if (this.examples is Collection<*>) ProgressIndicatorBar(this.examples.size) else null
while (examplesIterator.hasNext()) {
if (this.verbose) progress?.tick()
if (this.counter.exampleCount % this.batchSize == 0) // A new batch starts
this.newBatch()
this.newExample() // !! must be called after newBatch() !!
this.trainExample(examplesIterator.next())
}
}
/**
* @return an iterator of examples
*/
private fun buildExamplesIterator(): Iterator<ExampleType> =
if (this.shuffler != null)
ShuffledExamplesIterator(if (this.examples is List<ExampleType>) this.examples else this.examples.toList())
else
this.examples.iterator()
/**
* Train the neural model with a given example and accumulate the errors into the [optimizers].
*
* @param example an example to train the model with
*/
private fun trainExample(example: ExampleType) {
this.learnFromExample(example)
this.accumulateErrors()
if (this.counter.exampleCount == this.batchSize) { // a batch is just ended
this.optimizers.forEach { it.update() }
}
}
/**
* Validate the model and save it to file if a new best accuracy has been reached.
* If the [evaluator] is null then the model is saved automatically.
*/
protected fun validateAndSaveModel() {
var bestModel = true
if (this.evaluator != null) {
this.logValidationStart()
val stats: Statistics = this.evaluator.evaluate()
this.logValidationEnd(stats)
if (stats.accuracy > this.counter.bestAccuracy)
this.counter.bestAccuracy = stats.accuracy
else
bestModel = false
}
if (bestModel) {
this.dumpModel()
if (this.verbose)
println("Model saved to \"${this.modelFilename}\"")
}
}
/**
* Method to call every new epoch.
* In turn it calls the same method of the [optimizers].
*/
protected fun newEpoch() {
this.counter.newEpoch()
this.optimizers.forEach { it.newEpoch() }
}
/**
* Method to call every new batch.
* In turn it calls the same method of the [optimizers].
*/
protected fun newBatch() {
this.counter.newBatch()
this.optimizers.forEach { it.newBatch() }
}
/**
* Method to call every new example.
* In turn it calls the same method of the [optimizers].
*/
protected fun newExample() {
this.counter.newExample()
this.optimizers.forEach { it.newExample() }
}
/**
* Log when training starts.
*/
private fun logTrainingStart(epochIndex: Int) {
if (this.verbose) {
this.timer.reset()
println("\nEpoch ${epochIndex + 1} of ${this.epochs}")
println("\nStart training...")
}
}
/**
* Log when training ends.
*/
private fun logTrainingEnd() {
if (this.verbose) {
println("Elapsed time: %s".format(this.timer.formatElapsedTime()))
}
}
/**
* Log when validation starts.
*/
private fun logValidationStart() {
if (this.verbose) {
val evaluationExamples: Iterable<ExampleType> = this.evaluator!!.examples
this.timer.reset()
if (evaluationExamples is Collection<*>)
println("\nValidate on ${evaluationExamples.size} examples...")
else
println("\nValidate model...")
}
}
/**
* Log when validation ends.
*
* @param stats the evaluation statistics
*/
private fun logValidationEnd(stats: Statistics) {
if (this.verbose) {
println("Elapsed time: %s".format(this.timer.formatElapsedTime()))
println("\nStatistics:")
println(stats)
if (stats.accuracy > this.counter.bestAccuracy)
println("\nNEW BEST ACCURACY!")
}
}
}
| mpl-2.0 | 68f8a9193840502f5ca78bc03be09870 | 25.246429 | 119 | 0.663356 | 4.180319 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt | 1 | 2153 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.refactoring.rename.RenameProcessor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RenameParameterToMatchOverriddenMethodFix(
parameter: KtParameter,
private val newName: String
) : KotlinQuickFixAction<KtParameter>(parameter) {
override fun getFamilyName() = KotlinBundle.message("rename.identifier.fix.text")
override fun getText() = KotlinBundle.message("rename.parameter.to.match.overridden.method")
override fun startInWriteAction(): Boolean = false
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
RenameProcessor(project, element ?: return, newName, false, false).run()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val parameter = diagnostic.psiElement.getNonStrictParentOfType<KtParameter>() ?: return null
val parameterDescriptor = parameter.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL) ?: return null
val parameterFromSuperclassName = parameterDescriptor.overriddenDescriptors
.map { it.name.asString() }
.distinct()
.singleOrNull() ?: return null
return RenameParameterToMatchOverriddenMethodFix(parameter, parameterFromSuperclassName)
}
}
}
| apache-2.0 | 8d6c3a845cefbbb8d6adc2c763d01361 | 49.069767 | 158 | 0.774268 | 5.053991 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SelfReferenceConstructorParameterInspection.kt | 1 | 3124 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.primaryConstructorVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class SelfReferenceConstructorParameterInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = primaryConstructorVisitor(fun(constructor) {
val parameter = constructor.valueParameterList?.selfReferenceParameter() ?: return
val rangeInElement = parameter.typeReference?.textRange?.shiftRight(-parameter.startOffset) ?: return
holder.registerProblem(
parameter,
rangeInElement,
KotlinBundle.message("constructor.has.non.null.self.reference.parameter"),
ConvertToNullableTypeFix()
)
})
private fun KtParameterList.selfReferenceParameter(): KtParameter? {
val containingClass = this.containingClass() ?: return null
val className = containingClass.name ?: return null
val parameter = this.parameters.firstOrNull { it.typeReference?.text == className } ?: return null
if (parameter.isVarArg) return null
val typeReference = parameter.typeReference ?: return null
val context = analyze(BodyResolveMode.PARTIAL)
val type = context[BindingContext.TYPE, typeReference] ?: return null
if (type.isNullable()) return null
if (type.constructor.declarationDescriptor != context[BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass]) return null
return parameter
}
private class ConvertToNullableTypeFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("convert.to.nullable.type.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val parameter = descriptor.psiElement as? KtParameter ?: return
val typeReference = parameter.typeReference ?: return
val type = parameter.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return
parameter.setType(type.makeNullable())
}
}
} | apache-2.0 | 647bf3e588495d069c470dc2e0ff5d96 | 48.603175 | 158 | 0.760563 | 5.121311 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/prohibitRepeatedUseSiteTargetAnnotationsMigration/simple.kt | 13 | 341 | // LANGUAGE_VERSION: 1.4
// DISABLE-ERRORS
annotation class Ann(val x: Int)
@get:Ann(10)<caret>
val a: String
@Ann(20) get() = "foo"
@set:Ann(10)
var b: String = ""
@Ann(20) set(value) { field = value }
@setparam:Ann(10)
var c = " "
set(@Ann(20) x) {}
@get:Ann(10)
@get:Ann(20)
val d: String
@Ann(30) @Ann(40) get() = "foo" | apache-2.0 | 9f2f1f72f826651e01e0f09f60b827bb | 15.285714 | 41 | 0.580645 | 2.304054 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/sounds/custom/CustomNotificationsSettingsFragment.kt | 1 | 7007 | package org.thoughtcrime.securesms.components.settings.conversation.sounds.custom
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import android.provider.Settings
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.viewModels
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.database.RecipientDatabase
import org.thoughtcrime.securesms.notifications.NotificationChannels
import org.thoughtcrime.securesms.util.RingtoneUtil
class CustomNotificationsSettingsFragment : DSLSettingsFragment(R.string.CustomNotificationsDialogFragment__custom_notifications) {
private val vibrateLabels: Array<String> by lazy {
resources.getStringArray(R.array.recipient_vibrate_entries)
}
private val viewModel: CustomNotificationsSettingsViewModel by viewModels(factoryProducer = this::createFactory)
private lateinit var callSoundResultLauncher: ActivityResultLauncher<Intent>
private lateinit var messageSoundResultLauncher: ActivityResultLauncher<Intent>
private fun createFactory(): CustomNotificationsSettingsViewModel.Factory {
val recipientId = CustomNotificationsSettingsFragmentArgs.fromBundle(requireArguments()).recipientId
val repository = CustomNotificationsSettingsRepository(requireContext())
return CustomNotificationsSettingsViewModel.Factory(recipientId, repository)
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
messageSoundResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
handleResult(result, viewModel::setMessageSound)
}
callSoundResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
handleResult(result, viewModel::setCallSound)
}
viewModel.state.observe(viewLifecycleOwner) { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
private fun handleResult(result: ActivityResult, resultHandler: (Uri?) -> Unit) {
val resultCode = result.resultCode
val data = result.data
if (resultCode == Activity.RESULT_OK && data != null) {
val uri: Uri? = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
resultHandler(uri)
}
}
private fun getConfiguration(state: CustomNotificationsSettingsState): DSLConfiguration {
return configure {
sectionHeaderPref(R.string.CustomNotificationsDialogFragment__messages)
if (NotificationChannels.supported()) {
switchPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__use_custom_notifications),
isEnabled = state.isInitialLoadComplete,
isChecked = state.hasCustomNotifications,
onClick = { viewModel.setHasCustomNotifications(!state.hasCustomNotifications) }
)
}
clickPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__notification_sound),
summary = DSLSettingsText.from(getRingtoneSummary(requireContext(), state.messageSound, Settings.System.DEFAULT_NOTIFICATION_URI)),
isEnabled = state.controlsEnabled,
onClick = { requestSound(state.messageSound, false) }
)
if (NotificationChannels.supported()) {
switchPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__vibrate),
isEnabled = state.controlsEnabled,
isChecked = state.messageVibrateEnabled,
onClick = { viewModel.setMessageVibrate(RecipientDatabase.VibrateState.fromBoolean(!state.messageVibrateEnabled)) }
)
} else {
radioListPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__vibrate),
isEnabled = state.controlsEnabled,
listItems = vibrateLabels,
selected = state.messageVibrateState.id,
onSelected = {
viewModel.setMessageVibrate(RecipientDatabase.VibrateState.fromId(it))
}
)
}
if (state.showCallingOptions) {
dividerPref()
sectionHeaderPref(R.string.CustomNotificationsDialogFragment__call_settings)
clickPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__ringtone),
summary = DSLSettingsText.from(getRingtoneSummary(requireContext(), state.callSound, Settings.System.DEFAULT_RINGTONE_URI)),
isEnabled = state.controlsEnabled,
onClick = { requestSound(state.callSound, true) }
)
radioListPref(
title = DSLSettingsText.from(R.string.CustomNotificationsDialogFragment__vibrate),
isEnabled = state.controlsEnabled,
listItems = vibrateLabels,
selected = state.callVibrateState.id,
onSelected = {
viewModel.setCallVibrate(RecipientDatabase.VibrateState.fromId(it))
}
)
}
}
}
private fun getRingtoneSummary(context: Context, ringtone: Uri?, defaultNotificationUri: Uri?): String {
if (ringtone == null || ringtone == defaultNotificationUri) {
return context.getString(R.string.CustomNotificationsDialogFragment__default)
} else if (ringtone.toString().isEmpty()) {
return context.getString(R.string.preferences__silent)
} else {
val tone = RingtoneUtil.getRingtone(requireContext(), ringtone)
if (tone != null) {
return tone.getTitle(context)
}
}
return context.getString(R.string.CustomNotificationsDialogFragment__default)
}
private fun requestSound(current: Uri?, forCalls: Boolean) {
val existing: Uri? = when {
current == null -> getDefaultSound(forCalls)
current.toString().isEmpty() -> null
else -> current
}
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER).apply {
putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, if (forCalls) RingtoneManager.TYPE_RINGTONE else RingtoneManager.TYPE_NOTIFICATION)
putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, existing)
}
if (forCalls) {
callSoundResultLauncher.launch(intent)
} else {
messageSoundResultLauncher.launch(intent)
}
}
private fun getDefaultSound(forCalls: Boolean) = if (forCalls) Settings.System.DEFAULT_RINGTONE_URI else Settings.System.DEFAULT_NOTIFICATION_URI
}
| gpl-3.0 | 44b91e9aea15d5039329ff83cabf02e6 | 41.210843 | 147 | 0.74711 | 5.175037 | false | false | false | false |
all-of-us/workbench | api/src/main/java/org/pmiops/workbench/actionaudit/auditors/AdminAuditorImpl.kt | 1 | 4099 | package org.pmiops.workbench.actionaudit.auditors
import java.time.Clock
import java.util.Date
import java.util.logging.Logger
import javax.inject.Provider
import org.pmiops.workbench.actionaudit.ActionAuditEvent
import org.pmiops.workbench.actionaudit.ActionAuditService
import org.pmiops.workbench.actionaudit.ActionType
import org.pmiops.workbench.actionaudit.AgentType
import org.pmiops.workbench.actionaudit.TargetType
import org.pmiops.workbench.db.model.DbUser
import org.pmiops.workbench.model.AccessReason
import org.pmiops.workbench.model.AdminLockingRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
class AdminAuditorImpl @Autowired
constructor(
private val userProvider: Provider<DbUser>,
private val actionAuditService: ActionAuditService,
private val clock: Clock,
@Qualifier("ACTION_ID") private val actionIdProvider: Provider<String>
) : AdminAuditor {
override fun fireViewNotebookAction(workspaceNamespace: String, workspaceName: String, notebookFilename: String, accessReason: AccessReason) {
val dbUser = userProvider.get()
val actionId = actionIdProvider.get()
val timestamp = clock.millis()
val props = mapOf(
"workspace_namespace" to workspaceNamespace,
"workspace_name" to workspaceName,
"notebook_name" to notebookFilename,
"access_reason" to accessReason.reason
)
val events = props.map {
ActionAuditEvent(
actionId = actionId,
actionType = ActionType.VIEW,
agentType = AgentType.ADMINISTRATOR,
agentEmailMaybe = dbUser.username,
agentIdMaybe = dbUser.userId,
targetType = TargetType.NOTEBOOK,
targetPropertyMaybe = it.key,
newValueMaybe = it.value,
timestamp = timestamp) }
actionAuditService.send(events)
}
override fun fireLockWorkspaceAction(workspaceId: Long, adminLockingRequest: AdminLockingRequest) {
val dbUser = userProvider.get()
val actionId = actionIdProvider.get()
val timestamp = clock.millis()
val requestTimestamp = Date(adminLockingRequest.requestDateInMillis).toString()
val props = mapOf(
"locked" to "true",
"reason" to adminLockingRequest.requestReason,
"request_date" to requestTimestamp
)
val events = props.map {
ActionAuditEvent(
actionId = actionId,
actionType = ActionType.EDIT,
agentType = AgentType.ADMINISTRATOR,
agentEmailMaybe = dbUser.username,
agentIdMaybe = dbUser.userId,
targetType = TargetType.WORKSPACE,
targetIdMaybe = workspaceId,
targetPropertyMaybe = it.key,
newValueMaybe = it.value,
timestamp = timestamp) }
actionAuditService.send(events)
}
override fun fireUnlockWorkspaceAction(workspaceId: Long) {
val dbUser = userProvider.get()
val actionId = actionIdProvider.get()
val timestamp = clock.millis()
val event = ActionAuditEvent(
actionId = actionId,
actionType = ActionType.EDIT,
agentType = AgentType.ADMINISTRATOR,
agentEmailMaybe = dbUser.username,
agentIdMaybe = dbUser.userId,
targetType = TargetType.WORKSPACE,
targetIdMaybe = workspaceId,
targetPropertyMaybe = "locked",
newValueMaybe = "false",
timestamp = timestamp)
actionAuditService.send(event)
}
companion object {
private val logger = Logger.getLogger(AdminAuditorImpl::class.java.name)
}
}
| bsd-3-clause | 187e3e62730fbe521ab3dae18db6dfe8 | 37.669811 | 146 | 0.634545 | 5.282216 | false | false | false | false |
square/picasso | picasso/src/test/java/com/squareup/picasso3/MediaStoreRequestHandlerTest.kt | 1 | 4812 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import com.google.common.truth.Truth.assertThat
import com.squareup.picasso3.MediaStoreRequestHandler.Companion.getPicassoKind
import com.squareup.picasso3.MediaStoreRequestHandler.PicassoKind.FULL
import com.squareup.picasso3.MediaStoreRequestHandler.PicassoKind.MICRO
import com.squareup.picasso3.MediaStoreRequestHandler.PicassoKind.MINI
import com.squareup.picasso3.RequestHandler.Callback
import com.squareup.picasso3.Shadows.ShadowImageThumbnails
import com.squareup.picasso3.Shadows.ShadowVideoThumbnails
import com.squareup.picasso3.TestUtils.MEDIA_STORE_CONTENT_1_URL
import com.squareup.picasso3.TestUtils.MEDIA_STORE_CONTENT_2_URL
import com.squareup.picasso3.TestUtils.MEDIA_STORE_CONTENT_KEY_1
import com.squareup.picasso3.TestUtils.MEDIA_STORE_CONTENT_KEY_2
import com.squareup.picasso3.TestUtils.makeBitmap
import com.squareup.picasso3.TestUtils.mockAction
import com.squareup.picasso3.TestUtils.mockPicasso
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(shadows = [ShadowVideoThumbnails::class, ShadowImageThumbnails::class])
class MediaStoreRequestHandlerTest {
private lateinit var context: Context
private lateinit var picasso: Picasso
@Before fun setUp() {
context = RuntimeEnvironment.getApplication().applicationContext
picasso = mockPicasso(context)
Robolectric.setupContentProvider(TestContentProvider::class.java, "media")
}
@Test fun decodesVideoThumbnailWithVideoMimeType() {
val bitmap = makeBitmap()
val request = Request.Builder(
uri = MEDIA_STORE_CONTENT_2_URL,
resourceId = 0,
bitmapConfig = ARGB_8888
)
.stableKey(MEDIA_STORE_CONTENT_KEY_2)
.resize(100, 100)
.build()
val action = mockAction(picasso, request)
val requestHandler = MediaStoreRequestHandler(context)
requestHandler.load(
picasso = picasso,
request = action.request,
callback = object : Callback {
override fun onSuccess(result: RequestHandler.Result?) =
assertBitmapsEqual((result as RequestHandler.Result.Bitmap?)!!.bitmap, bitmap)
override fun onError(t: Throwable) = fail(t.message)
}
)
}
@Test fun decodesImageThumbnailWithImageMimeType() {
val bitmap = makeBitmap(20, 20)
val request = Request.Builder(
uri = MEDIA_STORE_CONTENT_1_URL,
resourceId = 0,
bitmapConfig = ARGB_8888
)
.stableKey(MEDIA_STORE_CONTENT_KEY_1)
.resize(100, 100)
.build()
val action = mockAction(picasso, request)
val requestHandler = MediaStoreRequestHandler(context)
requestHandler.load(
picasso = picasso,
request = action.request,
callback = object : Callback {
override fun onSuccess(result: RequestHandler.Result?) =
assertBitmapsEqual((result as RequestHandler.Result.Bitmap?)!!.bitmap, bitmap)
override fun onError(t: Throwable) = fail(t.message)
}
)
}
@Test fun getPicassoKindMicro() {
assertThat(getPicassoKind(96, 96)).isEqualTo(MICRO)
assertThat(getPicassoKind(95, 95)).isEqualTo(MICRO)
}
@Test fun getPicassoKindMini() {
assertThat(getPicassoKind(512, 384)).isEqualTo(MINI)
assertThat(getPicassoKind(100, 100)).isEqualTo(MINI)
}
@Test fun getPicassoKindFull() {
assertThat(getPicassoKind(513, 385)).isEqualTo(FULL)
assertThat(getPicassoKind(1000, 1000)).isEqualTo(FULL)
assertThat(getPicassoKind(1000, 384)).isEqualTo(FULL)
assertThat(getPicassoKind(1000, 96)).isEqualTo(FULL)
assertThat(getPicassoKind(96, 1000)).isEqualTo(FULL)
}
private fun assertBitmapsEqual(a: Bitmap, b: Bitmap) {
assertThat(a.height).isEqualTo(b.height)
assertThat(a.width).isEqualTo(b.width)
assertThat(shadowOf(a).description).isEqualTo(shadowOf(b).description)
}
}
| apache-2.0 | d67dba420dbb4388cf5ca46c00309871 | 36.302326 | 88 | 0.752286 | 4.123393 | false | true | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/exception/NetSubscriber.kt | 1 | 1067 | package csumissu.weatherforecast.exception
import csumissu.weatherforecast.common.BaseContract
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
/**
* @author yxsun
* @since 20/08/2017
*/
abstract class NetSubscriber<T>(private val baseView: BaseContract.IView? = null) : Subscriber<T> {
override fun onSubscribe(s: Subscription) {
baseView?.showProgress()
s.request(Long.MAX_VALUE)
}
override fun onComplete() {
baseView?.hideProgress()
}
override fun onError(t: Throwable) {
baseView?.hideProgress()
val error = transformError(t)
error.printStackTrace()
onFailed(error)
}
protected abstract fun onFailed(error: ResponseException)
private fun transformError(t: Throwable): ResponseException {
return if (t is ResponseException) {
t
} else {
val error = ResponseException(t)
error.errorCode = ErrorCode.INNER_ERROR
error.displayMessage = 0
error
}
}
} | mit | 4d8293adea0e7162698b3b355c1fa606 | 23.837209 | 99 | 0.651359 | 4.721239 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/ui/settings/license/LicensesFragment.kt | 1 | 3487 | /*
* Copyright (c) 2017 Lizhaotailang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.tonnyl.mango.ui.settings.license
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import io.github.tonnyl.mango.R
import kotlinx.android.synthetic.main.fragment_licenses.*
/**
* Created by lizhaotailang on 2017/7/21.
*
* Main ui for the licenses screen.
*/
class LicensesFragment : Fragment(), LicensesContract.View {
private lateinit var mPresenter: LicensesContract.Presenter
companion object {
@JvmStatic
fun newInstance(): LicensesFragment {
return LicensesFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_licenses, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
mPresenter.subscribe()
web_view.loadUrl("file:///android_asset/licenses.html")
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.unsubscribe()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
activity?.onBackPressed()
}
return true
}
override fun setPresenter(presenter: LicensesContract.Presenter) {
mPresenter = presenter
}
private fun initViews() {
val settings = web_view.settings
settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
settings.defaultTextEncodingName = "UTF-8"
settings.blockNetworkImage = false
settings.domStorageEnabled = true
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
web_view.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(webView: WebView?, request: WebResourceRequest?): Boolean {
webView?.loadUrl(request?.url.toString())
return true
}
}
}
} | mit | 6ec3b054dec491c742b9c02977ca02ac | 32.864078 | 116 | 0.714368 | 4.789835 | false | false | false | false |
GunoH/intellij-community | java/compiler/impl/src/com/intellij/compiler/cache/client/JpsServerAuthExtension.kt | 5 | 3688 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.compiler.cache.client
import com.intellij.compiler.cache.ui.CompilerCacheNotifications
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.EDT
import com.intellij.openapi.compiler.JavaCompilerBundle
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Extension point which provides authentication data for requests to the JPS cache server
*/
interface JpsServerAuthExtension {
/**
* This method should check if the user was authenticated, if not it should do any needed actions to provide
* auth token for further requests. This method will be called outside the EDT and should be asynchronous.
* If the user was authenticated the callback should be invoked.
*
* @param presentableReason reason for the token request
* @param parentDisposable controls the lifetime of the authentication
* @param onAuthCompleted callback on authentication complete, if token already exists it also should be invoked
*/
fun checkAuthenticated(presentableReason: String, parentDisposable: Disposable, onAuthCompleted: Runnable)
/**
* The method provides HTTP authentication headers for the requests to the server.
* It will be called in the background thread. The assertion that thread isn't EDT can
* be added to the implementation.
* @return Map with header name as key and token. If it's not possible to get the authentication
* headers, `null` will be returned.
*/
fun getAuthHeader(force: Boolean): Map<String, String>?
companion object {
private val NOTIFICATION_SHOWN_KEY = Key.create<Boolean>("AUTH_NOTIFICATION_SHOWN")
val EP_NAME = ExtensionPointName<JpsServerAuthExtension>("com.intellij.jpsServerAuthExtension")
fun getInstance(): JpsServerAuthExtension? = EP_NAME.extensionList.firstOrNull()
suspend fun checkAuthenticated(parentDisposable: Disposable, project: Project, onAuthCompleted: Runnable) {
val disposable = Disposer.newDisposable()
Disposer.register(parentDisposable, disposable)
val authExtension = getInstance()
if (authExtension == null) {
val userData = project.getUserData(NOTIFICATION_SHOWN_KEY)
if (userData == null) {
project.putUserData(NOTIFICATION_SHOWN_KEY, java.lang.Boolean.TRUE)
withContext(Dispatchers.EDT) {
CompilerCacheNotifications.ATTENTION
.createNotification(JavaCompilerBundle.message("notification.title.jps.caches.downloader"),
JavaCompilerBundle.message(
"notification.content.internal.authentication.plugin.required.for.correct.work"),
NotificationType.WARNING)
.setListener(NotificationListener.URL_OPENING_LISTENER)
.notify(project)
}
}
thisLogger().warn("JetBrains Internal Authentication plugin is required for the correct work. Please enable it.")
return
}
withContext(Dispatchers.IO) {
authExtension.checkAuthenticated("Jps Caches Downloader", disposable, Runnable {
Disposer.dispose(disposable)
onAuthCompleted.run()
})
}
}
}
} | apache-2.0 | 894cb88c5fa03511ae3d13b3cb5ae284 | 46.909091 | 121 | 0.734273 | 5.017687 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHRepoVirtualFile.kt | 8 | 2411 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.diff.editor.DiffVirtualFileBase.Companion.turnOffReopeningWindow
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.openapi.vfs.VirtualFileSystem
import com.intellij.openapi.vfs.VirtualFileWithoutContent
import com.intellij.testFramework.LightVirtualFileBase
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
/**
* [fileManagerId] is a [org.jetbrains.plugins.github.pullrequest.data.GHPRFilesManagerImpl.id] which is required to differentiate files
* between launches of a PR toolwindow.
* This is necessary to make the files appear in "Recent Files" correctly.
* See [com.intellij.vcs.editor.ComplexPathVirtualFileSystem.ComplexPath.sessionId] for details.
*/
abstract class GHRepoVirtualFile(protected val fileManagerId: String,
val project: Project,
val repository: GHRepositoryCoordinates)
: LightVirtualFileBase("", null, 0), VirtualFileWithoutContent, VirtualFilePathWrapper {
init {
turnOffReopeningWindow()
}
override fun enforcePresentableName() = true
override fun getFileSystem(): VirtualFileSystem = GHPRVirtualFileSystem.getInstance()
override fun getFileType(): FileType = FileTypes.UNKNOWN
override fun getLength() = 0L
override fun contentsToByteArray() = throw UnsupportedOperationException()
override fun getInputStream() = throw UnsupportedOperationException()
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long) = throw UnsupportedOperationException()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHRepoVirtualFile) return false
if (fileManagerId != other.fileManagerId) return false
if (project != other.project) return false
if (repository != other.repository) return false
return true
}
override fun hashCode(): Int {
var result = fileManagerId.hashCode()
result = 31 * result + project.hashCode()
result = 31 * result + repository.hashCode()
return result
}
}
| apache-2.0 | 29f86120e07edc34c196f5b5b9ef5244 | 42.053571 | 140 | 0.765657 | 4.841365 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/stories/ChooseGroupStoryBottomSheet.kt | 1 | 5174 | package org.thoughtcrime.securesms.mediasend.v2.stories
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.setFragmentResult
import androidx.recyclerview.widget.RecyclerView
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.contacts.paged.ContactSearchConfiguration
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.contacts.paged.ContactSearchMediator
import org.thoughtcrime.securesms.sharing.ShareContact
import org.thoughtcrime.securesms.sharing.ShareSelectionAdapter
import org.thoughtcrime.securesms.sharing.ShareSelectionMappingModel
import org.thoughtcrime.securesms.util.FeatureFlags
class ChooseGroupStoryBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() {
companion object {
const val GROUP_STORY = "group-story"
const val RESULT_SET = "groups"
}
private lateinit var confirmButton: View
private lateinit var selectedList: RecyclerView
private lateinit var backgroundHelper: View
private lateinit var divider: View
private lateinit var mediator: ContactSearchMediator
private var animatorSet: AnimatorSet? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)).inflate(R.layout.stories_choose_group_bottom_sheet, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.minimumHeight = resources.displayMetrics.heightPixels
val container = view.parent.parent.parent as FrameLayout
val bottomBar = LayoutInflater.from(requireContext()).inflate(R.layout.stories_choose_group_bottom_bar, container, true)
confirmButton = bottomBar.findViewById(R.id.share_confirm)
selectedList = bottomBar.findViewById(R.id.selected_list)
backgroundHelper = bottomBar.findViewById(R.id.background_helper)
divider = bottomBar.findViewById(R.id.divider)
val adapter = ShareSelectionAdapter()
selectedList.adapter = adapter
confirmButton.setOnClickListener {
onDone()
}
val contactRecycler: RecyclerView = view.findViewById(R.id.contact_recycler)
mediator = ContactSearchMediator(
this,
contactRecycler,
FeatureFlags.shareSelectionLimit(),
true
) { state ->
ContactSearchConfiguration.build {
query = state.query
addSection(
ContactSearchConfiguration.Section.Groups(
includeHeader = false,
returnAsGroupStories = true
)
)
}
}
mediator.getSelectionState().observe(viewLifecycleOwner) { state ->
adapter.submitList(
state.filterIsInstance(ContactSearchKey.RecipientSearchKey.Story::class.java)
.map { it.recipientId }
.mapIndexed { index, recipientId ->
ShareSelectionMappingModel(
ShareContact(recipientId),
index == 0
)
}
)
if (state.isEmpty()) {
animateOutBottomBar()
} else {
animateInBottomBar()
}
}
val searchField: EditText = view.findViewById(R.id.search_field)
searchField.doAfterTextChanged {
mediator.onFilterChanged(it?.toString())
}
}
override fun onDestroyView() {
super.onDestroyView()
animatorSet?.cancel()
}
private fun animateInBottomBar() {
animatorSet?.cancel()
animatorSet = AnimatorSet().apply {
playTogether(
ObjectAnimator.ofFloat(confirmButton, View.ALPHA, 1f),
ObjectAnimator.ofFloat(selectedList, View.TRANSLATION_Y, 0f),
ObjectAnimator.ofFloat(backgroundHelper, View.TRANSLATION_Y, 0f),
ObjectAnimator.ofFloat(divider, View.TRANSLATION_Y, 0f)
)
start()
}
}
private fun animateOutBottomBar() {
val translationY = DimensionUnit.DP.toPixels(48f)
animatorSet?.cancel()
animatorSet = AnimatorSet().apply {
playTogether(
ObjectAnimator.ofFloat(confirmButton, View.ALPHA, 0f),
ObjectAnimator.ofFloat(selectedList, View.TRANSLATION_Y, translationY),
ObjectAnimator.ofFloat(backgroundHelper, View.TRANSLATION_Y, translationY),
ObjectAnimator.ofFloat(divider, View.TRANSLATION_Y, translationY)
)
start()
}
}
private fun onDone() {
setFragmentResult(
GROUP_STORY,
Bundle().apply {
putParcelableArrayList(
RESULT_SET,
ArrayList(
mediator.getSelectedContacts()
.filterIsInstance(ContactSearchKey.RecipientSearchKey.Story::class.java)
.map { it.recipientId }
)
)
}
)
dismissAllowingStateLoss()
}
}
| gpl-3.0 | 8bfc91e21ea52b09ba95bf20f1a50716 | 32.166667 | 155 | 0.724005 | 4.908918 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-cbor/jvm/test/CborClientKotlinxSerializationTest.kt | 1 | 1767 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.serialization.kotlinx.test.cbor
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.contentnegotiation.tests.*
import io.ktor.http.*
import io.ktor.serialization.*
import io.ktor.serialization.kotlinx.*
import io.ktor.serialization.kotlinx.cbor.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import kotlinx.serialization.*
import kotlinx.serialization.cbor.*
import kotlinx.serialization.json.*
import org.junit.*
@OptIn(ExperimentalSerializationApi::class)
class CborClientKotlinxSerializationTest : AbstractClientContentNegotiationTest() {
override val defaultContentType: ContentType = ContentType.Application.Cbor
override val customContentType: ContentType = ContentType.parse("application/x-cbor")
override val webSocketsConverter: WebsocketContentConverter = KotlinxWebsocketSerializationConverter(DefaultCbor)
override fun ContentNegotiation.Config.configureContentNegotiation(contentType: ContentType) {
cbor(contentType = contentType)
}
override suspend fun <T : Any> ApplicationCall.respond(
responseJson: String,
contentType: ContentType,
serializer: KSerializer<T>
) {
val actual = Json.decodeFromString(serializer, responseJson)
val bytes = Cbor.encodeToByteArray(serializer, actual)
respondBytes(bytes, contentType)
}
override suspend fun ApplicationCall.respondWithRequestBody(contentType: ContentType) {
respondBytes(receive(), contentType)
}
@Test
@Ignore
override fun testSerializeNull() {
}
}
| apache-2.0 | 1d42fcbfd2d7555b5eff73559bbee7e8 | 35.8125 | 119 | 0.765705 | 4.565891 | false | true | false | false |
pureal-code/pureal-os | traits/src/net/pureal/traits/math/Vector3.kt | 1 | 2050 | package net.pureal.traits
trait Vector3 : Numbers {
fun plus(other: Vector3): Vector3 = vector(x.toDouble() + other.x.toDouble(), y.toDouble() + other.y.toDouble(), z.toDouble() + other.z.toDouble())
fun times(other: Number): Vector3 {
val s = other.toDouble()
return vector(x.toDouble() * s, y.toDouble() * s, z.toDouble() * s)
}
fun plus() = this
fun minus() = this * -1
fun minus(other: Vector3) = this + (-other)
fun div(other: Number) = this * (1 / other.toDouble())
fun get(i: Int): Number = when (i) {
0 -> x
1 -> y
2 -> z
else -> {
throw IllegalArgumentException()
}
}
val x: Number
val y: Number
val z: Number
val lengthSquared: Number get() {
val x = x.toDouble()
val y = y.toDouble()
val z = z.toDouble()
return x * x + y * y + z * z
}
val length: Number get() = Math.sqrt(lengthSquared.toDouble())
fun dotProduct(other: Vector3): Number = x.toDouble() * other.x.toDouble() + y.toDouble() * other.y.toDouble() + z.toDouble() * other.z.toDouble()
override fun iterator() = listOf(x, y, z).iterator()
override fun equals(other: Any?) = other is Vector3 && (x.toDouble() == other.x.toDouble() && y.toDouble() == other.y.toDouble() && z.toDouble() == other.z.toDouble())
override fun toString() = "vector(${x.toDouble()}, ${y.toDouble()}, ${z.toDouble()})"
fun times(other: Vector3) = this.dotProduct(other)
fun crossProduct(other: Vector3): Vector3 = vector(
y.toDouble() * other.z.toDouble() - z.toDouble() * other.y.toDouble(),
z.toDouble() * other.x.toDouble() - x.toDouble() * other.z.toDouble(),
x.toDouble() * other.y.toDouble() - y.toDouble() * other.x.toDouble())
}
fun vector(x: Number, y: Number, z: Number) = object : Vector3 {
override val x = x
override val y = y
override val z = z
}
fun vector3(get: (Int) -> Number) = vector(get(0), get(1), get(2))
val zeroVector3 = vector(0, 0, 0) | bsd-3-clause | 6bed20a5d96fb9977e0448f9cbb6728a | 34.362069 | 171 | 0.578537 | 3.39404 | false | false | false | false |
wcaokaze/JapaneCraft | japanecraft-core/src/main/kotlin/com/wcaokaze/japanecraft/JapaneCraftCore.kt | 1 | 6046 | package com.wcaokaze.japanecraft
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Executors
import kotlin.reflect.KProperty
class JapaneCraftCore(
private val configLoader: ConfigLoader,
private val romajiTableConfigLoader: RomajiTableConfigLoader,
private val dictionaryConfigLoader: DictionaryConfigLoader
) {
private val executor = Executors.newScheduledThreadPool(3)
private fun getConfiguration(): Configuration = configLoader.loadConfig()
private val romajiRegex: Regex by cached(
{ getConfiguration().romajiRegex },
{ Regex(it) }
)
private val timeFormatter: DateFormat by cached(
{ getConfiguration().timeFormat },
{ SimpleDateFormat(it) }
)
private val chatFormatter: VariableExpander by cached(
{ getConfiguration().chatFormat },
{ VariableExpander(it) }
)
data class ChatMessage(
val username: String,
val message: String,
val postDate: Date
)
data class ConvertResult(
val rawMessage: ChatMessage,
val japaneseMessage: String
)
fun interface ConversionFinishCallback {
fun onConverted(formattedMessage: String)
}
fun formatConvertedMessage(
chatMessage: ChatMessage,
conversionFinishCallback: ConversionFinishCallback
) {
executor.submit {
val convertedMessage = formatConvertedMessage(chatMessage)
conversionFinishCallback.onConverted(convertedMessage)
}
}
fun formatConvertedMessage(chatMessage: ChatMessage): String {
return try {
format(convert(chatMessage))
} catch (e: Exception) {
chatMessage.message
}
}
fun format(convertResult: ConvertResult): String {
val variableMap = mapOf(
"n" to "\n",
"$" to "\$",
"username" to convertResult.rawMessage.username,
"time" to timeFormatter.format(convertResult.rawMessage.postDate),
"rawMessage" to convertResult.rawMessage.message,
"convertedMessage" to convertResult.japaneseMessage
)
return chatFormatter.expand(variableMap)
}
fun convert(rawMessage: ChatMessage): ConvertResult {
try {
if (rawMessage.message.any { it >= 0x80.toChar() }) {
return ConvertResult(rawMessage, rawMessage.message)
}
val japaneseMessage = convertToJapanese(rawMessage.message)
if (japaneseMessage == rawMessage.message.filter { it != '`' }) {
return ConvertResult(rawMessage, rawMessage.message)
}
return ConvertResult(rawMessage, japaneseMessage)
} catch (e: Exception) {
return ConvertResult(rawMessage, rawMessage.message)
}
}
private fun convertToJapanese(englishMessage: String): String {
val configuration = getConfiguration()
val dictionaryAppliedWords = englishMessage.split('`')
.asSequence()
.flatMapIndexed { i, chunk ->
if (i % 2 == 1) {
sequenceOf(KanjiConverter.Word(KanjiConverter.Word.Type.ENGLISH, chunk))
} else {
val romajiChunks = splitWords(
chunk, configuration.wordSeparators.toCharArray())
romajiChunks.flatMap { romaji ->
if (romaji.matches(romajiRegex)) {
val hiragana = convertToHiragana(romaji)
val dictionaryAppliedChunks = applyDictionary(hiragana)
dictionaryAppliedChunks.map { appliedChunk ->
val type = if (appliedChunk.isApplied) {
KanjiConverter.Word.Type.DICTIONARY_APPLIED
} else {
KanjiConverter.Word.Type.HIRAGANA
}
KanjiConverter.Word(type, appliedChunk.text)
}
} else {
val dictionaryAppliedChunks = applyDictionary(romaji)
dictionaryAppliedChunks.map { appliedChunk ->
val type = if (appliedChunk.isApplied) {
KanjiConverter.Word.Type.DICTIONARY_APPLIED
} else {
KanjiConverter.Word.Type.ENGLISH
}
KanjiConverter.Word(type, appliedChunk.text)
}
}
}
}
}
if (!configuration.kanjiConverterEnabled) {
return dictionaryAppliedWords.joinToString(separator = "") { it.text }
}
return KanjiConverter.convertToKanji(dictionaryAppliedWords)
}
private fun convertToHiragana(romaji: String): String {
return romajiTableConfigLoader.get().convertToHiragana(romaji)
}
private fun applyDictionary(hiragana: String): Iterable<Dictionary.AppliedChunk> {
return dictionaryConfigLoader.get().apply(hiragana)
}
private fun splitWords(str: String, wordSeparatorChars: CharArray): Sequence<String> {
return sequence {
var i = 0
for (j in str.indices) {
if (str[j] in wordSeparatorChars) {
if (j > i) {
yield(str.substring(i, j))
}
yield(str.substring(j, j + 1))
i = j + 1
}
}
if (i < str.length) {
yield(str.substring(i))
}
}
}
private fun <K, T> cached(keyProvider: () -> K, valueProvider: (K) -> T) = object {
private var oldKey: K? = null
private var valueCache: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
val key = keyProvider()
if (key == oldKey) {
@Suppress("UNCHECKED_CAST")
return valueCache as T
}
val value = valueProvider(key)
oldKey = key
valueCache = value
return value
}
}
}
| mit | 7418d81f702b020ce904254436b60741 | 30.005128 | 89 | 0.587992 | 4.852327 | false | true | false | false |
werman/RadioDroid | app/src/play/java/net/programmierecke/radiodroid2/CastHandler.kt | 3 | 7238 | package net.programmierecke.radiodroid2
import android.content.Context
import android.net.Uri
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.google.android.gms.cast.MediaInfo
import com.google.android.gms.cast.MediaMetadata
import com.google.android.gms.cast.framework.*
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.images.WebImage
import net.programmierecke.radiodroid2.cast.CastAwareActivity
import net.programmierecke.radiodroid2.service.PauseReason
import net.programmierecke.radiodroid2.service.PlayerServiceUtil
private sealed class CastState {
abstract fun setActivity(activity: CastAwareActivity?)
abstract fun onPause()
abstract fun onResume()
abstract fun onSessionStarted(session: Session)
abstract fun onSessionResumed(session: Session)
abstract fun onSessionLost()
abstract fun play(title: String, url: String, iconurl: String?)
}
private object CastUnavailable : CastState() {
private const val TAG = "CastHandler.CastUnavailable"
override fun setActivity(activity: CastAwareActivity?) {
}
override fun onPause() {
}
override fun onResume() {
}
override fun onSessionStarted(session: Session) {
Log.e(TAG, "onSessionStarted: Illegal operation")
}
override fun onSessionResumed(session: Session) {
Log.e(TAG, "onSessionResumed: Illegal operation")
}
override fun onSessionLost() {
Log.e(TAG, "onSessionLost: Illegal operation")
}
override fun play(title: String, url: String, iconurl: String?) {
Log.e(TAG, "play: Illegal operation")
}
}
private class CastAvailable(val castContext: CastContext,
val sessionManager: SessionManager,
val sessionManagerListener: SessionManagerListener<Session>,
var castSession: CastSession?) : CastState() {
private var activity: CastAwareActivity? = null
override fun setActivity(activity: CastAwareActivity?) {
this.activity = activity
}
override fun onPause() {
sessionManager.removeSessionManagerListener(sessionManagerListener)
castSession = null
}
override fun onResume() {
sessionManager.addSessionManagerListener(sessionManagerListener)
castSession = sessionManager.currentCastSession
}
override fun onSessionStarted(session: Session) {
castSession = sessionManager.currentCastSession
invalidateOptions()
if (PlayerServiceUtil.isPlaying()) {
PlayerServiceUtil.pause(PauseReason.USER)
val station = PlayerServiceUtil.getCurrentStation()!!
play(station.Name, station.playableUrl, station.IconUrl)
}
}
override fun onSessionResumed(session: Session) {
castSession = sessionManager.currentCastSession
invalidateOptions()
}
override fun onSessionLost() {
castSession = null
invalidateOptions()
}
override fun play(title: String, url: String, iconurl: String?) {
val movieMetadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK)
movieMetadata.putString(MediaMetadata.KEY_TITLE, title)
movieMetadata.addImage(WebImage(Uri.parse(iconurl)))
val mediaInfo = MediaInfo.Builder(url)
.setStreamType(MediaInfo.STREAM_TYPE_LIVE)
.setContentType("audio/ogg")
.setMetadata(movieMetadata)
.build()
castSession?.remoteMediaClient?.load(mediaInfo, true)
}
private fun invalidateOptions() {
activity?.invalidateOptionsMenuForCast()
}
}
public class CastHandler {
companion object {
private const val TAG = "CastHandler"
}
private var castState: CastState = CastUnavailable
val isReal: Boolean
get() = true
val isCastAvailable: Boolean
get() = castState is CastAvailable
val isCastSessionAvailable: Boolean
get() = (castState as? CastAvailable)?.castSession != null
fun onCreate(context: Context) {
if (castState is CastAvailable) {
return
}
try {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(context)
if (result == ConnectionResult.SUCCESS) {
val castContext = CastContext.getSharedInstance(context)
val castState = CastAvailable(
castContext = castContext,
sessionManager = castContext.sessionManager,
sessionManagerListener = SessionManagerListenerImpl(),
castSession = null
)
castState.sessionManager.addSessionManagerListener(castState.sessionManagerListener)
this.castState = castState
}
} catch (e: Exception) {
Log.e(TAG, e.toString())
}
}
fun setActivity(activity: CastAwareActivity?) {
castState.setActivity(activity)
}
private inline fun <T, reified S : T> sealedIf(sealedInstance: T, block: (S) -> Unit): Any? {
return (sealedInstance as? S)?.also(block)
}
fun onPause() {
castState.onPause()
}
fun onResume() {
castState.onResume()
}
fun getRouteItem(context: Context, menu: Menu): MenuItem {
return CastButtonFactory.setUpMediaRouteButton(context,
menu,
R.id.media_route_menu_item)
}
fun playRemote(title: String, url: String, iconurl: String?) {
Log.i(TAG, title)
castState.play(title, url, iconurl)
}
inner class SessionManagerListenerImpl : SessionManagerListener<Session> {
override fun onSessionStarting(session: Session) {
Log.i(TAG, "onSessionStarting")
}
override fun onSessionStarted(session: Session, sessionId: String) {
Log.i(TAG, "onSessionStarted")
castState.onSessionStarted(session)
}
override fun onSessionStartFailed(session: Session, i: Int) {
Log.i(TAG, "onSessionStartFailed")
}
override fun onSessionEnding(session: Session) {
Log.i(TAG, "onSessionEnding")
}
override fun onSessionResumed(session: Session, wasSuspended: Boolean) {
Log.i(TAG, "onSessionStarting")
castState.onSessionResumed(session)
}
override fun onSessionResumeFailed(session: Session, i: Int) {
Log.i(TAG, "onSessionResumeFailed")
castState.onSessionLost()
}
override fun onSessionSuspended(session: Session, i: Int) {
Log.i(TAG, "onSessionSuspended")
castState.onSessionLost()
}
override fun onSessionEnded(session: Session, error: Int) {
Log.i(TAG, "onSessionEnded")
castState.onSessionLost()
}
override fun onSessionResuming(session: Session, s: String) {
Log.i(TAG, "onSessionResuming")
}
}
} | gpl-3.0 | f88c88021a3922949dd400bffdef5389 | 28.913223 | 100 | 0.648107 | 4.690862 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.