content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package io.gitlab.arturbosch.detekt.rules.style.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.SubRule
import org.jetbrains.kotlin.psi.KtClassOrObject
class ClassNaming(config: Config = Config.empty) : SubRule<KtClassOrObject>(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
debt = Debt.FIVE_MINS)
private val classPattern = Regex(valueOrDefault(CLASS_PATTERN, "^[A-Z$][a-zA-Z$]*$"))
override fun apply(element: KtClassOrObject) {
if (!element.identifierName().matches(classPattern)) {
report(CodeSmell(
issue.copy(description = "Class and Object names should match the pattern: $classPattern"),
Entity.from(element)))
}
}
companion object {
const val CLASS_PATTERN = "classPattern"
}
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/naming/ClassNaming.kt | 1839002078 |
/*
* Copyright 2016, Moshe Waisberg
*
* 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.duplicates.calendar
/**
* Calendar attendee.
*
* @author moshe.w
*/
class CalendarAttendee {
var id: Long = 0
var eventId: Long = 0
var email: String? = null
var name: String? = null
var status: Int = 0
var type: Int = 0
}
| duplicates-android/app/src/main/java/com/github/duplicates/calendar/CalendarAttendee.kt | 1478523545 |
package cs.ut.engine.tasks
import cs.ut.configuration.ConfigurationReader
import cs.ut.engine.Cache
import org.apache.logging.log4j.LogManager
import java.util.TimerTask
import kotlin.system.measureTimeMillis
class CacheCleanTask : TimerTask() {
override fun run() {
val time = measureTimeMillis {
log.debug("Running cache cleaning task")
log.debug("Cleaning job cache")
val toCleanUp = mutableListOf<String>()
Cache.jobCache.cachedItems().forEach { if (it.value.isExpired(timeToLive)) toCleanUp.add(it.key) }
log.debug("Found ${toCleanUp.size} items that will be cleaned up")
toCleanUp.forEach { Cache.jobCache.cachedItems().remove(it) }
log.debug("Job cache cleaned up")
log.debug("Cleaning up chart cache")
Cache.chartCache.values.forEach { holder ->
val chartCleanUp = mutableListOf<String>()
holder.cachedItems().forEach { if (it.value.isExpired(timeToLive)) chartCleanUp.add(it.key) }
log.debug("Cleaning up ${chartCleanUp.size} charts")
chartCleanUp.forEach { holder.cachedItems().remove(it) }
}
log.debug("Finished chart clean up")
}
log.debug("Clean up task finished in $time ms")
}
companion object {
private val log = LogManager.getLogger(CacheCleanTask::class)
private val timeToLive: Long =
ConfigurationReader.findNode("tasks/CacheCleanTask").valueWithIdentifier("timeToLive").value()
}
} | src/main/kotlin/cs/ut/engine/tasks/CacheCleanTask.kt | 1679955525 |
package org.http4k.aws
import org.http4k.security.HmacSha256
import org.http4k.security.HmacSha256.hmacSHA256
import org.http4k.util.Hex
internal object AwsSignatureV4Signer {
fun sign(
request: AwsCanonicalRequest,
scope: AwsCredentialScope,
awsCredentials: AwsCredentials,
date: AwsRequestDate
): String {
val signatureKey = getSignatureKey(awsCredentials.secretKey, date.basic, scope.region, scope.service)
val signature = hmacSHA256(signatureKey, request.stringToSign(scope, date))
return Hex.hex(signature)
}
private fun getSignatureKey(key: String, dateStamp: String, regionName: String, serviceName: String): ByteArray {
val kSecret = ("AWS4$key").toByteArray(charset("UTF8"))
val kDate = hmacSHA256(kSecret, dateStamp)
val kRegion = hmacSHA256(kDate, regionName)
val kService = hmacSHA256(kRegion, serviceName)
return hmacSHA256(kService, "aws4_request")
}
private fun AwsCanonicalRequest.stringToSign(requestScope: AwsCredentialScope, date: AwsRequestDate) =
"AWS4-HMAC-SHA256" +
"\n" +
date.full +
"\n" +
requestScope.datedScope(date) +
"\n" +
HmacSha256.hash(value)
}
| http4k-aws/src/main/kotlin/org/http4k/aws/AwsSignatureV4Signer.kt | 1483861011 |
package com.github.czyzby.setup.data.templates.official
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.ProjectTemplate
/**
* Generates no source files.
* @author MJ
*/
@ProjectTemplate(official = true)
class EmptyTemplate : Template {
override val id = "emptyTemplate"
override val description: String
get() = "No sources were generated."
override fun apply(project: Project) {
// Does nothing.
}
override fun getApplicationListenerContent(project: Project): String = ""
}
| src/main/kotlin/com/github/czyzby/setup/data/templates/official/empty.kt | 1384314747 |
package kotlin.sql.vendors
import java.util.*
import kotlin.sql.*
/**
* User: Andrey.Tarashevskiy
* Date: 08.05.2015
*/
internal object MysqlDialect : VendorDialect() {
override @Synchronized fun tableColumns(): Map<String, List<Pair<String, Boolean>>> {
val tables = HashMap<String, List<Pair<String, Boolean>>>()
val rs = Session.get().connection.createStatement().executeQuery(
"SELECT DISTINCT TABLE_NAME, COLUMN_NAME, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${getDatabase()}'")
while (rs.next()) {
val tableName = rs.getString("TABLE_NAME")!!
val columnName = rs.getString("COLUMN_NAME")!!
val nullable = rs.getBoolean("IS_NULLABLE")
tables[tableName] = (tables[tableName]?.plus(listOf(columnName to nullable)) ?: listOf(columnName to nullable))
}
return tables
}
override @Synchronized fun columnConstraints(vararg tables: Table): Map<Pair<String, String>, List<ForeignKeyConstraint>> {
val constraints = HashMap<Pair<String, String>, MutableList<ForeignKeyConstraint>>()
val tableNames = tables.map { it.tableName }
fun inTableList(): String {
if (tables.isNotEmpty()) {
return " AND ku.TABLE_NAME IN ${tableNames.joinToString("','", prefix = "('", postfix = "')")}"
}
return ""
}
val rs = Session.get().connection.createStatement().executeQuery(
"SELECT\n" +
" rc.CONSTRAINT_NAME,\n" +
" ku.TABLE_NAME,\n" +
" ku.COLUMN_NAME,\n" +
" ku.REFERENCED_TABLE_NAME,\n" +
" ku.REFERENCED_COLUMN_NAME,\n" +
" rc.DELETE_RULE\n" +
"FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n" +
" INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku\n" +
" ON ku.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA AND rc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME\n" +
"WHERE ku.TABLE_SCHEMA = '${getDatabase()}' ${inTableList()}")
while (rs.next()) {
val refereeTableName = rs.getString("TABLE_NAME")!!
if (refereeTableName !in tableNames) continue
val refereeColumnName = rs.getString("COLUMN_NAME")!!
val constraintName = rs.getString("CONSTRAINT_NAME")!!
val refTableName = rs.getString("REFERENCED_TABLE_NAME")!!
val refColumnName = rs.getString("REFERENCED_COLUMN_NAME")!!
val constraintDeleteRule = ReferenceOption.valueOf(rs.getString("DELETE_RULE")!!.replace(" ", "_"))
constraints.getOrPut(Pair(refereeTableName, refereeColumnName), {arrayListOf()}).add(ForeignKeyConstraint(constraintName, refereeTableName, refereeColumnName, refTableName, refColumnName, constraintDeleteRule))
}
return constraints
}
override @Synchronized fun existingIndices(vararg tables: Table): Map<String, List<Index>> {
val constraints = HashMap<String, MutableList<Index>>()
val rs = Session.get().connection.createStatement().executeQuery(
"""SELECT ind.* from (
SELECT
TABLE_NAME, INDEX_NAME, GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `COLUMNS`, NON_UNIQUE
FROM INFORMATION_SCHEMA.STATISTICS s
WHERE table_schema = '${getDatabase()}' and INDEX_NAME <> 'PRIMARY'
GROUP BY 1, 2) ind
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
on kcu.TABLE_NAME = ind.TABLE_NAME
and kcu.COLUMN_NAME = ind.columns
and TABLE_SCHEMA = '${getDatabase()}'
and kcu.REFERENCED_TABLE_NAME is not NULL
WHERE kcu.COLUMN_NAME is NULL;
""")
while (rs.next()) {
val tableName = rs.getString("TABLE_NAME")!!
val indexName = rs.getString("INDEX_NAME")!!
val columnsInIndex = rs.getString("COLUMNS")!!.split(',')
val isUnique = rs.getInt("NON_UNIQUE") == 0
constraints.getOrPut(tableName, { arrayListOf() }).add(Index(indexName, tableName, columnsInIndex, isUnique))
}
return constraints
}
override fun getDatabase(): String {
return Session.get().connection.catalog
}
override fun <T : String?> ExpressionWithColumnType<T>.match(pattern: String, mode: MatchMode?): Op<Boolean> = MATCH(this, pattern, mode ?: MysqlMatchMode.STRICT)
private class MATCH(val expr: ExpressionWithColumnType<*>, val pattern: String, val mode: MatchMode): Op<Boolean>() {
override fun toSQL(queryBuilder: QueryBuilder): String {
return "MATCH(${expr.toSQL(queryBuilder)}) AGAINST ('$pattern' ${mode.mode()})"
}
}
}
enum class MysqlMatchMode(val operator: String): MatchMode {
STRICT("IN BOOLEAN MODE"),
NATURAL_LANGUAGE("IN NATURAL LANGUAGE MODE");
override fun mode() = operator
} | src/main/kotlin/kotlin/sql/vendors/Mysql.kt | 4017106930 |
import com.github.umireon.my_random_stuff.Xorshift1024Star
import org.junit.Test
import kotlin.test.assertEquals
class Xorshift1024StarTest {
val rng = Xorshift1024Star(1)
@Test fun testNext() {
for (i in 0 until 9999) rng.next()
assertEquals(-7937336934166611007, rng.next())
}
@Test fun testJump() {
rng.jump()
assertEquals(-8637250259367291272, rng.next())
}
@Test fun testSplit() {
val newRng = rng.split()
rng.jump()
assertEquals(rng.next(), newRng.next())
}
}
| xorshift-kotlin/src/test/kotlin/Xorshift1024StarTest.kt | 3177209759 |
@file:Suppress("unused", "UnsafeCastFromDynamic", "NOTHING_TO_INLINE")
package org.musyozoku.vuekt
/**
* JavaScript native `this`
*/
external val `this`: dynamic
/**
* Typed JavaScript native `this`
*/
inline fun <T : Any> thisAs(): T = `this`
/**
* Type of `void 0`
*/
external interface Void
/**
* Constant of `void 0`
*/
val void: Void = js("void 0")
/**
* `{ [propertyName: String]: T }`
*/
external interface JsonOf<T>
inline operator fun <T> JsonOf<T>.get(propertyName: String): T = this.asDynamic()[propertyName]
inline operator fun <T> JsonOf<T>.set(propertyName: String, value: T) {
this.asDynamic()[propertyName] = value
}
/**
* `T | Array<T>`
*/
external interface OneOrMany<T>
inline fun <T> OneOrMany(value: T): OneOrMany<T> = value.asDynamic()
inline fun <T> OneOrMany(value: Array<T>): OneOrMany<T> = value.asDynamic()
| vuekt/src/main/kotlin/org/musyozoku/vuekt/util.kt | 2520494529 |
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.callTranslator
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.js.backend.ast.JsBlock
import org.jetbrains.kotlin.js.backend.ast.JsConditional
import org.jetbrains.kotlin.js.backend.ast.JsExpression
import org.jetbrains.kotlin.js.backend.ast.JsLiteral
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.reference.CallArgumentTranslator
import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils.getReceiverParameterForReceiver
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.isSafeCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
interface CallInfo {
val context: TranslationContext
val resolvedCall: ResolvedCall<out CallableDescriptor>
val dispatchReceiver: JsExpression?
val extensionReceiver: JsExpression?
fun constructSafeCallIfNeeded(result: JsExpression): JsExpression
}
abstract class AbstractCallInfo : CallInfo {
override fun toString(): String {
val location = DiagnosticUtils.atLocation(callableDescriptor)
val name = callableDescriptor.name.asString()
return "callableDescriptor: $name at $location; dispatchReceiver: $dispatchReceiver; extensionReceiver: $extensionReceiver"
}
}
// if value == null, it is get access
class VariableAccessInfo(callInfo: CallInfo, val value: JsExpression? = null) : AbstractCallInfo(), CallInfo by callInfo
class FunctionCallInfo(
callInfo: CallInfo,
val argumentsInfo: CallArgumentTranslator.ArgumentsInfo
) : AbstractCallInfo(), CallInfo by callInfo
/**
* no receivers - extensionOrDispatchReceiver = null, extensionReceiver = null
* this - extensionOrDispatchReceiver = this, extensionReceiver = null
* receiver - extensionOrDispatchReceiver = receiver, extensionReceiver = null
* both - extensionOrDispatchReceiver = this, extensionReceiver = receiver
*/
class ExplicitReceivers(val extensionOrDispatchReceiver: JsExpression?, val extensionReceiver: JsExpression? = null)
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
extensionOrDispatchReceiver: JsExpression?
): CallInfo {
return createCallInfo(resolvedCall, ExplicitReceivers(extensionOrDispatchReceiver))
}
// two receiver need only for FunctionCall in VariableAsFunctionResolvedCall
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out FunctionDescriptor>,
explicitReceivers: ExplicitReceivers
): FunctionCallInfo {
val argsBlock = JsBlock()
val argumentsInfo = CallArgumentTranslator.translate(resolvedCall, explicitReceivers.extensionOrDispatchReceiver, this, argsBlock)
val explicitReceiversCorrected =
if (!argsBlock.isEmpty && explicitReceivers.extensionOrDispatchReceiver != null) {
val receiverOrThisRef = cacheExpressionIfNeeded(explicitReceivers.extensionOrDispatchReceiver)
var receiverRef = explicitReceivers.extensionReceiver
if (receiverRef != null) {
receiverRef = defineTemporary(explicitReceivers.extensionReceiver!!)
}
ExplicitReceivers(receiverOrThisRef, receiverRef)
}
else {
explicitReceivers
}
this.addStatementsToCurrentBlockFrom(argsBlock)
val callInfo = createCallInfo(resolvedCall, explicitReceiversCorrected)
return FunctionCallInfo(callInfo, argumentsInfo)
}
private fun boxIfNeedeed(v: ReceiverValue?, d: ReceiverParameterDescriptor?, r: JsExpression?): JsExpression? {
if (r != null && v != null && KotlinBuiltIns.isCharOrNullableChar(v.type) &&
(d == null || !KotlinBuiltIns.isCharOrNullableChar(d.type))) {
return JsAstUtils.charToBoxedChar(r)
}
return r
}
private fun TranslationContext.getDispatchReceiver(receiverValue: ReceiverValue): JsExpression {
return getDispatchReceiver(getReceiverParameterForReceiver(receiverValue))
}
private fun TranslationContext.createCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
explicitReceivers: ExplicitReceivers
): CallInfo {
val receiverKind = resolvedCall.explicitReceiverKind
// I'm not sure if it's a proper code, and why it should work. Just copied similar logic from ExpressionCodegen.generateConstructorCall.
// See box/classes/inner/instantiateInDerived.kt
// TODO: revisit this code later, write more tests (or borrow them from JVM backend)
fun getDispatchReceiver(): JsExpression? {
val receiverValue = resolvedCall.dispatchReceiver ?: return null
return when (receiverKind) {
DISPATCH_RECEIVER, BOTH_RECEIVERS -> explicitReceivers.extensionOrDispatchReceiver
else -> getDispatchReceiver(receiverValue)
}
}
fun getExtensionReceiver(): JsExpression? {
val receiverValue = resolvedCall.extensionReceiver ?: return null
return when (receiverKind) {
EXTENSION_RECEIVER -> explicitReceivers.extensionOrDispatchReceiver
BOTH_RECEIVERS -> explicitReceivers.extensionReceiver
else -> getDispatchReceiver(receiverValue)
}
}
var dispatchReceiver = getDispatchReceiver()
// if (dispatchReceiver.toString().contains("myFuckingDir")) {
// "break on me"
// }
var extensionReceiver = getExtensionReceiver()
var notNullConditional: JsConditional? = null
if (resolvedCall.call.isSafeCall()) {
when (resolvedCall.explicitReceiverKind) {
BOTH_RECEIVERS, EXTENSION_RECEIVER -> {
notNullConditional = TranslationUtils.notNullConditional(extensionReceiver!!, JsLiteral.NULL, this)
extensionReceiver = notNullConditional.thenExpression
}
else -> {
notNullConditional = TranslationUtils.notNullConditional(dispatchReceiver!!, JsLiteral.NULL, this)
dispatchReceiver = notNullConditional.thenExpression
}
}
}
if (dispatchReceiver == null) {
val container = resolvedCall.resultingDescriptor.containingDeclaration
if (DescriptorUtils.isObject(container)) {
dispatchReceiver = ReferenceTranslator.translateAsValueReference(container, this)
}
}
dispatchReceiver = boxIfNeedeed(resolvedCall.dispatchReceiver,
resolvedCall.candidateDescriptor.dispatchReceiverParameter,
dispatchReceiver)
extensionReceiver = boxIfNeedeed(resolvedCall.extensionReceiver,
resolvedCall.candidateDescriptor.extensionReceiverParameter,
extensionReceiver)
return object : AbstractCallInfo(), CallInfo {
override val context: TranslationContext = this@createCallInfo
override val resolvedCall: ResolvedCall<out CallableDescriptor> = resolvedCall
override val dispatchReceiver: JsExpression? = dispatchReceiver
override val extensionReceiver: JsExpression? = extensionReceiver
val notNullConditionalForSafeCall: JsConditional? = notNullConditional
override fun constructSafeCallIfNeeded(result: JsExpression): JsExpression {
if (notNullConditionalForSafeCall == null) {
return result
}
else {
notNullConditionalForSafeCall.thenExpression = result
return notNullConditionalForSafeCall
}
}
}
}
| k2php/src/org/jetbrains/kotlin/js/translate/callTranslator/CallInfo.kt | 1366924258 |
/*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.ws.doclet
import java.io.Writer
/**
* Created by pdvrieze on 11/04/16.
*/
interface Table {
var targetWidth: Int
fun row(block: Row.()->Unit)
}
inline fun Row.col(c: CharSequence) {
col {text(c)}
}
interface Row {
/** Create a simple column */
fun col(block: Cell.()->Unit)
/** Create a paragraph column that does word wrapping*/
fun parcol(block: Cell.()->Unit)
}
interface Cell : FlowContent {
val width: Int
}
interface FlowContent {
fun text(c:CharSequence)
fun link(target:CharSequence, label:CharSequence?=null)
}
interface OutputGenerator: FlowContent {
fun heading1(s:CharSequence)
fun heading2(s:CharSequence)
fun heading3(s:CharSequence)
fun appendln(s:CharSequence)
fun appendln()
fun table(vararg columns:String, block: Table.()->Unit)
}
fun Writer.markDown(block: OutputGenerator.()->Unit) = this.use { MdGen(it).block() }
private class MdTable(val columns: Array<out String>) : Table {
fun appendTo(out: Appendable) {
val foldable = BooleanArray(columns.size)
val desiredColWidths = rows.fold(columns.map { it.length }.toTypedArray()) { array, row ->
row.cells.forEachIndexed { i, cell ->
if (cell.wrapped) {
foldable[i]=true
} else {
array[i] = Math.max(array[i], cell.width)
}
}
array
}
val foldableCount = foldable.count()
if (foldableCount>0) {
val totalExtra = targetWidth - (columns.size * 3 + 1) - desiredColWidths.sum()
if (totalExtra>0) { // Slightly complicated to handle rounding errors
var seenColumns = 0
var usedSpace = 0
foldable.forEachIndexed { i, foldable ->
if (foldable) {
++seenColumns
val extraSpace = (totalExtra * seenColumns / foldableCount) - usedSpace
desiredColWidths[i]+=extraSpace
usedSpace+=extraSpace
}
}
}
}
columns.mapIndexed { i, h -> "$h${' '.pad(desiredColWidths[i]-h.length)}" }.joinTo(out, " | ", "| ", " |")
out.appendln()
desiredColWidths.joinTo(out, "-|-", "|-", "-|") { '-'.pad(it) }
out.appendln()
rows.forEach { row ->
if (row.cells.count { it.wrapped }>0) {
val lines= row.cells.mapIndexed { i, cell -> // Make the cells into lists of lines
val escapedText = Escaper('|').apply { cell.appendTo(this) }
if (foldable[i]) {
escapedText.wordWrap(desiredColWidths[i])
} else {
sequenceOf(escapedText)
}
}.asSequence().flip()
lines.forEach { line ->
line.mapIndexed { i, part -> if (part==null) ' '.pad(desiredColWidths[i]) else "$part${' '.pad(desiredColWidths[i]-part.length)}" }
.joinTo(out, " | ", "| ", " |")
out.appendln()
}
} else {
row.cells.mapIndexed { i, cell ->
val text = Escaper('|').apply{ cell.appendTo(this) }
"$text${' '.pad(desiredColWidths[i]-text.length)}"
}.joinTo(out," | ", "| ", " |")
out.appendln()
}
}
}
private class Escaper(val escapeChar:Char='\\', vararg val escapedChars:Char): Appendable, CharSequence {
private val buffer= StringBuilder()
override val length: Int get() = buffer.length
override fun get(index: Int): Char = buffer.get(index)
override fun subSequence(startIndex: Int, endIndex: Int) = buffer.subSequence(startIndex, endIndex)
override fun append(csq: CharSequence?): Appendable = append(csq, 0, csq?.length?:4)
override fun append(csq: CharSequence?, start: Int, end: Int): Appendable {
if (csq==null) return append("null", start, end)
csq.forEach { append(it) }
return this
}
override fun append(c: Char): Appendable {
if (c==escapeChar || escapedChars.contains(c)) {
buffer.append(escapeChar)
}
buffer.append(c)
return this
}
override fun toString() = buffer.toString()
override fun equals(other: Any?) = buffer.equals(other)
override fun hashCode() = buffer.hashCode()
}
private val rows = mutableListOf<MdRow>()
override var targetWidth:Int = 100
override fun row(block: Row.() -> Unit) {
rows.add(MdRow(columns.size).apply { block() })
}
}
fun CharSequence.wordWrap(maxWidth:Int) : Sequence<CharSequence> {
val result = mutableListOf<CharSequence>()
var start=0
var lastWordEnd=0
forEachIndexed { i, c ->
when (c) {
'\n', '\r', ' ' -> lastWordEnd=i
',', '.', '!', '?' -> lastWordEnd=i+1
}
if ((start<=lastWordEnd && i-start>=maxWidth) || c=='\n' || c=='\r') { // don't wrap if the word is too long
result.add(subSequence(start, lastWordEnd))
start = lastWordEnd
while(start<length && get(start)==' ') { start++ }// start after any spaces
}
}
if (lastWordEnd<length) {
val last = subSequence(start, length)
if (! last.isBlank()) { result.add(last) }
}
return result.asSequence()
}
private class FlipIterator<T>(inSeq:Sequence<Sequence<T>>):Iterator<Sequence<T?>> {
val innerSequences:List<Iterator<T>> = inSeq.map{it.iterator()}.toList()
override fun hasNext() = innerSequences.any { it.hasNext() }
override fun next(): Sequence<T?> {
return innerSequences.asSequence().map { if (it.hasNext()) it.next() else null }
}
}
fun <T> Sequence<Sequence<T>>.flip():Sequence<Sequence<T?>> = object:Sequence<Sequence<T?>> {
override fun iterator(): Iterator<Sequence<T?>> = FlipIterator<T>(this@flip)
}
private fun Char.pad(count:Int):CharSequence = object:CharSequence {
override val length: Int = if(count>0) count else 0
override fun get(index: Int) = this@pad
override fun subSequence(startIndex: Int, endIndex: Int) = [email protected](endIndex-startIndex)
override fun toString(): String = StringBuilder(length).append(this).toString()
}
private class MdRow(val colCount:Int):Row {
val cells = mutableListOf<MdCell>()
override fun col(block: Cell.() -> Unit) { cells.add(MdCell().apply { block() }) }
override fun parcol(block: Cell.() -> Unit) { cells.add(MdCell(true).apply { block() }) }
}
private class MdCell(val wrapped:Boolean=false):Cell {
private val buffer = StringBuilder()
override fun text(c: CharSequence) {
buffer.append(c.normalize())
}
override fun link(target: CharSequence, label: CharSequence?) = buffer._link(target, label)
fun appendTo(a:Appendable) { a.append(buffer) }
override val width: Int get() = buffer.length
}
private class StripNewLines(val orig:CharSequence):CharSequence {
override val length:Int get() = orig.length
override fun get(index: Int) = orig.get(index).let{ when (it) {
'\n', '\r', '\t' -> ' '
else -> it
} }
override fun subSequence(startIndex: Int, endIndex: Int):CharSequence {
val subSequence = orig.subSequence(startIndex, endIndex)
return subSequence.normalize()
}
override fun toString(): String {
return StringBuilder(length).append(this).toString()
}
}
fun CharSequence?.normalize():CharSequence = StringBuilder(this?.length?:0).apply {
this@normalize?.forEach { c ->
when(c) {
in '\u0000'..'\u001f', ' ', '\u00a0' -> if (length>0 && last()!=' ') append(' ')
else -> append(c)
}
}
}
fun CharSequence.tidy():CharSequence = StringBuilder(this.length).apply {
var addNewLines:Int=0
[email protected] { c ->
when(c) {
'\u000a', '\u000d' -> addNewLines ++
in '\u0000'..'\u0009', '\u000b', '\u000c', in '\u000e'..'\u001f', ' ', '\u00a0' -> if (length>0 && last()!=' ') append(' ')
else -> {
if (addNewLines>1){ appendln(); appendln() };
addNewLines=0;
append(c)
}
}
}
}
private fun Appendable._link(target:CharSequence, label: CharSequence?) {
if (label!=null) {
append("[$label]($target)")
} else if(target.startsWith('#')) {
append("[${target.substring(1)}]($target)")
} else {
append("<$target>")
}
}
private class MdGen(val out: Appendable): OutputGenerator {
override fun heading1(s: CharSequence) { out.appendln("# $s") }
override fun heading2(s: CharSequence) { out.appendln("## $s") }
override fun heading3(s: CharSequence) { out.appendln("### $s") }
override fun text(s: CharSequence) { out.appendln(s.tidy().wordWrap(WORDWRAP)) }
override fun appendln(s: CharSequence) { out.appendln(s) }
override fun appendln() { out.appendln() }
override fun link(target: CharSequence, label: CharSequence?) = out._link(target, label)
override fun table(vararg columns: String, block: Table.() -> Unit) {
MdTable(columns).apply { this.block() }.appendTo(out)
}
}
/**
* Append each of the charSequences in the parameters as a new line.
*
* @param seq The sequence of items to append.
*/
fun Appendable.appendln(seq: Sequence<CharSequence>) {
seq.forEach { appendln(it) }
}
| PE-common/endpointDoclet/src/main/kotlin/nl/adaptivity/ws/doclet/mdGen.kt | 3377562989 |
package de.troido.bleacon.beaconno
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Handler
import de.troido.bleacon.ble.HandledBleActor
import de.troido.bleacon.ble.obtainScanner
import de.troido.bleacon.config.scan.scanSettings
import de.troido.bleacon.data.BleDeserializer
import de.troido.bleacon.data.UndefinedDeserializer
import de.troido.bleacon.scanner.BeaconMetaData
/**
* Example usage:
* ```
* BeaconnoScanner(
* context,
* bleFilter(uuid16 = Uuid16.fromString("17CF")),
* Int16Deserializer,
* UUID16_TRANSFORM,
* scanSettings()
* ) { scanner, device ->
* device.connect(
* context,
* bleConnectionCallback(
* Uuid16.fromString("23FF").toUuid(),
* Uuid16.fromString("4566").toUuid()
* ) { writer ->
* writer.write("Hello ${device.data}!".toByteArray())
* }
* )
* Log.d("Beaconno", "Found a beaconno with ${device.data}!")
* }
* ```
*/
class BeaconnoScanner<T>(context: Context,
filter: ScanFilter,
deserializer: BleDeserializer<T> = UndefinedDeserializer(),
dataTransform: (ByteArray) -> ByteArray,
private val settings: ScanSettings = scanSettings(),
handler: Handler = Handler(),
private val listener: OnBeaconno<T>
) : HandledBleActor(handler) {
private val scanner = obtainScanner()
private val filters = listOf(filter)
private val callback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
result.scanRecord
?.let {
BeaconnoDevice(context, deserializer, dataTransform, it,
BeaconMetaData(result.device, result.rssi, it.txPowerLevel))
}
?.let { listener(this@BeaconnoScanner, it) }
}
}
override fun start() {
handler.post { scanner.startScan(filters, settings, callback) }
}
override fun stop() {
handler.post { scanner.stopScan(callback) }
}
}
| library/src/main/java/de/troido/bleacon/beaconno/BeaconnoScanner.kt | 1613039100 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.streetcomplete.testutils.any
import de.westnordost.streetcomplete.testutils.mock
import de.westnordost.streetcomplete.testutils.on
import org.junit.Assert.*
import org.junit.Test
class CombineFiltersTest {
@Test fun `does not match if one doesn't match`() {
val f1: ElementFilter = mock()
on(f1.matches(any())).thenReturn(true)
val f2: ElementFilter = mock()
on(f2.matches(any())).thenReturn(false)
assertFalse(CombineFilters(f1, f2).matches(null))
}
@Test fun `does match if all match`() {
val f1: ElementFilter = mock()
on(f1.matches(any())).thenReturn(true)
val f2: ElementFilter = mock()
on(f2.matches(any())).thenReturn(true)
assertTrue(CombineFilters(f1, f2).matches(null))
}
@Test fun `concatenates OQL`() {
val f1: ElementFilter = mock()
on(f1.toOverpassQLString()).thenReturn("hell")
val f2: ElementFilter = mock()
on(f2.toOverpassQLString()).thenReturn("o")
assertEquals("hello", CombineFilters(f1, f2).toOverpassQLString())
}
}
| app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/filters/CombineFiltersTest.kt | 2935761223 |
package com.hendraanggrian.openpss.ui.login
import android.app.Dialog
import android.content.Context.INPUT_METHOD_SERVICE
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.View.OnFocusChangeListener
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import com.hendraanggrian.bundler.Extra
import com.hendraanggrian.bundler.bindExtras
import com.hendraanggrian.bundler.extrasOf
import com.hendraanggrian.openpss.BuildConfig2
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.api.OpenPSSApi
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.ui.BaseDialogFragment
import com.hendraanggrian.openpss.ui.TextDialogFragment
import com.hendraanggrian.openpss.ui.main.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class PasswordDialogFragment : BaseDialogFragment() {
@Extra lateinit var loginName: String
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
bindExtras()
val editText = EditText(context).apply {
if (BuildConfig2.DEBUG) setText(Employee.DEFAULT_PASSWORD)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
onFocusChangeListener = OnFocusChangeListener { view, _ ->
view.post {
val inputMethodManager =
context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
val manager = openpssActivity.supportFragmentManager
val dialog = AlertDialog.Builder(context!!)
.setTitle(getString(R2.string.password))
.setView(FrameLayout(context!!).apply {
addView(editText)
val medium = context.resources.getDimensionPixelSize(R.dimen.padding_medium)
val large = context.resources.getDimensionPixelSize(R.dimen.padding_large)
(editText.layoutParams as ViewGroup.MarginLayoutParams).setMargins(
large,
medium,
large,
medium
)
})
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(getString(R2.string.login)) { _, _ ->
runBlocking {
runCatching {
val login = withContext(Dispatchers.IO) {
OpenPSSApi.login(loginName, editText.text)
}
if (login == Employee.NOT_FOUND) error(getString(R2.string.login_failed))
startActivity(
Intent(context, MainActivity::class.java).putExtras(
extrasOf<MainActivity>(
login.name,
login.isAdmin,
login.id.value
)
)
)
openpssActivity.finish()
}.onFailure {
if (BuildConfig2.DEBUG) it.printStackTrace()
TextDialogFragment()
.args(extrasOf<TextDialogFragment>(it.message.toString()))
.show(manager)
}
}
}
.create()
dialog.setOnShowListener { editText.requestFocus() }
return dialog
}
}
| openpss-client-android/src/com/hendraanggrian/openpss/ui/login/PasswordDialogFragment.kt | 3969118835 |
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf
import com.google.protobuf.GeneratedMessageV3
import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll
import io.kotlintest.specs.ShouldSpec
import kotlinx.serialization.Serializable
import kotlinx.serialization.protobuf.TestData.*
class RandomTest : ShouldSpec() {
companion object {
fun Gen<String>.generateNotEmpty() = nextPrintableString(Gen.choose(1, 100).generate())
}
object KTestData {
@Serializable
data class KTestInt32(@ProtoNumber(1) val a: Int) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestInt32.newBuilder().setA(a).build()
companion object : Gen<KTestInt32> {
override fun generate(): KTestInt32 = KTestInt32(Gen.int().generate())
}
}
@Serializable
data class KTestSignedInt(@ProtoNumber(1) @ProtoType(ProtoIntegerType.SIGNED) val a: Int) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestSignedInt.newBuilder().setA(a).build()
companion object : Gen<KTestSignedInt> {
override fun generate(): KTestSignedInt = KTestSignedInt(Gen.int().generate())
}
}
@Serializable
data class KTestSignedLong(@ProtoNumber(1) @ProtoType(ProtoIntegerType.SIGNED) val a: Long) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestSignedLong.newBuilder().setA(a).build()
companion object : Gen<KTestSignedLong> {
override fun generate(): KTestSignedLong = KTestSignedLong(Gen.long().generate())
}
}
@Serializable
data class KTestFixedInt(@ProtoNumber(1) @ProtoType(ProtoIntegerType.FIXED) val a: Int) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestFixedInt.newBuilder().setA(a).build()
companion object : Gen<KTestFixedInt> {
override fun generate(): KTestFixedInt = KTestFixedInt(Gen.int().generate())
}
}
@Serializable
data class KTestDouble(@ProtoNumber(1) val a: Double) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestDouble.newBuilder().setA(a).build()
companion object : Gen<KTestDouble> {
override fun generate(): KTestDouble = KTestDouble(Gen.double().generate())
}
}
@Serializable
data class KTestBoolean(@ProtoNumber(1) val a: Boolean) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestBoolean.newBuilder().setA(a).build()
companion object : Gen<KTestBoolean> {
override fun generate(): KTestBoolean = KTestBoolean(Gen.bool().generate())
}
}
@Serializable
data class KTestAllTypes(
@ProtoNumber(1) val i32: Int,
@ProtoNumber(2) @ProtoType(ProtoIntegerType.SIGNED) val si32: Int,
@ProtoNumber(3) @ProtoType(ProtoIntegerType.FIXED) val f32: Int,
@ProtoNumber(10) val i64: Long,
@ProtoNumber(11) @ProtoType(ProtoIntegerType.SIGNED) val si64: Long,
@ProtoNumber(12) @ProtoType(ProtoIntegerType.FIXED) val f64: Long,
@ProtoNumber(21) val f: Float,
@ProtoNumber(22) val d: Double,
@ProtoNumber(41) val b: Boolean = false,
@ProtoNumber(51) val s: String
) : IMessage {
override fun toProtobufMessage(): TestAllTypes = TestAllTypes.newBuilder()
.setI32(i32)
.setSi32(si32)
.setF32(f32)
.setI64(i64)
.setSi64(si64)
.setF64(f64)
.setF(f)
.setD(d)
.setB(b)
.setS(s)
.build()
companion object : Gen<KTestAllTypes> {
override fun generate(): KTestAllTypes = KTestAllTypes(
Gen.int().generate(),
Gen.int().generate(),
Gen.int().generate(),
Gen.long().generate(),
Gen.long().generate(),
Gen.long().generate(),
Gen.float().generate(),
Gen.double().generate(),
Gen.bool().generate(),
Gen.string().generateNotEmpty()
)
}
}
@Serializable
data class KTestOuterMessage(
@ProtoNumber(1) val a: Int,
@ProtoNumber(2) val b: Double,
@ProtoNumber(10) val inner: KTestAllTypes,
@ProtoNumber(20) val s: String
) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestOuterMessage.newBuilder()
.setA(a)
.setB(b)
.setInner(inner.toProtobufMessage())
.setS(s)
.build()
companion object : Gen<KTestOuterMessage> {
override fun generate(): KTestOuterMessage = KTestOuterMessage(
Gen.int().generate(),
Gen.double().generate(),
KTestAllTypes.generate(),
Gen.string().generateNotEmpty()
)
}
}
@Serializable
data class KTestIntListMessage(
@ProtoNumber(1) val s: Int,
@ProtoNumber(10) val l: List<Int>
) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestRepeatedIntMessage.newBuilder().setS(s).addAllB(l).build()
companion object : Gen<KTestIntListMessage> {
override fun generate() = KTestIntListMessage(Gen.int().generate(), Gen.list(Gen.int()).generate())
}
}
@Serializable
data class KTestObjectListMessage(
@ProtoNumber(1) val inner: List<KTestAllTypes>
) : IMessage {
override fun toProtobufMessage(): GeneratedMessageV3 = TestRepeatedObjectMessage.newBuilder().addAllInner(inner.map { it.toProtobufMessage() }).build()
companion object : Gen<KTestObjectListMessage> {
override fun generate() = KTestObjectListMessage(Gen.list(KTestAllTypes.Companion).generate())
}
}
enum class KCoffee { AMERICANO, LATTE, CAPPUCCINO }
@Serializable
data class KTestEnum(@ProtoNumber(1) val a: KCoffee): IMessage {
override fun toProtobufMessage() = TestEnum.newBuilder().setA(TestEnum.Coffee.forNumber(a.ordinal)).build()
companion object : Gen<KTestEnum> {
override fun generate(): KTestEnum = KTestEnum(Gen.oneOf<KCoffee>().generate())
}
}
@Serializable
data class KTestMap(@ProtoNumber(1) val s: Map<String, String>, @ProtoNumber(2) val o: Map<Int, KTestAllTypes> = emptyMap()) :
IMessage {
override fun toProtobufMessage() = TestMap.newBuilder()
.putAllStringMap(s)
.putAllIntObjectMap(o.mapValues { it.value.toProtobufMessage() })
.build()
companion object : Gen<KTestMap> {
override fun generate(): KTestMap =
KTestMap(Gen.map(Gen.string(), Gen.string()).generate(), Gen.map(Gen.int(), KTestAllTypes).generate())
}
}
}
init {
"Protobuf serialization" {
should("serialize random int32") { forAll(KTestData.KTestInt32.Companion) { dumpCompare(it) } }
should("serialize random signed int32") { forAll(KTestData.KTestSignedInt.Companion) { dumpCompare(it) } }
should("serialize random signed int64") { forAll(KTestData.KTestSignedLong.Companion) { dumpCompare(it) } }
should("serialize random fixed int32") { forAll(KTestData.KTestFixedInt.Companion) { dumpCompare(it) } }
should("serialize random doubles") { forAll(KTestData.KTestDouble.Companion) { dumpCompare(it) } }
should("serialize random booleans") { forAll(KTestData.KTestBoolean.Companion) { dumpCompare(it) } }
should("serialize random enums") { forAll(KTestData.KTestEnum.Companion) { dumpCompare(it) } }
should("serialize all base random types") { forAll(KTestData.KTestAllTypes.Companion) { dumpCompare(it) } }
should("serialize random messages with embedded message") { forAll(KTestData.KTestOuterMessage.Companion) { dumpCompare(it) } }
should("serialize random messages with primitive list fields as repeated") { forAll(KTestData.KTestIntListMessage.Companion) { dumpCompare(it) } }
should("serialize messages with object list fields as repeated") { forAll(KTestData.KTestObjectListMessage.Companion) { dumpCompare(it) } }
should("serialize messages with scalar-key maps") { forAll(KTestData.KTestMap.Companion) { dumpCompare(it) } }
}
"Protobuf deserialization" {
should("read random int32") { forAll(KTestData.KTestInt32.Companion) { readCompare(it) } }
should("read random signed int32") { forAll(KTestData.KTestSignedInt.Companion) { readCompare(it) } }
should("read random signed int64") { forAll(KTestData.KTestSignedLong.Companion) { readCompare(it) } }
should("read random fixed int32") { forAll(KTestData.KTestFixedInt.Companion) { readCompare(it) } }
should("read random doubles") { forAll(KTestData.KTestDouble.Companion) { readCompare(it) } }
should("read random enums") { forAll(KTestData.KTestEnum.Companion) { readCompare(it) } }
should("read all base random types") { forAll(KTestData.KTestAllTypes.Companion) { readCompare(it) } }
should("read random messages with embedded message") { forAll(KTestData.KTestOuterMessage.Companion) { readCompare(it) } }
should("read random messages with primitive list fields as repeated") { forAll(KTestData.KTestIntListMessage.Companion) { readCompare(it) } }
should("read random messages with object list fields as repeated") { forAll(KTestData.KTestObjectListMessage.Companion) { readCompare(it) } }
should("read messages with scalar-key maps") { forAll(KTestData.KTestMap.Companion) { readCompare(it) } }
}
}
}
| formats/protobuf/jvmTest/src/kotlinx/serialization/protobuf/RandomTests.kt | 2131023760 |
/*
* 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.network.vanilla.command.argument
import org.lanternpowered.server.network.buffer.ByteBuffer
interface ArgumentCodec<A : Argument> {
/**
* Encodes extra data for the given [Argument].
*
* @param buf The byte buffer
* @param argument The argument
*/
fun encode(buf: ByteBuffer, argument: A)
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/command/argument/ArgumentCodec.kt | 4143190931 |
/*
* 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.archetype
import org.lanternpowered.server.catalog.AbstractCatalogBuilder
import org.lanternpowered.server.world.LanternWorldProperties
import org.lanternpowered.server.world.dimension.LanternDimensionType
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.data.persistence.DataContainer
import org.spongepowered.api.entity.living.player.gamemode.GameMode
import org.spongepowered.api.entity.living.player.gamemode.GameModes
import org.spongepowered.api.world.SerializationBehavior
import org.spongepowered.api.world.SerializationBehaviors
import org.spongepowered.api.world.WorldArchetype
import org.spongepowered.api.world.difficulty.Difficulties
import org.spongepowered.api.world.difficulty.Difficulty
import org.spongepowered.api.world.dimension.DimensionType
import org.spongepowered.api.world.dimension.DimensionTypes
import org.spongepowered.api.world.gen.GeneratorModifierType
import org.spongepowered.api.world.gen.GeneratorModifierTypes
import org.spongepowered.api.world.storage.WorldProperties
class LanternWorldArchetypeBuilder : AbstractCatalogBuilder<WorldArchetype, WorldArchetype.Builder>(), WorldArchetype.Builder {
private lateinit var gameMode: GameMode
private lateinit var difficulty: Difficulty
private lateinit var portalAgentType: LanternPortalAgentType<*>
private lateinit var serializationBehavior: SerializationBehavior
private lateinit var dimensionType: LanternDimensionType
// If not specified, fall back to dimension default
private var generatorModifier: GeneratorModifierType = GeneratorModifierTypes.NONE.get()
private var generatorSettings: DataContainer? = null
private var keepSpawnLoaded: Boolean? = null
private var waterEvaporates: Boolean? = null // Non-sponge property
private var allowPlayerRespawns: Boolean? = null // Non-sponge property
private var buildHeight = 0 // Non-sponge property
private var hardcore = false
private var enabled = false
private var loadOnStartup = false
private var generateStructures = true
private var commandEnabled = false
private var pvpEnabled = false
private var generateSpawnOnLoad = false
private var generateBonusChest = false
private var seedProvider: SeedProvider = SeedProvider.Random
init {
reset()
}
override fun from(archetype: WorldArchetype) = apply {
archetype as LanternWorldArchetype
this.difficulty = archetype.difficulty
this.hardcore = archetype.isHardcore
this.enabled = archetype.isEnabled
this.gameMode = archetype.gameMode
this.keepSpawnLoaded = archetype.keepSpawnLoaded
this.dimensionType = archetype.dimensionType
this.generatorModifier = archetype.generatorModifier
this.generatorSettings = archetype.generatorSettings
this.generateStructures = archetype.areStructuresEnabled()
this.commandEnabled = archetype.areCommandsEnabled()
this.waterEvaporates = archetype.waterEvaporates
this.buildHeight = archetype.buildHeight
this.allowPlayerRespawns = archetype.allowPlayerRespawns
this.pvpEnabled = archetype.isPVPEnabled
this.generateSpawnOnLoad = archetype.doesGenerateSpawnOnLoad()
this.generateBonusChest = archetype.doesGenerateBonusChest()
this.seedProvider = archetype.seedProvider
}
override fun from(properties: WorldProperties) = apply {
properties as LanternWorldProperties
this.difficulty = properties.difficulty
this.hardcore = properties.isHardcore
this.enabled = properties.isEnabled
this.gameMode = properties.gameMode
this.keepSpawnLoaded = properties.doesKeepSpawnLoaded()
this.seedProvider = SeedProvider.Constant(properties.seed)
this.dimensionType = properties.dimensionType
this.generatorModifier = properties.generatorModifierType
this.generatorSettings = properties.generatorSettings.copy()
this.generateStructures = properties.areStructuresEnabled()
this.waterEvaporates = properties.doesWaterEvaporate
this.buildHeight = properties.maxBuildHeight
this.pvpEnabled = properties.isPVPEnabled
this.generateSpawnOnLoad = properties.doesGenerateSpawnOnLoad()
this.generateBonusChest = properties.doesGenerateBonusChest()
}
override fun enabled(state: Boolean) = apply { this.enabled = state }
override fun loadOnStartup(state: Boolean) = apply { this.loadOnStartup = state }
override fun keepSpawnLoaded(state: Boolean) = apply { this.keepSpawnLoaded = state }
override fun generateSpawnOnLoad(state: Boolean) = apply { this.generateSpawnOnLoad = state }
override fun seed(seed: Long) = apply { this.seedProvider = SeedProvider.Constant(seed) }
override fun randomSeed() = apply { this.seedProvider = SeedProvider.Random }
override fun gameMode(gameMode: GameMode) = apply { this.gameMode = gameMode }
override fun generatorModifierType(modifier: GeneratorModifierType) = apply { this.generatorModifier = modifier }
override fun dimensionType(type: DimensionType) = apply { this.dimensionType = type as LanternDimensionType }
override fun difficulty(difficulty: Difficulty) = apply { this.difficulty = difficulty }
override fun generateStructures(state: Boolean) = apply { this.generateStructures = state }
override fun hardcore(enabled: Boolean) = apply { this.hardcore = enabled }
override fun generatorSettings(settings: DataContainer) = apply { this.generatorSettings = settings }
override fun pvpEnabled(enabled: Boolean) = apply { this.pvpEnabled = enabled }
override fun commandsEnabled(enabled: Boolean) = apply { this.commandEnabled = enabled }
override fun serializationBehavior(behavior: SerializationBehavior) = apply { this.serializationBehavior = behavior }
override fun generateBonusChest(enabled: Boolean) = apply { this.generateBonusChest = enabled }
fun waterEvaporates(evaporates: Boolean) = apply { this.waterEvaporates = evaporates }
fun allowPlayerRespawns(allow: Boolean) = apply { this.allowPlayerRespawns = allow }
fun buildHeight(buildHeight: Int) = apply {
check(buildHeight <= 256) { "the build height cannot be greater then 256" }
this.buildHeight = buildHeight
}
override fun build(key: NamespacedKey): WorldArchetype {
return LanternWorldArchetype(key,
allowPlayerRespawns = this.allowPlayerRespawns,
buildHeight = this.buildHeight,
commandsEnabled = this.commandEnabled,
difficulty = this.difficulty,
dimensionType = this.dimensionType,
enabled = this.enabled,
gameMode = this.gameMode,
generateStructures = this.generateStructures,
generateSpawnOnLoad = this.generateSpawnOnLoad,
generateBonusChest = this.generateBonusChest,
generatorSettings = this.generatorSettings,
generatorModifier = this.generatorModifier,
hardcore = this.hardcore,
keepSpawnLoaded = this.keepSpawnLoaded,
loadsOnStartup = this.loadOnStartup,
seedProvider = this.seedProvider,
serializationBehavior = this.serializationBehavior,
portalAgentType = this.portalAgentType,
pvpEnabled = this.pvpEnabled,
waterEvaporates = this.waterEvaporates
)
}
override fun reset() = apply {
this.gameMode = GameModes.SURVIVAL.get()
this.difficulty = Difficulties.NORMAL.get()
this.hardcore = false
this.keepSpawnLoaded = null
this.loadOnStartup = false
this.generateSpawnOnLoad = true
this.enabled = true
this.generateStructures = true
this.commandEnabled = true
this.dimensionType = DimensionTypes.OVERWORLD.get() as LanternDimensionType
this.seedProvider = SeedProvider.Random
this.generatorModifier = GeneratorModifierTypes.NONE.get()
this.generatorSettings = null
this.waterEvaporates = null
this.buildHeight = 256
this.serializationBehavior = SerializationBehaviors.AUTOMATIC.get()
this.generateBonusChest = false
}
}
| src/main/kotlin/org/lanternpowered/server/world/archetype/LanternWorldArchetypeBuilder.kt | 4223928863 |
package com.song.middleware.server.storage.exception
/**
* wrap all the exception raised by the storage layer.
* Created by song on 2017/8/5.
*/
class StorageException : RuntimeException {
constructor()
constructor(message: String) : super(message)
constructor(cause: Throwable) : super(cause)
constructor(message: String, cause: Throwable) : super(message, cause)
}
| general-server/src/main/java/com/song/middleware/server/storage/exception/StorageException.kt | 1827401932 |
package kotlinx.serialization.json
import kotlinx.serialization.KSerializer
class JsonDynamicImplicitNullsTest : AbstractJsonImplicitNullsTest() {
override fun <T> Json.encode(value: T, serializer: KSerializer<T>): String {
return JSON.stringify(encodeToDynamic(serializer, value))
}
override fun <T> Json.decode(json: String, serializer: KSerializer<T>): T {
val x: dynamic = JSON.parse(json)
return decodeFromDynamic(serializer, x)
}
}
| formats/json-tests/jsTest/src/kotlinx/serialization/json/JsonDynamicImplicitNullsTest.kt | 639426039 |
package com.bl_lia.kirakiratter.data.repository.datasource.account
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Relationship
import com.bl_lia.kirakiratter.domain.entity.Status
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
interface AccountService {
@GET("api/v1/accounts/{id}/statuses")
fun status(
@Path("id") id: Int?,
@Query("max_id") maxId: Int? = null,
@Query("since_id") sinceId: Int? = null,
@Query("limit") limit: Int? = null): Single<List<Status>>
@GET("api/v1/accounts/relationships")
fun relationships(@Query("id") id: Int?): Single<List<Relationship>>
@POST("api/v1/accounts/{id}/follow")
fun follow(@Path("id") id: Int?): Single<Relationship>
@POST("api/v1/accounts/{id}/unfollow")
fun unfollow(@Path("id") id: Int?): Single<Relationship>
@GET("api/v1/accounts/verify_credentials")
fun verifyCredentials(): Single<Account>
} | app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/account/AccountService.kt | 124626026 |
package com.mercadopago.android.px.internal.util
import com.mercadopago.android.px.addons.ESCManagerBehaviour
import com.mercadopago.android.px.addons.model.EscDeleteReason
import com.mercadopago.android.px.internal.callbacks.TaggedCallback
import com.mercadopago.android.px.internal.extensions.isNotNullNorEmpty
import com.mercadopago.android.px.internal.repository.CardTokenRepository
import com.mercadopago.android.px.model.*
import com.mercadopago.android.px.model.exceptions.CardTokenException
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.model.exceptions.MercadoPagoErrorWrapper
import com.mercadopago.android.px.tracking.internal.model.Reason
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
internal class TokenCreationWrapper private constructor(builder: Builder) {
private val cardTokenRepository: CardTokenRepository
private val escManagerBehaviour: ESCManagerBehaviour
private val card: Card?
private val token: Token?
private val paymentMethod: PaymentMethod
private val reason: Reason
init {
cardTokenRepository = builder.cardTokenRepository
escManagerBehaviour = builder.escManagerBehaviour
card = builder.card
token = builder.token
paymentMethod = builder.paymentMethod!!
reason = builder.reason!!
}
suspend fun createToken(cvv: String): Token {
return if (escManagerBehaviour.isESCEnabled) {
createTokenWithEsc(cvv)
} else {
createTokenWithoutEsc(cvv)
}
}
suspend fun createTokenWithEsc(cvv: String): Token {
return if (card != null) {
SavedESCCardToken.createWithSecurityCode(card.id!!, cvv).run {
validateSecurityCode(card)
createESCToken(this).apply { lastFourDigits = card.lastFourDigits }
}
} else {
SavedESCCardToken.createWithSecurityCode(token!!.cardId, cvv).run {
validateCVVFromToken(cvv)
createESCToken(this)
}
}
}
suspend fun createTokenWithoutEsc(cvv: String) =
SavedCardToken(card!!.id, cvv).run {
validateSecurityCode(card)
createToken(this)
}
suspend fun cloneToken(cvv: String) = putCVV(cvv, doCloneToken().id)
@Throws(CardTokenException::class)
fun validateCVVFromToken(cvv: String): Boolean {
if (token?.firstSixDigits.isNotNullNorEmpty()) {
CardToken.validateSecurityCode(cvv, paymentMethod, token!!.firstSixDigits)
} else if (!CardToken.validateSecurityCode(cvv)) {
throw CardTokenException(CardTokenException.INVALID_FIELD)
}
return true
}
private suspend fun createESCToken(savedESCCardToken: SavedESCCardToken): Token {
return suspendCoroutine {cont ->
cardTokenRepository
.createToken(savedESCCardToken).enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
if (Reason.ESC_CAP == reason) { // Remove previous esc for tracking purpose
escManagerBehaviour.deleteESCWith(savedESCCardToken.cardId, EscDeleteReason.ESC_CAP, null)
}
cardTokenRepository.clearCap(savedESCCardToken.cardId) { cont.resume(token) }
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun createToken(savedCardToken: SavedCardToken): Token {
return suspendCoroutine {cont ->
cardTokenRepository
.createToken(savedCardToken).enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun doCloneToken(): Token {
return suspendCoroutine {cont ->
cardTokenRepository.cloneToken(token!!.id)
.enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun putCVV(cvv: String, tokenId: String): Token {
return suspendCoroutine {cont ->
cardTokenRepository.putSecurityCode(cvv, tokenId).enqueue(
object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
class Builder(val cardTokenRepository: CardTokenRepository, val escManagerBehaviour: ESCManagerBehaviour) {
var card: Card? = null
private set
var token: Token? = null
private set
var paymentMethod: PaymentMethod? = null
private set
var reason: Reason? = Reason.NO_REASON
private set
fun with(card: Card) = apply {
this.card = card
this.paymentMethod = card.paymentMethod
}
fun with(token: Token) = apply { this.token = token }
fun with(paymentMethod: PaymentMethod) = apply { this.paymentMethod = paymentMethod }
fun with(paymentRecovery: PaymentRecovery) = apply {
card = paymentRecovery.card
token = paymentRecovery.token
paymentMethod = paymentRecovery.paymentMethod
reason = Reason.from(paymentRecovery)
}
fun build(): TokenCreationWrapper {
check(!(token == null && card == null)) { "Token and card can't both be null" }
checkNotNull(paymentMethod) { "Payment method not set" }
return TokenCreationWrapper(this)
}
}
} | px-checkout/src/main/java/com/mercadopago/android/px/internal/util/TokenCreationWrapper.kt | 1043986874 |
package six.ca.androidadvanced.dagger2.multibinds.intomap
import android.app.Activity
import android.os.Bundle
import javax.inject.Inject
/**
* @CopyRight six.ca
* Created by Heavens on 2018-10-15.
*/
class MultiParamCustomKeySample: Activity() {
@Inject lateinit var multiMap: Map<MultiParamKey, String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerMultiComponent.create().inject(this)
multiMap.forEach { key, value ->
println("xxl-key: $key; value: $value")
}
}
} | AndroidAdvanced/app/src/main/java/six/ca/androidadvanced/dagger2/multibinds/intomap/MultiParamCustomKeySample.kt | 832205042 |
package voice.playback
import android.content.ComponentName
import android.content.Context
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaControllerCompat
import voice.data.Chapter
import voice.logging.core.Logger
import voice.playback.misc.Decibel
import voice.playback.session.PlaybackService
import voice.playback.session.forcedNext
import voice.playback.session.forcedPrevious
import voice.playback.session.pauseWithRewind
import voice.playback.session.playPause
import voice.playback.session.setGain
import voice.playback.session.setPosition
import voice.playback.session.setVolume
import voice.playback.session.skipSilence
import javax.inject.Inject
import kotlin.time.Duration
class PlayerController
@Inject constructor(
private val context: Context,
) {
private var _controller: MediaControllerCompat? = null
private val callback = object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
super.onConnected()
Logger.v("onConnected")
_controller = MediaControllerCompat(context, browser.sessionToken)
}
override fun onConnectionSuspended() {
super.onConnectionSuspended()
Logger.v("onConnectionSuspended")
_controller = null
}
override fun onConnectionFailed() {
super.onConnectionFailed()
Logger.d("onConnectionFailed")
_controller = null
}
}
private val browser: MediaBrowserCompat = MediaBrowserCompat(
context,
ComponentName(context, PlaybackService::class.java),
callback,
null,
)
init {
browser.connect()
}
fun setPosition(time: Long, id: Chapter.Id) = execute { it.setPosition(time, id) }
fun skipSilence(skip: Boolean) = execute { it.skipSilence(skip) }
fun fastForward() = execute { it.fastForward() }
fun rewind() = execute { it.rewind() }
fun previous() = execute { it.forcedPrevious() }
fun next() = execute { it.forcedNext() }
fun play() = execute { it.play() }
fun playPause() = execute { it.playPause() }
fun pauseWithRewind(rewind: Duration) = execute { it.pauseWithRewind(rewind) }
fun setSpeed(speed: Float) = execute { it.setPlaybackSpeed(speed) }
fun setGain(gain: Decibel) = execute { it.setGain(gain) }
fun setVolume(volume: Float) = execute {
require(volume in 0F..1F)
it.setVolume(volume)
}
private inline fun execute(action: (MediaControllerCompat.TransportControls) -> Unit) {
_controller?.transportControls?.let(action)
}
}
| playback/src/main/kotlin/voice/playback/PlayerController.kt | 3117665872 |
package com.juankysoriano.rainbow.demo.sketch.rainbow.portrait
import android.graphics.Color.*
import android.view.ViewGroup
import com.juankysoriano.rainbow.core.Rainbow
import com.juankysoriano.rainbow.core.drawing.Modes
import com.juankysoriano.rainbow.core.drawing.RainbowDrawer
import com.juankysoriano.rainbow.core.graphics.RainbowImage
import com.juankysoriano.rainbow.core.matrix.RVector
import com.juankysoriano.rainbow.utils.RainbowMath.*
import kotlin.math.floor
private const val STEPS = 800
class RainbowMessyLinePaiting(viewGroup: ViewGroup) : Rainbow(viewGroup) {
private lateinit var originalImage: RainbowImage
private lateinit var thresholdImage: RainbowImage
private lateinit var paint: Paint
override fun onSketchSetup() {
with(rainbowDrawer) {
background(255)
smooth()
loadImage(com.juankysoriano.rainbow.demo.R.drawable.winnie,
width,
height,
Modes.LoadMode.LOAD_CENTER_CROP,
object : RainbowImage.LoadPictureListener {
override fun onLoadSucceed(image: RainbowImage) {
originalImage = image
originalImage.loadPixels()
thresholdImage = rainbowDrawer.createImage(width, height, Modes.Image.RGB)
thresholdImage.set(0, 0, originalImage)
thresholdImage.filter(Modes.Filter.THRESHOLD, 0.6f)
paint = Paint(rainbowDrawer, originalImage, thresholdImage)
paint.reset()
}
override fun onLoadFail() {
//no-op
}
})
}
}
override fun onDrawingStep() {
if (!::paint.isInitialized || stepCount() > width) {
return
}
for (i in 0..STEPS) {
paint.updateAndDisplay()
}
}
class Paint(private val rainbowDrawer: RainbowDrawer, private val originalImage: RainbowImage, private val thresholdImage: RainbowImage) {
var ppos = RVector()
var pos = RVector()
var vel = RVector()
var force = RVector()
var maxSpeed = 3f
var perception = 5f
var bound = 60
var boundForceFactor = 0.16f
var noiseScale = 100f
var noiseInfluence = 1 / 20f
var dropRate = 0.0001f
var dropRange = 40
var dropAlpha = 150f
var drawAlpha = 60f
var drawColor = rainbowDrawer.color(0f, 0f, 0f, drawAlpha)
var count = 0
var maxCount = 100
var z = 0f
fun updateAndDisplay() {
update()
show()
z += 0.01f
}
fun update() {
ppos = pos.copy()
force.mult(0f)
// Add pixels force
val target = RVector()
var count = 0
for (i in -floor(perception / 2f).toInt()..(perception / 2f).toInt()) {
for (j in -floor(perception / 2f).toInt()..(perception / 2f).toInt()) {
if (i == 0 && j == 0) {
continue
}
val x = floor(pos.x + i)
val y = floor(pos.y + j)
if (x <= rainbowDrawer.width - 1 && x >= 0 && y < rainbowDrawer.height - 1 && y >= 0) {
val c = get(x.toInt(), y.toInt())
var b = rainbowDrawer.brightness(c)
b = 1 - b / 100f
val p = RVector(i.toFloat(), j.toFloat())
p.normalize()
val pCopy = p.copy()
pCopy.mult(b)
pCopy.div(p.mag())
target.add(pCopy)
count++
}
}
}
if (count != 0) {
target.div(count.toFloat())
force.add(target)
}
var n = noise(pos.x / noiseScale, pos.y / noiseScale, z)
n = map(n, 0f, 1f, 0f, 5f * TWO_PI)
val p = RVector(cos(n), sin(n))
if (force.mag() < 0.01f) {
p.mult(noiseInfluence * 5)
} else {
p.mult(noiseInfluence)
}
force.add(p)
// Add bound force
val boundForce = RVector()
if (pos.x < bound) {
boundForce.x = (bound - pos.x) / bound
}
if (pos.x > rainbowDrawer.width - bound) {
boundForce.x = (pos.x - rainbowDrawer.width) / bound
}
if (pos.y < bound) {
boundForce.y = (bound - pos.y) / bound
}
if (pos.y > rainbowDrawer.height - bound) {
boundForce.y = (pos.y - rainbowDrawer.height) / bound
}
boundForce.mult(boundForceFactor)
force.add(boundForce)
vel.add(force)
vel.mult(0.9999f)
if (vel.mag() > maxSpeed) {
vel.mult(maxSpeed / vel.mag())
}
pos.add(vel)
if (pos.x > rainbowDrawer.width || pos.x < 0 || pos.y > rainbowDrawer.height || pos.y < 0) {
this.reset()
}
}
fun reset() {
count = 0
var hasFound = false
while (!hasFound) {
pos.x = random(rainbowDrawer.width).toFloat()
pos.y = random(rainbowDrawer.height).toFloat()
val c = get(floor(pos.x).toInt(), floor(pos.y).toInt())
val b = rainbowDrawer.brightness(c)
if (b < 70)
hasFound = true
}
val index = floor(pos.x).toInt() + rainbowDrawer.width * floor(pos.y).toInt()
drawColor = originalImage.pixels[index]
drawColor = rainbowDrawer.color(rainbowDrawer.brightness(drawColor), drawAlpha)
ppos = pos.copy()
vel.mult(0f)
}
fun show() {
count++
if (count > maxCount) {
this.reset()
}
rainbowDrawer.stroke(drawColor)
val brightness = rainbowDrawer.brightness(drawColor)
var drawWeight = 0.5f
if (brightness < 35) {
drawWeight = 1.5f
}
rainbowDrawer.strokeWeight(drawWeight)
if (force.mag() > 0.1f && random(1f) < dropRate) {
drawColor = rainbowDrawer.color(brightness, dropAlpha)
rainbowDrawer.stroke(drawColor)
val boldWeight = 0f + random(3f, 12f)
rainbowDrawer.strokeWeight(boldWeight)
drawColor = rainbowDrawer.color(brightness, drawAlpha)
}
rainbowDrawer.line(ppos.x, ppos.y, pos.x, pos.y)
this.fadeLineFromImg(ppos.x, ppos.y, pos.x, pos.y)
}
private fun fadeLineFromImg(x1: Float, y1: Float, x2: Float, y2: Float) {
val xOffset = floor(abs(x1 - x2))
val yOffset = floor(abs(y1 - y2))
val step = if (xOffset < yOffset) {
yOffset
} else {
xOffset
}
for (i in 0..step.toInt()) {
val x = floor(x1 + (x2 - x1) * i / step)
val y = floor(y1 + (y2 - y1) * i / step)
var originColor = get(x.toInt(), y.toInt())
val r = min(255, red(originColor) + 50)
val g = min(255, green(originColor) + 50)
val b = min(255, blue(originColor) + 50)
originColor = rainbowDrawer.color(r, g, b, rainbowDrawer.brightness(originColor).toInt())
set(x.toInt(), y.toInt(), originColor)
}
}
private fun get(x: Int, y: Int): Int {
val index = (y * rainbowDrawer.width + x)
return thresholdImage.pixels[index]
}
private fun set(x: Int, y: Int, color: Int) {
val index = (y * rainbowDrawer.width + x)
thresholdImage.pixels[index] = color
}
private fun RVector.copy(): RVector {
return RVector(x, y)
}
}
}
| demo/src/main/java/com/juankysoriano/rainbow/demo/sketch/rainbow/portrait/RainbowMessyLinePaiting.kt | 3099207571 |
package net.ndrei.teslapoweredthingies.machines.portablemultitank
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer
import net.minecraft.item.EnumDyeColor
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
import net.minecraft.world.World
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.IFluidTank
import net.ndrei.teslacorelib.gui.FluidTankPiece
import net.ndrei.teslacorelib.tileentities.SidedTileEntity
import net.ndrei.teslapoweredthingies.render.bakery.SelfRenderingTESR
/**
* Created by CF on 2017-07-16.
*/
class MultiTankEntity
: SidedTileEntity(MultiTankEntity::class.java.name.hashCode()) {
private lateinit var tanks: MutableList<IFluidTank>
override fun initializeInventories() {
super.initializeInventories()
this.tanks = mutableListOf()
arrayOf(EnumDyeColor.BLUE, EnumDyeColor.GREEN, EnumDyeColor.ORANGE, EnumDyeColor.RED).forEachIndexed { index, it ->
this.tanks.add(this.addSimpleFluidTank(TANK_CAPACITY, "Tank $index", it,
20 + FluidTankPiece.WIDTH * index, 24))
}
}
override fun supportsAddons() = false
override fun canBePaused() = false
override val allowRedstoneControl: Boolean
get() = false
override fun setWorld(worldIn: World?) {
super.setWorld(worldIn)
this.getWorld().markBlockRangeForRenderUpdate(this.getPos(), this.getPos())
}
override fun getRenderers(): MutableList<TileEntitySpecialRenderer<TileEntity>> {
return super.getRenderers().also { it.add(SelfRenderingTESR) }
}
fun getFluid(tankIndex: Int): FluidStack? = this.tanks[tankIndex].fluid
override fun readFromNBT(compound: NBTTagCompound) {
val initialFluids = this.tanks.map { it.fluid }
super.readFromNBT(compound)
val finalFluids = this.tanks.map { it.fluid }
if (this.hasWorld () && this.getWorld().isRemote && (0..3).any {
if (initialFluids[it] == null)
(finalFluids[it] != null)
else
!initialFluids[it]!!.isFluidStackIdentical(finalFluids[it])
}) {
this.getWorld().markBlockRangeForRenderUpdate(this.pos, this.pos)
}
}
override fun innerUpdate() {
// TODO: maybe blow up if the liquid is too hot or something? :S
}
companion object {
const val TANK_CAPACITY = 6000
}
} | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/portablemultitank/MultiTankEntity.kt | 3508971912 |
package plugin.extensions
annotation class ProvidedByPlugin
annotation class ProvidedByCore
@ProvidedByPlugin
interface Extension {
//Extension API
}
@ProvidedByCore
interface ExtensionHolder {
val extensions: List<Extension>
}
@ProvidedByCore
interface CoreService {
fun service()
}
@ProvidedByPlugin
interface ServiceFromThePlugin1 {
fun test()
}
@ProvidedByPlugin
interface ServiceFromThePlugin2 {
fun test()
}
| src/v8-module/src/main/java/api.kt | 909137715 |
/*
Copyright 2018 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators
import com.google.androidstudiopoet.models.ModuleBuildBazelBlueprint
import com.google.androidstudiopoet.models.ModuleDependency
import com.google.androidstudiopoet.writers.FileWriter
class ModuleBuildBazelGenerator(private val fileWriter: FileWriter) {
fun generate(blueprint: ModuleBuildBazelBlueprint) {
val deps: Set<String> = blueprint.dependencies.map {
when (it) {
is ModuleDependency -> "\"//${it.name}\""
else -> ""
}
}.toSet()
val depsString = """
deps = [
${deps.joinToString(separator = ",\n ") { it }}
],"""
val ruleClass = "java_library"
val targetName = blueprint.targetName
val ruleDefinition = """$ruleClass(
name = "$targetName",
srcs = glob(["src/main/java/**/*.java"]),
visibility = ["//visibility:public"],${if (deps.isNotEmpty()) depsString else ""}
)"""
fileWriter.writeToFile(ruleDefinition, blueprint.path)
}
}
| aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/ModuleBuildBazelGenerator.kt | 2327264450 |
package rx.lang.kotlin.examples
import rx.Observable
import rx.lang.kotlin.observable
import rx.lang.kotlin.onError
import rx.lang.kotlin.plusAssign
import rx.lang.kotlin.toObservable
import rx.lang.kotlin.zip
import rx.lang.kotlin.combineLatest
import rx.subscriptions.CompositeSubscription
import java.net.URL
import java.util.*
import kotlin.concurrent.thread
fun main(args: Array<String>) {
val subscrition = CompositeSubscription()
val printArticle = { art: String ->
println("--- Article ---\n${art.substring(0, 125)}")
}
val printIt = { it: String -> println(it) }
subscrition += asyncObservable().subscribe(printIt)
subscrition += syncObservable().subscribe(printIt)
subscrition.clear()
simpleComposition()
asyncWiki("Tiger", "Elephant").subscribe(printArticle)
asyncWikiWithErrorHandling("Tiger", "Elephant").subscribe(printArticle) { e ->
println("--- Error ---\n${e.message}")
}
combineLatest(listOfObservables())
zip(listOfObservables())
}
private fun URL.toScannerObservable() = observable<String> { s ->
this.openStream().use { stream ->
Scanner(stream).useDelimiter("\\A").toObservable().subscribe(s)
}
}
public fun syncObservable(): Observable<String> =
observable { subscriber ->
(0..75).toObservable()
.map { "Sync value_$it" }
.subscribe(subscriber)
}
public fun asyncObservable(): Observable<String> =
observable { subscriber ->
thread {
(0..75).toObservable()
.map { "Async value_$it" }
.subscribe(subscriber)
}
}
public fun asyncWiki(vararg articleNames: String): Observable<String> =
observable { subscriber ->
thread {
articleNames.toObservable()
.flatMap { name -> URL("http://en.wikipedia.org/wiki/$name").toScannerObservable().first() }
.subscribe(subscriber)
}
}
public fun asyncWikiWithErrorHandling(vararg articleNames: String): Observable<String> =
observable { subscriber ->
thread {
articleNames.toObservable()
.flatMap { name -> URL("http://en.wikipedia.org/wiki/$name").toScannerObservable().first() }
.onError { e ->
subscriber.onError(e) }
.subscribe(subscriber)
}
}
public fun simpleComposition() {
asyncObservable().skip(10).take(5)
.map { s -> "${s}_xform" }
.subscribe { s -> println("onNext => $s") }
}
public fun listOfObservables(): List<Observable<String>> = listOf(syncObservable(), syncObservable())
public fun combineLatest(observables: List<Observable<String>>) {
observables.combineLatest { it.reduce { one, two -> one + two } }.subscribe { println(it) }
}
public fun zip(observables: List<Observable<String>>) {
observables.zip { it.reduce { one, two -> one + two } }.subscribe { println(it) }
} | src/examples/kotlin/rx/lang/kotlin/examples/examples.kt | 1678375433 |
package com.example.ap.kotlinap
import com.google.auto.service.AutoService
import java.io.File
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import com.example.ap.kotlinannotation.KotlinAnnotation
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.TypeSpec
@AutoService(Processor::class)
class AnnotationProcessorKotlin : AbstractProcessor() {
override fun getSupportedAnnotationTypes(): MutableSet<String> {
return mutableSetOf(KotlinAnnotation::class.java.name)
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latest()
}
override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean {
roundEnv.getElementsAnnotatedWith(KotlinAnnotation::class.java)
.forEach {
val className = it.simpleName.toString()
val pkg = processingEnv.elementUtils.getPackageOf(it).toString()
generateClass(className, pkg)
}
return true
}
private fun generateClass(name: String, pkg: String) {
val genDir = processingEnv.options["kapt.kotlin.generated"]
val fileName = "${name}_"
val file = FileSpec
.builder(pkg, fileName)
.addType(TypeSpec
.classBuilder(fileName)
.build()
).build()
file.writeTo(File(genDir))
}
}
| test/com/facebook/buck/jvm/kotlin/testdata/kotlin_library_description/com/example/ap/kotlinap/AnnotationProcessorKotlin.kt | 1844033023 |
package za.org.grassroot2.presenter.activity
import retrofit2.Response
import za.org.grassroot2.model.exception.AuthenticationInvalidException
import za.org.grassroot2.model.exception.ServerUnreachableException
interface GrassrootPresenter {
fun handleResponseError(response: Response<*>)
fun handleNetworkConnectionError(t: Throwable)
fun handleNetworkUploadError(t: Throwable)
fun handleAuthenticationError(t: AuthenticationInvalidException)
fun handleServerUnreachableError(t: ServerUnreachableException)
}
| app/src/main/java/za/org/grassroot2/presenter/activity/GrassrootPresenter.kt | 2071749649 |
/*
* Copyright (c) 2016 Fredrik Henricsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.jesterlabs.jesture.recognizers.onedollar
data class Result(val name: String, val score: Double) | recognizers/src/main/kotlin/com/jesterlabs/jesture/recognizers/onedollar/Result.kt | 3311058511 |
/*****************************************************************************
* MediaItemDetailsFragment.java
*
* Copyright © 2014-2019 VLC authors, VideoLAN and VideoLabs
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.television.ui
import android.annotation.TargetApi
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.leanback.app.BackgroundManager
import androidx.leanback.app.DetailsSupportFragment
import androidx.leanback.widget.*
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.moviepedia.database.models.MediaImage
import org.videolan.moviepedia.database.models.MediaImageType
import org.videolan.moviepedia.database.models.MediaMetadata
import org.videolan.moviepedia.database.models.Person
import org.videolan.moviepedia.repository.MediaMetadataRepository
import org.videolan.moviepedia.repository.MediaPersonRepository
import org.videolan.moviepedia.viewmodel.MediaMetadataFull
import org.videolan.moviepedia.viewmodel.MediaMetadataModel
import org.videolan.resources.ACTION_REMOTE_STOP
import org.videolan.tools.HttpImageLoader
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.AudioUtil
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.video.VideoPlayerActivity
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.repository.BrowserFavRepository
import org.videolan.vlc.util.FileUtils
import org.videolan.vlc.util.getScreenWidth
import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist
private const val TAG = "MediaItemDetailsFragment"
private const val ID_PLAY = 1
private const val ID_NEXT_EPISODE = 2
private const val ID_LISTEN = 3
private const val ID_FAVORITE_ADD = 4
private const val ID_FAVORITE_DELETE = 5
private const val ID_BROWSE = 6
private const val ID_DL_SUBS = 7
private const val ID_PLAY_FROM_START = 8
private const val ID_PLAYLIST = 9
private const val ID_GET_INFO = 10
private const val ID_FAVORITE = 11
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class MediaItemDetailsFragment : DetailsSupportFragment(), CoroutineScope by MainScope(), OnItemViewClickedListener {
private lateinit var detailsDescriptionPresenter: DetailsDescriptionPresenter
private lateinit var backgroundManager: BackgroundManager
private lateinit var rowsAdapter: ArrayObjectAdapter
private lateinit var browserFavRepository: BrowserFavRepository
private lateinit var mediaMetadataRepository: MediaMetadataRepository
private lateinit var mediaPersonRepository: MediaPersonRepository
private lateinit var mediaMetadataModel: MediaMetadataModel
private lateinit var detailsOverview: DetailsOverviewRow
private lateinit var arrayObjectAdapterPosters: ArrayObjectAdapter
private var mediaStarted: Boolean = false
private val viewModel: MediaItemDetailsModel by activityViewModels()
private val actionsAdapter = SparseArrayObjectAdapter()
private val imageDiffCallback = object : DiffCallback<MediaImage>() {
override fun areItemsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url
override fun areContentsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url
}
private val personsDiffCallback = object : DiffCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId
override fun areContentsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId && oldItem.image == newItem.image && oldItem.name == newItem.name
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
backgroundManager = BackgroundManager.getInstance(requireActivity())
backgroundManager.isAutoReleaseOnStop = false
browserFavRepository = BrowserFavRepository.getInstance(requireContext())
viewModel.mediaStarted = false
detailsDescriptionPresenter = org.videolan.television.ui.DetailsDescriptionPresenter()
arrayObjectAdapterPosters = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.POSTER))
val extras = requireActivity().intent.extras ?: savedInstanceState ?: return
viewModel.mediaItemDetails = extras.getParcelable("item") ?: return
val hasMedia = extras.containsKey("media")
val media = (extras.getParcelable<Parcelable>("media")
?: MLServiceLocator.getAbstractMediaWrapper(AndroidUtil.LocationToUri(viewModel.mediaItemDetails.location))) as MediaWrapper
viewModel.media = media
if (!hasMedia) viewModel.media.setDisplayTitle(viewModel.mediaItemDetails.title)
title = viewModel.media.title
mediaMetadataRepository = MediaMetadataRepository.getInstance(requireContext())
mediaPersonRepository = MediaPersonRepository.getInstance(requireContext())
mediaStarted = false
buildDetails()
mediaMetadataModel = ViewModelProviders.of(this, MediaMetadataModel.Factory(requireActivity(), mlId = media.id)).get(media.uri.path
?: "", MediaMetadataModel::class.java)
mediaMetadataModel.updateLiveData.observe(this, Observer {
updateMetadata(it)
})
mediaMetadataModel.nextEpisode.observe(this, Observer {
if (it != null) {
actionsAdapter.set(ID_NEXT_EPISODE, Action(ID_NEXT_EPISODE.toLong(), getString(R.string.next_episode)))
actionsAdapter.notifyArrayItemRangeChanged(0, actionsAdapter.size())
}
})
onItemViewClickedListener = this
}
override fun onResume() {
super.onResume()
// buildDetails()
if (!backgroundManager.isAttached) backgroundManager.attachToView(view)
}
override fun onPause() {
backgroundManager.release()
super.onPause()
if (viewModel.mediaStarted) {
context?.sendBroadcast(Intent(ACTION_REMOTE_STOP))
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putParcelable("item", viewModel.mediaItemDetails)
outState.putParcelable("media", viewModel.media)
super.onSaveInstanceState(outState)
}
override fun onItemClicked(itemViewHolder: Presenter.ViewHolder?, item: Any?, rowViewHolder: RowPresenter.ViewHolder?, row: Row?) {
when (item) {
is MediaImage -> {
mediaMetadataModel.updateMetadataImage(item)
}
}
}
private fun loadBackdrop(url: String? = null) {
lifecycleScope.launchWhenStarted {
when {
!url.isNullOrEmpty() -> HttpImageLoader.downloadBitmap(url)
viewModel.media.type == MediaWrapper.TYPE_AUDIO || viewModel.media.type == MediaWrapper.TYPE_VIDEO -> {
withContext(Dispatchers.IO) {
AudioUtil.readCoverBitmap(viewModel.mediaItemDetails.artworkUrl, 512)?.let { UiTools.blurBitmap(it) }
}
}
else -> null
}?.let { backgroundManager.setBitmap(it) }
}
}
private fun updateMetadata(mediaMetadataFull: MediaMetadataFull?) {
var backdropLoaded = false
mediaMetadataFull?.let { mediaMetadata ->
detailsDescriptionPresenter.metadata = mediaMetadata.metadata
mediaMetadata.metadata?.metadata?.let {
loadBackdrop(it.currentBackdrop)
backdropLoaded = true
}
lifecycleScope.launchWhenStarted {
if (!mediaMetadata.metadata?.metadata?.currentPoster.isNullOrEmpty()) {
detailsOverview.setImageBitmap(requireActivity(), HttpImageLoader.downloadBitmap(mediaMetadata.metadata?.metadata?.currentPoster!!))
}
}
title = mediaMetadata.metadata?.metadata?.title
val items = ArrayList<Any>()
items.add(detailsOverview)
if (!mediaMetadata.writers.isNullOrEmpty()) {
val arrayObjectAdapterWriters = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterWriters.setItems(mediaMetadata.writers, personsDiffCallback)
val headerWriters = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.written_by))
items.add(ListRow(headerWriters, arrayObjectAdapterWriters))
}
if (!mediaMetadata.actors.isNullOrEmpty()) {
val arrayObjectAdapterActors = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterActors.setItems(mediaMetadata.actors, personsDiffCallback)
val headerActors = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.casting))
items.add(ListRow(headerActors, arrayObjectAdapterActors))
}
if (!mediaMetadata.directors.isNullOrEmpty()) {
val arrayObjectAdapterDirectors = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterDirectors.setItems(mediaMetadata.directors, personsDiffCallback)
val headerDirectors = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.directed_by))
items.add(ListRow(headerDirectors, arrayObjectAdapterDirectors))
}
if (!mediaMetadata.producers.isNullOrEmpty()) {
val arrayObjectAdapterProducers = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterProducers.setItems(mediaMetadata.producers, personsDiffCallback)
val headerProducers = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.produced_by))
items.add(ListRow(headerProducers, arrayObjectAdapterProducers))
}
if (!mediaMetadata.musicians.isNullOrEmpty()) {
val arrayObjectAdapterMusicians = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterMusicians.setItems(mediaMetadata.musicians, personsDiffCallback)
val headerMusicians = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.music_by))
items.add(ListRow(headerMusicians, arrayObjectAdapterMusicians))
}
mediaMetadata.metadata?.let { metadata ->
if (metadata.images.any { it.imageType == MediaImageType.POSTER }) {
arrayObjectAdapterPosters.setItems(metadata.images.filter { it.imageType == MediaImageType.POSTER }, imageDiffCallback)
val headerPosters = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.posters))
items.add(ListRow(headerPosters, arrayObjectAdapterPosters))
}
if (metadata.images.any { it.imageType == MediaImageType.BACKDROP }) {
val arrayObjectAdapterBackdrops = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.BACKDROP))
arrayObjectAdapterBackdrops.setItems(metadata.images.filter { it.imageType == MediaImageType.BACKDROP }, imageDiffCallback)
val headerBackdrops = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.backdrops))
items.add(ListRow(headerBackdrops, arrayObjectAdapterBackdrops))
}
}
rowsAdapter.setItems(items, object : DiffCallback<Row>() {
override fun areItemsTheSame(oldItem: Row, newItem: Row) = (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow && (oldItem.item == newItem.item)) || (oldItem is ListRow && newItem is ListRow && oldItem.contentDescription == newItem.contentDescription && oldItem.adapter.size() == newItem.adapter.size() && oldItem.id == newItem.id)
override fun areContentsTheSame(oldItem: Row, newItem: Row): Boolean {
if (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow) {
return oldItem.item as org.videolan.television.ui.MediaItemDetails == newItem.item as org.videolan.television.ui.MediaItemDetails
}
return true
}
})
rowsAdapter.notifyItemRangeChanged(0, 1)
}
if (!backdropLoaded) loadBackdrop()
}
private fun buildDetails() {
val selector = ClassPresenterSelector()
// Attach your media item details presenter to the row presenter:
val rowPresenter = FullWidthDetailsOverviewRowPresenter(detailsDescriptionPresenter)
val videoPresenter = VideoDetailsPresenter(requireActivity(), requireActivity().getScreenWidth())
val activity = requireActivity()
detailsOverview = DetailsOverviewRow(viewModel.mediaItemDetails)
val actionAdd = Action(ID_FAVORITE_ADD.toLong(), getString(R.string.favorites_add))
val actionDelete = Action(ID_FAVORITE_DELETE.toLong(), getString(R.string.favorites_remove))
rowPresenter.backgroundColor = ContextCompat.getColor(activity, R.color.orange500)
rowPresenter.onActionClickedListener = OnActionClickedListener { action ->
when (action.id.toInt()) {
ID_LISTEN -> {
MediaUtils.openMedia(activity, viewModel.media)
viewModel.mediaStarted = true
}
ID_PLAY -> {
viewModel.mediaStarted = false
TvUtil.playMedia(activity, viewModel.media)
activity.finish()
}
ID_PLAYLIST -> requireActivity().addToPlaylist(arrayListOf(viewModel.media))
ID_FAVORITE_ADD -> {
val uri = Uri.parse(viewModel.mediaItemDetails.location)
val local = "file" == uri.scheme
lifecycleScope.launch {
if (local)
browserFavRepository.addLocalFavItem(uri, viewModel.mediaItemDetails.title
?: "", viewModel.mediaItemDetails.artworkUrl)
else
browserFavRepository.addNetworkFavItem(uri, viewModel.mediaItemDetails.title
?: "", viewModel.mediaItemDetails.artworkUrl)
}
actionsAdapter.set(ID_FAVORITE, actionDelete)
rowsAdapter.notifyArrayItemRangeChanged(0, rowsAdapter.size())
Toast.makeText(activity, R.string.favorite_added, Toast.LENGTH_SHORT).show()
}
ID_FAVORITE_DELETE -> {
lifecycleScope.launch { browserFavRepository.deleteBrowserFav(Uri.parse(viewModel.mediaItemDetails.location)) }
actionsAdapter.set(ID_FAVORITE, actionAdd)
rowsAdapter.notifyArrayItemRangeChanged(0, rowsAdapter.size())
Toast.makeText(activity, R.string.favorite_removed, Toast.LENGTH_SHORT).show()
}
ID_BROWSE -> TvUtil.openMedia(activity, viewModel.media, null)
ID_DL_SUBS -> MediaUtils.getSubs(requireActivity(), viewModel.media)
ID_PLAY_FROM_START -> {
viewModel.mediaStarted = false
VideoPlayerActivity.start(requireActivity(), viewModel.media.uri, true)
activity.finish()
}
ID_GET_INFO -> startActivity(Intent(requireActivity(), MediaScrapingTvActivity::class.java).apply { putExtra(MediaScrapingTvActivity.MEDIA, viewModel.media) })
ID_NEXT_EPISODE -> mediaMetadataModel.nextEpisode.value?.media?.let {
TvUtil.showMediaDetail(requireActivity(), it)
requireActivity().finish()
}
}
}
selector.addClassPresenter(DetailsOverviewRow::class.java, rowPresenter)
selector.addClassPresenter(VideoDetailsOverviewRow::class.java, videoPresenter)
selector.addClassPresenter(ListRow::class.java,
ListRowPresenter())
rowsAdapter = ArrayObjectAdapter(selector)
lifecycleScope.launchWhenStarted {
val cover = if (viewModel.media.type == MediaWrapper.TYPE_AUDIO || viewModel.media.type == MediaWrapper.TYPE_VIDEO)
withContext(Dispatchers.IO) { AudioUtil.readCoverBitmap(viewModel.mediaItemDetails.artworkUrl, 512) }
else null
val browserFavExists = browserFavRepository.browserFavExists(Uri.parse(viewModel.mediaItemDetails.location))
val isDir = viewModel.media.type == MediaWrapper.TYPE_DIR
val canSave = isDir && withContext(Dispatchers.IO) { FileUtils.canSave(viewModel.media) }
if (activity.isFinishing) return@launchWhenStarted
val res = resources
if (isDir) {
detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, if (TextUtils.equals(viewModel.media.uri.scheme, "file"))
R.drawable.ic_menu_folder_big
else
R.drawable.ic_menu_network_big)
detailsOverview.isImageScaleUpAllowed = true
actionsAdapter.set(ID_BROWSE, Action(ID_BROWSE.toLong(), res.getString(R.string.browse_folder)))
if (canSave) actionsAdapter.set(ID_FAVORITE, if (browserFavExists) actionDelete else actionAdd)
} else if (viewModel.media.type == MediaWrapper.TYPE_AUDIO) {
// Add images and action buttons to the details view
if (cover == null) {
detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_default_cone)
} else {
detailsOverview.setImageBitmap(context, cover)
}
actionsAdapter.set(ID_PLAY, Action(ID_PLAY.toLong(), res.getString(R.string.play)))
actionsAdapter.set(ID_LISTEN, Action(ID_LISTEN.toLong(), res.getString(R.string.listen)))
actionsAdapter.set(ID_PLAYLIST, Action(ID_PLAYLIST.toLong(), res.getString(R.string.add_to_playlist)))
} else if (viewModel.media.type == MediaWrapper.TYPE_VIDEO) {
// Add images and action buttons to the details view
if (cover == null) {
detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_default_cone)
} else {
detailsOverview.setImageBitmap(context, cover)
}
actionsAdapter.set(ID_PLAY, Action(ID_PLAY.toLong(), res.getString(R.string.play)))
actionsAdapter.set(ID_PLAY_FROM_START, Action(ID_PLAY_FROM_START.toLong(), res.getString(R.string.play_from_start)))
if (FileUtils.canWrite(viewModel.media.uri))
actionsAdapter.set(ID_DL_SUBS, Action(ID_DL_SUBS.toLong(), res.getString(R.string.download_subtitles)))
actionsAdapter.set(ID_PLAYLIST, Action(ID_PLAYLIST.toLong(), res.getString(R.string.add_to_playlist)))
//todo reenable entry point when ready
if (BuildConfig.DEBUG) actionsAdapter.set(ID_GET_INFO, Action(ID_GET_INFO.toLong(), res.getString(R.string.find_metadata)))
}
adapter = rowsAdapter
detailsOverview.actionsAdapter = actionsAdapter
// updateMetadata(mediaMetadataModel.updateLiveData.value)
}
}
}
class MediaItemDetailsModel : ViewModel() {
lateinit var mediaItemDetails: org.videolan.television.ui.MediaItemDetails
lateinit var media: MediaWrapper
var mediaStarted = false
}
class VideoDetailsOverviewRow(val item: MediaMetadata) : DetailsOverviewRow(item)
| application/television/src/main/java/org/videolan/television/ui/MediaItemDetailsFragment.kt | 2762441286 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class OkHttpTest {
@Test
fun testVersion() {
assertThat(OkHttp.VERSION).matches("[0-9]+\\.[0-9]+\\.[0-9]+(-.+)?")
}
}
| okhttp/src/test/java/okhttp3/OkHttpTest.kt | 2459322873 |
/*
Copyright 2015 Andreas Würl
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.blitzortung.android.dialogs
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.view.KeyEvent
import org.blitzortung.android.app.R
import org.blitzortung.android.app.components.VersionComponent
class InfoDialog(context: Context, versionComponent: VersionComponent) : AlertDialog(context) {
init {
setTitle("" + context.resources.getText(R.string.app_name) + " V" + versionComponent.versionName + " (" + versionComponent.versionCode + ")")
@SuppressLint("InflateParams") val infoDialogView = layoutInflater.inflate(R.layout.info_dialog, null, false)
setView(infoDialogView)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_MENU) {
dismiss()
return true
}
return super.onKeyUp(keyCode, event)
}
}
| app/src/main/java/org/blitzortung/android/dialogs/InfoDialog.kt | 4227245907 |
package com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo
import android.util.Range
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.PhotoShelfPost
/**
* Created by dave on 10/03/18.
* Helper util to group photos by id
*/
object PhotoGroup {
fun calcGroupIds(items: List<PhotoShelfPost>) {
if (items.isEmpty()) {
return
}
val count = items.size
var groupId = 0
var last = items[0].firstTag
items[0].groupId = groupId
var i = 1
while (i < count) {
// set same groupId for all identical tags
while (i < count && items[i].firstTag.equals(last, ignoreCase = true)) {
items[i++].groupId = groupId
}
if (i < count) {
++groupId
items[i].groupId = groupId
last = items[i].firstTag
}
i++
}
}
fun getRangeFromPosition(items: List<PhotoShelfPost>, position: Int, groupId: Int): Range<Int>? {
if (position < 0) {
return null
}
var min = position
var max = position
while (min > 0 && items[min - 1].groupId == groupId) {
--min
}
val lastIndex = items.size - 1
while (max < lastIndex && items[max].groupId == groupId) {
++max
}
// group is empty
return if (min == max) {
null
} else Range.create(min, max)
}
}
| tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/photo/PhotoGroup.kt | 4153842939 |
package com.neeplayer.ui.now_playing
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.*
import android.graphics.Bitmap
import android.media.AudioManager
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.MediaStore
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationCompat
import androidx.media.app.NotificationCompat.MediaStyle
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.ContentDataSource
import com.google.android.exoplayer2.util.Log
import com.google.android.exoplayer2.util.Log.LOG_LEVEL_ALL
import com.bumptech.glide.Glide
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON
import com.google.android.exoplayer2.MediaItem
import com.neeplayer.BuildConfig
import com.neeplayer.R
import com.neeplayer.model.Song
import com.neeplayer.toast
import com.neeplayer.ui.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
class MusicService : Service(), NowPlayingView {
private val handler = Handler(Looper.getMainLooper())
private val mainScope = MainScope()
private val presenter by inject<NowPlayingPresenter>()
private val mediaSourceFactory = ProgressiveMediaSource.Factory { ContentDataSource(this) }
private val mediaSession by lazy {
MediaSessionCompat(
this,
BuildConfig.APPLICATION_ID,
ComponentName(this, MediaButtonEventsReceiver::class.java),
PendingIntent.getBroadcast(this, 0, Intent(Intent.ACTION_MEDIA_BUTTON), PENDING_INTENT_FLAG_MUTABLE)
)
}
private var wasForeground = false
private val player by lazy {
SimpleExoPlayer.Builder(
applicationContext,
DefaultRenderersFactory(applicationContext).setExtensionRendererMode(EXTENSION_RENDERER_MODE_ON),
).build().apply {
val audioAttributes = AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
.setContentType(C.CONTENT_TYPE_MUSIC)
.build()
setAudioAttributes(audioAttributes, /*handleAudioFocus=*/ true)
addListener(object : Player.Listener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
stopTicking()
presenter.onNextClicked()
}
}
override fun onPlayerError(error: ExoPlaybackException) {
stopTicking()
applicationContext.toast(R.string.media_player_error)
}
})
Log.setLogLevel(LOG_LEVEL_ALL)
}
}
private var currentSong: Song? = null
set(value) {
if (value != field && value != null) {
val songUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, value.id)
player.setMediaSource(mediaSourceFactory.createMediaSource(MediaItem.fromUri(songUri)))
player.prepare()
field = value
}
}
override fun onCreate() {
super.onCreate()
presenter.bind(mainScope, this)
MediaSessionConnector(mediaSession).apply {
setPlayer(player)
}
mediaSession.setCallback(mediaSessionCallback)
mediaSession.isActive = true
registerReceiver(headsetPlugReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY))
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
PLAY_PREVIOUS_ACTION -> presenter.onPreviousClicked()
PLAY_OR_PAUSE_ACTION -> presenter.onPlayPauseClicked()
PLAY_NEXT_ACTION -> presenter.onNextClicked()
}
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent?): IBinder? = null
override fun render(song: Song, paused: Boolean) {
currentSong = song
player.playWhenReady = !paused
if (paused) {
stopTicking()
} else {
tick()
}
mainScope.launch {
withContext(Dispatchers.IO) {
updateInfo(song, paused)
}
}
}
override fun seek(progress: Int) {
player.seekTo(progress.toLong())
}
//endregion
//endregion
override fun onDestroy() {
stopTicking()
player.stop()
player.release()
mediaSession.release()
unregisterReceiver(headsetPlugReceiver)
wasForeground = false
stopForeground(true)
mainScope.cancel()
presenter.onDestroy()
}
override fun onTaskRemoved(rootIntent: Intent?) {
stopSelf()
super.onTaskRemoved(rootIntent)
}
private fun updateInfo(song: Song, paused: Boolean) {
val largeIconHeight = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height)
val largeIconWidth = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width)
val albumArt = try {
Glide.with(this).asBitmap().load(song.album.art).submit(largeIconWidth, largeIconHeight).get()
} catch (e: Exception) {
null
}
mediaSession.setMetadata(
MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.album.artist.name)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.album.title)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title)
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt)
.build()
)
mediaSession.setPlaybackState(
PlaybackStateCompat.Builder()
.setState(if (paused) PlaybackStateCompat.STATE_PAUSED else PlaybackStateCompat.STATE_PLAYING, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1f)
.setActions(PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
.build()
)
updateNotification(song, paused, albumArt)
}
//region Notifications
private fun updateNotification(song: Song, paused: Boolean, albumArt: Bitmap?) {
val intent = Intent(this, MainActivity::class.java)
.setAction(MainActivity.OPEN_NOW_PLAYING_ACTION)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(NotificationChannel(CHANNEL_ID,
getString(R.string.music_notification_channel_description),
NotificationManager.IMPORTANCE_LOW).apply { setSound(null, null) })
val mediaStyle = MediaStyle().setMediaSession(mediaSession.sessionToken)
.setShowActionsInCompactView(0, 1, 2)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setTicker(song.title)
.setContentTitle(song.title)
.setContentText(song.album.artist.name)
.setContentIntent(contentIntent)
.setLargeIcon(albumArt)
.setSmallIcon(R.drawable.ic_play_arrow_white)
.addMediaAction(R.drawable.ic_fast_rewind_black_medium, PLAY_PREVIOUS_ACTION)
.addMediaAction(if (paused) R.drawable.ic_play_arrow_black_medium else R.drawable.ic_pause_black_medium, PLAY_OR_PAUSE_ACTION)
.addMediaAction(R.drawable.ic_fast_forward_black_medium, PLAY_NEXT_ACTION)
.setStyle(mediaStyle)
.build()
when {
!paused -> {
wasForeground = true
startForeground(NOTIFICATION_ID, notification)
}
wasForeground -> {
stopForeground(false)
notificationManager.notify(NOTIFICATION_ID, notification)
}
}
}
private fun NotificationCompat.Builder.addMediaAction(@DrawableRes drawableRes: Int, action: String): NotificationCompat.Builder {
return addAction(drawableRes, action, createPendingIntent(action))
}
private fun createPendingIntent(action: String): PendingIntent {
val intent = Intent(this, MusicService::class.java).setAction(action)
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
//endregion
private fun tick() {
presenter.onSeek(player.currentPosition.toInt())
handler.postDelayed({ tick() }, TICK_PERIOD)
}
private fun stopTicking() {
handler.removeCallbacksAndMessages(null)
}
private val mediaSessionCallback = object : MediaSessionCompat.Callback() {
//TODO implement methods
}
private val headsetPlugReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
presenter.onPauseClicked()
}
}
class MediaButtonEventsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
//TODO handle events
}
}
}
private const val NOTIFICATION_ID = 42
private const val PLAY_PREVIOUS_ACTION = "PLAY_PREVIOUS"
private const val PLAY_OR_PAUSE_ACTION = "PLAY_OR_PAUSE"
private const val PLAY_NEXT_ACTION = "PLAY_NEXT"
private const val TICK_PERIOD = 100L
private const val CHANNEL_ID = "music_controls"
@SuppressLint("InlinedApi") // const will be inlined
private const val PENDING_INTENT_FLAG_MUTABLE = PendingIntent.FLAG_MUTABLE
| app/src/main/java/com/neeplayer/ui/now_playing/MusicService.kt | 851089005 |
package arcs
import kotlinx.wasm.jsinterop.* // ktlint-disable no-wildcard-imports
/**
* These are the method declarations for calling in WasmParticle.js
*/
// FIXME: replace with native CPP malloc copy
@SymbolName("Konan_js_get_String_length")
external fun getStringLength(arena: Int, stringIndex: Int): Int
@SymbolName("Konan_js_get_String_at")
external fun getStringCharCodeAt(arena: Int, stringIndex: Int, index: Int): Char
@SymbolName("arcs_WasmParticle_setState")
external fun setExternalState(arena: Int, index: Int, statePtr: Int, stateLen: Int)
@SymbolName("arcs_WasmParticle_log")
external fun logExternal(arena: Int, index: Int, msgPtr: Int, msgLen: Int)
@SymbolName("arcs_WasmParticle_getState")
external fun getExternalState(arena: Int, index: Int): JsValue
@SymbolName("arcs_WasmParticle_updateVariable")
external fun updateVariableExternal(
arena: Int,
index: Int,
propNamePtr: Int,
propNameLen: Int,
stateStrPtr: Int,
stateStrLen: Int
)
@SymbolName("arcs_WasmParticle_getInstance")
external fun getWasmParticleInstance(resultArena: Int): Int
@SymbolName("arcs_WasmParticle_service")
external fun invokeService(
objArena: Int,
objIndex: Int,
resultArena: Int,
stringPtr: Int,
strLen:
Int
): Int
@SymbolName("arcs_WasmParticle_setEventHandler")
external fun setEventHandler(arena: Int, index: Int, handlerPtr: Int, handlerLen: Int, func: Int)
@SymbolName("knjs__Promise_then")
public external fun knjs__Promise_then(
arena: Int,
index: Int,
lambdaIndex: Int,
lambdaResultArena: Int,
resultArena: Int
): Int
fun setEventHandler(obj: JsValue, property: String, lambda: KtFunction<Unit>) {
val pointer = wrapFunction(lambda)
setEventHandler(
obj.arena, obj.index, stringPointer(property),
stringLengthBytes(property), pointer
)
}
fun WasmParticle.setEventHandler(property: String, lambda: KtFunction<Unit>) {
setEventHandler(this, property, lambda)
}
open class Promise(arena: Int, index: Int) : JsValue(arena, index) {
constructor(jsValue: JsValue) : this(jsValue.arena, jsValue.index)
fun <Rlambda> then(lambda: KtFunction<Rlambda>): Promise {
val lambdaIndex = wrapFunction<Rlambda>(lambda)
val wasmRetVal = knjs__Promise_then(
this.arena,
this.index,
lambdaIndex,
ArenaManager.currentArena,
ArenaManager.currentArena
)
return Promise(ArenaManager.currentArena, wasmRetVal)
}
}
val JsValue.asPromise: Promise
get() {
return Promise(this.arena, this.index)
}
// UGLY: fix using internal KString.cpp functions
val JsValue.asString: String
get() {
val len = getStringLength(this.arena, this.index)
if (len > 0) {
val chars: CharArray = CharArray(len)
for (i in 0 until len) {
chars.store(i, getStringCharCodeAt(this.arena, this.index, i))
}
return String(chars)
}
return ""
}
| particles/Native/Kotlin/src/wasm/arcs/imports.kt | 784053392 |
package de.rheinfabrik.heimdall2
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
class OAuth2AccessTokenIsExpiredTest {
@Test
fun `when the expirationDate is null, isExpired method should return false`() {
// given an accessToken
val accessToken = OAuth2AccessToken(expirationDate = null)
// when the isExpired method is called
val value = accessToken.isExpired()
// then false is returned
assertEquals(value, false)
}
@Test
fun `when the expirationDate is in the past, isExpired method should return false`() {
// given a date in the past
val pastCalendar = Calendar.getInstance()
pastCalendar.add(Calendar.YEAR, 1)
// and a token with a past date
val accessToken = OAuth2AccessToken(expirationDate = pastCalendar)
// when the isExpired method is called
val value = accessToken.isExpired()
// then true is returned
assertEquals(value, false)
}
@Test
fun `when the expirationDate is in the future, isExpired method should return false`() {
// given a date in the past
val futureDate = Calendar.getInstance()
futureDate.add(Calendar.YEAR, 1)
// and a token with a past date
val accessToken = OAuth2AccessToken(expirationDate = futureDate)
// when the isExpired method is called
val value = accessToken.isExpired()
// then true is returned
assertEquals(value, false)
}
}
| library/src/test/java/de/rheinfabrik/heimdall2/OAuth2AccessTokenIsExpiredTest.kt | 4192466593 |
package com.flexpoker.pushnotificationhandlers
import com.flexpoker.framework.pushnotifier.PushNotificationHandler
import com.flexpoker.pushnotifications.ChatSentPushNotification
import org.springframework.messaging.simp.SimpMessageSendingOperations
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class ChatSentPushNotificationHandler @Inject constructor(private val messagingTemplate: SimpMessageSendingOperations) :
PushNotificationHandler<ChatSentPushNotification> {
@Async
override fun handle(pushNotification: ChatSentPushNotification) {
messagingTemplate.convertAndSend(pushNotification.destination, pushNotification)
}
} | src/main/kotlin/com/flexpoker/pushnotificationhandlers/ChatSentPushNotificationHandler.kt | 1890774246 |
package io.gitlab.arturbosch.detekt.core.settings
import io.gitlab.arturbosch.detekt.api.PropertiesAware
import io.gitlab.arturbosch.detekt.api.UnstableApi
import java.util.concurrent.ConcurrentHashMap
@OptIn(UnstableApi::class)
internal class PropertiesFacade : PropertiesAware {
private val _properties: MutableMap<String, Any?> = ConcurrentHashMap()
override val properties: Map<String, Any?> = _properties
override fun register(key: String, value: Any) {
_properties[key] = value
}
}
| detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/settings/PropertiesFacade.kt | 2295166852 |
package nl.sogeti.android.gpstracker.ng.features.graphs
import javax.inject.Inject
class GraphSpeedConverter @Inject constructor() {
fun speedToYValue(meterPerSecond: Float): Float {
if (meterPerSecond < 0.001) {
return 0F
}
return (1F / meterPerSecond) / 0.06F
}
fun yValueToSpeed(minutePerKilometer: Float): Float {
val kilometerPerMinute = 1F / minutePerKilometer
return kilometerPerMinute * 1000 / 60
}
}
| studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/graphs/GraphSpeedConverter.kt | 3961006807 |
package net.nemerosa.ontrack.extension.api
import org.springframework.security.config.web.servlet.HttpSecurityDsl
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component
/**
* Allows to customize the security settings for the UI.
*/
interface UISecurityExtension {
/**
* Extending the HTTP security for the UI.
*/
fun configure(httpSecurityDsl: HttpSecurityDsl, successHandler: AuthenticationSuccessHandler)
}
@Component
class NOPUISecurityExtension : UISecurityExtension {
override fun configure(httpSecurityDsl: HttpSecurityDsl, successHandler: AuthenticationSuccessHandler) {
}
} | ontrack-extension-api/src/main/java/net/nemerosa/ontrack/extension/api/UISecurityExtension.kt | 1996848411 |
package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.util.ProcessingContext
import org.rust.lang.core.completion.CompletionEngine.KEYWORD_PRIORITY
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.psi.ext.returnType
import org.rust.lang.core.types.ty.TyUnit
class RsKeywordCompletionProvider(
private vararg val keywords: String
) : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
for (keyword in keywords) {
var builder = LookupElementBuilder.create(keyword)
builder = addInsertionHandler(keyword, builder, parameters)
result.addElement(PrioritizedLookupElement.withPriority(builder, KEYWORD_PRIORITY))
}
}
}
class AddSuffixInsertionHandler(val suffix: String) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
context.document.insertString(context.selectionEndOffset, suffix)
EditorModificationUtil.moveCaretRelatively(context.editor, suffix.length)
}
}
private val ALWAYS_NEEDS_SPACE = setOf("crate", "const", "enum", "extern", "fn", "impl", "let", "mod", "mut", "pub",
"static", "struct", "trait", "type", "unsafe", "use")
private fun addInsertionHandler(keyword: String, builder: LookupElementBuilder, parameters: CompletionParameters): LookupElementBuilder {
val suffix = when (keyword) {
in ALWAYS_NEEDS_SPACE -> " "
"return" -> {
val fn = parameters.position.parentOfType<RsFunction>() ?: return builder
if (fn.returnType !is TyUnit) " " else ";"
}
else -> return builder
}
return builder.withInsertHandler(AddSuffixInsertionHandler(suffix))
}
| src/main/kotlin/org/rust/lang/core/completion/RsKeywordCompletionProvider.kt | 2794091637 |
package com.beust.kobalt.maven.aether
import com.beust.kobalt.api.IClasspathDependency
import com.beust.kobalt.api.Project
import org.eclipse.aether.util.artifact.JavaScopes
sealed class Scope(val scope: String, val dependencyLambda: (Project) -> List<IClasspathDependency>) {
companion object {
fun toScopes(isTest: Boolean) = if (isTest) listOf(TEST, COMPILE) else listOf(COMPILE)
}
object COMPILE : Scope(JavaScopes.COMPILE, Project::compileDependencies)
object PROVIDED : Scope(JavaScopes.PROVIDED, Project::compileProvidedDependencies)
object COMPILEONLY : Scope("compileOnly", Project::compileOnlyDependencies)
object SYSTEM : Scope(JavaScopes.SYSTEM, { project -> emptyList() })
object RUNTIME : Scope(JavaScopes.RUNTIME, Project::compileRuntimeDependencies)
object TEST : Scope(JavaScopes.TEST, Project::testDependencies)
} | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/Scope.kt | 39071725 |
package com.coxautodev.java.graphql.client.maven.plugin
import com.apollographql.apollo.compiler.GraphQLCompiler
import com.apollographql.apollo.compiler.NullableValueType
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugins.annotations.LifecyclePhase
import org.apache.maven.plugins.annotations.Mojo
import org.apache.maven.plugins.annotations.Parameter
import org.apache.maven.plugins.annotations.ResolutionScope
import org.apache.maven.project.MavenProject
import org.codehaus.plexus.util.FileUtils
import org.reflections.Reflections
import org.reflections.scanners.ResourcesScanner
import org.reflections.util.ConfigurationBuilder
import java.io.File
import java.nio.file.Files
import java.util.regex.Pattern
import java.util.stream.Collectors
/**
* Generates classes for a graphql API
*/
@Mojo(name = "generate",
requiresDependencyCollection = ResolutionScope.COMPILE,
requiresDependencyResolution = ResolutionScope.COMPILE,
defaultPhase = LifecyclePhase.GENERATE_SOURCES,
threadSafe = true
)
class GraphQLClientMojo: AbstractMojo() {
@Parameter(property = "outputDirectory", defaultValue = "\${project.build.directory}/generated-sources/graphql-client")
private var outputDirectory: File? = null
@Parameter(property = "basePackage", defaultValue = "com.example.graphql.client")
private var basePackage: String? = null
@Parameter(property = "introspectionFile", defaultValue = "\${project.basedir}/src/main/graphql/schema.json")
private var introspectionFile: File? = null
@Parameter(property = "addSourceRoot", defaultValue = "true")
private var addSourceRoot: Boolean? = null
@Parameter(readonly = true, required = true, defaultValue = "\${project}")
private var project: MavenProject? = null
@Throws(MojoExecutionException::class)
override fun execute() {
val project = this.project!!
val outputDirectory = this.outputDirectory!!
val basePackage = this.basePackage!!
val introspectionFile = this.introspectionFile!!
val basePackageDirName = basePackage.replace('.', File.separatorChar)
val sourceDirName = joinPath("src", "main", "graphql")
val queryDir = File(project.basedir, sourceDirName)
if(!queryDir.isDirectory) {
throw IllegalArgumentException("'${queryDir.absolutePath}' must be a directory")
}
val queries = Files.walk(queryDir.toPath())
.filter { it.toFile().isFile && it.toFile().name.endsWith(".graphql") }
.map { it.toFile().relativeTo(queryDir) }
.collect(Collectors.toList())
if(queries.isEmpty()) {
throw IllegalArgumentException("No queries found under '${queryDir.absolutePath}")
}
val baseTargetDir = File(project.build.directory, joinPath("graphql-schema", sourceDirName, basePackageDirName))
val schema = File(baseTargetDir, "schema.json")
val nodeModules = File(project.build.directory, joinPath("apollo-codegen-node-modules", "node_modules"))
nodeModules.deleteRecursively()
nodeModules.mkdirs()
val nodeModuleResources = Reflections(ConfigurationBuilder().setScanners(ResourcesScanner())
.setUrls(javaClass.getResource("/node_modules")))
.getResources(Pattern.compile(".*"))
nodeModuleResources.map { "/$it" }.forEach { resource ->
val path = resource.replaceFirst("/node_modules/", "").replace(Regex("/"), File.separator)
val diskPath = File(nodeModules, path)
diskPath.parentFile.mkdirs()
FileUtils.copyURLToFile(javaClass.getResource(resource), diskPath)
}
val apolloCli = File(nodeModules, joinPath("apollo-codegen", "lib", "cli.js"))
apolloCli.setExecutable(true)
if(!introspectionFile.isFile) {
throw IllegalArgumentException("Introspection JSON not found: ${introspectionFile.absolutePath}")
}
if(!apolloCli.isFile) {
throw IllegalStateException("Apollo codegen cli not found: '${apolloCli.absolutePath}'")
}
schema.parentFile.mkdirs()
queries.forEach { query ->
val src = File(queryDir, query.path)
val dest = File(baseTargetDir, query.path)
dest.parentFile.mkdirs()
src.copyTo(dest, overwrite = true)
}
// https://stackoverflow.com/a/25080297
// https://stackoverflow.com/questions/32827329/how-to-get-the-full-path-of-an-executable-in-java-if-launched-from-windows-envi
val node = System.getenv("PATH")?.split(File.pathSeparator)?.map { File(it, "node") }?.find {
it.isFile && it.canExecute()
} ?: throw IllegalStateException("No 'node' executable found on PATH!")
log.info("Found node executable: ${node.absolutePath}")
val arguments = listOf("generate", *queries.map { File(baseTargetDir, it.path).absolutePath }.toTypedArray(), "--target", "json", "--schema", introspectionFile.absolutePath, "--output", schema.absolutePath)
log.info("Running apollo cli (${apolloCli.absolutePath}) with arguments: ${arguments.joinToString(" ")}")
val proc = ProcessBuilder(node.absolutePath, apolloCli.absolutePath, *arguments.toTypedArray())
.directory(nodeModules.parentFile)
.inheritIO()
.start()
if(proc.waitFor() != 0) {
throw IllegalStateException("Apollo codegen cli command failed")
}
val compiler = GraphQLCompiler()
compiler.write(GraphQLCompiler.Arguments(schema, outputDirectory, mapOf(), NullableValueType.JAVA_OPTIONAL, true, true))
if(addSourceRoot == true) {
project.addCompileSourceRoot(outputDirectory.absolutePath)
}
}
private fun joinPath(vararg names: String): String = names.joinToString(File.separator)
}
| apollo-client-maven-plugin/src/main/kotlin/com/coxautodev/java/graphql/client/maven/plugin/GraphQLClientMojo.kt | 3235699882 |
/*
* Copyright 2019 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.domain.search
import android.content.Context
import io.plaidapp.core.interfaces.SearchDataSourceFactory
import io.plaidapp.core.interfaces.SearchDataSourceFactoryProvider
import io.plaidapp.designernews.dagger.DaggerDesignerNewsSearchComponent
import io.plaidapp.designernews.dagger.DesignerNewsPreferencesModule
import io.plaidapp.ui.PlaidApplication.Companion.coreComponent
/**
* Provider for DesignerNews implementations of [SearchDataSourceFactory]
*/
class DesignerNewsSearchDataSourceFactoryProvider : SearchDataSourceFactoryProvider {
/**
* To construct the concrete implementation of [SearchDataSourceFactory], we need to build the
* dependency graph
*/
override fun getFactory(context: Context): SearchDataSourceFactory {
return DaggerDesignerNewsSearchComponent.builder()
.coreComponent(coreComponent(context))
.designerNewsPreferencesModule(
DesignerNewsPreferencesModule(context)
)
.build().factory()
}
}
| designernews/src/main/java/io/plaidapp/designernews/domain/search/DesignerNewsSearchDataSourceFactoryProvider.kt | 2999825302 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.actions
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap
import com.demonwav.mcdev.platform.mixin.handlers.ShadowHandler
import com.demonwav.mcdev.util.ActionData
import com.demonwav.mcdev.util.getDataFromActionEvent
import com.demonwav.mcdev.util.invokeLater
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiReference
import com.intellij.ui.LightColors
import com.intellij.ui.awt.RelativePoint
abstract class SrgActionBase : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val data = getDataFromActionEvent(e) ?: return showBalloon("Unknown failure", e)
if (data.element !is PsiIdentifier) {
showBalloon("Not a valid element", e)
return
}
val mcpModule = data.instance.getModuleOfType(McpModuleType) ?: return showBalloon("No mappings found", e)
mcpModule.srgManager?.srgMap?.onSuccess { srgMap ->
var parent = data.element.parent ?: return@onSuccess showBalloon("Not a valid element", e)
if (parent is PsiMember) {
val shadowTarget = ShadowHandler.getInstance()?.findFirstShadowTargetForReference(parent)?.element
if (shadowTarget != null) {
parent = shadowTarget
}
}
if (parent is PsiReference) {
parent = parent.resolve() ?: return@onSuccess showBalloon("Not a valid element", e)
}
withSrgTarget(parent, srgMap, e, data)
}?.onError {
showBalloon(it.message ?: "No MCP data available", e)
} ?: showBalloon("No mappings found", e)
}
abstract fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData)
protected fun showBalloon(message: String, e: AnActionEvent) {
val balloon = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, null, LightColors.YELLOW, null)
.setHideOnAction(true)
.setHideOnClickOutside(true)
.setHideOnKeyOutside(true)
.createBalloon()
val project = e.project ?: return
val statusBar = WindowManager.getInstance().getStatusBar(project)
invokeLater {
balloon.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight)
}
}
protected fun showSuccessBalloon(editor: Editor, element: PsiElement, text: String) {
val balloon = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, null, LightColors.SLIGHTLY_GREEN, null)
.setHideOnAction(true)
.setHideOnClickOutside(true)
.setHideOnKeyOutside(true)
.createBalloon()
invokeLater {
balloon.show(
RelativePoint(
editor.contentComponent,
editor.visualPositionToXY(editor.offsetToVisualPosition(element.textRange.endOffset))
),
Balloon.Position.atRight
)
}
}
}
| src/main/kotlin/platform/mcp/actions/SrgActionBase.kt | 2749884098 |
/*
* Copyright (C) 2016 Mihály Szabó
*
* 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 org.libreplicator.core.time
import kotlinx.coroutines.experimental.CompletableDeferred
import kotlinx.coroutines.experimental.channels.actor
import org.libreplicator.core.time.api.TimeProvider
class SynchronizedTimeProvider(private val timeProvider: TimeProvider) : TimeProvider {
private val timeProviderActor = actor<TimeProviderMessage> {
for (message in channel) {
when (message) {
is TimeProviderMessage.GetTime -> message.deferred.complete(timeProvider.getTime())
}
}
}
override suspend fun getTime(): Long {
val deferred = CompletableDeferred<Long>()
timeProviderActor.send(TimeProviderMessage.GetTime(deferred))
return deferred.await()
}
private sealed class TimeProviderMessage {
class GetTime(val deferred: CompletableDeferred<Long>) : TimeProviderMessage()
}
}
| libreplicator-core/src/main/kotlin/org/libreplicator/core/time/SynchronizedTimeProvider.kt | 3138112337 |
/*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.bilibili
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ViewHolderInflater
import com.drakeet.multitype.sample.R
/**
* @author Drakeet Xu
*/
class HorizontalPostsHolderInflater : ViewHolderInflater<PostList, HorizontalPostsHolderInflater.ViewHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
return ViewHolder(inflater.inflate(R.layout.item_horizontal_list, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, item: PostList) {
holder.setPosts(item.posts)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val adapter: PostsAdapter = PostsAdapter()
private val recyclerView: RecyclerView = itemView.findViewById(R.id.post_list)
init {
val layoutManager = LinearLayoutManager(itemView.context)
layoutManager.orientation = LinearLayoutManager.HORIZONTAL
recyclerView.layoutManager = layoutManager
LinearSnapHelper().attachToRecyclerView(recyclerView)
recyclerView.adapter = adapter
}
fun setPosts(posts: List<Post>) {
adapter.setPosts(posts)
adapter.notifyDataSetChanged()
}
}
}
| sample/src/main/kotlin/com/drakeet/multitype/sample/bilibili/HorizontalPostsHolderInflater.kt | 1905875546 |
/*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.manager
import net.mm2d.upnp.Device
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.internal.thread.ThreadCondition
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* A class holding [Device] found in [net.mm2d.upnp.ControlPoint].
*
* Check the expiration date of Device, and notify the expired Device as Lost.
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*
* @constructor initialize
* @param expireListener Listener to receive expired notifications
*/
internal class DeviceHolder(
taskExecutors: TaskExecutors,
private val expireListener: (Device) -> Unit
) : Runnable {
private val threadCondition = ThreadCondition(taskExecutors.manager)
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val deviceMap = mutableMapOf<String, Device>()
val deviceList: List<Device>
get() = lock.withLock {
deviceMap.values.toList()
}
val size: Int
get() = lock.withLock {
deviceMap.size
}
fun start() {
threadCondition.start(this)
}
fun stop() {
threadCondition.stop()
}
fun add(device: Device) {
lock.withLock {
deviceMap[device.udn] = device
condition.signalAll()
}
}
operator fun get(udn: String): Device? = lock.withLock {
deviceMap[udn]
}
fun remove(device: Device): Device? = lock.withLock {
deviceMap.remove(device.udn)
}
fun remove(udn: String): Device? = lock.withLock {
deviceMap.remove(udn)
}
fun clear(): Unit = lock.withLock {
deviceMap.clear()
}
override fun run() {
Thread.currentThread().let {
it.name = it.name + "-device-holder"
}
lock.withLock {
try {
while (!threadCondition.isCanceled()) {
while (deviceMap.isEmpty()) {
condition.await()
}
expireDevice()
waitNextExpireTime()
}
} catch (ignored: InterruptedException) {
}
}
}
private fun expireDevice() {
val now = System.currentTimeMillis()
deviceMap.values
.filter { it.expireTime < now }
.forEach {
deviceMap.remove(it.udn)
expireListener.invoke(it)
}
}
@Throws(InterruptedException::class)
private fun waitNextExpireTime() {
if (deviceMap.isEmpty()) {
return
}
val mostRecentExpireTime = deviceMap.values.map { it.expireTime }.minOrNull() ?: 0L
val duration = mostRecentExpireTime - System.currentTimeMillis() + MARGIN_TIME
val sleep = maxOf(duration, MARGIN_TIME) // avoid negative value
condition.await(sleep, TimeUnit.MILLISECONDS)
}
companion object {
private val MARGIN_TIME = TimeUnit.SECONDS.toMillis(10)
}
}
| mmupnp/src/main/java/net/mm2d/upnp/internal/manager/DeviceHolder.kt | 2079830359 |
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.content.preferences
import java.util.*
import kotlin.properties.ReadWriteProperty
object PreferencesDelegates {
fun int(
defaultValue: Int = 0,
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, Int> = IntPreferencesProperty(defaultValue, key)
fun float(
defaultValue: Float = 0f,
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, Float> = FloatPreferencesProperty(defaultValue, key)
fun string(
defaultValue: String = "",
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, String> = StringPreferencesProperty(defaultValue, key)
fun boolean(
defaultValue: Boolean = false,
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, Boolean> = BooleanPreferencesProperty(defaultValue, key)
fun date(
defaultValue: Long = 0,
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, Date> = DatePreferencesProperty(defaultValue, key)
fun calendar(
defaultValue: Long = 0,
key: String? = null
): ReadWriteProperty<SharedPreferencesProvider, Calendar> = CalendarPreferencesProperty(defaultValue, key)
fun <T> custom(
defaultValue: T,
key: String? = null,
mapperFrom: (String) -> T
): ReadWriteProperty<SharedPreferencesProvider, T> = CustomPreferencesProperty(defaultValue, key, mapperFrom)
fun <T> custom(
defaultValue: T,
key: String? = null,
mapperFrom: (String) -> T,
mapperTo: (T) -> String
): ReadWriteProperty<SharedPreferencesProvider, T> = CustomPreferencesProperty(defaultValue, key, mapperFrom, mapperTo)
} | akommons/src/main/java/com/dewarder/akommons/content/preferences/PreferencesDelegates.kt | 1881944527 |
package com.hedvig.botService.services.events
data class SignedOnWaitlistEvent (
val email: String
)
| src/main/java/com/hedvig/botService/services/events/SignedOnWaitlistEvent.kt | 2757440655 |
/*
* Copyright 2020 Patches Klinefelter
*
* 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.isupatches.wisefy.logging
/**
* Interface for clients for logging
*
* @author Patches
* @since 5.0
*/
interface WiseFyLogger {
/**
* Logs an info message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun i(tag: String, message: String, vararg args: Any)
/**
* Logs an verbose message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun v(tag: String, message: String, vararg args: Any)
/**
* Logs a debug message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun d(tag: String, message: String, vararg args: Any)
/**
* Logs a warning message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun w(tag: String, message: String, vararg args: Any)
/**
* Logs an error message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun e(tag: String, message: String, vararg args: Any)
/**
* Logs an error message with throwable
*
* @param tag The tag for the log message
* @param throwable A throwable to log with the message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun e(tag: String, throwable: Throwable, message: String, vararg args: Any)
/**
* Logs a terrible failure message
*
* @param tag The tag for the log message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun wtf(tag: String, message: String, vararg args: Any)
/**
* Logs a terrible failure message with throwable
*
* @param tag The tag for the log message
* @param throwable A throwable to log with the message
* @param message The message to log (can include placeholders)
* @param args The formatting arguments for the log message
*
* @author Patches
* @since 5.0
*/
fun wtf(tag: String, throwable: Throwable, message: String, vararg args: Any)
}
| wisefy/src/main/java/com/isupatches/wisefy/logging/WiseFyLogger.kt | 2609547379 |
/*
* Copyright (c) 2019 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package ffc.android
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.widget.TextView
fun TextView.getDouble(default: Double? = null): Double? {
val text = text.toString()
if (text.isBlank()) return default
return text.toDouble()
}
@Deprecated("Consider replace with drawableStart to better support right-to-left Layout",
ReplaceWith("drawableStart"),
DeprecationLevel.WARNING)
var TextView.drawableLeft: Drawable?
get() = compoundDrawables[0]
set(drawable) = setCompoundDrawablesWithIntrinsicBounds(drawable, drawableTop, drawableRight, drawableBottom)
var TextView.drawableStart: Drawable?
get() = compoundDrawablesRelative[0]
set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(start = drawable)
var TextView.drawableTop: Drawable?
get() = compoundDrawablesRelative[1]
set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(top = drawable)
@Deprecated("Consider replace with drawableEnd to better support right-to-left Layout",
ReplaceWith("drawableEnd"),
DeprecationLevel.WARNING)
var TextView.drawableRight: Drawable?
get() = compoundDrawables[2]
set(drawable) = setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawable, drawableBottom)
var TextView.drawableEnd: Drawable?
get() = compoundDrawablesRelative[2]
set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(end = drawable)
var TextView.drawableBottom: Drawable?
get() = compoundDrawablesRelative[3]
set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(bottom = drawable)
private fun TextView.compoundDrawablesRelativeWithIntrinsicBounds(
start: Drawable? = drawableStart,
top: Drawable? = drawableTop,
end: Drawable? = drawableEnd,
bottom: Drawable? = drawableBottom
) {
setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom)
}
class TextWatcherDsl : TextWatcher {
private var afterChanged: ((Editable?) -> Unit)? = null
private var beforeChanged: ((s: CharSequence?, start: Int, count: Int, after: Int) -> Unit)? = null
private var onChanged: ((s: CharSequence?, start: Int, before: Int, count: Int) -> Unit)? = null
override fun afterTextChanged(s: Editable?) {
afterChanged?.invoke(s)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
beforeChanged?.invoke(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onChanged?.invoke(s, start, before, count)
}
fun afterTextChanged(block: (s: Editable?) -> Unit) {
afterChanged = block
}
fun beforeTextChanged(block: (s: CharSequence?, start: Int, count: Int, after: Int) -> Unit) {
beforeChanged = block
}
fun onTextChanged(block: (s: CharSequence?, start: Int, before: Int, count: Int) -> Unit) {
onChanged = block
}
}
fun TextView.addTextWatcher(block: TextWatcherDsl.() -> Unit) {
addTextChangedListener(TextWatcherDsl().apply(block))
}
| ffc/src/main/kotlin/ffc/android/TextView.kt | 2377852118 |
package org.lrs.kmodernlrs
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.lrs.kmodernlrs.domain.Actor
import org.lrs.kmodernlrs.domain.Statement
import org.lrs.kmodernlrs.domain.Verb
import org.lrs.kmodernlrs.domain.XapiObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.json.JsonTest
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.json.GsonTester
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit4.SpringRunner
import java.sql.Timestamp
import java.util.*
@ActiveProfiles("test")
@RunWith(SpringRunner::class)
@SpringBootTest(classes = arrayOf(Application::class))
@JsonTest
open class StatementsTest {
@Autowired lateinit var jsonTester: GsonTester<Statement>
val log: Logger = LoggerFactory.getLogger(StatementsTest::class.java)
lateinit var statement: Statement
var jsonWithActor: String = "{\"id\": \"12345678-1234-5678-1234-567812345678\","+
"\"actor\":{"+
"\"mbox\":\"mailto:[email protected]\","+
"\"name\":\"test actor\","+
"\"objectType\": \"Group\","+
"\"member\": ["+
"{\"objectType\": \"Agent\","+
"\"name\": \"member one\""+
"}],\"account\": {"+
"\"homePage\": \"http://www.example.pl\","+
"\"name\": \"1625378\"}},"+
"\"verb\":{"+
"\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
"\"display\":{\"en-US\":\"created\""+
"}},\"object\":{\"id\":\"http://example.adlnet.gov/xapi/example/activity\"}}"
var jsonWithActivityObject: String = "{\"id\": \"12345678-1234-5678-1234-567812345678\","+
"\"actor\":{"+
"\"mbox\":\"mailto:[email protected]\","+
"\"name\":\"test actor\","+
"\"objectType\": \"Group\","+
"\"member\": ["+
"{\"objectType\": \"Agent\","+
"\"name\": \"member one\""+
"}],\"account\": {"+
"\"homePage\": \"http://www.example.pl\","+
"\"name\": \"1625378\"}},"+
"\"verb\":{"+
"\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
"\"display\":{\"en-US\":\"created\""+
"}},\"object\":{"+
"\"id\": \"http://www.example.co.uk/exampleactivity\","+
"\"definition\": {"+
"\"name\": { \"en-GB\": \"example activity\","+
"\"en-US\": \"example activity\" },"+
"\"description\": {\"en-GB\": \"An example of an activity\","+
"\"en-US\": \"An example of an activity\" },"+
"\"type\": \"http://www.example.co.uk/types/exampleactivitytype\""+
"},\"objectType\": \"Activity\"}}"
var jsonWithSubstatementObject: String = "{\"id\": \"12345678-1234-5678-1234-567812345678\","+
"\"actor\":{"+
"\"mbox\":\"mailto:[email protected]\","+
"\"name\":\"test actor\","+
"\"objectType\": \"Group\","+
"\"member\": ["+
"{\"objectType\": \"Agent\","+
"\"name\": \"member one\""+
"}],\"account\": {"+
"\"homePage\": \"http://www.example.pl\","+
"\"name\": \"1625378\"}},"+
"\"verb\":{"+
"\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
"\"display\":{\"en-US\":\"created\""+
"}},\"object\":{\"objectType\": \"SubStatement\","+
"\"actor\" : { \"objectType\": \"Agent\", \"mbox\":\"mailto:[email protected]\" "+
"},\"verb\" : { \"id\":\"http://example.com/confirmed\", \"display\":{"+
"\"en\":\"confirmed\"} },\"object\": {\"objectType\":\"StatementRef\","+
"\"id\" :\"9e13cefd-53d3-4eac-b5ed-2cf6693903bb\"}}}"
var longStatement: String = "{\"id\": \"6690e6c9-3ef0-4ed3-8b37-7f3964730bee\","+
"\"actor\": {\"name\": \"Team PB\",\"mbox\": \"mailto:[email protected]\","+
"\"member\": [{\"name\": \"Andrew Downes\",\"account\": {"+
"\"homePage\": \"http://www.example.com\",\"name\": \"13936749\"},"+
"\"objectType\": \"Agent\"}, { \"name\": \"Toby Nichols\","+
"\"openid\": \"http://toby.openid.example.org/\","+
"\"objectType\": \"Agent\"},{\"name\": \"Ena Hills\","+
"\"mbox_sha1sum\": \"ebd31e95054c018b10727ccffd2ef2ec3a016ee9\","+
"\"objectType\": \"Agent\"}], \"objectType\": \"Group\"},\"verb\": {"+
"\"id\": \"http://adlnet.gov/expapi/verbs/attended\", \"display\": {"+
"\"en-GB\": \"attended\",\"en-US\": \"attended\"}}, \"result\": {"+
//"\"extensions\": {\"http://example.com/profiles/meetings/resultextensions/minuteslocation\": \"X:/meetings/minutes/examplemeeting.one\"\"},"+
"\"success\": true,\"completion\": true,\"response\": \"We agreed on some example actions.\","+
"\"duration\": \"PT1H0M0S\"},\"context\": {"+
"\"registration\": \"ec531277-b57b-4c15-8d91-d292c5b2b8f7\","+
"\"contextActivities\": {\"parent\": [{\"id\": \"http://www.example.com/meetings/series/267\","+
"\"objectType\": \"Activity\"}],\"category\": [{"+
"\"id\": \"http://www.example.com/meetings/categories/teammeeting\","+
"\"objectType\": \"Activity\",\"definition\": {\"name\": {"+
"\"en\": \"team meeting\"},\"description\": {"+
"\"en\": \"A category of meeting used for regular team meetings.\""+
"},\"type\": \"http://example.com/expapi/activities/meetingcategory\""+
"}}],\"other\": [{\"id\": \"http://www.example.com/meetings/occurances/34257\","+
"\"objectType\": \"Activity\"}, {\"id\": \"http://www.example.com/meetings/occurances/3425567\","+
"\"objectType\": \"Activity\"}]},\"instructor\" :{\"name\": \"Andrew Downes\","+
"\"account\": { \"homePage\": \"http://www.example.com\",\"name\":\"13936749\""+
"},\"objectType\": \"Agent\"},\"team\":{\"name\": \"Team PB\","+
"\"mbox\": \"mailto:[email protected]\",\"objectType\": \"Group\""+
"}, \"platform\" : \"Example virtual meeting software\",\"language\" : \"tlh\","+
"\"statement\" : {\"objectType\":\"StatementRef\","+
"\"id\":\"6690e6c9-3ef0-4ed3-8b37-7f3964730bee\" }},\"timestamp\": \"2013-05-18T05:32:34.804+00:00\","+
"\"stored\": \"2013-05-18T05:32:34.804+00:00\","+
"\"authority\": {\"account\": { \"homePage\": \"http://cloud.scorm.com/\","+
"\"name\": \"anonymous\"},\"objectType\": \"Agent\"},\"version\": \"1.0.0\","+
"\"object\": {\"id\": \"http://www.example.com/meetings/occurances/34534\",\"definition\": {"+
"\"extensions\": {\"http://example.com/profiles/meetings/activitydefinitionextensions/room\": "+
"{\"name\": \"Kilby\", \"id\" :\"http://example.com/rooms/342\"}"+
"},\"name\": {\"en-GB\": \"example meeting\","+
"\"en-US\": \"example meeting\"},\"description\": {"+
"\"en-GB\": \"An example meeting that happened on a specific occasion with certain people present.\","+
"\"en-US\": \"An example meeting that happened on a specific occasion with certain people present.\""+
"},\"type\": \"http://adlnet.gov/expapi/activities/meeting\","+
"\"moreInfo\": \"http://virtualmeeting.example.com/345256\""+
"},\"objectType\": \"Activity\"}}"
@Before
fun initialize() {
val actor: Actor = Actor()
actor.mbox = "mailto:[email protected]"
val verb: Verb = Verb("http://example.com/xapi/verbs#defenestrated", hashMapOf("pl" to "test"))
val obj: XapiObject = XapiObject("testid", "Activity", null)
statement = Statement("1", actor, verb, obj, null, null, null, Timestamp(Calendar.getInstance().time.time).toString(), null, "1.0", emptyList())
val gson: Gson = GsonBuilder().create()
GsonTester.initFields(this, gson)
}
@Test
fun whenStatementGivenJsonTesterShouldntBeNull() {
assertNotNull(jsonTester.write(statement))
}
@Test
fun whenJsonActorGivenObjectShouldHaveAllFields() {
log.debug(">>>> json with actor -> "+ jsonWithActor)
val statement: Statement = jsonTester.parseObject(jsonWithActor)
assertNotNull(statement.id)
assertNotNull(statement.actor?.mbox)
assertNotNull(statement.actor?.name)
assertNotNull(statement.actor?.objectType)
assertNotNull(statement.actor?.member?.toTypedArray()?.get(0)!!.objectType)
assertNotNull(statement.actor?.member?.toTypedArray()?.get(0)!!.name)
assertNotNull(statement.actor?.account?.name)
assertNotNull(statement.actor?.account?.homePage)
assertNotNull(statement.verb?.id)
assertNotNull(statement.verb?.display)
assertNotNull(statement.xapiObj?.id)
}
@Test
fun whenJsonActivityGivenObjectShouldHaveAllFields() {
log.debug(">>>> json with object as an activity -> "+ jsonWithActivityObject)
val statement: Statement = jsonTester.parseObject(jsonWithActivityObject)
assertNotNull(statement.id)
assertNotNull(statement.xapiObj?.id)
assertThat(statement.xapiObj?.objectType).isEqualTo("Activity")
assertNotNull(statement.xapiObj?.definition)
assertThat(statement.xapiObj?.definition?.name).isNotEmpty
assertThat(statement.xapiObj?.definition?.description).isNotEmpty
assertThat(statement.xapiObj?.definition?.type).isEqualTo("http://www.example.co.uk/types/exampleactivitytype")
}
@Test
fun whenJsonSubstatementGivenObjectShouldHaveAllFields() {
log.debug(">>>> json with object as a substatement -> "+ jsonWithSubstatementObject)
val statement: Statement = jsonTester.parseObject(jsonWithSubstatementObject)
assertThat(statement.xapiObj?.objectType).isEqualTo("SubStatement")
assertNotNull(statement.xapiObj?.actor)
assertThat(statement.xapiObj?.actor?.objectType).isEqualTo("Agent")
assertThat(statement.xapiObj?.actor?.mbox).isEqualTo("mailto:[email protected]")
assertNotNull(statement.xapiObj?.verb)
assertThat(statement.xapiObj?.verb?.display).containsEntry("en","confirmed")
assertThat(statement.xapiObj?.xapiObj?.objectType).isEqualTo("StatementRef")
assertThat(statement.xapiObj?.xapiObj?.id).isEqualTo("9e13cefd-53d3-4eac-b5ed-2cf6693903bb")
}
@Test
fun whenLargeJsonStatementGivenObjectShouldHaveAllFields() {
log.debug(">>>> json long statement -> "+ longStatement)
val statement: Statement = jsonTester.parseObject(longStatement)
assertThat(statement.actor?.member).hasSize(3)
assertThat(statement.verb?.id).isEqualTo("http://adlnet.gov/expapi/verbs/attended")
assertThat(statement.result?.response).isEqualTo("We agreed on some example actions.")
assertThat(statement.context?.registration).isEqualTo("ec531277-b57b-4c15-8d91-d292c5b2b8f7")
assertThat(statement.context?.contextActivities?.parent?.first()?.objectType).isEqualTo("Activity")
assertThat(statement.context?.contextActivities?.category?.first()?.definition?.description)
.containsEntry("en", "A category of meeting used for regular team meetings.")
assertThat(statement.context?.contextActivities?.other?.get(1)?.objectType).isEqualTo("Activity")
assertThat(statement.context?.instructor?.name).isEqualTo("Andrew Downes")
assertThat(statement.context?.instructor?.account?.name).isEqualTo("13936749")
assertThat(statement.context?.team?.mbox).isEqualTo("mailto:[email protected]")
assertThat(statement.context?.language).isEqualTo("tlh")
assertThat(statement.context?.statement?.id).isEqualTo("6690e6c9-3ef0-4ed3-8b37-7f3964730bee")
assertNotNull(statement.timestamp)
assertNotNull(statement.stored)
assertThat(statement.authority?.account?.homePage).isEqualTo("http://cloud.scorm.com/")
assertThat(statement.version).isEqualTo("1.0.0")
assertThat(statement.xapiObj?.definition?.extensions).containsKey("http://example.com/profiles/meetings/activitydefinitionextensions/room")
assertThat(statement.xapiObj?.definition?.moreInfo).isEqualTo("http://virtualmeeting.example.com/345256")
}
} | src/tests/org/lrs/kmodernlrs/StatementsTest.kt | 876357994 |
package dolvic.gw2.api.mechanics
import java.net.URI
data class Outfit(
val id: Int,
val name: String,
val icon: URI,
val unlockItems: List<Int>
)
| types/src/main/kotlin/dolvic/gw2/api/mechanics/Outfit.kt | 2984543275 |
package li.doerf.hacked.ui.viewmodels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import li.doerf.hacked.db.AppDatabase
import li.doerf.hacked.db.daos.BreachedSiteDao
import li.doerf.hacked.db.entities.BreachedSite
class BreachedSitesViewModel(application: Application) : AndroidViewModel(application) {
private val myBreachedSitesDao: BreachedSiteDao = AppDatabase.get(application).brachedSiteDao
private var myBreachedSites: LiveData<List<BreachedSite>>?
private var myBreachedSitesMostRecent: LiveData<List<BreachedSite>>? = null
private val filterLiveData: MutableLiveData<Pair<Order, String>> = MutableLiveData(Pair(Order.NAME, ""))
val breachesSites: LiveData<List<BreachedSite>>?
get() {
if (myBreachedSites == null) {
myBreachedSites = myBreachedSitesDao.allLD
}
return myBreachedSites
}
fun setFilter(filter: String) {
filterLiveData.value = Pair(Order.NAME, filter)
}
val breachesSitesMostRecent: LiveData<List<BreachedSite>>?
get() {
if (myBreachedSitesMostRecent == null) {
myBreachedSitesMostRecent = myBreachedSitesDao.listMostRecent()
}
return myBreachedSitesMostRecent
}
fun orderByName() {
filterLiveData.value = Pair(Order.NAME, "")
}
fun orderByCount() {
filterLiveData.value = Pair(Order.COUNT, "")
}
fun orderByDate() {
filterLiveData.value = Pair(Order.DATE, "")
}
private enum class Order {
NAME, COUNT, DATE
}
init {
myBreachedSites = Transformations.switchMap(filterLiveData
) { (o: Order, filter: String) ->
when(o) {
Order.NAME -> {
if (filter.trim { it <= ' ' } == "") {
return@switchMap myBreachedSitesDao.allLD
} else {
return@switchMap myBreachedSitesDao.getAllByName("%$filter%")
}
}
Order.COUNT -> {
return@switchMap myBreachedSitesDao.allByPwnCountLD
}
Order.DATE -> {
return@switchMap myBreachedSitesDao.allByDateAddedLD
}
}
}
}
} | app/src/main/kotlin/li/doerf/hacked/ui/viewmodels/BreachedSitesViewModel.kt | 3740461048 |
package de.mkammerer.unisontray.util
import org.slf4j.LoggerFactory
import java.io.InputStreamReader
import java.util.concurrent.atomic.AtomicReference
object ProcessUtil {
private val logger = LoggerFactory.getLogger(javaClass)
fun startAndReadProcess(builder: ProcessBuilder): ProcessResult {
builder.redirectErrorStream(true)
val output = AtomicReference<String>()
val exception = AtomicReference<Exception>()
logger.debug("Starting process")
val process = builder.start()
val thread = Thread({
try {
logger.debug("Reading process output")
InputStreamReader(process.inputStream, Charsets.UTF_8).use {
output.set(it.readText())
}
} catch (e: Exception) {
exception.set(e)
}
}, "process-capture")
thread.start()
logger.debug("Waiting for process exit")
val exitCode = process.waitFor()
thread.interrupt()
thread.join()
logger.debug("Process has exited with {}", exitCode)
// Rethrow exception if one happened
exception.get()?.let { throw it }
return ProcessResult(output.get(), exitCode)
}
data class ProcessResult(val output: String, val exitCode: Int)
} | src/main/kotlin/de/mkammerer/unisontray/util/Process.kt | 3474375642 |
package com.stripe.android.test.core.ui
import androidx.test.uiautomator.UiDevice
class AddPaymentMethodButton(private val device: UiDevice) {
fun isDisplayed(): Boolean {
return UiAutomatorText("+ Add", null, device).exists()
}
}
| paymentsheet-example/src/androidTestDebug/java/com/stripe/android/test/core/ui/AddPaymentMethodButton.kt | 1311412060 |
package com.stripe.android.identity
import android.content.Context
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.Fragment
import com.stripe.android.core.injection.Injectable
import com.stripe.android.core.injection.Injector
import com.stripe.android.core.injection.InjectorKey
import com.stripe.android.core.injection.WeakMapInjectorRegistry
import com.stripe.android.identity.injection.DaggerIdentityVerificationSheetComponent
import com.stripe.android.identity.injection.IdentityVerificationSheetComponent
internal class StripeIdentityVerificationSheet internal constructor(
private val activityResultLauncher: ActivityResultLauncher<IdentityVerificationSheetContract.Args>,
context: Context,
private val configuration: IdentityVerificationSheet.Configuration
) : IdentityVerificationSheet, Injector {
constructor(
from: ComponentActivity,
configuration: IdentityVerificationSheet.Configuration,
identityVerificationCallback: IdentityVerificationSheet.IdentityVerificationCallback
) : this(
from.registerForActivityResult(
IdentityVerificationSheetContract(),
identityVerificationCallback::onVerificationFlowResult
),
from,
configuration
)
constructor(
from: Fragment,
configuration: IdentityVerificationSheet.Configuration,
identityVerificationCallback: IdentityVerificationSheet.IdentityVerificationCallback
) : this(
from.registerForActivityResult(
IdentityVerificationSheetContract(),
identityVerificationCallback::onVerificationFlowResult
),
from.requireContext(),
configuration
)
@InjectorKey
private val injectorKey: String =
WeakMapInjectorRegistry.nextKey(requireNotNull(StripeIdentityVerificationSheet::class.simpleName))
init {
WeakMapInjectorRegistry.register(this, injectorKey)
}
private val identityVerificationSheetComponent: IdentityVerificationSheetComponent =
DaggerIdentityVerificationSheetComponent.builder()
.context(context)
.build()
override fun present(
verificationSessionId: String,
ephemeralKeySecret: String
) {
activityResultLauncher.launch(
IdentityVerificationSheetContract.Args(
verificationSessionId,
ephemeralKeySecret,
configuration.brandLogo,
injectorKey,
System.currentTimeMillis()
)
)
}
override fun inject(injectable: Injectable<*>) {
when (injectable) {
is IdentityActivity -> {
identityVerificationSheetComponent.inject(injectable)
}
else -> {
throw IllegalArgumentException("invalid Injectable $injectable requested in $this")
}
}
}
}
| identity/src/main/java/com/stripe/android/identity/StripeIdentityVerificationSheet.kt | 486601846 |
package com.stripe.android.model
import com.google.common.truth.Truth.assertThat
import kotlin.test.Test
class TokenizationMethodTest {
@Test
fun `android_pay should map to GooglePay`() {
assertThat(
TokenizationMethod.fromCode("android_pay")
).isEqualTo(TokenizationMethod.GooglePay)
}
@Test
fun `google should map to GooglePay`() {
assertThat(
TokenizationMethod.fromCode("google")
).isEqualTo(TokenizationMethod.GooglePay)
}
@Test
fun `apple_pay should map to ApplePay`() {
assertThat(
TokenizationMethod.fromCode("apple_pay")
).isEqualTo(TokenizationMethod.ApplePay)
}
}
| payments-core/src/test/java/com/stripe/android/model/TokenizationMethodTest.kt | 2588839800 |
package com.stripe.android.payments.bankaccount.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountContract
import com.stripe.android.payments.bankaccount.ui.CollectBankAccountViewEffect.FinishWithResult
import com.stripe.android.payments.bankaccount.ui.CollectBankAccountViewEffect.OpenConnectionsFlow
import com.stripe.android.payments.financialconnections.FinancialConnectionsPaymentsProxy
/**
* No-UI activity that will handle collect bank account logic.
*/
internal class CollectBankAccountActivity : AppCompatActivity() {
private val starterArgs: CollectBankAccountContract.Args? by lazy {
CollectBankAccountContract.Args.fromIntent(intent)
}
private lateinit var financialConnectionsPaymentsProxy: FinancialConnectionsPaymentsProxy
private val viewModel: CollectBankAccountViewModel by viewModels {
CollectBankAccountViewModel.Factory {
requireNotNull(starterArgs)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initConnectionsPaymentsProxy()
lifecycleScope.launchWhenStarted {
viewModel.viewEffect.collect { viewEffect ->
when (viewEffect) {
is OpenConnectionsFlow -> viewEffect.launch()
is FinishWithResult -> viewEffect.launch()
}
}
}
}
private fun initConnectionsPaymentsProxy() {
financialConnectionsPaymentsProxy = FinancialConnectionsPaymentsProxy.create(
activity = this,
onComplete = viewModel::onConnectionsResult
)
}
private fun OpenConnectionsFlow.launch() {
financialConnectionsPaymentsProxy.present(
financialConnectionsSessionClientSecret = financialConnectionsSessionSecret,
publishableKey = publishableKey,
stripeAccountId = stripeAccountId
)
}
private fun FinishWithResult.launch() {
setResult(
Activity.RESULT_OK,
Intent().putExtras(
CollectBankAccountContract.Result(result).toBundle()
)
)
finish()
}
}
| payments-core/src/main/java/com/stripe/android/payments/bankaccount/ui/CollectBankAccountActivity.kt | 3648322468 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.privacysandbox.tools.core.generator
import androidx.privacysandbox.tools.core.model.AnnotatedInterface
import androidx.privacysandbox.tools.core.model.AnnotatedValue
import androidx.privacysandbox.tools.core.model.ParsedApi
import androidx.privacysandbox.tools.core.model.Type
import androidx.privacysandbox.tools.core.model.Types
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ClientBinderCodeConverterTest {
private val converter = ClientBinderCodeConverter(
ParsedApi(
services = setOf(
AnnotatedInterface(
type = Type(packageName = "com.mysdk", simpleName = "MySdk"),
)
),
values = setOf(
AnnotatedValue(
type = Type(packageName = "com.mysdk", simpleName = "Value"),
properties = listOf()
)
),
callbacks = setOf(
AnnotatedInterface(
type = Type(packageName = "com.mysdk", simpleName = "Callback"),
)
),
)
)
@Test
fun convertToModelCode_primitive() {
assertThat(
converter.convertToModelCode(
Types.int, expression = "5"
).toString()
).isEqualTo("5")
}
@Test
fun convertToModelCode_value() {
assertThat(
converter.convertToModelCode(
Type(packageName = "com.mysdk", simpleName = "Value"), expression = "value"
).toString()
).isEqualTo("com.mysdk.ValueConverter.fromParcelable(value)")
}
@Test
fun convertToModelCode_callback() {
assertThat(
converter.convertToModelCode(
Type(packageName = "com.mysdk", simpleName = "Callback"), expression = "callback"
).toString()
).isEqualTo("com.mysdk.CallbackClientProxy(callback)")
}
} | privacysandbox/tools/tools-core/src/test/java/androidx/privacysandbox/tools/core/generator/ClientBinderCodeConverterTest.kt | 3003140819 |
package expo.modules.battery
import android.content.Context
import expo.modules.core.BasePackage
import expo.modules.core.ExportedModule
class BatteryPackage : BasePackage() {
override fun createExportedModules(context: Context): List<ExportedModule> {
return listOf(BatteryModule(context))
}
}
| packages/expo-battery/android/src/main/java/expo/modules/battery/BatteryPackage.kt | 2027890397 |
package au.com.codeka.warworlds.server
import au.com.codeka.warworlds.common.Log
import org.joda.time.DateTime
import java.io.File
import java.io.PrintWriter
import java.nio.file.Files
/**
* This class works with the Log class to provide a concrete implementation we can use in the
* server.
*/
object LogImpl {
private lateinit var config: Configuration.LoggingConfig
fun setup(config: Configuration.LoggingConfig) {
LogImpl.config = config
Log.setImpl(LogImplImpl())
}
val levelMap = arrayOf("ERROR", "WARNING", "INFO", "DEBUG")
private class LogImplImpl : Log.LogImpl {
private var lastOpenTime: DateTime? = null
private var file: File? = null
private var writer: PrintWriter? = null
private val maxLevel: Int = levelMap.indexOf(config.maxLevel)
override fun isLoggable(tag: String, level: Int): Boolean {
return level <= maxLevel
}
override fun write(tag: String, level: Int, msg: String) {
if (level > maxLevel) {
return
}
val sb = StringBuilder()
LogFormatter.DATE_TIME_FORMATTER.printTo(sb, DateTime.now())
sb.append(" ")
sb.append(levelMap[level])
sb.append(" ")
sb.append(tag)
sb.append(": ")
sb.append(msg)
// First write to the console.
val str = sb.toString()
println(str)
// Then to the log file.
synchronized(LogImpl) {
ensureOpen()
with(writer!!) {
println(str)
flush()
}
}
}
private fun ensureOpen() {
if (isFileTooOld()) {
close()
}
if (file == null) {
open()
}
}
private fun open() {
if (file == null) {
file = File(config.fileName + ".log")
}
val f = file ?: return
if (f.exists()) {
backup()
}
f.parentFile.mkdirs()
writer = PrintWriter(f, Charsets.UTF_8)
}
private fun close() {
val w = writer ?: return
w.close()
writer = null
}
private fun backup() {
val date = lastOpenTime ?: DateTime.now()
val f = file ?: return
var n = 1
var backupFile: File
do {
backupFile = File(
String.format(
config.fileName + "-%04d-%02d-%02d-%04d.log",
date.year, date.monthOfYear, date.dayOfMonth, n))
n++
} while (backupFile.exists())
Files.move(f.toPath(), backupFile.toPath())
cleanup()
}
private fun isFileTooOld(): Boolean {
val time = lastOpenTime ?: return false
val now = DateTime.now()
// It's a different day, it's too old.
return !now.toDate().equals(time.toDate())
}
/** When have too many log files, delete some of the older ones. */
private fun cleanup() {
val f = file ?: return
val existingFiles = ArrayList<File>()
for (existing in f.parentFile.listFiles() ?: arrayOf()) {
if (existing.isFile && existing.extension == "log") {
existingFiles.add(existing)
}
}
// Sort them from newest to oldest
existingFiles.sortBy { file -> file.lastModified() }
// Once we get above the limit for cumulative file size, start deleting.
var totalSize = 0L
for (existingFile in existingFiles) {
totalSize += existingFile.length()
if (totalSize > 10L * 1024L * 1024L) {
existingFile.delete()
}
}
}
}
}
| server/src/main/kotlin/au/com/codeka/warworlds/server/LogImpl.kt | 61140766 |
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.basicpermissions.util
import android.support.design.widget.Snackbar
import android.view.View
fun View.showSnackbar(msgId: Int, length: Int) {
showSnackbar(context.getString(msgId), length)
}
fun View.showSnackbar(msg: String, length: Int) {
showSnackbar(msg, length, null, {})
}
fun View.showSnackbar(
msgId: Int,
length: Int,
actionMessageId: Int,
action: (View) -> Unit
) {
showSnackbar(context.getString(msgId), length, context.getString(actionMessageId), action)
}
fun View.showSnackbar(
msg: String,
length: Int,
actionMessage: CharSequence?,
action: (View) -> Unit
) {
val snackbar = Snackbar.make(this, msg, length)
if (actionMessage != null) {
snackbar.setAction(actionMessage) {
action(this)
}.show()
}
}
| kotlinApp/Application/src/main/java/com/example/android/basicpermissions/util/ViewExt.kt | 2106876118 |
package com.teamwizardry.librarianlib.mosaic
import net.minecraft.client.render.RenderLayer
import net.minecraft.util.Identifier
import java.awt.image.BufferedImage
/**
* This class represents a section of a [Mosaic]
*/
public class MosaicSprite internal constructor(private val mosaic: Mosaic, public val name: String) : Sprite {
private lateinit var definition: SpriteDefinition
override val texture: Identifier
get() = mosaic.location
override var width: Int = 0
private set
override var height: Int = 0
private set
override var uSize: Float = 0f
private set
override var vSize: Float = 0f
private set
override var pinLeft: Boolean = true
private set
override var pinTop: Boolean = true
private set
override var pinRight: Boolean = true
private set
override var pinBottom: Boolean = true
private set
override var minUCap: Float = 0f
private set
override var minVCap: Float = 0f
private set
override var maxUCap: Float = 0f
private set
override var maxVCap: Float = 0f
private set
override var frameCount: Int = 1
private set
public var images: List<BufferedImage> = emptyList()
private set
init {
loadDefinition()
}
internal fun loadDefinition() {
definition = mosaic.getSpriteDefinition(name)
pinLeft = definition.minUPin
pinTop = definition.minVPin
pinRight = definition.maxUPin
pinBottom = definition.maxVPin
minUCap = definition.minUCap / definition.size.xf
minVCap = definition.minVCap / definition.size.yf
maxUCap = definition.maxUCap / definition.size.xf
maxVCap = definition.maxVCap / definition.size.yf
frameCount = definition.frameUVs.size
width = mosaic.logicalU(definition.size.x)
height = mosaic.logicalV(definition.size.y)
uSize = definition.texU(definition.size.x)
vSize = definition.texV(definition.size.y)
images = definition.frameImages
}
/**
* The minimum U coordinate (0-1)
*/
override fun minU(animFrames: Int): Float {
return definition.texU(definition.frameUVs[animFrames % frameCount].x)
}
/**
* The minimum V coordinate (0-1)
*/
override fun minV(animFrames: Int): Float {
return definition.texV(definition.frameUVs[animFrames % frameCount].y)
}
/**
* The maximum U coordinate (0-1)
*/
override fun maxU(animFrames: Int): Float {
return definition.texU(definition.frameUVs[animFrames % frameCount].x + definition.size.x)
}
/**
* The maximum V coordinate (0-1)
*/
override fun maxV(animFrames: Int): Float {
return definition.texV(definition.frameUVs[animFrames % frameCount].y + definition.size.y)
}
override fun toString(): String {
return "Sprite(texture=${mosaic.location}, name=$name)"
}
}
| modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/MosaicSprite.kt | 1270618510 |
package me.tomassetti.sandy.ast
import me.tomassetti.sandy.parsing.SandyAntlrParserFacade
import java.util.*
import kotlin.test.assertEquals
import org.junit.Test as test
class ModelTest {
@test fun transformVarName() {
val startTree = SandyFile(listOf(
VarDeclaration("A", IntLit("10")),
Assignment("A", IntLit("11")),
Print(VarReference("A"))))
val expectedTransformedTree = SandyFile(listOf(
VarDeclaration("B", IntLit("10")),
Assignment("B", IntLit("11")),
Print(VarReference("B"))))
assertEquals(expectedTransformedTree, startTree.transform {
when (it) {
is VarDeclaration -> VarDeclaration("B", it.value)
is VarReference -> VarReference("B")
is Assignment -> Assignment("B", it.value)
else -> it
}
})
}
fun toAst(code: String) : SandyFile = SandyAntlrParserFacade.parse(code).root!!.toAst()
@test fun processAllVarDeclarations() {
val ast = toAst("""var a = 1
|a = 2 * 5
|var b = a
|print(b)
|var c = b * b""".trimMargin("|"))
val varDeclarations = LinkedList<String>()
ast.specificProcess(VarDeclaration::class.java, { varDeclarations.add(it.varName) })
assertEquals(listOf("a", "b", "c"), varDeclarations)
}
}
| src/test/kotlin/me/tomassetti/sandy/ast/ModelTest.kt | 183587645 |
package com.habitrpg.android.habitica.models.tasks
enum class Frequency constructor(val value: String) {
WEEKLY("weekly"),
DAILY("daily"),
MONTHLY("monthly"),
YEARLY("yearly");
companion object {
fun from(type: String?): Frequency? = values().find { it.value == type }
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/models/tasks/Frequency.kt | 3444164016 |
@file:JvmName("Sdk23LayoutsKt")
package org.jetbrains.anko
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout
import android.appwidget.AppWidgetHostView
import android.view.View
import android.webkit.WebView
import android.widget.AbsoluteLayout
import android.widget.ActionMenuView
import android.widget.Gallery
import android.widget.GridLayout
import android.widget.GridView
import android.widget.AbsListView
import android.widget.HorizontalScrollView
import android.widget.ImageSwitcher
import android.widget.LinearLayout
import android.widget.RadioGroup
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextSwitcher
import android.widget.Toolbar
import android.app.ActionBar
import android.widget.ViewAnimator
import android.widget.ViewSwitcher
open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _WebView(ctx: Context): WebView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = ViewGroup.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = ViewGroup.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) {
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
x: Int,
y: Int,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
x: Int,
y: Int
): T {
val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = AbsoluteLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ViewGroup.LayoutParams?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ViewGroup.LayoutParams?
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ActionMenuView.LayoutParams?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ActionMenuView.LayoutParams?
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = ActionMenuView.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
}
open class _FrameLayout(ctx: Context): FrameLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _Gallery(ctx: Context): Gallery(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = Gallery.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = Gallery.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = Gallery.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _GridLayout(ctx: Context): GridLayout(ctx) {
inline fun <T: View> T.lparams(
rowSpec: GridLayout.Spec?,
columnSpec: GridLayout.Spec?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
rowSpec: GridLayout.Spec?,
columnSpec: GridLayout.Spec?
): T {
val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = GridLayout.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.LayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.LayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.MarginLayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: GridLayout.LayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: GridLayout.LayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
context: Context?,
attrs: AttributeSet?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(context!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
context: Context?,
attrs: AttributeSet?
): T {
val layoutParams = GridLayout.LayoutParams(context!!, attrs!!)
[email protected] = layoutParams
return this
}
}
open class _GridView(ctx: Context): GridView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = AbsListView.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = AbsListView.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
viewType: Int,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(width, height, viewType)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
viewType: Int
): T {
val layoutParams = AbsListView.LayoutParams(width, height, viewType)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = AbsListView.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _LinearLayout(ctx: Context): LinearLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = LinearLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
weight: Float,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(width, height, weight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
weight: Float
): T {
val layoutParams = LinearLayout.LayoutParams(width, height, weight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: LinearLayout.LayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: LinearLayout.LayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _RadioGroup(ctx: Context): RadioGroup(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = RadioGroup.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = RadioGroup.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = RadioGroup.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = RadioGroup.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = RelativeLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: RelativeLayout.LayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: RelativeLayout.LayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ScrollView(ctx: Context): ScrollView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TableLayout(ctx: Context): TableLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = TableLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = TableLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = TableLayout.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = TableLayout.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = TableLayout.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = TableLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TableRow(ctx: Context): TableRow(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = TableRow.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = TableRow.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = TableRow.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = TableRow.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
column: Int,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(column)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
column: Int
): T {
val layoutParams = TableRow.LayoutParams(column)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = TableRow.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = TableRow.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _Toolbar(ctx: Context): Toolbar(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = Toolbar.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = Toolbar.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = Toolbar.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
gravity: Int,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
gravity: Int
): T {
val layoutParams = Toolbar.LayoutParams(gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: Toolbar.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: Toolbar.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ActionBar.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ActionBar.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
| anko/library/generated/sdk23/src/Layouts.kt | 3888262796 |
package org.jtalks.pochta.smtp
import org.subethamail.smtp.auth.EasyAuthenticationHandlerFactory
import org.subethamail.smtp.auth.UsernamePasswordValidator
import org.jtalks.pochta.config.Config
import org.subethamail.smtp.auth.LoginFailedException
import org.jtalks.pochta.util.Context
/**
*
*/
class AuthenticatorFactory(config: Config.Mailboxes) : EasyAuthenticationHandlerFactory(
object: UsernamePasswordValidator {
override fun login(username: String?, password: String?) {
Context.remove(Context.PASSWORD)
config.filter {(mbox) -> mbox.login.equals(username) && mbox.password.equals(password) }
.forEach {(mbox) -> Context.put(Context.PASSWORD, mbox.password); }
if (!Context.contains(Context.PASSWORD)) throw LoginFailedException()
}
}
) | src/main/kotlin/org/jtalks/pochta/smtp/AuthenticatorFactory.kt | 3042553426 |
package com.devbrackets.android.exomedia.core.renderer.provider
import com.devbrackets.android.exomedia.core.renderer.RendererType
import androidx.media3.exoplayer.Renderer
/**
* Provides the capabilities for building renderers
*/
interface RenderProvider {
/**
* The [RendererType] that this provider builds
*/
fun type(): RendererType
/**
* the list of pre-defined classes to that the provider supports
*/
fun rendererClasses(): List<String>
/**
* Retrieves the latest built renderers
*/
fun getLatestRenderers(): List<Renderer>
} | library/src/main/kotlin/com/devbrackets/android/exomedia/core/renderer/provider/RenderProvider.kt | 3309785571 |
/*
* 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 androidx.compose.ui.graphics
import org.jetbrains.skia.Matrix33
internal fun identityMatrix33() = Matrix33(
1f, 0f, 0f,
0f, 1f, 0f,
0f, 0f, 1f
) | compose/ui/ui-graphics/src/skikoMain/kotlin/androidx/compose/ui/graphics/Matrices.skiko.kt | 2854520729 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.util
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.concurrency.AppExecutorUtil
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
/**
* This is just a wrapper around [AppExecutorUtil.createBoundedApplicationPoolExecutor]
* with improved exception logging behavior.
*/
class ExecutorWithExceptionLogging(name: String, maxThreads: Int) {
private val backend = AppExecutorUtil.createBoundedScheduledExecutorService(name, maxThreads)
fun execute(task: () -> Unit) {
backend.execute(addLogging(task))
}
fun <T> submit(task: () -> T): Future<T> {
return backend.submit<T>(addLogging(task))
}
fun scheduleWithFixedDelay(task: () -> Unit, initialDelay: Long, delay: Long, unit: TimeUnit) {
backend.scheduleWithFixedDelay(addLogging(task), initialDelay, delay, unit)
}
fun shutdownNow(): List<Runnable> {
return backend.shutdownNow()
}
private fun <T> addLogging(task: () -> T): () -> T {
return { doWithLogging(task) }
}
private fun <T> doWithLogging(task: () -> T): T {
try {
return task()
}
catch (e: Throwable) {
if (e !is ControlFlowException) {
// Log the exception, because ScheduledExecutorService will silently suppresses it!
Logger.getInstance(ExecutorWithExceptionLogging::class.java).error(e)
}
throw e
}
}
}
| src/main/java/com/google/idea/perf/util/ExecutorWithExceptionLogging.kt | 1853759209 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.egl.templates
import org.lwjgl.generator.*
import org.lwjgl.egl.*
val KHR_swap_buffers_with_damage = "KHRSwapBuffersWithDamage".nativeClassEGL("KHR_swap_buffers_with_damage", postfix = KHR) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension provides a means to issue a swap buffers request to display the contents of the current back buffer and also specify a list of damage
rectangles that can be passed to a system compositor so it can minimize how much it has to recompose.
This should be used in situations where an application is only animating a small portion of a surface since it enables the compositor to avoid wasting
time recomposing parts of the surface that haven't changed.
Requires ${EGL14.core}.
"""
EGLBoolean(
"SwapBuffersWithDamageKHR",
"",
EGLDisplay.IN("dpy", ""),
EGLSurface.IN("surface", ""),
nullable..EGLint_p.OUT("rects", ""),
AutoSize("rects")..EGLint.IN("n_rects", "")
)
} | modules/templates/src/main/kotlin/org/lwjgl/egl/templates/KHR_swap_buffers_with_damage.kt | 1080899622 |
package app
import com.github.theholywaffle.teamspeak3.api.event.ClientJoinEvent
/**
* Created by jacob on 2017-06-09 (YYYY-MM-DD).
*/
interface ISender {
val uniqueId: String
}
interface ICommand {
val sender: ISender
val prefix: String
val suffix: String
}
interface IMessage {
val sender: ISender
val message: String
}
interface IClientJoined {
val clientId: Int
val channelId: Int
}
interface IMoved {
val channelIdMovedTo: Int
val clientId: Int
}
interface IClient { //This might be missing relations to channel
val id: Int // The clients current instance id.
val uniqueId: String
val databaseId: Int
val nickName: String
val channelGroupId: Int
// val type: //The framework value is Int, which doesn't make any sense.
val isInputMuted: Boolean
val isOutputMuted: Boolean
val isOutputOnlyMuted: Boolean
val isUsingHardwareInput: Boolean
val isUsingHardwareOutput: Boolean
val isRecording: Boolean
val isTalking: Boolean
val isPrioritySpeaker: Boolean
val isChannelCommander: Boolean
val isAway: Boolean
val awayMessage: String
val amountOfServerGroups: Int
val ServerGroups: MutableCollection<IServerGroup>
val avatarId: String
val talkPower: Int
val country: String
}
interface IServerGroup {
}
enum class ClientType {
query,
user
}
class InheritedClient(event: ClientJoinEvent): IClient {
override val uniqueId: String = event.uniqueClientIdentifier
override val databaseId: Int = event.clientDatabaseId
override val id: Int = event.clientId
override val nickName: String = event.clientNickname
override val channelGroupId: Int = event.clientChannelGroupId
// val type: //The framework value is Int, which doesn't make any sense.
override val isInputMuted: Boolean = event.isClientInputMuted
override val isOutputMuted: Boolean = event.isClientOutputMuted
override val isOutputOnlyMuted: Boolean = event.isClientOutputOnlyMuted
override val isUsingHardwareInput: Boolean = event.isClientUsingHardwareInput
override val isUsingHardwareOutput: Boolean = event.isClientUsingHardwareOutput
override val isRecording: Boolean = event.isClientRecording
override val isTalking: Boolean = event.isClientTalking
override val isPrioritySpeaker: Boolean = event.isClientPrioritySpeaker
override val isChannelCommander: Boolean = event.isClientChannelCommander
override val isAway: Boolean = event.isClientAway
override val awayMessage: String = event.clientAwayMessage
override val amountOfServerGroups: Int = event.amountOfServerGroups
override val ServerGroups: MutableCollection<IServerGroup> = arrayListOf() //TODO: Define and add Servergroups
override val avatarId: String = event.clientFlagAvatarId
override val talkPower: Int = event.clientTalkPower
override val country: String = event.clientCountry
}
| src/main/kotlin/app/Events.kt | 1887843930 |
package io.github.config4k
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class TestToConfigForCollection : WordSpec({
"List<Person>.toConfig" should {
"return Config having list of Person" {
val list = listOf(Person("foo", 20), Person("bar", 25))
list.toConfig("list")
.extract<List<Person>>("list") shouldBe list
}
}
"Map<String, Person>.toConfig" should {
"return Config having Map<String, Person>" {
val map = mapOf(
"foo" to Person("foo", 20),
"bar" to Person("bar", 25),
"@foobar" to Person("bar", 30)
)
map.toConfig("map")
.extract<Map<String, Person>>("map") shouldBe map
}
}
"Map<Int, Person>.toConfig" should {
"return Config having Map<Int, Person>" {
val map = mapOf(
7 to Person("Jon", 12),
20 to Person("Doe", 15)
)
map.toConfig("map")
.extract<Map<Int, Person>>("map") shouldBe map
}
}
})
| src/test/kotlin/io/github/config4k/TestToConfigForCollection.kt | 1252682428 |
import org.apache.commons.lang3.RandomStringUtils
import org.junit.Before
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.security.SecureRandom
import java.util.concurrent.ThreadLocalRandom
import kotlin.experimental.and
import kotlin.streams.asSequence
import kotlin.test.assertEquals
const val STRING_LENGTH = 10
const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+"
class RandomStringUnitTest {
private val charPool : List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
@Test
fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() {
var randomString = ThreadLocalRandom.current()
.ints(STRING_LENGTH.toLong(), 0, charPool.size)
.asSequence()
.map(charPool::get)
.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingKotlin_thenReturnAlphanumericString() {
var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString() {
var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH)
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
@Test
fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() {
val random = SecureRandom()
val bytes = ByteArray(STRING_LENGTH)
random.nextBytes(bytes)
var randomString = (0..bytes.size - 1).map { i ->
charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt())
}.joinToString("")
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
assertEquals(STRING_LENGTH, randomString.length)
}
} | projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt | 2231433047 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.service.job
import android.support.annotation.CheckResult
import com.evernote.android.job.util.support.PersistableBundleCompat
import com.pyamsoft.powermanager.base.preference.AirplanePreferences
import com.pyamsoft.powermanager.base.preference.BluetoothPreferences
import com.pyamsoft.powermanager.base.preference.DataPreferences
import com.pyamsoft.powermanager.base.preference.DataSaverPreferences
import com.pyamsoft.powermanager.base.preference.DozePreferences
import com.pyamsoft.powermanager.base.preference.PhonePreferences
import com.pyamsoft.powermanager.base.preference.SyncPreferences
import com.pyamsoft.powermanager.base.preference.WifiPreferences
import com.pyamsoft.powermanager.job.JobQueuer
import com.pyamsoft.powermanager.job.JobRunner
import com.pyamsoft.powermanager.model.StateModifier
import com.pyamsoft.powermanager.model.StateObserver
import io.reactivex.Completable
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.SECONDS
internal abstract class ManageJobRunner(private val jobQueuer: JobQueuer,
private val chargingObserver: StateObserver, private val wearableObserver: StateObserver,
private val wifiModifier: StateModifier, private val dataModifier: StateModifier,
private val bluetoothModifier: StateModifier, private val syncModifier: StateModifier,
private val dozeModifier: StateModifier, private val airplaneModifier: StateModifier,
private val dataSaverModifier: StateModifier, private val wifiPreferences: WifiPreferences,
private val dataPreferences: DataPreferences,
private val bluetoothPreferences: BluetoothPreferences,
private val syncPreferences: SyncPreferences,
private val airplanePreferences: AirplanePreferences,
private val dozePreferences: DozePreferences,
private val dataSaverPreferences: DataSaverPreferences,
private val phonePreferences: PhonePreferences, private val phoneObserver: StateObserver,
private val subScheduler: Scheduler) : JobRunner {
private val composite = CompositeDisposable()
private val wifiConditions = object : ManageConditions {
override val tag: String
get() = "Wifi"
override val ignoreCharging: Boolean
get() = wifiPreferences.ignoreChargingWifi
override val ignoreWearable: Boolean
get() = wifiPreferences.ignoreWearWifi
override val managed: Boolean
get() = wifiPreferences.wifiManaged
override val original: Boolean
get() = wifiPreferences.originalWifi
override val periodic: Boolean
get() = wifiPreferences.periodicWifi
}
private val dozeConditions = object : ManageConditions {
override val tag: String
get() = "Doze Mode"
override val ignoreCharging: Boolean
get() = dozePreferences.ignoreChargingDoze
override val ignoreWearable: Boolean
get() = dozePreferences.ignoreWearDoze
override val managed: Boolean
get() = dozePreferences.dozeManaged
override val original: Boolean
get() = dozePreferences.originalDoze
override val periodic: Boolean
get() = dozePreferences.periodicDoze
}
private val airplaneConditions = object : ManageConditions {
override val tag: String
get() = "Airplane Mode"
override val managed: Boolean
get() = airplanePreferences.airplaneManaged
override val ignoreCharging: Boolean
get() = airplanePreferences.ignoreChargingAirplane
override val ignoreWearable: Boolean
get() = airplanePreferences.ignoreWearAirplane
override val original: Boolean
get() = airplanePreferences.originalAirplane
override val periodic: Boolean
get() = airplanePreferences.periodicAirplane
}
private val dataConditions = object : ManageConditions {
override val tag: String
get() = "Data"
override val ignoreCharging: Boolean
get() = dataPreferences.ignoreChargingData
override val ignoreWearable: Boolean
get() = dataPreferences.ignoreWearData
override val managed: Boolean
get() = dataPreferences.dataManaged
override val original: Boolean
get() = dataPreferences.originalData
override val periodic: Boolean
get() = dataPreferences.periodicData
}
private val bluetoothConditions = object : ManageConditions {
override val tag: String
get() = "Bluetooth"
override val ignoreCharging: Boolean
get() = bluetoothPreferences.ignoreChargingBluetooth
override val ignoreWearable: Boolean
get() = bluetoothPreferences.ignoreWearBluetooth
override val managed: Boolean
get() = bluetoothPreferences.bluetoothManaged
override val original: Boolean
get() = bluetoothPreferences.originalBluetooth
override val periodic: Boolean
get() = bluetoothPreferences.periodicBluetooth
}
private val syncConditions = object : ManageConditions {
override val tag: String
get() = "Sync"
override val ignoreCharging: Boolean
get() = syncPreferences.ignoreChargingSync
override val ignoreWearable: Boolean
get() = syncPreferences.ignoreWearSync
override val managed: Boolean
get() = syncPreferences.syncManaged
override val original: Boolean
get() = syncPreferences.originalSync
override val periodic: Boolean
get() = syncPreferences.periodicSync
}
private val dataSaverConditions = object : ManageConditions {
override val tag: String
get() = "Data Saver"
override val ignoreCharging: Boolean
get() = dataSaverPreferences.ignoreChargingDataSaver
override val ignoreWearable: Boolean
get() = dataSaverPreferences.ignoreWearDataSaver
override val managed: Boolean
get() = dataSaverPreferences.dataSaverManaged
override val original: Boolean
get() = dataSaverPreferences.originalDataSaver
override val periodic: Boolean
get() = dataSaverPreferences.periodicDataSaver
}
@CheckResult private fun runJob(tag: String, screenOn: Boolean, firstRun: Boolean): Boolean {
checkTag(tag)
if (screenOn) {
return runEnableJob(tag, firstRun)
} else {
return runDisableJob(tag, firstRun)
}
}
private fun checkTag(tag: String) {
if (tag != JobQueuer.ENABLE_TAG && tag == JobQueuer.ENABLE_TAG) {
throw IllegalArgumentException("Illegal tag for JobRunner: " + tag)
}
}
@CheckResult private fun runEnableJob(tag: String, firstRun: Boolean): Boolean {
var didSomething = false
val latch = CountDownLatch(6)
didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = dozeModifier, conditions = dozeConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = airplaneModifier, conditions = airplaneConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = dataSaverModifier, conditions = dataSaverConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = wifiModifier, conditions = wifiConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = dataModifier, conditions = dataConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = bluetoothModifier, conditions = bluetoothConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false,
modifier = syncModifier, conditions = syncConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
await(latch)
return isJobRepeatRequired(didSomething)
}
private fun enable(firstRun: Boolean, latch: CountDownLatch, isCharging: Boolean,
isWearableConnected: Boolean, modifier: StateModifier,
conditions: ManageConditions): Boolean {
if (isCharging && conditions.ignoreCharging) {
Timber.w("Do not disable %s while device is charging", conditions.tag)
latch.countDown()
return false
} else if (isWearableConnected && conditions.ignoreWearable) {
Timber.w("Do not disable %s while wearable is connected", conditions.tag)
latch.countDown()
return false
} else if (conditions.managed && conditions.original && (firstRun || conditions.periodic)) {
composite.add(Completable.fromAction {
modifier.set()
}.subscribeOn(subScheduler).observeOn(subScheduler).doAfterTerminate {
latch.countDown()
}.subscribe({
Timber.d("ENABLE: %s", conditions.tag)
}, { Timber.e(it, "Error enabling %s", conditions.tag) }))
return true
} else {
Timber.w("Not managed: %s", conditions.tag)
latch.countDown()
return false
}
}
private fun disable(firstRun: Boolean, latch: CountDownLatch, isCharging: Boolean,
isWearableConnected: Boolean, modifier: StateModifier,
conditions: ManageConditions): Boolean {
if (isCharging && conditions.ignoreCharging) {
Timber.w("Do not disable %s while device is charging", conditions.tag)
latch.countDown()
return false
} else if (isWearableConnected && conditions.ignoreWearable) {
Timber.w("Do not disable %s while wearable is connected", conditions.tag)
latch.countDown()
return false
} else if (conditions.managed && conditions.original && (firstRun || conditions.periodic)) {
composite.add(Completable.fromAction {
modifier.unset()
}.subscribeOn(subScheduler).observeOn(subScheduler).doAfterTerminate {
latch.countDown()
}.subscribe({
Timber.d("DISABLE: %s", conditions.tag)
}, { Timber.e(it, "Error disabling %s", conditions.tag) }))
return true
} else {
Timber.w("Not managed: %s", conditions.tag)
latch.countDown()
return false
}
}
@CheckResult private fun runDisableJob(tag: String, firstRun: Boolean): Boolean {
if (phonePreferences.isIgnoreDuringPhoneCall()) {
if (!phoneObserver.unknown()) {
if (phoneObserver.enabled()) {
Timber.w("Do not manage, device is in a phone call.")
return false
}
}
}
var didSomething = false
val isCharging = chargingObserver.enabled()
val isWearableConnected = wearableObserver.enabled()
val latch = CountDownLatch(6)
didSomething = disable(firstRun, latch, isCharging, isWearableConnected,
modifier = wifiModifier, conditions = wifiConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = disable(firstRun, latch, isCharging, isWearableConnected,
modifier = dataModifier, conditions = dataConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = disable(firstRun, latch, isCharging, isWearableConnected,
modifier = bluetoothModifier, conditions = bluetoothConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = disable(firstRun, latch, isCharging, isWearableConnected,
modifier = syncModifier, conditions = syncConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging, isWearableConnected,
modifier = airplaneModifier, conditions = airplaneConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging, isWearableConnected, modifier = dozeModifier,
conditions = dozeConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
didSomething = enable(firstRun, latch, isCharging, isWearableConnected,
modifier = dataSaverModifier, conditions = dataSaverConditions) || didSomething
if (isStopped) {
Timber.w("%s: Stopped early", tag)
return false
}
await(latch)
return isJobRepeatRequired(didSomething)
}
private fun await(latch: CountDownLatch) {
Timber.d("Wait for Latch... (30 seconds)")
try {
latch.await(30L, SECONDS)
} catch (e: InterruptedException) {
Timber.e(e, "Timer was interrupted")
}
Timber.d("Job complete, clear composite")
composite.clear()
}
@CheckResult private fun isJobRepeatRequired(didSomething: Boolean): Boolean {
val repeatWifi = wifiPreferences.wifiManaged && wifiPreferences.periodicWifi
val repeatData = dataPreferences.dataManaged && dataPreferences.periodicData
val repeatBluetooth = bluetoothPreferences.bluetoothManaged && bluetoothPreferences.periodicBluetooth
val repeatSync = syncPreferences.syncManaged && syncPreferences.periodicSync
val repeatAirplane = airplanePreferences.airplaneManaged && airplanePreferences.periodicAirplane
val repeatDoze = dozePreferences.dozeManaged && dozePreferences.periodicDoze
val repeatDataSaver = dataSaverPreferences.dataSaverManaged && dataSaverPreferences.periodicDataSaver
return didSomething && (repeatWifi || repeatData || repeatBluetooth || repeatSync || repeatAirplane || repeatDoze || repeatDataSaver)
}
private fun repeatIfRequired(tag: String, screenOn: Boolean, windowOnTime: Long,
windowOffTime: Long) {
val newDelayTime: Long
// Switch them
if (screenOn) {
newDelayTime = windowOnTime
} else {
newDelayTime = windowOffTime
}
val newTag: String
if (tag == JobQueuer.DISABLE_TAG) {
newTag = JobQueuer.ENABLE_TAG
} else {
newTag = JobQueuer.DISABLE_TAG
}
val entry = ManageJobQueuerEntry(tag = newTag,
firstRun = false, oneShot = false, screenOn = !screenOn, delay = newDelayTime,
repeatingOffWindow = windowOffTime, repeatingOnWindow = windowOnTime)
jobQueuer.queue(entry)
}
/**
* Runs the Job. Called either by managed jobs or directly by the JobQueuer
*/
override fun run(tag: String, extras: PersistableBundleCompat) {
val screenOn = extras.getBoolean(
ManageJobQueuerEntry.KEY_SCREEN, true)
val windowOnTime = extras.getLong(
ManageJobQueuerEntry.KEY_ON_WINDOW, 0)
val windowOffTime = extras.getLong(
ManageJobQueuerEntry.KEY_OFF_WINDOW, 0)
val oneshot = extras.getBoolean(
ManageJobQueuerEntry.KEY_ONESHOT, false)
val firstRun = extras.getBoolean(
ManageJobQueuerEntry.KEY_FIRST_RUN, false)
if (runJob(tag, screenOn, firstRun) && !oneshot) {
repeatIfRequired(tag, screenOn, windowOnTime, windowOffTime)
}
}
/**
* Override in the actual ManagedJobs to call Job.isCancelled();
* If it is not a managed job it never isStopped, always run to completion
*/
@get:CheckResult internal abstract val isStopped: Boolean
private interface ManageConditions {
val tag: String
@get:CheckResult get
val ignoreCharging: Boolean
@get:CheckResult get
val ignoreWearable: Boolean
@get:CheckResult get
val managed: Boolean
@get:CheckResult get
val original: Boolean
@get:CheckResult get
val periodic: Boolean
@get:CheckResult get
}
}
| powermanager-service/src/main/java/com/pyamsoft/powermanager/service/job/ManageJobRunner.kt | 2373250549 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class NoEdt
| src/test/kotlin/framework/NoEdt.kt | 1840202486 |
/*
* Copyright (c) 2016 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.timeline.meta
import android.content.Intent
import android.os.Bundle
import android.provider.BaseColumns
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import org.andstatus.app.ActivityRequestCode
import org.andstatus.app.IntentExtra
import org.andstatus.app.R
import org.andstatus.app.account.MyAccount
import org.andstatus.app.net.social.Actor
import org.andstatus.app.origin.Origin
import org.andstatus.app.util.TriState
import org.andstatus.app.view.MySimpleAdapter
import org.andstatus.app.view.SelectorDialog
import java.util.*
import java.util.stream.Collectors
/**
* @author [email protected]
*/
class TimelineSelector : SelectorDialog() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val arguments = requireArguments()
setTitle(R.string.dialog_title_select_timeline)
val currentTimeline = myContext.timelines.fromId(arguments.getLong(IntentExtra.TIMELINE_ID.key, 0))
val currentMyAccount = myContext.accounts.fromAccountName(
arguments.getString(IntentExtra.ACCOUNT_NAME.key))
val timelines = myContext.timelines.filter(
true,
TriState.fromBoolean(currentTimeline.isCombined),
TimelineType.UNKNOWN, currentMyAccount.actor, Origin.EMPTY).collect(Collectors.toSet())
if (!currentTimeline.isCombined && currentMyAccount.isValid) {
timelines.addAll(myContext.timelines.filter(
true,
TriState.fromBoolean(currentTimeline.isCombined),
TimelineType.UNKNOWN, Actor.EMPTY, currentMyAccount.origin).collect(Collectors.toSet()))
}
if (timelines.isEmpty()) {
returnSelectedTimeline(Timeline.EMPTY)
return
} else if (timelines.size == 1) {
returnSelectedTimeline(timelines.iterator().next())
return
}
val viewItems: MutableList<ManageTimelinesViewItem> = ArrayList()
for (timeline2 in timelines) {
val viewItem = ManageTimelinesViewItem(myContext, timeline2,
myContext.accounts.currentAccount, true)
viewItems.add(viewItem)
}
viewItems.sortWith(ManageTimelinesViewItemComparator(R.id.displayedInSelector, sortDefault = true, isTotal = false))
removeDuplicates(viewItems)
setListAdapter(newListAdapter(viewItems))
listView?.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, view: View, _: Int, _: Long ->
val timelineId = (view.findViewById<View?>(R.id.id) as TextView).text.toString().toLong()
returnSelectedTimeline(myContext.timelines.fromId(timelineId))
}
}
private fun removeDuplicates(timelines: MutableList<ManageTimelinesViewItem>) {
val unique: MutableMap<String?, ManageTimelinesViewItem?> = HashMap()
var removeSomething = false
for (viewItem in timelines) {
val key: String = viewItem.timelineTitle.toString()
if (unique.containsKey(key)) {
removeSomething = true
} else {
unique[key] = viewItem
}
}
if (removeSomething) {
timelines.retainAll(unique.values)
}
}
private fun newListAdapter(listData: MutableList<ManageTimelinesViewItem>): MySimpleAdapter {
val list: MutableList<MutableMap<String, String>> = ArrayList()
val syncText = getText(R.string.synced_abbreviated).toString()
for (viewItem in listData) {
val map: MutableMap<String, String> = HashMap()
map[KEY_VISIBLE_NAME] = viewItem.timelineTitle.toString()
map[KEY_SYNC_AUTO] = if (viewItem.timeline.isSyncedAutomatically()) syncText else ""
map[BaseColumns._ID] = viewItem.timeline.getId().toString()
list.add(map)
}
return MySimpleAdapter(activity ?: throw IllegalStateException("No activity"),
list, R.layout.accountlist_item, arrayOf(KEY_VISIBLE_NAME, KEY_SYNC_AUTO, BaseColumns._ID),
intArrayOf(R.id.visible_name, R.id.sync_auto, R.id.id), true)
}
private fun returnSelectedTimeline(timeline: Timeline) {
returnSelected(Intent().putExtra(IntentExtra.TIMELINE_ID.key, timeline.getId()))
}
companion object {
private val KEY_VISIBLE_NAME: String = "visible_name"
private val KEY_SYNC_AUTO: String = "sync_auto"
fun selectTimeline(activity: FragmentActivity, requestCode: ActivityRequestCode,
timeline: Timeline, currentMyAccount: MyAccount) {
val selector: SelectorDialog = TimelineSelector()
selector.setRequestCode(requestCode)
selector.arguments?.putLong(IntentExtra.TIMELINE_ID.key, timeline.getId())
selector.arguments?.putString(IntentExtra.ACCOUNT_NAME.key, currentMyAccount.getAccountName())
selector.show(activity)
}
}
}
| app/src/main/kotlin/org/andstatus/app/timeline/meta/TimelineSelector.kt | 3869458698 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins
import com.demonwav.mcdev.nbt.lang.gen.psi.NbttInt
import com.demonwav.mcdev.nbt.lang.psi.NbttElement
import com.demonwav.mcdev.nbt.tags.TagIntArray
interface NbttIntArrayMixin : NbttElement {
fun getIntList(): List<NbttInt>
fun getIntArrayTag(): TagIntArray
}
| src/main/kotlin/nbt/lang/psi/mixins/NbttIntArrayMixin.kt | 4027421218 |
package ru.fantlab.android.ui.modules.classificator.characteristics
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Classificator
import ru.fantlab.android.data.dao.model.ClassificatorModel
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.adapter.viewholder.ClassificatorViewHolder
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.classificator.ClassificatorPagerMvp
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import java.util.*
class ClassificationCharacteristicsFragment :
BaseFragment<ClassificationCharacteristicsMvp.View, ClassificationCharacteristicsPresenter>(),
ClassificationCharacteristicsMvp.View {
private var pagerCallback: ClassificatorPagerMvp.View? = null
var selectedItems = 0
override fun fragmentLayout() = R.layout.micro_grid_refresh_list
override fun providePresenter() = ClassificationCharacteristicsPresenter()
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
presenter.onFragmentCreated(arguments!!)
}
override fun onInitViews(classificators: ArrayList<ClassificatorModel>) {
hideProgress()
fastScroller.attachRecyclerView(recycler)
refresh.setOnRefreshListener(this)
val nodes = arrayListOf<TreeNode<*>>()
classificators.forEach {
val root = TreeNode(Classificator(it.name, it.descr, it.id))
nodes.add(root)
work(it, root, false)
}
val adapter = TreeViewAdapter(nodes, Arrays.asList(ClassificatorViewHolder()))
recycler.adapter = adapter
adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener {
override fun onSelected(extra: Int, add: Boolean) {
if (add)
selectedItems++
else
selectedItems--
onSetTabCount(selectedItems)
pagerCallback?.onSelected(extra, add)
}
override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean {
val viewHolder = holder as ClassificatorViewHolder.ViewHolder
val state = viewHolder.checkbox.isChecked
if (!node.isLeaf) {
onToggle(!node.isExpand, holder)
if (!state && !node.isExpand) {
viewHolder.checkbox.isChecked = true
}
} else {
viewHolder.checkbox.isChecked = !state
}
return false
}
override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) {
val viewHolder = holder as ClassificatorViewHolder.ViewHolder
val ivArrow = viewHolder.arrow
val rotateDegree = if (isExpand) 90.0f else -90.0f
ivArrow.animate().rotationBy(rotateDegree)
.start()
}
})
}
private fun work(it: ClassificatorModel, root: TreeNode<Classificator>, lastLevel: Boolean) {
if (it.childs != null) {
val counter = root.childList.size - 1
it.childs.forEach {
val child = TreeNode(Classificator(it.name, it.descr, it.id))
if (lastLevel) {
val childB = TreeNode(Classificator(it.name, it.descr, it.id))
root.childList[counter].addChild(childB)
} else root.addChild(child)
work(it, root, true)
}
}
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
override fun showErrorMessage(msgRes: String?) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun onRefresh() {
hideProgress()
}
fun onSetTabCount(count: Int) {
pagerCallback?.onSetBadge(1, count)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is ClassificatorPagerMvp.View) {
pagerCallback = context
}
}
override fun onDetach() {
pagerCallback = null
super.onDetach()
}
companion object {
fun newInstance(workId: Int): ClassificationCharacteristicsFragment {
val view = ClassificationCharacteristicsFragment()
view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end()
return view
}
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/characteristics/ClassificationCharacteristicsFragment.kt | 790474085 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.common
import com.mycollab.core.MyCollabException
/**
* @author MyCollab Ltd.
* @since 4.0
*/
class InvalidTokenException(message: String) : MyCollabException(message) | mycollab-services/src/main/java/com/mycollab/common/InvalidTokenException.kt | 466945865 |
package de.pbauerochse.worklogviewer.fx.shortcutkeys
import javafx.beans.property.ObjectProperty
import javafx.scene.input.KeyCombination
data class KeyboardShortcutDefinition(
val label: String,
val property: ObjectProperty<KeyCombination>
) | application/src/main/java/de/pbauerochse/worklogviewer/fx/shortcutkeys/KeyboardShortcutDefinition.kt | 4071838455 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.leadForms.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
/**
* @param label
* @param key
*/
data class LeadFormsQuestionItemOption(
@SerializedName("label")
val label: String,
@SerializedName("key")
val key: String? = null
)
| api/src/main/java/com/vk/sdk/api/leadForms/dto/LeadFormsQuestionItemOption.kt | 2487272119 |
/*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.preferences
import android.content.Context
import android.preference.PreferenceManager
import javax.inject.Inject
class GizmodoPreferences {
private lateinit var context: Context
@Inject
constructor(context: Context) {
this.context = context
}
private fun preferences() = PreferenceManager.getDefaultSharedPreferences(context)
fun getInt(name: String, default: Int) = PreferenceManager
.getDefaultSharedPreferences(context).getInt(name, default)
fun getInt(name: String) = getInt(name, -1)
fun putInt(name: String, value: Int) = preferences().edit().putInt(name, value).apply()
fun getLong(name: String) = getLong(name, -1L)
fun getLong(name: String, default: Long) = PreferenceManager
.getDefaultSharedPreferences(context).getLong(name, default)
fun putLong(name: String, value: Long) = preferences().edit().putLong(name, value).apply()
fun getBoolean(name: String) = PreferenceManager
.getDefaultSharedPreferences(context).getBoolean(name, false)
fun putBoolean(name: String, value: Boolean) = preferences().edit().putBoolean(name, value).apply()
} | app/src/main/kotlin/com/hpedrorodrigues/gzmd/preferences/GizmodoPreferences.kt | 2820598116 |
package jupyter.kotlin.providers
interface UserHandlesProvider : KotlinKernelHostProvider, NotebookProvider, SessionOptionsProvider
| jupyter-lib/lib/src/main/kotlin/jupyter/kotlin/providers/UserHandlesProvider.kt | 2064638976 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.data.elementfilter.quoteIfNecessary
/** ~key(word)? */
class HasKeyLike(key: String) : ElementFilter {
val key = key.toRegex()
override fun toOverpassQLString() = "[" + "~" + "^(${key.pattern})$".quoteIfNecessary() + " ~ '.*']"
override fun toString() = toOverpassQLString()
override fun matches(obj: Element?) = obj?.tags?.keys?.find { it.matches(key) } != null
} | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasKeyLike.kt | 3693198073 |
/*
* Copyright (C) 2019-2021 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.xdm.module.path
enum class XdmModuleType(val extensions: Array<String>) {
DotNet(arrayOf()), // Saxon
DTD(arrayOf()), // EXPath Package
Java(arrayOf()), // BaseX, eXist-db, Saxon
NVDL(arrayOf()), // EXPath Package
RelaxNG(arrayOf()), // EXPath Package
RelaxNGCompact(arrayOf()), // EXPath Package
Resource(arrayOf()), // EXPath Package
Schematron(arrayOf()), // EXPath Package
XMLSchema(arrayOf(".xsd")), // Schema Aware Feature, EXPath Package
XPath(arrayOf()), // XSLT
XProc(arrayOf()), // EXPath Package
XQuery(arrayOf(".xq", ".xqm", ".xqy", ".xql", ".xqu", ".xquery")), // Module Feature, EXPath Package
XSLT(arrayOf()); // MarkLogic, EXPath Package
companion object {
val JAVA: Array<XdmModuleType> = arrayOf(Java)
val MODULE: Array<XdmModuleType> = arrayOf(XQuery, Java, DotNet)
val MODULE_OR_SCHEMA: Array<XdmModuleType> = arrayOf(XQuery, XMLSchema, Java, DotNet)
val NONE: Array<XdmModuleType> = arrayOf()
val XPATH_OR_XQUERY: Array<XdmModuleType> = arrayOf(XPath, XQuery)
val XQUERY: Array<XdmModuleType> = arrayOf(XQuery)
val RESOURCE: Array<XdmModuleType> = arrayOf(Resource)
val SCHEMA: Array<XdmModuleType> = arrayOf(XMLSchema)
val STYLESHEET: Array<XdmModuleType> = arrayOf(XSLT)
}
}
| src/lang-xdm/main/uk/co/reecedunn/intellij/plugin/xdm/module/path/XdmModuleType.kt | 1009175814 |
package com.rhm.pwn.home_feature
import com.rhm.pwn.model.URLCheck
sealed class UiEvent {
data class ViewClicked(val urlCheck: URLCheck) : UiEvent()
data class EditClicked(val urlCheck: URLCheck) : UiEvent()
object DebugClicked : UiEvent()
} | app/src/main/java/com/rhm/pwn/home_feature/UiEvent.kt | 2365900720 |
/*
* Copyright (C) 2016-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.xpath.codeInspection.ijvs
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import com.intellij.util.SmartList
import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection
import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree
import uk.co.reecedunn.intellij.plugin.intellij.lang.Saxon
import uk.co.reecedunn.intellij.plugin.intellij.lang.Version
import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathMapConstructorEntry
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
import uk.co.reecedunn.intellij.plugin.xquery.project.settings.XQueryProjectSettings
import xqt.platform.intellij.xpath.XPathTokenProvider
class IJVS0004 : Inspection("ijvs/IJVS0004.md", IJVS0004::class.java.classLoader) {
private fun conformsTo(element: XPathMapConstructorEntry, productVersion: Version?): Boolean {
val conformanceElement = element.separator
if (conformanceElement === element.firstChild) {
return true
}
val isSaxonExtension =
productVersion?.kind === Saxon && productVersion.value >= 9.4 && productVersion.value <= 9.7
return conformanceElement.elementType === XPathTokenProvider.AssignEquals == isSaxonExtension
}
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (file !is XQueryModule) return null
val settings = XQueryProjectSettings.getInstance(file.getProject())
val productVersion: Version = settings.productVersion
val descriptors = SmartList<ProblemDescriptor>()
file.walkTree().filterIsInstance<XPathMapConstructorEntry>().forEach { element ->
if (!conformsTo(element, productVersion)) {
val context = element.separator
val description = XQueryPluginBundle.message("inspection.XPST0003.map-constructor-entry.message")
descriptors.add(
manager.createProblemDescriptor(
context,
description,
null as LocalQuickFix?,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly
)
)
}
}
return descriptors.toTypedArray()
}
}
| src/main/java/uk/co/reecedunn/intellij/plugin/xpath/codeInspection/ijvs/IJVS0004.kt | 1729858393 |
package sqlbuilder.pool
import java.sql.ResultSet
import java.util.concurrent.Callable
interface PreparedStatementInterceptor {
fun intercept(query: String, execution: Callable<ResultSet>): ResultSet
}
| src/main/kotlin/sqlbuilder/pool/PreparedStatementInterceptor.kt | 3149828899 |
package com.reactnativenavigation.viewcontrollers.stack
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.content.Context
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import androidx.core.animation.doOnEnd
import com.reactnativenavigation.options.FadeAnimation
import com.reactnativenavigation.options.Options
import com.reactnativenavigation.options.StackAnimationOptions
import com.reactnativenavigation.options.params.Bool
import com.reactnativenavigation.utils.awaitRender
import com.reactnativenavigation.utils.resetViewProperties
import com.reactnativenavigation.viewcontrollers.common.BaseAnimator
import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController
import com.reactnativenavigation.views.element.TransitionAnimatorCreator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
open class StackAnimator @JvmOverloads constructor(
context: Context,
private val transitionAnimatorCreator: TransitionAnimatorCreator = TransitionAnimatorCreator()
) : BaseAnimator(context) {
@VisibleForTesting
val runningPushAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap()
@VisibleForTesting
val runningPopAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap()
@VisibleForTesting
val runningSetRootAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap()
fun cancelPushAnimations() = runningPushAnimations.values.forEach(Animator::cancel)
open fun isChildInTransition(child: ViewController<*>?): Boolean {
return runningPushAnimations.containsKey(child) ||
runningPopAnimations.containsKey(child) ||
runningSetRootAnimations.containsKey(child)
}
fun cancelAllAnimations() {
runningPushAnimations.clear()
runningPopAnimations.clear()
runningSetRootAnimations.clear()
}
fun setRoot(
appearing: ViewController<*>,
disappearing: ViewController<*>,
options: Options,
additionalAnimations: List<Animator>,
onAnimationEnd: Runnable
) {
val set = createSetRootAnimator(appearing, onAnimationEnd)
runningSetRootAnimations[appearing] = set
val setRoot = options.animations.setStackRoot
if (setRoot.waitForRender.isTrue) {
appearing.view.alpha = 0f
appearing.addOnAppearedListener {
appearing.view.alpha = 1f
animateSetRoot(set, setRoot, appearing, disappearing, additionalAnimations)
}
} else {
animateSetRoot(set, setRoot, appearing, disappearing, additionalAnimations)
}
}
fun push(
appearing: ViewController<*>,
disappearing: ViewController<*>,
resolvedOptions: Options,
additionalAnimations: List<Animator>,
onAnimationEnd: Runnable
) {
val set = createPushAnimator(appearing, onAnimationEnd)
runningPushAnimations[appearing] = set
if (resolvedOptions.animations.push.sharedElements.hasValue()) {
pushWithElementTransition(appearing, disappearing, resolvedOptions, set)
} else {
pushWithoutElementTransitions(appearing, disappearing, resolvedOptions, set, additionalAnimations)
}
}
open fun pop(
appearing: ViewController<*>,
disappearing: ViewController<*>,
disappearingOptions: Options,
additionalAnimations: List<Animator>,
onAnimationEnd: Runnable
) {
if (runningPushAnimations.containsKey(disappearing)) {
runningPushAnimations[disappearing]!!.cancel()
onAnimationEnd.run()
} else {
animatePop(
appearing,
disappearing,
disappearingOptions,
additionalAnimations,
onAnimationEnd
)
}
}
private fun animatePop(
appearing: ViewController<*>,
disappearing: ViewController<*>,
disappearingOptions: Options,
additionalAnimations: List<Animator>,
onAnimationEnd: Runnable
) {
GlobalScope.launch(Dispatchers.Main.immediate) {
val set = createPopAnimator(disappearing, onAnimationEnd)
if (disappearingOptions.animations.pop.sharedElements.hasValue()) {
popWithElementTransitions(appearing, disappearing, disappearingOptions, set)
} else {
popWithoutElementTransitions(appearing, disappearing, disappearingOptions, set, additionalAnimations)
}
}
}
private suspend fun popWithElementTransitions(appearing: ViewController<*>, disappearing: ViewController<*>, resolvedOptions: Options, set: AnimatorSet) {
val pop = resolvedOptions.animations.pop
val fade = if (pop.content.exit.isFadeAnimation()) pop else FadeAnimation
val transitionAnimators = transitionAnimatorCreator.create(pop, fade.content.exit, disappearing, appearing)
set.playTogether(fade.content.exit.getAnimation(disappearing.view), transitionAnimators)
transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) }
transitionAnimators.removeAllListeners()
set.start()
}
private fun popWithoutElementTransitions(
appearing: ViewController<*>,
disappearing: ViewController<*>,
disappearingOptions: Options,
set: AnimatorSet,
additionalAnimations: List<Animator>
) {
val pop = disappearingOptions.animations.pop
val animators = mutableListOf(pop.content.exit.getAnimation(disappearing.view, getDefaultPopAnimation(disappearing.view)))
animators.addAll(additionalAnimations)
if (pop.content.enter.hasValue()) {
animators.add(pop.content.enter.getAnimation(appearing.view))
}
set.playTogether(animators.toList())
set.start()
}
private fun createPopAnimator(disappearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet {
val set = createAnimatorSet()
runningPopAnimations[disappearing] = set
set.addListener(object : AnimatorListenerAdapter() {
private var cancelled = false
override fun onAnimationCancel(animation: Animator) {
if (!runningPopAnimations.contains(disappearing)) return
cancelled = true
runningPopAnimations.remove(disappearing)
}
override fun onAnimationEnd(animation: Animator) {
if (!runningPopAnimations.contains(disappearing)) return
runningPopAnimations.remove(disappearing)
if (!cancelled) onAnimationEnd.run()
}
})
return set
}
private fun createPushAnimator(appearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet {
val set = createAnimatorSet()
set.addListener(object : AnimatorListenerAdapter() {
private var isCancelled = false
override fun onAnimationCancel(animation: Animator) {
if (!runningPushAnimations.contains(appearing)) return
isCancelled = true
runningPushAnimations.remove(appearing)
onAnimationEnd.run()
}
override fun onAnimationEnd(animation: Animator) {
if (!runningPushAnimations.contains(appearing)) return
if (!isCancelled) {
runningPushAnimations.remove(appearing)
onAnimationEnd.run()
}
}
})
return set
}
private fun createSetRootAnimator(appearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet {
val set = createAnimatorSet()
set.addListener(object : AnimatorListenerAdapter() {
private var isCancelled = false
override fun onAnimationCancel(animation: Animator) {
if (!runningSetRootAnimations.contains(appearing)) return
isCancelled = true
runningSetRootAnimations.remove(appearing)
onAnimationEnd.run()
}
override fun onAnimationEnd(animation: Animator) {
if (!runningSetRootAnimations.contains(appearing)) return
if (!isCancelled) {
runningSetRootAnimations.remove(appearing)
onAnimationEnd.run()
}
}
})
return set
}
private fun pushWithElementTransition(
appearing: ViewController<*>,
disappearing: ViewController<*>,
options: Options,
set: AnimatorSet
) = GlobalScope.launch(Dispatchers.Main.immediate) {
appearing.setWaitForRender(Bool(true))
appearing.view.alpha = 0f
appearing.awaitRender()
val fade = if (options.animations.push.content.enter.isFadeAnimation()) options.animations.push.content.enter else FadeAnimation.content.enter
val transitionAnimators = transitionAnimatorCreator.create(options.animations.push, fade, disappearing, appearing)
set.playTogether(fade.getAnimation(appearing.view), transitionAnimators)
transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) }
transitionAnimators.removeAllListeners()
set.start()
}
private fun pushWithoutElementTransitions(
appearing: ViewController<*>,
disappearing: ViewController<*>,
resolvedOptions: Options,
set: AnimatorSet,
additionalAnimations: List<Animator>
) {
val push = resolvedOptions.animations.push
if (push.waitForRender.isTrue) {
appearing.view.alpha = 0f
appearing.addOnAppearedListener {
appearing.view.alpha = 1f
animatePushWithoutElementTransitions(set, push, appearing, disappearing, additionalAnimations)
}
} else {
animatePushWithoutElementTransitions(set, push, appearing, disappearing, additionalAnimations)
}
}
private fun animatePushWithoutElementTransitions(
set: AnimatorSet,
push: StackAnimationOptions,
appearing: ViewController<*>,
disappearing: ViewController<*>,
additionalAnimations: List<Animator>
) {
val animators = mutableListOf(push.content.enter.getAnimation(appearing.view, getDefaultPushAnimation(appearing.view)))
animators.addAll(additionalAnimations)
if (push.content.exit.hasValue()) {
animators.add(push.content.exit.getAnimation(disappearing.view))
}
set.playTogether(animators.toList())
set.doOnEnd {
if (!disappearing.isDestroyed) disappearing.view.resetViewProperties()
}
set.start()
}
private fun animateSetRoot(
set: AnimatorSet,
setRoot: StackAnimationOptions,
appearing: ViewController<*>,
disappearing: ViewController<*>,
additionalAnimations: List<Animator>
) {
val animators = mutableListOf(setRoot.content.enter.getAnimation(
appearing.view,
getDefaultSetStackRootAnimation(appearing.view)
))
animators.addAll(additionalAnimations)
if (setRoot.content.exit.hasValue()) {
animators.add(setRoot.content.exit.getAnimation(disappearing.view))
}
set.playTogether(animators.toList())
set.start()
}
protected open fun createAnimatorSet(): AnimatorSet = AnimatorSet()
@RestrictTo(RestrictTo.Scope.TESTS)
fun endPushAnimation(view: ViewController<*>) {
if (runningPushAnimations.containsKey(view)) {
runningPushAnimations[view]!!.end()
}
}
}
| lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/stack/StackAnimator.kt | 3711734426 |
/*
* Copyright (C) 2019-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.saxon.query.s9api.binding
import uk.co.reecedunn.intellij.plugin.core.reflection.getMethodOrNull
import uk.co.reecedunn.intellij.plugin.core.reflection.loadClassOrNull
import uk.co.reecedunn.intellij.plugin.processor.query.UnsupportedJarFileException
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.SaxonS9API
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.proxy.TraceListener
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.proxy.proxy
import javax.xml.transform.Source
class Processor {
private val `object`: Any
private val `class`: Class<*>
constructor(classLoader: ClassLoader, licensedEdition: Boolean) {
try {
`class` = classLoader.loadClass("net.sf.saxon.s9api.Processor")
`object` = `class`.getConstructor(Boolean::class.java).newInstance(licensedEdition)
} catch (e: ClassNotFoundException) {
throw UnsupportedJarFileException(SaxonS9API.presentation.presentableText!!)
}
// Using the Saxon EE optimizer can generate a NoClassDefFoundError
// resolving com/saxonica/ee/bytecode/GeneratedCode. This appears to
// be due to the way the Saxon processor modifies the Java class loader.
setConfigurationProperty("OPTIMIZATION_LEVEL", "0")
}
constructor(classLoader: ClassLoader, configuration: Source) {
`class` = classLoader.loadClass("net.sf.saxon.s9api.Processor")
`object` = `class`.getConstructor(Source::class.java).newInstance(configuration)
// Using the Saxon EE optimizer can generate a NoClassDefFoundError
// resolving com/saxonica/ee/bytecode/GeneratedCode. This appears to
// be due to the way the Saxon processor modifies the Java class loader.
setConfigurationProperty("OPTIMIZATION_LEVEL", "0")
}
val classLoader: ClassLoader
get() = `class`.classLoader
private val saxonEdition: String?
get() = `class`.getMethodOrNull("getSaxonEdition")?.invoke(`object`) as? String
private val saxonProductVersion: String
get() = `class`.getMethod("getSaxonProductVersion").invoke(`object`) as String
val version: String
get() = saxonEdition?.let { "$saxonProductVersion ($it)" } ?: saxonProductVersion
val typeHierarchy: Any
get() {
val configurationClass = `class`.classLoader.loadClass("net.sf.saxon.Configuration")
val configuration = `class`.getMethod("getUnderlyingConfiguration").invoke(`object`)
return configurationClass.getMethod("getTypeHierarchy").invoke(configuration)
}
fun setTraceListener(listener: TraceListener?) {
val configurationClass = `class`.classLoader.loadClass("net.sf.saxon.Configuration")
val listenerClass = `class`.classLoader.loadClassOrNull("net.sf.saxon.lib.TraceListener") // Saxon >= 9.3
?: `class`.classLoader.loadClass("net.sf.saxon.trace.TraceListener") // Saxon <= 9.2.1
val listener2Class = `class`.classLoader.loadClassOrNull("net.sf.saxon.lib.TraceListener2")
val proxy = listener?.let {
listener2Class?.let { listener.proxy(listenerClass, it) } ?: listener.proxy(listenerClass)
}
// Call getDefaultStaticQueryContext to ensure the TraceCodeInjector is set,
// so the TraceListener events get called the first time the query is run.
val configuration = `class`.getMethod("getUnderlyingConfiguration").invoke(`object`)
configurationClass.getMethod("getDefaultStaticQueryContext").invoke(configuration)
configurationClass.getMethod("setTraceListener", listenerClass).invoke(configuration, proxy)
}
private fun setConfigurationProperty(name: String, value: Any) {
val configurationClass = `class`.classLoader.loadClass("net.sf.saxon.Configuration")
val configuration = `class`.getMethod("getUnderlyingConfiguration").invoke(`object`)
val featureClass = `class`.classLoader.loadClassOrNull("net.sf.saxon.lib.Feature")
if (featureClass == null) { // Saxon <= 9.7
val featureKeysClass = `class`.classLoader.loadClassOrNull("net.sf.saxon.lib.FeatureKeys") // Saxon >= 9.3
?: `class`.classLoader.loadClass("net.sf.saxon.FeatureKeys") // Saxon <= 9.2.1
configurationClass.getMethod("setConfigurationProperty", String::class.java, Any::class.java)
.invoke(configuration, featureKeysClass.getField(name).get(null), value)
} else { // Saxon >= 9.8
configurationClass.getMethod("setConfigurationProperty", featureClass, Any::class.java)
.invoke(configuration, featureClass.getField(name).get(null), value)
}
}
fun newDocumentBuilder(): DocumentBuilder {
val compiler = `class`.getMethod("newDocumentBuilder").invoke(`object`)
return DocumentBuilder(compiler, `class`.classLoader.loadClass("net.sf.saxon.s9api.DocumentBuilder"))
}
fun newXPathCompiler(): XPathCompiler {
val compiler = `class`.getMethod("newXPathCompiler").invoke(`object`)
return XPathCompiler(compiler, `class`.classLoader.loadClass("net.sf.saxon.s9api.XPathCompiler"))
}
fun newXQueryCompiler(): XQueryCompiler {
val compiler = `class`.getMethod("newXQueryCompiler").invoke(`object`)
return XQueryCompiler(compiler, `class`.classLoader.loadClass("net.sf.saxon.s9api.XQueryCompiler"))
}
fun newXsltCompiler(): XsltCompiler {
val compiler = `class`.getMethod("newXsltCompiler").invoke(`object`)
return XsltCompiler(compiler, `class`.classLoader.loadClass("net.sf.saxon.s9api.XsltCompiler"))
}
}
| src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/Processor.kt | 1870730198 |
fun f(x: Long, zzz: Long = 1): Long
{
return if (x <= 1) zzz
else f(x-1, x*zzz)
}
fun box() : String
{
val six: Long = 6;
if (f(six) != 720.toLong()) return "Fail"
return "OK"
}
| backend.native/tests/external/codegen/box/primitiveTypes/kt665.kt | 4146265557 |
import org.apache.commons.lang3.time.FastDateFormat.getInstance
import org.http4k.core.Filter
import org.http4k.core.then
import org.http4k.routing.routes
import org.http4k.server.ServerConfig
import org.http4k.server.asServer
import java.util.TimeZone.getTimeZone
object Http4kBenchmarkServer {
private val dateFormat = getInstance("EEE, d MMM yyyy HH:mm:ss 'GMT'", getTimeZone("GMT"))
private val dateAndServer = Filter {
next ->
{
next(it)
.header("Server", "Example")
.header("Date", dateFormat.format(System.currentTimeMillis()))
}
}
private val database = Database(System.getenv("DBHOST") ?: "localhost")
val routes = listOf(PlainTextRoute(),
JsonRoute(),
FortunesRoute(database)
).plus(WorldRoutes(database))
fun start(config: ServerConfig) = dateAndServer.then(routes(*routes.toTypedArray())).asServer(config).start().block()
} | frameworks/Kotlin/http4k/src/main/kotlin/Http4kBenchmarkServer.kt | 2118141701 |
package org.stepic.droid.code.highlight.themes
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.util.ColorUtil
object Presets {
val themes = arrayOf(
CodeTheme(
name = App.getAppContext().getString(R.string.light_theme_name),
syntax = CodeSyntax(
plain = ColorUtil.getColorArgb(R.color.light_theme_plain),
string = ColorUtil.getColorArgb(R.color.light_theme_string),
keyword = ColorUtil.getColorArgb(R.color.light_theme_keyword),
comment = ColorUtil.getColorArgb(R.color.light_theme_comment),
type = ColorUtil.getColorArgb(R.color.light_theme_type),
literal = ColorUtil.getColorArgb(R.color.light_theme_literal),
punctuation = ColorUtil.getColorArgb(R.color.light_theme_punctuation),
attributeName = ColorUtil.getColorArgb(R.color.light_theme_attribute_name),
attributeValue = ColorUtil.getColorArgb(R.color.light_theme_attribute_value)
),
background = ColorUtil.getColorArgb(R.color.light_theme_background),
lineNumberBackground = ColorUtil.getColorArgb(R.color.light_theme_line_number_background),
lineNumberText = ColorUtil.getColorArgb(R.color.light_theme_line_number_text),
selectedLineBackground = ColorUtil.getColorArgb(R.color.light_theme_selected_line_background),
lineNumberStroke = ColorUtil.getColorArgb(R.color.light_theme_line_number_stroke),
bracketsHighlight = ColorUtil.getColorArgb(R.color.light_theme_brackets_highlight)
),
CodeTheme(
name = App.getAppContext().getString(R.string.github_theme_name),
syntax = CodeSyntax(
plain = ColorUtil.getColorArgb(R.color.github_theme_plain),
string = ColorUtil.getColorArgb(R.color.github_theme_string),
comment = ColorUtil.getColorArgb(R.color.github_theme_comment),
type = ColorUtil.getColorArgb(R.color.github_theme_type),
literal = ColorUtil.getColorArgb(R.color.github_theme_literal),
attributeName = ColorUtil.getColorArgb(R.color.github_theme_attribute_name),
attributeValue = ColorUtil.getColorArgb(R.color.github_theme_attribute_value)
),
background = ColorUtil.getColorArgb(R.color.github_theme_background),
lineNumberBackground = ColorUtil.getColorArgb(R.color.github_theme_line_number_background),
lineNumberText = ColorUtil.getColorArgb(R.color.github_theme_line_number_text),
selectedLineBackground = ColorUtil.getColorArgb(R.color.github_theme_selected_line_background),
lineNumberStroke = ColorUtil.getColorArgb(R.color.github_theme_line_number_stroke)
),
CodeTheme(
name = App.getAppContext().getString(R.string.tomorrow_night_theme_name),
syntax = CodeSyntax(
plain = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_plain),
string = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_string),
keyword = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_keyword),
comment = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_comment),
type = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_type),
literal = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_literal),
tag = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_tag),
attributeName = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_attribute_name),
attributeValue = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_attribute_value),
declaration = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_declaration)
),
background = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_background),
lineNumberBackground = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_background),
lineNumberText = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_text),
selectedLineBackground = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_selected_line_background),
lineNumberStroke = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_stroke)
),
CodeTheme(
name = App.getAppContext().getString(R.string.tranquil_heart_theme_name),
syntax = CodeSyntax(
plain = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_plain),
string = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_string),
keyword = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_keyword),
comment = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_comment),
type = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_type),
literal = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_literal),
tag = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_tag),
attributeName = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_attribute_name),
attributeValue = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_attribute_value),
declaration = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_declaration)
),
background = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_background),
lineNumberBackground = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_background),
lineNumberText = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_text),
selectedLineBackground = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_selected_line_background),
lineNumberStroke = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_stroke)
)
)
} | app/src/main/java/org/stepic/droid/code/highlight/themes/Presets.kt | 1213453639 |
package org.stepik.android.presentation.story_deeplink
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepik.android.domain.story_deeplink.interactor.StoryDeepLinkInteractor
import ru.nobird.android.presentation.base.PresenterBase
import javax.inject.Inject
class StoryDeepLinkPresenter
@Inject
constructor(
private val storyDeepLinkInteractor: StoryDeepLinkInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<StoryDeepLinkView>() {
private var state: StoryDeepLinkView.State = StoryDeepLinkView.State.Idle
set(value) {
field = value
view?.setState(value)
}
fun onData(storyId: Long) {
if (state != StoryDeepLinkView.State.Idle) return
state = StoryDeepLinkView.State.Loading
compositeDisposable += storyDeepLinkInteractor
.getStoryTemplate(storyId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = StoryDeepLinkView.State.Success(it) },
onError = { state = StoryDeepLinkView.State.Error }
)
}
} | app/src/main/java/org/stepik/android/presentation/story_deeplink/StoryDeepLinkPresenter.kt | 1788094207 |
/*
* Copyright (C) 2017 José Roberto de Araújo Júnior
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.platestack.api.message
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import org.platestack.api.message.Text.RawText
import org.platestack.api.minecraft.item.ItemStack
import org.platestack.api.server.PlateStack
/**
* An action that happens when a player points the pointer to a [Text]
*/
sealed class HoverEvent(val action: String) {
protected abstract val value: Any
/**
* A text will be shown inside a tooltip.
* @property text The text to be show. The [Text.hoverEvent] and [Text.clickEvent] will be ignored.
*
* @constructor Creates this event using any [Text]
* @param text See [text]
*/
class ShowText(val text: Text): HoverEvent("show_text") {
constructor(text: String): this(RawText(text))
override val value: Text get() = text
}
class ShowItem(val serializedItem: JsonObject): HoverEvent("show_item") {
constructor(serializedItem: String): this(JsonParser().parse(serializedItem).asJsonObject)
constructor(stack: ItemStack): this(PlateStack.internal.createShowItemJSON(stack))
override val value: JsonObject get() = serializedItem
}
class ShowAchievement(val id: String): HoverEvent("show_achievement") {
override val value: String get() = id
}
class ShowEntity(val serializedEntity: JsonObject): HoverEvent("show_entity") {
override val value: JsonObject get() = serializedEntity
}
/**
* The hover event will be equals only if it deeply matches all properties
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as HoverEvent
if (action != other.action) return false
return true
}
/**
* Calculates the hashcode for this event
*/
override fun hashCode(): Int {
return action.hashCode()
}
/**
* Returns a verbose string
*/
override fun toString(): String {
return "HoverEvent(action='$action')"
}
}
| src/main/kotlin/org/platestack/api/message/HoverEvent.kt | 1117649000 |
package com.czbix.klog.http
import com.czbix.klog.common.Config
import com.czbix.klog.database.dao.UserDao
import com.czbix.klog.http.HttpContextKey.*
import com.czbix.klog.http.SecureCookie.secureValue
import com.czbix.klog.http.core.DefaultHttpPostRequestDecoder
import com.czbix.klog.utils.now
import io.netty.handler.codec.http.*
import java.util.*
import java.util.concurrent.TimeUnit
inline fun <reified T> HttpContext.getWithType(key: HttpContextKey): T? {
return get(key) as T?
}
inline fun <reified T : Any> HttpContext.getWithType(key: HttpContextKey, block: () -> T?): T? {
val value = get(key) as T?
return value ?: block()?.let {
put(key, it)
it
}
}
val HttpContext.args: Map<String, String>
get() {
return getWithType(HANDLER_ARGS)!!
}
val HttpContext.request: HttpRequest
get() {
return getWithType(REQUEST)!!
}
val HttpContext.postData: DefaultHttpPostRequestDecoder
get() {
return DefaultHttpPostRequestDecoder(request)
}
val HttpContext.cookies: Map<String, Cookie>
get() {
return getWithType<Map<String, Cookie>>(COOKIES) {
val cookiesHeader = request.headers().get(HttpHeaderNames.COOKIE)?.toString()
if (cookiesHeader == null) return@getWithType mapOf()
ServerCookieDecoder.decode(cookiesHeader).associateBy { it.name() }
}!!
}
fun HttpContext.setCookie(name: String, value: String?, domain: String? = null, expiresDate: Date? = null,
path: String = "/", expiresDays: Int? = null, httpOnly: Boolean = true,
secureValue: Boolean = false) {
var cookies = getWithType<MutableMap<String, Cookie>>(COOKIES_SET)
if (cookies == null) {
cookies = mutableMapOf()
this[COOKIES_SET] = cookies
}
val cookie = DefaultCookie(name, value).let {
if (secureValue) {
it.secureValue = value
}
if (domain != null) {
it.setDomain(domain)
}
var maxAge = if (expiresDays != null && expiresDate == null) {
TimeUnit.DAYS.toSeconds(expiresDays.toLong())
} else if (expiresDate != null) {
TimeUnit.MILLISECONDS.toSeconds(expiresDate.time - now())
} else 0
it.setMaxAge(maxAge)
it.setPath(path)
it.isHttpOnly = httpOnly
if (Config.isCookieSecure()) {
it.isSecure = true
}
return@let it
}
cookies[name] = cookie
}
var HttpContext.user: UserDao.User?
get() {
var user = getWithType<UserDao.User?>(USER)
if (user == null) {
val username = cookies["username"]?.secureValue
if (username == null) {
return null
}
user = UserDao.get(username)
user?.let {
this[USER] = it
}
}
return user
}
set(value) {
if (value == null) {
remove(USER)
setCookie("username", null, expiresDays = -365)
} else {
this[USER] = value
setCookie("username", value.username, expiresDays = 365, secureValue = true)
}
}
| src/main/kotlin/com/czbix/klog/http/HttpContextUtils.kt | 4069670468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.