content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package org.jrenner.learngl
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.graphics.Texture
import kotlin.properties.Delegates
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture.TextureFilter
import com.badlogic.gdx.graphics.Texture.TextureWrap
import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter
class Assets {
val manager = AssetManager()
private val texturePath = "texture/"
fun load(){
val texParam = TextureParameter()
texParam.genMipMaps = true
texParam.magFilter = TextureFilter.Linear
texParam.minFilter = TextureFilter.MipMapLinearLinear
fun loadTex(path: String) = manager.load(texturePath + path, Texture::class.java, texParam)
arrayOf(
"dirt.png"
//"grass.png"
).forEach {
loadTex(it)
}
manager.load("ui/ui.json", Skin::class.java)
manager.finishLoading()
skin = manager.get("ui/ui.json")
setupSkinFonts()
}
private fun getTexture(name: String): Texture = manager.get(texturePath + name, Texture::class.java)
val grassTexture by lazy { getTexture("grass.png") }
val dirtTexture by lazy { getTexture("dirt.png") }
fun setupSkinFonts() {
skin.get(LabelStyle::class.java).font = fonts.normal
}
val uvTestTexture: Texture by lazy {
val sz = 64
val pixmap = Pixmap(sz, sz, Pixmap.Format.RGBA8888)
pixmap.setColor(Color.GRAY)
pixmap.fill()
pixmap.setColor(Color.BLACK)
pixmap.drawCircle(sz / 2, sz / 2, sz / 2 - 2)
pixmap.setColor(Color.BLUE)
val c = sz / 2
pixmap.drawLine(c, c, c + 8, c)
pixmap.setColor(Color.MAGENTA)
pixmap.drawLine(c, c, c, c + 8)
pixmap.setColor(Color.YELLOW)
pixmap.drawRectangle(c, c + 8, 3, 3)
pixmap.setColor(Color.RED)
pixmap.drawRectangle(c + 8, c, 3, 3)
val tex = Texture(pixmap, true)
tex.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear)
tex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat)
pixmap.dispose()
tex
}
fun createTexture(baseColor: Color): Texture {
val sz = 64
val pixmap = Pixmap(sz, sz, Pixmap.Format.RGBA8888)
for (y in 0..sz-1) {
for (x in 0..sz-1) {
val c = MathUtils.random(0.3f, 0.6f)
val r = Math.max(0f, baseColor.r - c)
val g = Math.max(0f, baseColor.g - c)
val b = Math.max(0f, baseColor.b - c)
pixmap.setColor(r, g, b, 1.0f)
pixmap.drawPixel(x, y)
}
}
val tex = Texture(pixmap, true)
//tex.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear)
tex.setFilter(TextureFilter.Nearest, TextureFilter.Nearest)
tex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat)
pixmap.dispose()
return tex
}
}
| core/src/main/kotlin/org/jrenner/learngl/Assets.kt | 1248695160 |
package com.github.prologdb.runtime.stdlib.essential.math
import com.github.prologdb.runtime.ClauseIndicator
import com.github.prologdb.runtime.term.CompoundTerm
import com.github.prologdb.runtime.term.PrologNumber
import com.github.prologdb.runtime.util.ArityMap
/**
* Takes an arithmetic compound term (e.g. +(1,2) or mod(23,4)) and returns the calculated value
*/
typealias Calculator = (CompoundTerm) -> PrologNumber
/**
* Keeps track of ways to evaluate mathematical compounds. This is global; registring a new calculator
* will affect all prolog runtimes.
*
* **This is not an [com.github.prologdb.runtime.util.OperatorRegistry]!**
*/
object MathOperatorRegistry {
/**
* Maps operator names to calculators
*/
private val calculators: MutableMap<String, ArityMap<Calculator>> = mutableMapOf()
fun registerOperator(operatorName: String, arities: IntRange, calculator: Calculator) {
if (arities.first <= 0) {
throw IllegalArgumentException("Cannot register an arithmetic operator with arity less than 1")
}
val arityMap: ArityMap<Calculator>
if (operatorName in calculators) {
arityMap = calculators[operatorName]!!
} else {
arityMap = ArityMap()
calculators[operatorName] = arityMap
}
for (arity in arities) {
arityMap[arity] = calculator
}
}
fun getCalculator(operatorName: String, arity: Int): Calculator? = calculators[operatorName]?.get(arity)
/**
* Evaluates the given compound term as an arithmetic expression.
*/
fun evaluate(compoundTerm: CompoundTerm): PrologNumber {
val calculator = getCalculator(compoundTerm.functor, compoundTerm.arity)
?: throw UndefinedMathOperatorException(ClauseIndicator.of(compoundTerm))
return calculator(compoundTerm)
}
fun registerOperator(operatorName: String, calculator: (PrologNumber) -> PrologNumber) {
registerOperator(operatorName, 1..1) { termAST ->
if (termAST.arity != 1 || termAST.functor != operatorName) {
throw InvalidMathOperatorInvocationException(ClauseIndicator.of(operatorName, 1), ClauseIndicator.of(termAST))
}
calculator(termAST.arguments[0].asPrologNumber)
}
}
fun registerOperator(operatorName: String, calculator: (PrologNumber, PrologNumber) -> PrologNumber) {
registerOperator(operatorName, 2..2) { compoundTerm ->
if (compoundTerm.arity != 2 || compoundTerm.functor != operatorName) {
throw InvalidMathOperatorInvocationException(ClauseIndicator.of(operatorName, 2), ClauseIndicator.of(compoundTerm))
}
calculator(compoundTerm.arguments[0].asPrologNumber, compoundTerm.arguments[1].asPrologNumber)
}
}
init {
// common binary operators
registerOperator("+", PrologNumber::plus)
registerOperator("-", PrologNumber::minus)
registerOperator("*", PrologNumber::times)
registerOperator("/", PrologNumber::div)
registerOperator("mod", PrologNumber::rem)
registerOperator("^", PrologNumber::toThe)
registerOperator("+", PrologNumber::unaryPlus)
registerOperator("-", PrologNumber::unaryMinus)
}
}
| stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/essential/math/MathOperatorRegistry.kt | 2757863835 |
import java.util.*
fun main(args: Array<String>) {
val length = 10 // password length
println(generatePswd(length))
}
internal fun generatePswd(len: Int): CharArray {
println("Your Password:")
val charsCaps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val chars = "abcdefghijklmnopqrstuvwxyz"
val nums = "0123456789"
val symbols = "!@#$%^&*_=+-/€.?<>)"
val passSymbols = charsCaps + chars + nums + symbols
val rnd = Random()
val password = CharArray(len)
for (i in 0..len - 1) {
password[i] = passSymbols[rnd.nextInt(passSymbols.length)]
}
return password
}
| utilities/passwordgen.kt | 238512561 |
/*
* Copyright 2019 Andrey Mukamolov
*
* 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.bookcrossing.mobile.util.adapters
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.navigation.findNavController
import butterknife.BindView
import butterknife.OnClick
import com.bookcrossing.mobile.R
import com.bookcrossing.mobile.models.Book
import com.bookcrossing.mobile.ui.profile.AcquiredBookItemView
import com.bookcrossing.mobile.util.EXTRA_KEY
/**
* View holder for acquired books list item
*/
class AcquiredBooksViewHolder(view: View) : BaseViewHolder(view), AcquiredBookItemView {
private lateinit var key: String
@BindView(R.id.book_name)
lateinit var bookName: TextView
@BindView(R.id.author)
lateinit var author: TextView
override fun bind(book: Book, key: String?) {
bookName.text = book.name
author.text = book.author
this.key = key.orEmpty()
}
/**
* Handle release of the acquired book
*/
@OnClick(R.id.release_button)
fun release() {
itemView.findNavController()
.navigate(R.id.releaseAcquiredBookFragment, bundleOf(EXTRA_KEY to key))
}
} | app/src/main/java/com/bookcrossing/mobile/util/adapters/AcquiredBooksViewHolder.kt | 2618099480 |
package com.github.davinkevin.podcastserver.find.finders.francetv
import com.github.davinkevin.podcastserver.service.image.ImageServiceConfig
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.web.reactive.function.client.WebClient
import reactor.netty.http.client.HttpClient
import com.github.davinkevin.podcastserver.service.image.ImageService
/**
* Created by kevin on 01/11/2019
*/
@Configuration
@Import(ImageServiceConfig::class)
class FranceTvFinderConfig {
@Bean
fun franceTvFinder(wcb: WebClient.Builder, imageService: ImageService): FranceTvFinder {
val client = wcb.clone()
.clientConnector(ReactorClientHttpConnector(HttpClient.create().followRedirect(true)))
.baseUrl("https://www.france.tv/")
.build()
return FranceTvFinder(client, imageService)
}
}
| backend/src/main/kotlin/com/github/davinkevin/podcastserver/find/finders/francetv/FranceTvFinderConfig.kt | 4219663287 |
package com.jayrave.falkon.engine.jdbc
import com.jayrave.falkon.engine.*
import javax.sql.DataSource
/**
* [driverSupportsResultSetScrolling] is `false` by default as there are widely used
* JDBC drivers that don't support scrollable result set (eg., xerial's sqlite)
*/
class JdbcEngineCore(
dataSource: DataSource,
private val driverSupportsResultSetScrolling: Boolean = false) : EngineCore {
private val transactionManager = TransactionManagerImpl(dataSource)
private val connectionManager = ConnectionManagerImpl(dataSource, transactionManager)
/**
* Database resources created inside a transaction shouldn't be passed outside as
* the underlying database connection would be closed when the transaction completes
* (which may lead to exceptions being thrown when the resources are acted upon).
* Therefore, don't pass any [CompiledStatement] or [Source] (or any such resources)
* outside of the transaction block
*/
override fun <R> executeInTransaction(operation: () -> R): R {
return transactionManager.executeInTransaction(operation)
}
override fun isInTransaction(): Boolean {
return transactionManager.isInTransaction()
}
override fun compileSql(rawSql: String): CompiledStatement<Unit> {
return UnitReturningCompiledStatement(rawSql, connectionManager)
}
override fun compileInsert(rawSql: String): CompiledStatement<Int> {
return IUD_CompiledStatement(rawSql, connectionManager)
}
override fun compileUpdate(rawSql: String): CompiledStatement<Int> {
return IUD_CompiledStatement(rawSql, connectionManager)
}
override fun compileDelete(rawSql: String): CompiledStatement<Int> {
return IUD_CompiledStatement(rawSql, connectionManager)
}
override fun compileInsertOrReplace(rawSql: String): CompiledStatement<Int> {
return IUD_CompiledStatement(rawSql, connectionManager)
}
override fun compileQuery(rawSql: String): CompiledStatement<Source> {
return CompiledQuery(rawSql, connectionManager, driverSupportsResultSetScrolling)
}
} | falkon-engine-jdbc/src/main/kotlin/com/jayrave/falkon/engine/jdbc/JdbcEngineCore.kt | 4168196584 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.android.datastore.data
import kotlinx.coroutines.flow.flowOf
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object TasksRepository {
private val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
// In a real app, this would be coming from a data source like a database
val tasks = flowOf(
listOf(
Task(
name = "Open codelab",
deadline = simpleDateFormat.parse("2020-07-03")!!,
priority = TaskPriority.LOW,
completed = true
),
Task(
name = "Import project",
deadline = simpleDateFormat.parse("2020-04-03")!!,
priority = TaskPriority.MEDIUM,
completed = true
),
Task(
name = "Check out the code", deadline = simpleDateFormat.parse("2020-05-03")!!,
priority = TaskPriority.LOW
),
Task(
name = "Read about DataStore", deadline = simpleDateFormat.parse("2020-06-03")!!,
priority = TaskPriority.HIGH
),
Task(
name = "Implement each step",
deadline = Date(),
priority = TaskPriority.MEDIUM
),
Task(
name = "Understand how to use DataStore",
deadline = simpleDateFormat.parse("2020-04-03")!!,
priority = TaskPriority.HIGH
),
Task(
name = "Understand how to migrate to DataStore",
deadline = Date(),
priority = TaskPriority.HIGH
)
)
)
}
| app/src/main/java/com/codelab/android/datastore/data/TasksRepository.kt | 1385284253 |
package clustering
open class Cluster<T:Clusterable>(val nodes:MutableList<T>)
{
fun addNode(node:T)
{
nodes.add(node)
}
}
class CentroidCluster<T:Clusterable>(val center:Clusterable ,nodes:MutableList<T> = mutableListOf()) : Cluster<T>(nodes)
{
}
| src/main/kotlin/clustering/Cluster.kt | 1134349729 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.store.bukkit.event.purchase
interface RPKPurchaseDeleteEvent : RPKPurchaseEvent | bukkit/rpk-store-lib-bukkit/src/main/kotlin/com/rpkit/store/bukkit/event/purchase/RPKPurchaseDeleteEvent.kt | 1673233413 |
package io.github.manamiproject.manami.gui.search
import tornadofx.FXEvent
object ClearAutoCompleteSuggestionsGuiEvent: FXEvent() | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/search/ClearAutoCompleteSuggestionsGuiEvent.kt | 2766059000 |
/*
* Copyright (c) 2018 deltaDNA Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.deltadna.android.sdk.ads
import android.app.Activity
import com.google.common.truth.Truth.*
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class DynamicActivityCatcherTest {
@Test
fun activityCaptured() {
with(DynamicActivityCatcher(mock())) {
val activity1 = mock<Activity>()
val activity2 = mock<Activity>()
val activity3 = mock<Activity>()
onActivityCreated(activity1, mock())
onActivityCreated(activity2, mock())
onActivityCreated(activity3, mock())
assertThat(getActivity()).isNull()
onActivityDestroyed(activity3)
assertThat(getActivity()).isNull()
onAnalyticsStarted()
assertThat(getActivity()).isSameAs(activity2)
}
}
@Test
fun activityReleased() {
with(DynamicActivityCatcher(mock())) {
val activity = mock<Activity>()
onActivityCreated(activity, mock())
onAnalyticsStarted()
onAnalyticsStopped()
assertThat(getActivity()).isNull()
}
}
@Test
fun resumeAndPauseCallbacks() {
val listener = mock<ActivityCatcher.LifecycleCallbacks>()
with(DynamicActivityCatcher(listener)) {
val activity = mock<Activity>()
onActivityCreated(activity, mock())
onAnalyticsStarted()
onActivityResumed(activity)
verify(listener).onResumed()
onActivityPaused(activity)
verify(listener).onPaused()
}
}
@Test
fun ignoresOtherActivities() {
val listener = mock<ActivityCatcher.LifecycleCallbacks>()
with(DynamicActivityCatcher(listener)) {
val activity1 = mock<Activity>()
val activity2 = mock<Activity>()
onActivityCreated(activity1, mock())
onAnalyticsStarted()
onActivityCreated(activity2, mock())
onActivityResumed(activity2)
onActivityPaused(activity2)
verifyZeroInteractions(listener)
onActivityDestroyed(activity2)
assertThat(getActivity()).isNotNull()
}
}
}
| library/src/test/kotlin/com/deltadna/android/sdk/ads/DynamicActivityCatcherTest.kt | 2642813641 |
package v_collections
fun example4() {
val max = listOf(1, 42, 4).max()
val longestString = listOf("a", "b").maxBy { it.length() }
}
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? {
// Return a customer who ordered maximum number of orders
todoCollectionTask()
}
fun Customer.getMostExpensiveOrderedProduct(): Product? {
// Return the most expensive ordered product
todoCollectionTask()
}
| src/v_collections/E_MaxMin.kt | 1358510302 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.groovy
import groovy.lang.GroovyRuntimeException
import groovy.util.GroovyScriptEngine
import uk.co.nickthecoder.tickle.Director
import uk.co.nickthecoder.tickle.Producer
import uk.co.nickthecoder.tickle.Role
import uk.co.nickthecoder.tickle.scripts.Language
import uk.co.nickthecoder.tickle.scripts.ScriptException
import java.io.File
import java.util.regex.Pattern
class GroovyLanguage : Language() {
private lateinit var engine: GroovyScriptEngine
override val fileExtension = "groovy"
override val name = "Groovy"
private lateinit var path: File
override fun setClasspath(directory: File) {
path = directory
createEngine()
}
private fun createEngine() {
engine = GroovyScriptEngine(path.path)
engine.config.minimumRecompilationInterval = 0
}
override fun loadScript(file: File): Class<*> {
try {
return engine.loadScriptByName(file.name)
} catch (e: GroovyRuntimeException) {
throw convertException(e)
} catch (e: Exception) {
e.printStackTrace()
throw ScriptException(e)
}
}
override fun clear() {
super.clear()
// By creating a new engine, I hope that the classes used by the previous engine's
// classloader can be garbage collected.
createEngine()
}
override fun generateScript(name: String, type: Class<*>?): String {
return when (type) {
Role::class.java -> generateRole(name)
Director::class.java -> generateDirector(name)
Producer::class.java -> generateProducer(name)
else -> generatePlainScript(name, type)
}
}
fun generatePlainScript(name: String, type: Class<*>?) = """import uk.co.nickthecoder.tickle.*
${if (type == null || type.`package`.name == "uk.co.nickthecoder.tickle") "" else "import ${type.name}"}
import uk.co.nickthecoder.tickle.resources.*
class $name ${if (type == null) "" else (if (type.isInterface) "implements" else "extends") + " ${type.simpleName}"}{
}
"""
fun generateRole(name: String) = """import uk.co.nickthecoder.tickle.*
import uk.co.nickthecoder.tickle.resources.*
class $name extends AbstractRole {
// NOTE. Some common methods were automatically generated.
// These may be removed if you don't need them.
void begin() {
}
void activated() {
}
// tick is called 60 times per second (a Role MUST have a tick method).
void tick() {
}
}
"""
fun generateDirector(name: String) = """import uk.co.nickthecoder.tickle.*
import uk.co.nickthecoder.tickle.resources.*
import uk.co.nickthecoder.tickle.events.*
class $name extends AbstractDirector {
// NOTE. Some common methods were automatically generated.
// These may be removed if you don't need them.
void sceneLoaded() {
}
void begin() {
}
void activated() {
}
void onKey(KeyEvent event) {
}
void onMouseButton(MouseEvent event) {
}
}
"""
fun generateProducer(name: String) = """import uk.co.nickthecoder.tickle.*
import uk.co.nickthecoder.tickle.resources.*
import uk.co.nickthecoder.tickle.events.*
class $name extends AbstractProducer {
// NOTE. Some common methods were automatically generated.
// These may be removed if you don't need them.
void begin() {
}
void sceneLoaded() {
}
void sceneBegin() {
}
void sceneEnd() {
}
void sceneActivated() {
}
void tick() {
}
void onKey(KeyEvent event) {
}
void onMouseButton(MouseEvent event) {
}
}
"""
companion object {
private val messagePattern = Pattern.compile("file\\:(?<FILE>.*?\\.groovy)|line (?<LINE>\\d*), column (?<COLUMN>\\d*)")
fun convertException(e: GroovyRuntimeException): ScriptException {
var message = e.message ?: return ScriptException(e)
val matcher = messagePattern.matcher(message)
var file: File? = null
var line: Int? = null
var column: Int? = null
while (matcher.find()) {
matcher.group("FILE")?.let { file = File(it) }
matcher.group("LINE")?.let { line = it.toInt() }
matcher.group("COLUMN")?.let {
column = it.toInt()
message = message.substring(0, matcher.end())
}
}
message = message.removePrefix("startup failed:\n")
return ScriptException(message, e, file, line, column)
}
}
}
| tickle-groovy/src/main/kotlin/uk/co/nickthecoder/tickle/groovy/GroovyLanguage.kt | 1888628469 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.constraintlayout
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.fragment.app.DialogFragment
import java.util.*
private const val LOREM_IPSUM_LONG = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
/**
* A SIMPLIFIED/minimalist version of the problem I am encountering.
* Contains a [ConstraintLayout] with two sections:
* 1. textSection: Section for the text. THIS SECTION KEEPS GETTING UNDESIRABLY CROPPED
* - When increasing font-size of the device, such that the content gets bigger than the screen,
* I would have this section scrollable (currently leaving scroll out for simplicity)
* 2. buttonSection: Section for sticky buttons anchored to the bottom of the dialog
* - When increasing font-size of the device, such that the content gets bigger than the screen,
* I want this section to stick to the bottom (as opposed to be scrollable)
* (In my real example, there are more items in each section. Hence, the use of [Box])
*/
@Preview(widthDp = 270, heightDp = 320, backgroundColor = 0xFFFFFF, showBackground = true)
@Composable
fun TestDialogContent() {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
val (textSection, buttonSection) = createRefs()
Column(
modifier = Modifier.constrainAs(textSection) {
top.linkTo(parent.top, margin = 48.dp)
bottom.linkTo(buttonSection.top, margin = 16.dp)
start.linkTo(parent.start, margin = 24.dp)
end.linkTo(parent.end, margin = 24.dp)
width = Dimension.matchParent
/**
* I want this to wrap the height of the entire [Text]
* Instead, I'm only seeing a cropped section of the [Text]
* I've also tried:
* - Dimension.preferredWrapContent.atLeastWrapContent
* - Dimension.fillToConstraints.atLeastWrapContent
* - Dimension.preferredWrapContent
*/
height = Dimension.preferredWrapContent
}
) {
Text(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
text = "Lorem ipsum dolor sit amet",
style = MaterialTheme.typography.h5,
color = Color.Gray,
fontWeight = FontWeight.Medium,
)
Spacer(Modifier.height(8.dp))
Text(
text = LOREM_IPSUM_LONG,
style = MaterialTheme.typography.body2,
color = Color.Gray
)
}
Box(
modifier = Modifier.constrainAs(buttonSection) {
bottom.linkTo(parent.bottom, margin = 48.dp)
start.linkTo(parent.start, margin = 24.dp)
end.linkTo(parent.end, margin = 24.dp)
width = Dimension.matchParent
height = Dimension.wrapContent
}
) {
Button(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
onClick = { },
shape = RoundedCornerShape(30.dp),
contentPadding = PaddingValues(horizontal = 24.dp, vertical = 14.dp),
) {
Text(text = "BUTTON", textAlign = TextAlign.Center)
}
}
}
}
| projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/Bug01Composable.kt | 1425529804 |
package cz.jacktech.gugorganizer.ui.util
import android.support.v4.app.Fragment
import cz.jacktech.gugorganizer.ui.MainActivity
/**
* Created by toor on 13.8.15.
*/
public open class MainActivityFragment : Fragment() {
protected fun activity(): MainActivity {
return getActivity() as MainActivity
}
}
| app/src/main/java/cz/jacktech/gugorganizer/ui/util/MainActivityFragment.kt | 550200859 |
//
// Calendar Notifications Plus
// Copyright (C) 2017 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.monitorstorage
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.github.quarck.calnotify.calendar.MonitorEventAlertEntry
import com.github.quarck.calnotify.logs.DevLog
//import com.github.quarck.calnotify.logs.Logger
import java.io.Closeable
class MonitorStorage(val context: Context)
: SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_CURRENT_VERSION), Closeable, MonitorStorageInterface {
private var impl: MonitorStorageImplInterface
init {
impl = MonitorStorageImplV1(context);
}
override fun onCreate(db: SQLiteDatabase)
= impl.createDb(db)
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
DevLog.info(LOG_TAG, "onUpgrade $oldVersion -> $newVersion")
if (oldVersion != newVersion) {
throw Exception("DB storage error: upgrade from $oldVersion to $newVersion is not supported")
}
}
override fun addAlert(entry: MonitorEventAlertEntry)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.addAlert(it, entry) } }
override fun addAlerts(entries: Collection<MonitorEventAlertEntry>)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.addAlerts(it, entries) } }
override fun deleteAlert(entry: MonitorEventAlertEntry)
= deleteAlert(entry.eventId, entry.alertTime, entry.instanceStartTime)
override fun deleteAlerts(entries: Collection<MonitorEventAlertEntry>)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlerts(it, entries) } }
override fun deleteAlert(eventId: Long, alertTime: Long, instanceStart: Long)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlert(it, eventId, alertTime, instanceStart) } }
override fun deleteAlertsMatching(filter: (MonitorEventAlertEntry) -> Boolean)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlertsMatching(it, filter) } }
override fun updateAlert(entry: MonitorEventAlertEntry)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.updateAlert(it, entry) } }
override fun updateAlerts(entries: Collection<MonitorEventAlertEntry>)
= synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.updateAlerts(it, entries) } }
override fun getAlert(eventId: Long, alertTime: Long, instanceStart: Long): MonitorEventAlertEntry?
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlert(it, eventId, alertTime, instanceStart) } }
override fun getInstanceAlerts(eventId: Long, instanceStart: Long): List<MonitorEventAlertEntry>
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getInstanceAlerts(it, eventId, instanceStart) } }
override fun getNextAlert(since: Long): Long?
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getNextAlert(it, since) } }
override fun getAlertsAt(time: Long): List<MonitorEventAlertEntry>
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsAt(it, time) } }
override val alerts: List<MonitorEventAlertEntry>
get() = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlerts(it) } }
override fun getAlertsForInstanceStartRange(scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry>
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsForInstanceStartRange(it, scanFrom, scanTo) } }
override fun getAlertsForAlertRange(scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry>
= synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsForAlertRange(it, scanFrom, scanTo) } }
companion object {
private const val LOG_TAG = "MonitorStorage"
private const val DATABASE_VERSION_V1 = 1
private const val DATABASE_CURRENT_VERSION = DATABASE_VERSION_V1
private const val DATABASE_NAME = "CalendarMonitor"
}
} | app/src/main/java/com/github/quarck/calnotify/monitorstorage/MonitorStorage.kt | 4012198326 |
package org.luxons.sevenwonders.model.boards
import kotlinx.serialization.Serializable
import org.luxons.sevenwonders.model.cards.TableCard
import org.luxons.sevenwonders.model.resources.CountedResource
import org.luxons.sevenwonders.model.resources.ResourceType
import org.luxons.sevenwonders.model.wonders.ApiWonder
@Serializable
data class Board(
val playerIndex: Int,
val wonder: ApiWonder,
val production: Production,
val publicProduction: Production,
val science: Science,
val military: Military,
val playedCards: List<List<TableCard>>,
val gold: Int,
val bluePoints: Int,
val canPlayAnyCardForFree: Boolean,
)
@Serializable
data class Requirements(
val gold: Int = 0,
val resources: List<CountedResource> = emptyList(),
)
@Serializable
data class Production(
val fixedResources: List<CountedResource>,
val alternativeResources: List<Set<ResourceType>>,
)
@Serializable
data class Military(
val nbShields: Int,
val victoryPoints: Int,
val totalPoints: Int,
val nbDefeatTokens: Int,
)
@Serializable
data class Science(
val jokers: Int,
val nbWheels: Int,
val nbCompasses: Int,
val nbTablets: Int,
)
| sw-common-model/src/commonMain/kotlin/org/luxons/sevenwonders/model/boards/Boards.kt | 4233837534 |
package net.perfectdreams.loritta.cinnamon.showtime.frontend.utils
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.coroutines.sync.withLock
import kotlinx.dom.removeClass
import net.perfectdreams.loritta.cinnamon.showtime.frontend.ShowtimeFrontend
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.onClick
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.select
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.selectAll
import org.w3c.dom.Element
import org.w3c.dom.HTMLBodyElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLTitleElement
import org.w3c.dom.asList
import org.w3c.dom.url.URL
class LinkPreloaderManager(val showtime: ShowtimeFrontend) {
companion object {
private const val PRELOAD_LINK_ATTRIBUTE = "data-preload-link"
private const val PRELOAD_LINK_ACTIVE_ATTRIBUTE = "data-preload-link-activated"
private const val PRELOAD_PERSIST_ATTRIBUTE = "data-preload-persist"
private const val PRELOAD_KEEP_SCROLL = "data-preload-keep-scroll"
}
fun setupLinkPreloader() {
println("Setting up link preloader")
document.querySelectorAll("a[$PRELOAD_LINK_ATTRIBUTE=\"true\"]:not([$PRELOAD_LINK_ACTIVE_ATTRIBUTE=\"true\"])")
.asList().forEach {
if (it is Element) {
setupLinkPreloader(it)
}
}
}
fun setupLinkPreloader(element: Element) {
val location = document.location ?: return // I wonder when location can be null...
var pageUrl = element.getAttribute("href")!!
if (pageUrl.startsWith("http")) {
if (!pageUrl.startsWith(window.location.origin)) // Mesmo que seja no mesmo domínio, existe as políticas de CORS
return
val urlLocation = URL(pageUrl)
pageUrl = urlLocation.pathname
}
element.setAttribute(PRELOAD_LINK_ACTIVE_ATTRIBUTE, "true")
element.onClick { it ->
println("Clicked!!! $pageUrl")
val body = document.body ?: return@onClick // If we don't have a body, what we will switch to?
if (it.asDynamic().ctrlKey as Boolean || it.asDynamic().metaKey as Boolean || it.asDynamic().shiftKey as Boolean)
return@onClick
it.preventDefault()
// Same page, no need to redirect
/* if (pageUrl == window.location.pathname)
return@onClick */
println("Going to load $pageUrl")
showtime.launchGlobal {
// Close navbar if it is open, this avoids the user clicking on something and wondering "but where is the new content?"
val navbar = document.select<Element?>("#navigation-bar")
navbar?.removeClass("expanded")
document.body!!.style.overflowY = ""
// Start progress indicator
showtime.startFakeProgressIndicator()
// First prepare the page preload, this is useful so the page can preload data (do queries, as an example) before we totally switch
val preparePreLoadJob = showtime.async { showtime.viewManager.preparePreLoad(pageUrl) }
// Switch page
// We need to rebuild the URL from scratch, if we just do a "pageUrl" request, it won't add the port for some reason
val content = ShowtimeFrontend.http.get(location.protocol + "//" + location.host + pageUrl) {
header("Link-Preload", true)
}
println("Content:")
println(content)
// Find all persistent elements in the old page
val persistentElements = document.selectAll<HTMLElement>("[$PRELOAD_PERSIST_ATTRIBUTE=\"true\"]")
// Find all keep scroll elements in the old page
// The values needs to be stored before switching, if not the value will be "0"
val keepScrollElements = document.selectAll<HTMLElement>("[$PRELOAD_KEEP_SCROLL=\"true\"]")
.map { it.id to it.scrollTop }
// We need to create a dummy element to append our inner HTML
val dummyElement = document.createElement("html")
dummyElement.innerHTML = content.bodyAsText()
// Await until preLoad is done to continue
preparePreLoadJob.await()
// We are now going to reuse the mutex in the pageManager
// The reason we reuse it is to avoid calling "onLoad()" before "onPreLoad()" is finished! :3
showtime.viewManager.preparingMutex.withLock {
// Replace the page's title
dummyElement.select<HTMLTitleElement?>("title")?.let {
println("Page title is ${it.outerHTML}")
document.select<HTMLTitleElement?>("title")?.outerHTML = it.outerHTML
}
// Switch the page's content (not all, just the body xoxo)
body.innerHTML = dummyElement.select<HTMLBodyElement?>("body")?.innerHTML ?: "Broken!"
// Push the current page to history
showtime.pushState(pageUrl)
// Now copy the persistent elements
persistentElements.forEach {
val newElementThatShouldBeReplaced = document.getElementById(it.id) as HTMLElement?
println("Persisted element $it is going to persist thru $newElementThatShouldBeReplaced")
newElementThatShouldBeReplaced?.replaceWith(it)
}
// Also copy the keep scroll of the affected elements
keepScrollElements.forEach {
val newElementThatShouldChangeTheScroll = document.getElementById(it.first) as HTMLElement?
println("Keeping element $it scroll, value: ${it.second}")
newElementThatShouldChangeTheScroll?.scrollTop = it.second
}
// Now that all of the elements are loaded, we can switch from the preparing to the active view
showtime.viewManager.switchPreparingToActiveView()
// Reset scroll to the top of the page
window.scrollTo(0.0, 0.0)
// remove visible class and set progress bar to 100%
showtime.stopFakeProgressIndicator()
// Setup link preloader again
setupLinkPreloader()
// Also setup ads
NitroPayUtils.renderAds()
}
}
}
}
} | web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/utils/LinkPreloaderManager.kt | 2399143620 |
package de.maibornwolff.codecharta.serialization
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import de.maibornwolff.codecharta.model.ProjectWrapper
import java.lang.reflect.Type
class ProjectWrapperJsonDeserializer : JsonDeserializer<ProjectWrapper> {
override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext): ProjectWrapper {
val projectJsonDeserializer = ProjectJsonDeserializer()
val jsonObject = json.asJsonObject
val data = jsonObject.get("data")
val checksum = jsonObject.get("checksum")
return if (data != null && checksum != null) {
val project = projectJsonDeserializer.deserialize(data, typeOfT, context)
ProjectWrapper(project, data.toString())
} else {
val project = projectJsonDeserializer.deserialize(json, typeOfT, context)
ProjectWrapper(project, json.toString())
}
}
}
| analysis/model/src/main/kotlin/de/maibornwolff/codecharta/serialization/ProjectWrapperJsonDeserializer.kt | 41227614 |
package za.co.dvt.android.showcase.ui.contact
import android.arch.lifecycle.ViewModel
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import za.co.dvt.android.showcase.injection.ShowcaseComponent
import za.co.dvt.android.showcase.model.Office
import za.co.dvt.android.showcase.repository.OfficesRepository
import za.co.dvt.android.showcase.repository.TrackingRepository
import za.co.dvt.android.showcase.utils.SingleLiveEvent
import javax.inject.Inject
/**
* @author rebeccafranks
* @since 2017/06/25.
*/
class ContactUsViewModel : ViewModel(), ShowcaseComponent.Injectable {
override fun inject(component: ShowcaseComponent) {
component.inject(this)
}
@Inject
lateinit var officesRepository: OfficesRepository
fun getOffices(): Flowable<List<Office>> = officesRepository.getOffices()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
@Inject
lateinit var trackingRepository: TrackingRepository
val openEmail: SingleLiveEvent<Office> = SingleLiveEvent()
val openCall: SingleLiveEvent<Office> = SingleLiveEvent()
val openNavigate: SingleLiveEvent<Office> = SingleLiveEvent()
fun openEmail(office: Office) {
trackingRepository.trackEmailOffice(office)
openEmail.value = office
}
fun openCall(office: Office) {
trackingRepository.trackCallOffice(office)
openCall.value = office
}
fun openNavigation(office: Office) {
trackingRepository.trackNavigationOffice(office)
openNavigate.value = office
}
} | app/src/main/kotlin/za/co/dvt/android/showcase/ui/contact/ContactUsViewModel.kt | 1888625233 |
/*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myflightbook.android.webservices
import android.content.Context
import org.ksoap2.serialization.SoapSerializationEnvelope
import model.MFBImageInfo
import model.LatLong
import com.myflightbook.android.marshal.MarshalDouble
class ImagesSvc : MFBSoap(), Runnable {
private var mContext: Context? = null
override fun addMappings(e: SoapSerializationEnvelope) {
e.addMapping(NAMESPACE, "MFBImageInfo", MFBImageInfo::class.java)
e.addMapping(NAMESPACE, "LatLong", LatLong::class.java)
val md = MarshalDouble()
md.register(e)
}
override fun run() {
invoke(mContext)
}
fun deleteImage(szAuthToken: String?, mfbii: MFBImageInfo?, c: Context?) {
val request = setMethod("DeleteImage")
request.addProperty("szAuthUserToken", szAuthToken)
request.addProperty("mfbii", mfbii)
mContext = c
Thread(this).start()
}
fun updateImageAnnotation(szAuthToken: String?, mfbii: MFBImageInfo?, c: Context?) {
val request = setMethod("UpdateImageAnnotation")
request.addProperty("szAuthUserToken", szAuthToken)
request.addProperty("mfbii", mfbii)
mContext = c
Thread(this).start()
}
} | app/src/main/java/com/myflightbook/android/webservices/ImagesSvc.kt | 1592087178 |
package uy.kohesive.keplin.kotlin.script.jsr223
import uy.kohesive.keplin.kotlin.script.jsr223.core.AbstractEngineFactory
import javax.script.ScriptEngine
open class EvalOnlyJsr223ReplEngineFactory : AbstractEngineFactory() {
override fun getScriptEngine(): ScriptEngine {
return EvalOnlyJsr223ReplEngine(this).apply { fixupArgsForScriptTemplate() }
}
override fun getEngineName(): String = "Kotlin Eval-Only Scripting Engine"
override fun getNames(): List<String> = listOf(jsr223EngineName)
override fun getThreadingModel(): String = "MULTITHREADED"
companion object {
val jsr223EngineName = EvalOnlyJsr223ReplEngine.jsr223EngineName
}
} | keplin-jsr223-kotlin-engine/src/main/kotlin/uy/kohesive/keplin/kotlin/script/jsr223/EvalOnlyJsr223ReplEngineFactory.kt | 1883694655 |
package i_introduction._7_Nullable_Types
import util.TODO
import util.doc7
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0
}
fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO(
"""
Task 7.
Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression.
Declarations of Client, PersonalInfo and Mailer are given below.
""",
documentation = doc7(),
references = { JavaCode7().sendMessageToClient(client, message, mailer) }
)
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
val email = client?.personalInfo?.email ?: return
if (message == null) {
return
}
mailer.sendMessage(email, message)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
| src/i_introduction/_7_Nullable_Types/NullableTypes.kt | 2075828761 |
@file:Suppress("unused")
package at.cpickl.gadsu.tcm.model
enum class YinYang(val label: String) {
Yin("Yin"),
Yang("Yang")
}
enum class YinYangMiddle(val label: String, val yy: YinYang?) {
Yin(YinYang.Yin.label, YinYang.Yin),
Yang(YinYang.Yang.label, YinYang.Yang),
Middle("Mitte", null)
}
enum class YinYangSize(val labelChinese: String) {
Lesser("Shao"),
Greater("Tai"),
Bright("Ming"),
Terminal("Jue")
}
// https://en.wikipedia.org/wiki/Six_levels
enum class YinYangLevel(val labelChinese: String, val yy: YinYang, val size: YinYangSize) {
GreaterYin("Tai Yin", YinYang.Yin, YinYangSize.Greater),
LesserYin("Shao Yin", YinYang.Yin, YinYangSize.Lesser),
TerminalYin("Jue Yin", YinYang.Yin, YinYangSize.Terminal),
GreaterYang("Tai Yang", YinYang.Yang, YinYangSize.Greater),
BrightYang("Yang Ming", YinYang.Yang, YinYangSize.Bright),
LesserYang("Shao Yang", YinYang.Yang, YinYangSize.Lesser)
}
enum class YinYangDetailMiddle(val yy: YinYangLevel?) {
YinBig(YinYangLevel.GreaterYin),
YinSmall(YinYangLevel.LesserYin),
YangBig(YinYangLevel.GreaterYang),
YangSmall(YinYangLevel.LesserYang),
Middle(null),
}
| src/main/kotlin/at/cpickl/gadsu/tcm/model/yinyang.kt | 3827765841 |
package com.kazakago.preferhythm
/**
* Annotation of Preferences ModelField.
*
* Created by KazaKago on 2017/03/08.
*/
@Target(AnnotationTarget.FIELD)
annotation class PrefField(val value: String = "") | annotations/src/main/java/com/kazakago/preferhythm/PrefField.kt | 4261679704 |
package io.kotest.assertions.arrow.either
import arrow.core.Either
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.beInstanceOf2
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@UseExperimental(ExperimentalContracts::class)
fun <T> Either<*, T>.shouldBeRight() {
contract {
returns() implies (this@shouldBeRight is Either.Right<*>)
}
this should beRight()
}
fun <T> Either<Any?, T>.shouldNotBeRight() = this shouldNot beRight()
fun <T> beRight() = beInstanceOf2<Either<Any?, T>, Either.Right<T>>()
inline infix fun <B> Either<*, B>.shouldBeRight(fn: (B) -> Unit) {
this should beRight()
fn((this as Either.Right<B>).b)
}
infix fun <B> Either<Any?, B>.shouldBeRight(b: B) = this should beRight(b)
infix fun <B> Either<Any?, B>.shouldNotBeRight(b: B) = this shouldNot beRight(b)
fun <B> beRight(b: B) = object : Matcher<Either<Any?, B>> {
override fun test(value: Either<Any?, B>): MatcherResult {
return when (value) {
is Either.Left -> {
MatcherResult(false, "Either should be Right($b) but was Left(${value.a})", "Either should not be Right($b)")
}
is Either.Right -> {
if (value.b == b)
MatcherResult(true, "Either should be Right($b)", "Either should not be Right($b)")
else
MatcherResult(false, "Either should be Right($b) but was Right(${value.b})", "Either should not be Right($b)")
}
}
}
}
@UseExperimental(ExperimentalContracts::class)
fun <T> Either<T, Any?>.shouldBeLeft() {
contract {
returns() implies (this@shouldBeLeft is Either.Left<*>)
}
this should beLeft()
}
fun <T> Either<T, Any?>.shouldNotBeLeft() = this shouldNot beLeft()
fun <T> beLeft() = beInstanceOf2<Either<T, Any?>, Either.Left<T>>()
inline infix fun <A> Either<A, *>.shouldBeLeft(fn: (A) -> Unit) {
this should beLeft()
fn((this as Either.Left<A>).a)
}
infix fun <A> Either<A, Any?>.shouldBeLeft(a: A) = this should beLeft(a)
infix fun <A> Either<A, Any?>.shouldNotBeLeft(a: A) = this shouldNot beLeft(a)
fun <A> beLeft(a: A) = object : Matcher<Either<A, Any?>> {
override fun test(value: Either<A, Any?>): MatcherResult {
return when (value) {
is Either.Right -> {
MatcherResult(false, "Either should be Left($a) but was Right(${value.b})", "Either should not be Right($a)")
}
is Either.Left -> {
if (value.a == a)
MatcherResult(true, "Either should be Left($a)", "Either should not be Left($a)")
else
MatcherResult(false, "Either should be Left($a) but was Left(${value.a})", "Either should not be Right($a)")
}
}
}
}
inline fun <reified A> Either<Any?, Any?>.shouldBeLeftOfType() = this should beLeftOfType<A>()
inline fun <reified A> Either<Any?, Any?>.shouldNotBeLeftOfType() = this shouldNot beLeftOfType<A>()
inline fun <reified A> beLeftOfType() = object : Matcher<Either<Any?, Any?>> {
override fun test(value: Either<Any?, Any?>): MatcherResult {
return when (value) {
is Either.Right -> {
MatcherResult(false, "Either should be Left<${A::class.qualifiedName}> but was Right(${value.b})", "")
}
is Either.Left -> {
val valueA = value.a
if (valueA is A)
MatcherResult(true, "Either should be Left<${A::class.qualifiedName}>", "Either should not be Left")
else
MatcherResult(false,
"Either should be Left<${A::class.qualifiedName}> but was Left<${if (valueA == null) "Null" else valueA::class.qualifiedName}>",
"Either should not be Left")
}
}
}
}
| kotest-assertions/kotest-assertions-arrow/src/jvmMain/kotlin/io/kotest/assertions/arrow/either/matchers.kt | 600831052 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.samples.dynamicfeatures
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import com.google.android.play.core.splitcompat.SplitCompat
import java.util.Locale
/** We have to use a custom Application class, because we want to
* initialize the selected language before SplitCompat#install() has a chance to run.
*/
class MyApplication : Application() {
override fun attachBaseContext(base: Context) {
LanguageHelper.init(base)
val ctx = LanguageHelper.getLanguageConfigurationContext(base)
super.attachBaseContext(ctx)
SplitCompat.install(this)
}
}
internal const val LANG_EN = "en"
internal const val LANG_PL = "pl"
private const val PREFS_LANG = "language"
/**
* A singleton helper for storing and retrieving the user selected language in a
* SharedPreferences instance. It is required for persisting the user language choice between
* application restarts.
*/
object LanguageHelper {
lateinit var prefs: SharedPreferences
var language: String
get() {
return prefs.getString(PREFS_LANG, LANG_EN)!!
}
set(value) {
prefs.edit().putString(PREFS_LANG, value).apply()
}
fun init(ctx: Context) {
prefs = ctx.getSharedPreferences(PREFS_LANG, Context.MODE_PRIVATE)
}
/**
* Get a Context that overrides the language selection in the Configuration instance used by
* getResources() and getAssets() by one that is stored in the LanguageHelper preferences.
*
* @param ctx a base context to base the new context on
*/
fun getLanguageConfigurationContext(ctx: Context): Context {
val conf = getLanguageConfiguration()
return ctx.createConfigurationContext(conf)
}
/**
* Get an empty Configuration instance that only sets the language that is
* stored in the LanguageHelper preferences.
* For use with Context#createConfigurationContext or Activity#applyOverrideConfiguration().
*/
fun getLanguageConfiguration(): Configuration {
val conf = Configuration()
conf.setLocale(Locale.forLanguageTag(language))
return conf
}
}
| DynamicFeatures/app/src/main/java/com/google/android/samples/dynamicfeatures/MyApplication.kt | 3196033974 |
package me.giacoppo.examples.kotlin.mvp.repository.interactor.executor
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
class JobExecutor private constructor() : ThreadExecutor {
private val INITIAL_POOL_SIZE = 3
private val MAX_POOL_SIZE = 5
private val KEEP_ALIVE_TIME = 10
private val KEEP_ALIVE_TIME_UNIT: TimeUnit = TimeUnit.SECONDS
private val threadPoolExecutor: ThreadPoolExecutor
private object Holder {
val instance: JobExecutor = JobExecutor()
}
companion object {
val instance: JobExecutor by lazy { Holder.instance }
}
init {
val workQueue : BlockingQueue<Runnable> = LinkedBlockingQueue()
threadPoolExecutor = ThreadPoolExecutor(INITIAL_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME.toLong(),KEEP_ALIVE_TIME_UNIT,workQueue)
}
override fun execute(runnable: Runnable) {
this.threadPoolExecutor.execute(runnable)
}
} | core/src/main/java/me/giacoppo/examples/kotlin/mvp/repository/interactor/executor/JobExecutor.kt | 1410522308 |
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.template.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.util.template.*
import java.net.*
import javax.inject.*
/**
* Lets the user browser another Sone.
*/
@TemplatePath("/templates/viewSone.html")
@ToadletPath("viewSone.html")
class ViewSonePage @Inject constructor(webInterface: WebInterface, loaders: Loaders, templateRenderer: TemplateRenderer) :
SoneTemplatePage(webInterface, loaders, templateRenderer) {
override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) {
templateContext["soneId"] = soneRequest.parameters["sone"]
soneRequest.parameters["sone"]!!.let(soneRequest.core::getSone)?.let { sone ->
templateContext["sone"] = sone
val sonePosts = sone.posts
val directedPosts = soneRequest.core.getDirectedPosts(sone.id)
(sonePosts + directedPosts)
.sortedByDescending(Post::getTime)
.paginate(soneRequest.core.preferences.postsPerPage)
.apply { page = soneRequest.parameters["postPage"]?.toIntOrNull() ?: 0 }
.also {
templateContext["postPagination"] = it
templateContext["posts"] = it.items
}
sone.replies
.mapPresent(PostReply::getPost)
.distinct()
.minus(sonePosts)
.minus(directedPosts)
.sortedByDescending { soneRequest.core.getReplies(it.id).first().time }
.paginate(soneRequest.core.preferences.postsPerPage)
.apply { page = soneRequest.parameters["repliedPostPage"]?.toIntOrNull() ?: 0 }
.also {
templateContext["repliedPostPagination"] = it
templateContext["repliedPosts"] = it.items
}
}
}
override fun isLinkExcepted(link: URI) = true
override fun getPageTitle(soneRequest: SoneRequest): String =
soneRequest.parameters["sone"]!!.let(soneRequest.core::getSone)?.let { sone ->
"${SoneAccessor.getNiceName(sone)} - ${translation.translate("Page.ViewSone.Title")}"
} ?: translation.translate("Page.ViewSone.Page.TitleWithoutSone")
}
| src/main/kotlin/net/pterodactylus/sone/web/pages/ViewSonePage.kt | 3424980613 |
/*
* Copyright @ 2018 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj
enum class Features {
TRANSCEIVER_PCAP_DUMP
}
| jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/Features.kt | 4260034704 |
package com.myapp.domain
import com.myapp.generated.tables.records.UserStatsRecord
data class UserStats(
val micropostCnt: Long,
val followingCnt: Long,
val followerCnt: Long
) {
constructor(record: UserStatsRecord) : this(
micropostCnt = record.micropostCnt,
followerCnt = record.followerCnt,
followingCnt = record.followingCnt
)
} | src/main/kotlin/com/myapp/domain/UserStats.kt | 1041953888 |
package com.myapp.service
import com.myapp.domain.Micropost
import com.myapp.dto.request.PageParams
interface FeedService {
fun findFeed(pageParams: PageParams): List<Micropost>
}
| src/main/kotlin/com/myapp/service/FeedService.kt | 3467764767 |
/*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.ktp
import com.nhaarman.mockitokotlin2.mock
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldNotBe
import org.amshove.kluent.shouldNotBeNull
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import toothpick.Toothpick
import toothpick.configuration.Configuration
import toothpick.configuration.ConfigurationHolder
class KTPTest {
@AfterEach
fun tearDown() {
KTP.reset()
}
@Test
fun `openRootScope should open default root scope`() {
// GIVEN
KTP.isRootScopeOpen().shouldBeFalse()
// WHEN
val scope = KTP.openRootScope()
// THEN
scope.shouldNotBeNull()
KTP.isRootScopeOpen().shouldBeTrue()
}
@Test
fun `openRootScope should open default root scope with a scope config`() {
// GIVEN
var configApplied = false
// WHEN
val scope = KTP.openRootScope { configApplied = true }
// THEN
scope.shouldNotBeNull()
KTP.isRootScopeOpen().shouldBeTrue()
configApplied.shouldBeTrue()
}
@Test
fun `openScope should open scope`() {
// GIVEN
Toothpick.isScopeOpen("name").shouldBeFalse()
// WHEN
val scope = KTP.openScope("name")
// THEN
scope.name shouldEqual "name"
Toothpick.isScopeOpen("name").shouldBeTrue()
KTP.isScopeOpen("name").shouldBeTrue()
}
@Test
fun `openScope should open scope with a scope config`() {
// GIVEN
Toothpick.isScopeOpen("name").shouldBeFalse()
var configApplied = false
// WHEN
val scope = KTP.openScope("name") { configApplied = true }
// THEN
scope.name shouldEqual "name"
Toothpick.isScopeOpen("name").shouldBeTrue()
KTP.isScopeOpen("name").shouldBeTrue()
configApplied.shouldBeTrue()
}
@Test
fun `openScopes should open scopes and child scope`() {
// GIVEN
Toothpick.isScopeOpen("parent").shouldBeFalse()
Toothpick.isScopeOpen("child").shouldBeFalse()
// WHEN
val scope = KTP.openScopes("parent", "child")
// THEN
scope.name shouldEqual "child"
Toothpick.isScopeOpen("parent").shouldBeTrue()
KTP.isScopeOpen("parent").shouldBeTrue()
Toothpick.isScopeOpen("child").shouldBeTrue()
KTP.isScopeOpen("child").shouldBeTrue()
}
@Test
fun `closeScope should close scope`() {
// GIVEN
Toothpick.openScope("name")
Toothpick.isScopeOpen("name").shouldBeTrue()
// WHEN
KTP.closeScope("name")
// THEN
Toothpick.isScopeOpen("name").shouldBeFalse()
}
@Test
fun `isScopeOpen should return true when scope is open`() {
// GIVEN
Toothpick.openScope("name")
Toothpick.isScopeOpen("name").shouldBeTrue()
// THEN
KTP.isScopeOpen("name").shouldBeTrue()
}
@Test
fun `isScopeOpen should return false when scope is closed`() {
// GIVEN
Toothpick.isScopeOpen("name").shouldBeFalse()
// THEN
KTP.isScopeOpen("name").shouldBeFalse()
}
@Test
fun `setConfiguration should set the configuration`() {
// GIVEN
val configuration: Configuration = mock()
ConfigurationHolder.configuration shouldNotBe configuration
// WHEN
KTP.setConfiguration(configuration)
// THEN
ConfigurationHolder.configuration shouldBe configuration
}
}
| ktp/src/test/kotlin/toothpick/ktp/KTPTest.kt | 2279685200 |
import Json.*
fun main(args: Array<String>) {
//kotlin¿¡¼ °´Ã¼ ¼±¾ðÇϰí ÇÔ¼ö È£ÃâÇÏ´Â Çü½ÄÀÌ ÀÌ¿Í °°³ª
var jobj = JsonObject()
jobj.add("õÁ¤ÇÊ", 29)
jobj.add("½ÉÇö¿ì", 30)
println("json array serialize ==> ${jobj.toJsonString()}")
var jobj3 = JsonObject()
jobj3.add("À̵¿¿ì", 99)
var jobj2 = JsonObject()
jobj2.add("idiots", jobj)
jobj2.add("genius", jobj3)
jobj2.add("null test", null)
println("nested json object serialize ==> ${jobj2.toJsonString()}")
var jarr = JsonArray()
jarr.add(123)
jarr.add("asd")
jarr.add(0.323)
jarr.add(true)
println("json array serialize ==> ${jarr.toJsonString()}")
var parser: JsonParser = JsonParser()
var parsedJobj: JsonObject = parser.parse(jobj2.toJsonString()) as JsonObject
var geniusJobj: JsonObject? = parsedJobj.get("genius")?.asObject()
var parsedJarr: JsonArray = parser.parse(jarr.toJsonString()) as JsonArray
println("json object deserialize input jsonstr : ${jobj2.toJsonString()} parsedJobj : ${parsedJobj.toJsonString()} genius : ==> ${geniusJobj?.toJsonString()}")
} | JsonParser/src/main.kt | 4158978034 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.extensions
import org.gradle.internal.Cast
internal
fun <T> Any.uncheckedCast(): T =
Cast.uncheckedNonnullCast(this)
| subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/extensions/CastExtensions.kt | 437153666 |
@file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.preference
import androidx.annotation.CheckResult
import androidx.preference.Preference
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of change events on the [Preference] instance
* where the value emitted is the new value of the [Preference].
*
* Note: Created flow keeps a strong reference to the [Preference] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* preference.preferenceClicks()
* .onEach { value ->
* // handle value
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun Preference.preferenceChanges(): Flow<Any> = callbackFlow {
checkMainThread()
val listener = Preference.OnPreferenceChangeListener { _, newValue ->
trySend(newValue)
true
}
onPreferenceChangeListener = listener
awaitClose { onPreferenceChangeListener = null }
}.conflate()
| flowbinding-preference/src/main/java/reactivecircus/flowbinding/preference/PreferenceChangedFlow.kt | 2182911526 |
package de.ph1b.audiobook.features.bookOverview
import androidx.datastore.core.DataStore
import de.paulwoitaschek.flowpref.Pref
import de.ph1b.audiobook.common.pref.CurrentBook
import de.ph1b.audiobook.common.pref.PrefKeys
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.data.repo.BookRepo2
import de.ph1b.audiobook.features.bookOverview.list.BookOverviewViewState
import de.ph1b.audiobook.features.bookOverview.list.header.BookOverviewCategory
import de.ph1b.audiobook.features.gridCount.GridCount
import de.ph1b.audiobook.playback.PlayerController
import de.ph1b.audiobook.playback.playstate.PlayStateManager
import de.ph1b.audiobook.playback.playstate.PlayStateManager.PlayState
import de.ph1b.audiobook.scanner.MediaScanTrigger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Named
class BookOverviewViewModel
@Inject
constructor(
private val repo: BookRepo2,
private val mediaScanner: MediaScanTrigger,
private val playStateManager: PlayStateManager,
private val playerController: PlayerController,
@CurrentBook
private val currentBookDataStore: DataStore<Book2.Id?>,
@Named(PrefKeys.GRID_MODE)
private val gridModePref: Pref<GridMode>,
private val gridCount: GridCount,
) {
fun attach() {
mediaScanner.scan()
}
fun useGrid(useGrid: Boolean) {
gridModePref.value = if (useGrid) GridMode.GRID else GridMode.LIST
}
fun state(): Flow<BookOverviewState> {
val playingStream = playStateManager.playStateFlow()
.map { it == PlayState.Playing }
.distinctUntilChanged()
return combine(
repo.flow(),
currentBookDataStore.data,
playingStream,
mediaScanner.scannerActive,
gridModePref.flow
) { books, currentBookId, playing, scannerActive, gridMode ->
state(
books = books,
scannerActive = scannerActive,
currentBookId = currentBookId,
playing = playing,
gridMode = gridMode
)
}
}
private fun state(
books: List<Book2>,
scannerActive: Boolean,
currentBookId: Book2.Id?,
playing: Boolean,
gridMode: GridMode
): BookOverviewState {
if (books.isEmpty()) {
return if (scannerActive) {
BookOverviewState.Loading
} else {
BookOverviewState.NoFolderSet
}
}
return content(
books = books,
currentBookId = currentBookId,
playing = playing,
gridMode = gridMode
)
}
private fun content(
books: List<Book2>,
currentBookId: Book2.Id?,
playing: Boolean,
gridMode: GridMode
): BookOverviewState.Content {
val currentBookPresent = books.any { it.id == currentBookId }
val amountOfColumns = gridCount.gridColumnCount(gridMode)
val categoriesWithContents = LinkedHashMap<BookOverviewCategory, BookOverviewCategoryContent>()
BookOverviewCategory.values().forEach { category ->
val content = content(books, category, currentBookId, amountOfColumns)
if (content != null) {
categoriesWithContents[category] = content
}
}
return BookOverviewState.Content(
playing = playing,
currentBookPresent = currentBookPresent,
categoriesWithContents = categoriesWithContents,
columnCount = amountOfColumns
)
}
private fun content(
books: List<Book2>,
category: BookOverviewCategory,
currentBookId: Book2.Id?,
amountOfColumns: Int
): BookOverviewCategoryContent? {
val booksOfCategory = books.filter(category.filter).sortedWith(category.comparator)
if (booksOfCategory.isEmpty()) {
return null
}
val rows = when (category) {
BookOverviewCategory.CURRENT -> 4
BookOverviewCategory.NOT_STARTED -> 4
BookOverviewCategory.FINISHED -> 2
}
val models = booksOfCategory.take(rows * amountOfColumns).map { book ->
BookOverviewViewState(book, amountOfColumns, currentBookId)
}
val hasMore = models.size != booksOfCategory.size
return BookOverviewCategoryContent(models, hasMore)
}
fun playPause() {
playerController.playPause()
}
}
| app/src/main/kotlin/de/ph1b/audiobook/features/bookOverview/BookOverviewViewModel.kt | 1887863845 |
package voice.playbackScreen
import androidx.datastore.core.DataStore
import de.ph1b.audiobook.common.pref.CurrentBook
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.data.durationMs
import de.ph1b.audiobook.data.markForPosition
import de.ph1b.audiobook.data.repo.BookRepo2
import de.ph1b.audiobook.data.repo.BookmarkRepo
import de.ph1b.audiobook.playback.PlayerController
import de.ph1b.audiobook.playback.playstate.PlayStateManager
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import voice.sleepTimer.SleepTimer
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
class BookPlayViewModel
@Inject constructor(
private val repo: BookRepo2,
private val player: PlayerController,
private val sleepTimer: SleepTimer,
private val playStateManager: PlayStateManager,
private val bookmarkRepo: BookmarkRepo,
@CurrentBook
private val currentBookId: DataStore<Book2.Id?>,
private val navigator: BookPlayNavigator
) {
private val scope = MainScope()
private val _viewEffects = MutableSharedFlow<BookPlayViewEffect>(extraBufferCapacity = 1)
val viewEffects: Flow<BookPlayViewEffect> get() = _viewEffects
lateinit var bookId: Book2.Id
fun viewState(): Flow<BookPlayViewState> {
scope.launch {
currentBookId.updateData { bookId }
}
return combine(
repo.flow(bookId).filterNotNull(), playStateManager.playStateFlow(), sleepTimer.leftSleepTimeFlow
) { book, playState, sleepTime ->
val currentMark = book.currentChapter.markForPosition(book.content.positionInChapter)
val hasMoreThanOneChapter = book.chapters.sumOf { it.chapterMarks.count() } > 1
BookPlayViewState(
sleepTime = sleepTime,
playing = playState == PlayStateManager.PlayState.Playing,
title = book.content.name,
showPreviousNextButtons = hasMoreThanOneChapter,
chapterName = currentMark.name.takeIf { hasMoreThanOneChapter },
duration = currentMark.durationMs.milliseconds,
playedTime = (book.content.positionInChapter - currentMark.startMs).milliseconds,
cover = book.content.cover,
skipSilence = book.content.skipSilence
)
}
}
fun next() {
player.next()
}
fun previous() {
player.previous()
}
fun playPause() {
player.playPause()
}
fun rewind() {
player.rewind()
}
fun fastForward() {
player.fastForward()
}
fun onSettingsClicked() {
navigator.toSettings()
}
fun onCurrentChapterClicked() {
navigator.toSelectChapters(bookId)
}
fun onPlaybackSpeedIconClicked() {
navigator.toChangePlaybackSpeed()
}
fun onBookmarkClicked() {
navigator.toBookmarkDialog(bookId)
}
fun seekTo(ms: Long) {
scope.launch {
val book = repo.flow(bookId).first() ?: return@launch
val currentChapter = book.currentChapter
val currentMark = currentChapter.markForPosition(book.content.positionInChapter)
player.setPosition(currentMark.startMs + ms, currentChapter.id)
}
}
fun toggleSleepTimer() {
if (sleepTimer.sleepTimerActive()) {
sleepTimer.setActive(false)
} else {
_viewEffects.tryEmit(BookPlayViewEffect.ShowSleepTimeDialog)
}
}
fun toggleSkipSilence() {
scope.launch {
val book = repo.flow(bookId).first() ?: return@launch
val skipSilence = book.content.skipSilence
player.skipSilence(!skipSilence)
}
}
}
| playbackScreen/src/main/kotlin/voice/playbackScreen/BookPlayViewModel.kt | 291875683 |
package es.ffgiraldez.comicsearch.query.search.presentation
import es.ffgiraldez.comicsearch.comics.domain.Volume
import es.ffgiraldez.comicsearch.query.base.presentation.QueryViewState
import es.ffgiraldez.comicsearch.query.base.presentation.SuspendQueryStateViewModel
import es.ffgiraldez.comicsearch.query.base.presentation.toViewState
import es.ffgiraldez.comicsearch.query.search.data.SuspendSearchRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
class SuspendSearchViewModel private constructor(
queryToResult: (Flow<String>) -> Flow<QueryViewState<Volume>>
) : SuspendQueryStateViewModel<Volume>(queryToResult) {
companion object {
operator fun invoke(repo: SuspendSearchRepository): SuspendSearchViewModel = SuspendSearchViewModel { query ->
query.flatMapLatest { term ->
repo.findByTerm(term)
.map { it.toViewState() }
.onStart { emit(QueryViewState.loading()) }
}.onStart { emit(QueryViewState.idle()) }
}
}
} | app/src/main/java/es/ffgiraldez/comicsearch/query/search/presentation/SuspendSearchViewModel.kt | 1092592381 |
/*
* Copyright (c) 2016. Manuel Rebollo Báez
*
* 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.mrebollob.m2p.presentation.view
interface MvpView {
} | app/src/main/java/com/mrebollob/m2p/presentation/view/MvpView.kt | 199533570 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.childrenOfType
class MacroExpander(project: Project) {
val psiFactory = RsPsiFactory(project)
fun expandMacro(def: RsMacroDefinition, call: RsMacroCall): List<ExpansionResult>? {
val case = def.macroDefinitionBodyStubbed
?.macroDefinitionCaseList
?.singleOrNull()
?: return null
val patGroup = case.macroPattern.macroBindingGroupList.singleOrNull()
?: return null
val patBinding = patGroup.macroBindingList.singleOrNull()
?: return null
val name = patBinding.colon.prevSibling?.text
val type = patBinding.colon.nextSibling?.text
if (!(name != null && type != null && type == "item")) return null
val expGroup = case.macroExpansion.macroExpansionReferenceGroupList.singleOrNull()
?: return null
val expansionText = expGroup.textBetweenParens(expGroup.lparen, expGroup.rparen)?.toString() ?: return null
val items = parseBodyAsItemList(call) ?: return null
val newText = items.joinToString("\n\n") { item ->
expansionText.replace("$" + name, item.text)
}
val expandedFile = psiFactory.createFile(newText)
return expandedFile.childrenOfType()
}
private val RsMacroDefinition.macroDefinitionBodyStubbed: RsMacroDefinitionBody?
get() {
val stub = stub ?: return macroDefinitionBody
val text = stub.macroBody ?: return null
return CachedValuesManager.getCachedValue(this) {
CachedValueProvider.Result.create(
psiFactory.createMacroDefinitionBody(text),
PsiModificationTracker.MODIFICATION_COUNT
)
}
}
private fun parseBodyAsItemList(call: RsMacroCall): List<RsElement>? {
val text = call.macroArgument?.braceListBodyText() ?: return null
val file = psiFactory.createFile(text) as? RsFile ?: return null
return file.childrenOfType()
}
}
private fun PsiElement.braceListBodyText(): CharSequence? =
textBetweenParens(firstChild, lastChild)
private fun PsiElement.textBetweenParens(bra: PsiElement?, ket: PsiElement?): CharSequence? {
if (bra == null || ket == null || bra == ket) return null
return containingFile.text.subSequence(
bra.textRange.endOffset + 1,
ket.textRange.startOffset
)
}
| src/main/kotlin/org/rust/lang/core/macros/MacroExpander.kt | 3330061505 |
package com.example.frontend
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| tfagents-flutter/step6/frontend/android/app/src/main/kotlin/com/example/frontend/MainActivity.kt | 2656069240 |
package com.github.kory33.signvote.constants
/**
* Keys in json file which stores information about vote points
* @author Kory
*/
object VotePointDataFileKeys {
val NAME = "name"
private val VOTE_SIGN = "votesign"
val VOTE_SIGN_WORLD = VOTE_SIGN + ".world"
private val VOTE_SIGN_LOC = VOTE_SIGN + ".location"
val VOTE_SIGN_LOC_X = VOTE_SIGN_LOC + ".X"
val VOTE_SIGN_LOC_Y = VOTE_SIGN_LOC + ".Y"
val VOTE_SIGN_LOC_Z = VOTE_SIGN_LOC + ".Z"
}
| src/main/kotlin/com/github/kory33/signvote/constants/VotePointDataFileKeys.kt | 477886249 |
package com.example.dashclicker
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| in_app_purchases/step_10/app/android/app/src/main/kotlin/com/example/dashclicker/MainActivity.kt | 1659995681 |
// 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
//
// 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.kotlindemos
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.kotlindemos.OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
/**
* This demo shows some features supported in lite mode.
* In particular it demonstrates the use of [com.google.android.gms.maps.model.Marker]s to
* launch the Google Maps Mobile application, [com.google.android.gms.maps.CameraUpdate]s
* and [com.google.android.gms.maps.model.Polygon]s.
*/
class LiteDemoActivity : AppCompatActivity(), OnGlobalLayoutAndMapReadyListener {
private lateinit var map: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set the layout
setContentView(R.layout.lite_demo)
// Get the map and register for the ready callback
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
OnMapAndViewReadyListener(mapFragment, this)
}
/**
* Move the camera to center on Darwin.
*/
fun showDarwin(v: View?) {
if (!::map.isInitialized) return
// Center camera on Adelaide marker
map.moveCamera(CameraUpdateFactory.newLatLngZoom(DARWIN, 10f))
}
/**
* Move the camera to center on Adelaide.
*/
fun showAdelaide(v: View?) {
if (!::map.isInitialized) return
// Center camera on Adelaide marker
map.moveCamera(CameraUpdateFactory.newLatLngZoom(ADELAIDE, 10f))
}
/**
* Move the camera to show all of Australia.
* Construct a [com.google.android.gms.maps.model.LatLngBounds] from markers positions,
* then move the camera.
*/
fun showAustralia(v: View?) {
if (!::map.isInitialized) return
// Create bounds that include all locations of the map
val boundsBuilder = LatLngBounds.builder()
.include(PERTH)
.include(ADELAIDE)
.include(MELBOURNE)
.include(SYDNEY)
.include(DARWIN)
.include(BRISBANE)
// Move camera to show all markers and locations
map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 20))
}
/**
* Called when the map is ready to add all markers and objects to the map.
*/
override fun onMapReady(googleMap: GoogleMap?) {
// return early if the map was not initialised properly
map = googleMap ?: return
addMarkers()
addPolyObjects()
showAustralia(null)
}
/**
* Add a Polyline and a Polygon to the map.
* The Polyline connects Melbourne, Adelaide and Perth. The Polygon is located in the Northern
* Territory (Australia).
*/
private fun addPolyObjects() {
map.addPolyline(
PolylineOptions()
.add(
MELBOURNE,
ADELAIDE,
PERTH
)
.color(Color.GREEN)
.width(5f)
)
map.addPolygon(
PolygonOptions()
.add(*POLYGON)
.fillColor(Color.CYAN)
.strokeColor(Color.BLUE)
.strokeWidth(5f)
)
}
/**
* Add Markers with default info windows to the map.
*/
private fun addMarkers() {
map.addMarker(
MarkerOptions()
.position(BRISBANE)
.title("Brisbane")
)
map.addMarker(
MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
)
map.addMarker(
MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
)
map.addMarker(
MarkerOptions()
.position(ADELAIDE)
.title("Adelaide")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
)
map.addMarker(
MarkerOptions()
.position(PERTH)
.title("Perth")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
)
}
companion object {
private val BRISBANE = LatLng(-27.47093, 153.0235)
private val MELBOURNE = LatLng(-37.81319, 144.96298)
private val SYDNEY = LatLng(-33.87365, 151.20689)
private val ADELAIDE = LatLng(-34.92873, 138.59995)
private val PERTH = LatLng(-31.952854, 115.857342)
private val DARWIN = LatLng(-12.459501, 130.839915)
/**
* A Polygon with five points in the Norther Territory, Australia.
*/
private val POLYGON = arrayOf(
LatLng(-18.000328, 130.473633), LatLng(-16.173880, 135.087891),
LatLng(-19.663970, 137.724609), LatLng(-23.202307, 135.395508),
LatLng(-19.705347, 129.550781)
)
}
} | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/LiteDemoActivity.kt | 4100683925 |
package io.piano.android.id.models
import io.piano.android.id.PianoIdClient.Companion.toPianoIdException
import io.piano.android.id.PianoIdException
sealed class PianoIdAuthResult {
val isSuccess: Boolean
get() = this is PianoIdAuthSuccessResult
val isFailure: Boolean
get() = this is PianoIdAuthFailureResult
@Suppress("NOTHING_TO_INLINE")
companion object {
internal inline fun success(token: PianoIdToken?, isNewUser: Boolean): PianoIdAuthResult =
PianoIdAuthSuccessResult(token, isNewUser)
internal inline fun failure(throwable: Throwable): PianoIdAuthResult =
PianoIdAuthFailureResult(throwable.toPianoIdException())
}
}
class PianoIdAuthSuccessResult internal constructor(
val token: PianoIdToken?,
val isNewUser: Boolean
) : PianoIdAuthResult()
class PianoIdAuthFailureResult internal constructor(
val exception: PianoIdException
) : PianoIdAuthResult()
| id/id/src/main/java/io/piano/android/id/models/PianoIdAuthResult.kt | 940591014 |
package it.sephiroth.android.library.bottomnavigation
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.annotation.IdRes
import it.sephiroth.android.library.bottonnavigation.R
import java.util.*
/**
* Created by alessandro crugnola on 4/12/16.
* BadgeProvider
*
* The MIT License
*/
@Suppress("unused")
open class BadgeProvider(private val navigation: BottomNavigation) {
private val map = HashSet<Int>()
private val badgeSize: Int = navigation.context.resources.getDimensionPixelSize(R.dimen.bbn_badge_size)
fun save(): Bundle {
val bundle = Bundle()
bundle.putSerializable("map", map)
return bundle
}
@Suppress("UNCHECKED_CAST")
fun restore(bundle: Bundle) {
val set = bundle.getSerializable("map")
if (null != set && set is HashSet<*>) {
map.addAll(set as HashSet<Int>)
}
}
/**
* Returns if the menu item will require a badge
*
* @param itemId the menu item id
* @return true if the menu item has to draw a badge
*/
fun hasBadge(@IdRes itemId: Int): Boolean {
return map.contains(itemId)
}
internal fun getBadge(@IdRes itemId: Int): Drawable? {
return if (map.contains(itemId)) {
newDrawable(itemId, navigation.menu!!.badgeColor)
} else null
}
protected open fun newDrawable(@IdRes itemId: Int, preferredColor: Int): Drawable {
return BadgeDrawable(preferredColor, badgeSize)
}
/**
* Request to display a new badge over the passed menu item id
*
* @param itemId the menu item id
*/
fun show(@IdRes itemId: Int) {
map.add(itemId)
navigation.invalidateBadge(itemId)
}
/**
* Remove the currently displayed badge
*
* @param itemId the menu item id
*/
open fun remove(@IdRes itemId: Int) {
if (map.remove(itemId)) {
navigation.invalidateBadge(itemId)
}
}
}
| bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BadgeProvider.kt | 1461821377 |
/*
* Copyright 2020 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.app_navigation
import androidx.annotation.IdRes
import com.github.vase4kin.teamcityapp.R
enum class AppNavigationItem(@IdRes val id: Int) {
PROJECTS(R.id.projects),
FAVORITES(R.id.favorites),
RUNNING_BUILDS(R.id.running_builds),
BUILD_QUEUE(R.id.build_queue),
AGENTS(R.id.agents);
}
| app/src/main/java/com/github/vase4kin/teamcityapp/app_navigation/AppNavigationItem.kt | 2916709343 |
package net.kibotu.android.recyclerviewpresenter.cirkle
import org.junit.Test
import kotlin.test.assertEquals
class CircularListTest {
@Test
fun get() {
val given = listOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')
val actual = given.circular()
given.forEachIndexed { index, i ->
assertEquals(i, actual[index])
}
// off by one
assertEquals(given.last(), actual[-1])
assertEquals(given.first(), actual[actual.lastIndex + 1])
// off by size + 1
assertEquals(given.first(), actual[-(actual.size)])
assertEquals(given.first(), actual[actual.size])
assertEquals(given.last(), actual[-(actual.size + 1)])
assertEquals(given.drop(1).first(), actual[-(actual.size - 1)])
}
@Test
fun listIterator() {
}
@Test
fun subList() {
}
} | lib/src/test/java/net/kibotu/android/recyclerviewpresenter/cirkle/CircularListTest.kt | 2541701632 |
/*
* Copyright 2018 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 app.tivi.data.mappers
import app.tivi.data.entities.Season
import javax.inject.Inject
import javax.inject.Singleton
import com.uwetrottmann.trakt5.entities.Season as TraktSeason
@Singleton
class TraktSeasonToSeason @Inject constructor() : Mapper<TraktSeason, Season> {
override suspend fun map(from: TraktSeason) = Season(
showId = 0,
traktId = from.ids?.trakt,
tmdbId = from.ids?.tmdb,
number = from.number,
title = from.title,
summary = from.overview,
traktRating = from.rating?.toFloat() ?: 0f,
traktRatingVotes = from.votes ?: 0,
episodeCount = from.episode_count,
episodesAired = from.aired_episodes,
network = from.network
)
}
| data/src/main/java/app/tivi/data/mappers/TraktSeasonToSeason.kt | 3977508638 |
package com.charlag.promind.util.rx
import io.reactivex.Observable
/**
* Created by charlag on 28/05/2017.
*/
fun <T> Observable<T>.onErrorComplete(): Observable<T> = this.onErrorResumeNext(Observable.empty()) | app/src/main/java/com/charlag/promind/util/rx/Errors.kt | 3516170435 |
package org.acme
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Parameters
@Command(name = "greeting", mixinStandardHelpOptions = true)
class GreetingCommand : Runnable {
@Parameters(paramLabel = "<name>", defaultValue = "picocli", description = ["Your name."])
var name: String? = null
override fun run() {
System.out.printf("Hello %s, go go commando!\n", name)
}
} | devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/picocli-codestart/kotlin/src/main/kotlin/org/acme/GreetingCommand.kt | 1005675026 |
package org.roylance.yaorm.services.mysql.myisam
import org.junit.Test
import org.roylance.yaorm.services.EntityService
import org.roylance.yaorm.services.jdbc.JDBCGranularDatabaseService
import org.roylance.yaorm.services.mysql.MySQLConnectionSourceFactory
import org.roylance.yaorm.services.mysql.MySQLGeneratorService
import org.roylance.yaorm.utilities.ConnectionUtilities
import org.roylance.yaorm.utilities.common.INestedEnumTest
import org.roylance.yaorm.utilities.common.NestedEnumTestUtilities
class MySQLNestedEnumTest : MySQLISAMBase(), INestedEnumTest {
@Test
override fun simpleMultipleStringsTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
ConnectionUtilities.getMySQLConnectionInfo()
val sourceConnection = MySQLConnectionSourceFactory(
ConnectionUtilities.mysqlHost!!,
ConnectionUtilities.mysqlSchema!!,
ConnectionUtilities.mysqlUserName!!,
ConnectionUtilities.mysqlPassword!!)
val granularDatabaseService = JDBCGranularDatabaseService(
sourceConnection,
false,
true)
val mySqlGeneratorService = MySQLGeneratorService(sourceConnection.schema, useMyISAM = true)
val entityService = EntityService(granularDatabaseService, mySqlGeneratorService)
NestedEnumTestUtilities.simpleMultipleStringsTest(entityService, cleanup())
}
@Test
override fun simplePassThroughExecutionsTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
ConnectionUtilities.getMySQLConnectionInfo()
val sourceConnection = MySQLConnectionSourceFactory(
ConnectionUtilities.mysqlHost!!,
ConnectionUtilities.mysqlSchema!!,
ConnectionUtilities.mysqlUserName!!,
ConnectionUtilities.mysqlPassword!!)
val granularDatabaseService = JDBCGranularDatabaseService(
sourceConnection,
false,
true)
val mySqlGeneratorService = MySQLGeneratorService(sourceConnection.schema, useMyISAM = true)
val entityService = EntityService(granularDatabaseService, mySqlGeneratorService)
NestedEnumTestUtilities.simplePassThroughExecutionsTest(entityService, cleanup())
}
@Test
override fun simpleTablesTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
NestedEnumTestUtilities.simpleTablesTest(buildEntityService(), cleanup(), ConnectionUtilities.mysqlSchema!!)
}
@Test
override fun simpleTableDefinitionTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
NestedEnumTestUtilities.simpleTableDefinitionTest(buildEntityService(), cleanup(), ConnectionUtilities.mysqlSchema!!)
}
@Test
override fun simpleTableDefinitionNullableTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
NestedEnumTestUtilities.simpleTableDefinitionNullableTest(buildEntityService(), cleanup(), ConnectionUtilities.mysqlSchema!!)
}
@Test
override fun simplePassThroughTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
NestedEnumTestUtilities.simplePassThroughTest(buildEntityService(), cleanup())
}
@Test
override fun simplePassThroughTest2() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
NestedEnumTestUtilities.simplePassThroughTest2(buildEntityService(), cleanup())
}
} | yaorm/src/test/java/org/roylance/yaorm/services/mysql/myisam/MySQLNestedEnumTest.kt | 3470004473 |
package com.booboot.vndbandroid.ui.login
import android.app.Application
import com.booboot.vndbandroid.App
import com.booboot.vndbandroid.api.VNDBServer
import com.booboot.vndbandroid.ui.base.StartupSyncViewModel
class LoginViewModel constructor(application: Application) : StartupSyncViewModel(application) {
init {
(application as App).appComponent.inject(this)
}
fun login() = coroutine(DISPOSABLE_LOGIN) {
VNDBServer.closeAll()
startupSyncInternal()
}
companion object {
private const val DISPOSABLE_LOGIN = "DISPOSABLE_LOGIN"
}
} | app/src/main/java/com/booboot/vndbandroid/ui/login/LoginViewModel.kt | 2472794993 |
package com.natpryce.krouton.example
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.isEmptyString
import com.natpryce.hamkrest.present
import com.natpryce.krouton.PathTemplate
import com.natpryce.krouton.PathTemplate2
import com.natpryce.krouton.Projection
import com.natpryce.krouton.Tuple3
import com.natpryce.krouton.asA
import com.natpryce.krouton.getValue
import com.natpryce.krouton.http4k.resources
import com.natpryce.krouton.int
import com.natpryce.krouton.locale
import com.natpryce.krouton.path
import com.natpryce.krouton.plus
import com.natpryce.krouton.root
import com.natpryce.krouton.string
import com.natpryce.krouton.tuple
import dev.minutest.rootContext
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.FOUND
import org.http4k.core.Status.Companion.MOVED_PERMANENTLY
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.core.Status.Companion.OK
import org.junit.platform.commons.annotation.Testable
import java.time.DateTimeException
import java.time.LocalDate
import java.time.LocalDate.now
import java.time.format.DateTimeFormatter
import java.util.Locale
// An application-specific mapping between parsed URL elements and typed data
object LocalDate_ : Projection<Tuple3<Int, Int, Int>, LocalDate> {
override fun fromParts(parts: Tuple3<Int, Int, Int>): LocalDate? {
val (year, month, day) = parts
return try {
LocalDate.of(year, month, day)
}
catch (e: DateTimeException) {
null
}
}
override fun toParts(mapped: LocalDate) =
tuple(mapped.year, mapped.monthValue, mapped.dayOfMonth)
}
// Components of the application's routes
val year by int
val month by int
val day by int
val date = year + month + day asA LocalDate_
// The application's routes
val reverse = root + "reverse" + string
val negate = root + "negate" + int
// Note: without these explicit type declarations, the Kotlin compiler crashes with an internal error
val weekday: PathTemplate2<Locale, LocalDate> = root + "weekday" + locale.named("locale") + date
val weekdayToday: PathTemplate<Locale> = root + "weekday" + locale.named("locale") + "today"
// Obsolete routes that each redirect to one of the routes above
val negative = root + "negative" + int
val reversed = root + "reversed" + string
// The server that uses the routes
val demo = resources {
root methods {
GET { ok("Hello, World.") }
}
negate methods {
GET { _, i -> ok((-i).toString()) }
}
negative methods {
// Note - reverse routing from integer to URL path
GET { _, i -> redirect(MOVED_PERMANENTLY, negate.path(i)) }
}
reverse methods {
GET { _, s -> ok(s.reversed()) }
}
reversed methods {
GET { _, s -> redirect(MOVED_PERMANENTLY, reverse.path(s)) }
}
weekday methods {
GET { _, (locale, date) -> ok(date.format(DateTimeFormatter.ofPattern("EEEE", locale))) }
}
weekdayToday methods {
/* Note - reverse routing using user-defined projection*/
GET { _, locale -> redirect(FOUND, weekday.path(locale, now())) }
}
}
private fun ok(s: String) =
Response(OK).body(s)
private fun redirect(status: Status, location: String) =
Response(status).header("Location", location)
@Testable
fun `HttpRouting tests`() = rootContext<HttpHandler> {
fixture { demo }
test("negate") {
assertThat(getText("/negate/100"), equalTo("-100"))
}
test("negative_redirects_to_negate") {
assertThat(getText("/negative/20"), equalTo("-20"))
}
test("reverse") {
assertThat(getText("/reverse/hello%20world"), equalTo("dlrow olleh"))
}
test("weekday") {
assertThat(getText("/weekday/en/2016/02/29"), equalTo("Monday"))
assertThat(getText("/weekday/fr/2016/02/29"), equalTo("lundi"))
assertThat(getText("/weekday/de/2016/02/29"), equalTo("Montag"))
assertThat(getText("/weekday/en/2016/03/01"), equalTo("Tuesday"))
}
test("weekday_today") {
assertThat(getText("/weekday/en/today"), present(!isEmptyString))
}
test("bad_dates_not_found") {
assertThat(get("/weekday/2016/02/30").status, equalTo(NOT_FOUND))
}
test("root") {
assertThat(getText("/"), equalTo("Hello, World."))
}
}
| src/test/kotlin/com/natpryce/krouton/example/HttpRoutingExample.kt | 3173831769 |
package com.airbnb.mvrx
internal data class MavericksTuple1<A>(val a: A)
internal data class MavericksTuple2<A, B>(val a: A, val b: B)
internal data class MavericksTuple3<A, B, C>(val a: A, val b: B, val c: C)
internal data class MavericksTuple4<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
internal data class MavericksTuple5<A, B, C, D, E>(val a: A, val b: B, val c: C, val d: D, val e: E)
internal data class MavericksTuple6<A, B, C, D, E, F>(val a: A, val b: B, val c: C, val d: D, val e: E, val f: F)
internal data class MavericksTuple7<A, B, C, D, E, F, G>(val a: A, val b: B, val c: C, val d: D, val e: E, val f: F, val g: G)
| mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksTuples.kt | 1656547317 |
package com.airbnb.mvrx.hellodagger
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(R.layout.activity_main)
| hellodagger/src/main/java/com/airbnb/mvrx/hellodagger/MainActivity.kt | 2656666262 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.manager
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import com.klinker.android.send_message.BroadcastUtils
import javax.inject.Inject
class WidgetManagerImpl @Inject constructor(private val context: Context) : WidgetManager {
override fun updateUnreadCount() {
BroadcastUtils.sendExplicitBroadcast(context, Intent(), WidgetManager.ACTION_NOTIFY_DATASET_CHANGED)
}
override fun updateTheme() {
val ids = AppWidgetManager.getInstance(context)
.getAppWidgetIds(ComponentName("com.moez.QKSMS", "com.moez.QKSMS.feature.widget.WidgetProvider"))
val intent = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
BroadcastUtils.sendExplicitBroadcast(context, intent, AppWidgetManager.ACTION_APPWIDGET_UPDATE)
}
} | data/src/main/java/com/moez/QKSMS/manager/WidgetManagerImpl.kt | 1732980053 |
/*
* Copyright (c) 2016 Drimachine.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("SpacedCombinators")
package org.drimachine.grakmat
import java.util.*
var SPACE: Parser<Char> = anyOf(' ', '\t', '\r', '\n') withName "SPACE"
val SPACES: Parser<String> = oneOrMore(SPACE)
.map { spaces: List<Char> -> spaces.joinToString("") }
.withName("SPACES")
val OPTIONAL_SPACES: Parser<String> = zeroOrMore(SPACE)
.map { spaces: List<Char> -> spaces.joinToString("") }
.withName("OPTIONAL SPACES")
/**
* Works like [and], but inserts spaces between parsers.
*/
infix fun <A, B> Parser<A>._and_(other: Parser<B>): Parser<Pair<A, B>> = SpacedAndParser(this, other)
/**
* Works like [_and_], but returns only second result.
*/
infix fun <A, B> Parser<A>._then_(other: Parser<B>): Parser<B> = this _and_ other map { it.second }
/**
* Works like [_and_], but returns only first result.
*/
infix fun <A, B> Parser<A>._before_(other: Parser<B>): Parser<A> = this _and_ other map { it.first }
/**
* @see _and_
*/
class SpacedAndParser<out A, out B>(val leftParser: Parser<A>, val rightParser: Parser<B>) : Parser<Pair<A, B>> {
override val expectedDescription: String
get() = "${leftParser.expectedDescription} and ${rightParser.expectedDescription}"
override fun eat(source: Source, input: String): Result<Pair<A, B>> {
val leftResult: Result<A> = leftParser.eat(source, input)
val middleResult: Result<String> = OPTIONAL_SPACES.eat(source, leftResult.remainder)
val rightResult: Result<B> = rightParser.eat(source, middleResult.remainder)
return Result(leftResult.value to rightResult.value, rightResult.remainder)
}
override fun toString(): String = expectedDescription
}
/**
* Works like [repeat], but inserts spaces between results.
*/
infix fun <A> Parser<A>._repeat_(times: Int): Parser<List<A>> = SpacedRepeatParser(this, times)
/**
* @see _repeat_
*/
class SpacedRepeatParser<out A>(val target: Parser<A>, val times: Int) : Parser<List<A>> {
override val expectedDescription: String
get() = "${target.expectedDescription} exactly $times times"
override fun eat(source: Source, input: String): Result<List<A>> {
val list = ArrayList<A>()
var remainder = input
// (1..times) - repeat folding 'times' times
for (time in 1..times) {
val next: Result<A> = target.eat(source, remainder)
list.add(next.value)
val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, next.remainder)
remainder = spacesResult.value
}
return Result(Collections.unmodifiableList(list), remainder)
}
override fun toString(): String = expectedDescription
}
/**
* Works like [atLeast], but inserts spaces between results.
*/
infix fun <A> Parser<A>._atLeast_(times: Int): Parser<List<A>> = SpacedAtLeastParser(this, times)
/**
* Alias to `atLeast(0, xxx)`.
*
* @see atLeast
*/
fun <A> _zeroOrMore_(target: Parser<A>): Parser<List<A>> = target _atLeast_ 0
/**
* Alias to `atLeast(1, xxx)`.
*
* @see atLeast
*/
fun <A> _oneOrMore_(target: Parser<A>): Parser<List<A>> = target _atLeast_ 1
/**
* @see _atLeast_
*/
class SpacedAtLeastParser<out A>(val target: Parser<A>, val times: Int) : Parser<List<A>> {
override val expectedDescription: String
get() = "${target.expectedDescription} at least $times times"
override fun eat(source: Source, input: String): Result<List<A>> {
var (list: List<A>, remainder: String) = target.repeat(times).eat(source, input)
list = ArrayList<A>(list)
do {
val (next: A?, nextRemainder: String) = optional(target).eat(source, remainder)
if (next != null) {
list.add(next)
val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, nextRemainder)
remainder = spacesResult.remainder
} else {
remainder = nextRemainder
}
} while (next != null)
return Result(Collections.unmodifiableList(list), remainder)
}
override fun toString(): String = expectedDescription
}
/**
* Works like [inRange], but inserts spaces between results.
*/
infix fun <A> Parser<A>._inRange_(bounds: IntRange) : Parser<List<A>> = SpacedRangedParser(this, bounds)
/**
* @see _inRange_
*/
class SpacedRangedParser<out A>(val target: Parser<A>, val bounds: IntRange) : Parser<List<A>> {
override val expectedDescription: String
get() = "${target.expectedDescription}{${bounds.start},${bounds.endInclusive}}"
override fun eat(source: Source, input: String): Result<List<A>> {
var (list, remainder) = target.repeat(bounds.start).eat(source, input)
list = ArrayList<A>(list)
do {
val (next: A?, nextRemainder: String) = optional(target).eat(source, remainder)
if (next != null) {
list.add(next)
remainder = nextRemainder
} else {
val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, nextRemainder)
remainder = spacesResult.remainder
}
} while (next != null && list.size < bounds.endInclusive)
return Result(Collections.unmodifiableList(list), remainder)
}
override fun toString(): String = expectedDescription
}
| src/main/kotlin/org/drimachine/grakmat/SpacedCombinators.kt | 1924470510 |
package solutions.alterego.android.unisannio.repository
import org.jsoup.nodes.Document
import rx.Single
import solutions.alterego.android.unisannio.models.Article
interface Parser {
fun parse(document: Document): Single<List<Article>>
}
class ArticleParser : Parser {
override fun parse(document: Document): Single<List<Article>> {
return Single.fromCallable {
document.select("item")
.asSequence()
.map {
Article(
id = it.select("guid").first()?.text().orEmpty(),
title = it.select("title").first().text(),
author = it.select("author").first().text(),
url = it.select("link").first().text(),
body = it.select("description").first().text(),
date = it.select("pubDate").first()?.text().orEmpty()
)
}
.toList()
}
}
}
| app/src/main/java/solutions/alterego/android/unisannio/repository/Parser.kt | 2043305562 |
/*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.domain.karuta.model
import me.rei_m.hyakuninisshu.domain.ValueObject
/**
* 歌の番号.
*
* @param value 値
*
* @throws IllegalArgumentException
*/
data class KarutaNo @Throws(IllegalArgumentException::class) constructor(
val value: Int
) : ValueObject {
init {
if (value < MIN_VALUE || MAX_VALUE < value) {
throw IllegalArgumentException("KarutaNo is Invalid, value is $value")
}
}
companion object {
private const val MIN_VALUE = 1
private const val MAX_VALUE = 100
val MIN = KarutaNo(MIN_VALUE)
val MAX = KarutaNo(MAX_VALUE)
val LIST = (MIN.value..MAX.value).map { KarutaNo(it) }
}
}
| domain/src/main/java/me/rei_m/hyakuninisshu/domain/karuta/model/KarutaNo.kt | 3337777206 |
package org.ooverkommelig
import kotlin.test.Test
import kotlin.test.assertSame
class FailingObjectRequestTest {
@Test
fun objectRequestFailureInWireResultsInOriginalExceptionBeingThrown() {
// Passing "exception" explicitly because of: https://youtrack.jetbrains.com/issue/KT-8120
class ObjectRequestFailureInWireResultsInOriginalExceptionThrownTestSgd(private val exception: Exception) : SubGraphDefinition() {
val definitionRequestingFailingDefinitionInWire by Once { SOME_OBJECT }
.eager()
.wire { req(failingDefinition) }
val failingDefinition: Definition<Any> by Once {
throw exception
}
}
class ObjectRequestFailureInWireResultsInOriginalExceptionThrownTestOgd(exception: Exception) : ObjectGraphDefinition() {
val main: ObjectRequestFailureInWireResultsInOriginalExceptionThrownTestSgd = add(ObjectRequestFailureInWireResultsInOriginalExceptionThrownTestSgd(exception))
inner class Graph : DefinitionObjectGraph()
}
val exception = Exception()
val objectGraphDefinition = ObjectRequestFailureInWireResultsInOriginalExceptionThrownTestOgd(exception)
try {
objectGraphDefinition.Graph()
throw IllegalStateException("Expected exception to be thrown.")
} catch (graphCreationException: Exception) {
assertSame(exception, graphCreationException)
}
}
companion object {
private const val SOME_OBJECT = ""
}
}
| main/src/commonTest/kotlin/org/ooverkommelig/FailingObjectRequestTest.kt | 3157387759 |
package cm.aptoide.pt.wallet
import cm.aptoide.pt.app.DownloadModel
import cm.aptoide.pt.app.DownloadStateParser
import cm.aptoide.pt.install.Install
import cm.aptoide.pt.install.InstallManager
import cm.aptoide.pt.install.InstalledRepository
import cm.aptoide.pt.promotions.WalletApp
import cm.aptoide.pt.view.app.AppCenter
import cm.aptoide.pt.view.app.DetailedAppRequestResult
import rx.Observable
class WalletAppProvider(val appCenter: AppCenter, val installedRepository: InstalledRepository,
val installManager: InstallManager,
val downloadStateParser: DownloadStateParser) {
fun getWalletApp(): Observable<WalletApp> {
return appCenter.loadDetailedApp("com.appcoins.wallet", "catappult")
.toObservable()
.map { app -> this.mapToWalletApp(app) }.flatMap { walletApp ->
val walletAppObs = Observable.just<WalletApp>(walletApp)
val isWalletInstalled = installedRepository.isInstalled(walletApp.packageName)
val walletDownload = installManager.getInstall(walletApp.md5sum, walletApp.packageName,
walletApp.versionCode)
Observable.combineLatest<WalletApp, Boolean, Install, WalletApp>(walletAppObs,
isWalletInstalled, walletDownload
) { walletApp, isInstalled, walletDownload ->
this.mergeToWalletApp(walletApp, isInstalled, walletDownload)
}
}
}
private fun mergeToWalletApp(walletApp: WalletApp, isInstalled: Boolean,
walletDownload: Install): WalletApp {
val downloadModel = mapToDownloadModel(walletDownload.type, walletDownload.progress,
walletDownload.state, walletDownload.isIndeterminate, walletDownload.appSize)
walletApp.downloadModel = downloadModel
walletApp.isInstalled = isInstalled
return walletApp
}
private fun mapToDownloadModel(type: Install.InstallationType,
progress: Int,
state: Install.InstallationStatus,
isIndeterminate: Boolean, appSize: Long): DownloadModel {
return DownloadModel(downloadStateParser.parseDownloadType(type, false),
progress, downloadStateParser.parseDownloadState(state, isIndeterminate), appSize)
}
private fun mapToWalletApp(result: DetailedAppRequestResult): WalletApp {
if (result.hasError() || result.isLoading) return WalletApp()
val app = result.detailedApp
return WalletApp(null, false, app.name, app.icon, app.id,
app.packageName, app.md5, app.versionCode, app.versionName,
app.path, app.pathAlt, app.obb, app.size, app.developer.name, app.stats.rating.average,
app.splits,
app.requiredSplits)
}
}
| app/src/main/java/cm/aptoide/pt/wallet/WalletAppProvider.kt | 3042341122 |
package ro.cluj.totemz.mqtt
/* ktlint-disable no-wildcard-imports */
import android.app.Application
import android.provider.Settings
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.experimental.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.experimental.launch
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttAsyncClient
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import timber.log.Timber
import java.util.*
import kotlin.concurrent.fixedRateTimer
class TotemzMqttManager(private val application: Application, private val accountManager: FirebaseAuth) : MqttManager {
private var maxNumberOfRetries = 4
private var retryInterval = 4000L
private var topics: Array<String> = arrayOf()
private var qos: IntArray = intArrayOf()
private var timerReconnect: Timer? = null
private var retryCount = 0
private var isMqttClientConnected = false
private var mqttClient: MqttAsyncClient? = null
private val mqttMessageChannel by lazy { ConflatedBroadcastChannel<Pair<String, MqttMessage>>() }
private val mqttConnectionStateChannel by lazy { ConflatedBroadcastChannel<Boolean>() }
private var explicitDisconnection = false
@SuppressWarnings("HardwareIds")
override fun connect(serverURI: String, topics: Array<String>, qos: IntArray) {
if (isMqttClientConnected) {
Timber.w("connect was called although the mqttClient is already connected")
return
}
[email protected] = topics
[email protected] = qos
val clientId = "${Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID)}"
mqttClient = MqttAsyncClient(serverURI, clientId, MemoryPersistence())
mqttClient?.setCallback(object : MqttCallback {
@Throws(Exception::class)
override fun messageArrived(topic: String, message: MqttMessage) {
val msg = message.payload.toString(Charsets.UTF_8)
Timber.w("Message arrived: $msg")
launch { mqttMessageChannel.send(topic to message) }
}
override fun deliveryComplete(token: IMqttDeliveryToken?) = Unit
override fun connectionLost(cause: Throwable) {
isMqttClientConnected = false
launch { mqttConnectionStateChannel.send(false) }
mqttConnectionStateChannel.close()
Timber.w(cause, "MQTT connection lost")
if (!explicitDisconnection) {
resetTimer()
retry()
}
}
})
val connectAction: IMqttActionListener = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
isMqttClientConnected = true
sendConnectionStatus(true)
Timber.w("MQTT connected")
mqttClient?.subscribe(topics, qos, null, object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
Timber.w("MQTT subscription successful")
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) {
Timber.e(exception, "MQTT could not subscribe")
}
})
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) {
isMqttClientConnected = false
mqttMessageChannel.close()
mqttConnectionStateChannel.close()
Timber.e(exception, "MQTT could not establish connection")
if (!explicitDisconnection) {
retry()
}
}
}
try {
val options = MqttConnectOptions().apply {
isCleanSession = true
userName = accountManager.currentUser?.displayName
}
mqttClient?.connect(options, null, connectAction)
} catch (cause: MqttException) {
Timber.e(cause, "MQTT connecting issue: ")
}
}
fun sendConnectionStatus(isConnected: Boolean) = launch { mqttConnectionStateChannel.send(isConnected) }
fun sendMqttMessage(message: Pair<String, MqttMessage>) = launch { mqttMessageChannel.send(message) }
override fun disconnect() {
if (!isMqttClientConnected) {
Timber.w("disconnect was called although the mqttClient is not connected")
return
}
val disconnectAction: IMqttActionListener = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
Timber.w("Mqtt Client disconnected")
isMqttClientConnected = false
explicitDisconnection = true
mqttMessageChannel.close()
mqttConnectionStateChannel.close()
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) {
Timber.e(exception, "Could not disconnect MQTT client")
}
}
try {
if (mqttClient?.isConnected == true)
mqttClient?.disconnect(null, disconnectAction)
} catch (cause: MqttException) {
if (cause.reasonCode == MqttException.REASON_CODE_CLIENT_ALREADY_DISCONNECTED.toInt()) {
isMqttClientConnected = false
explicitDisconnection = true
Timber.e(cause, "Client is already disconnected!")
} else {
Timber.e(cause, "Disconnection error")
}
}
}
override fun setRetryIntervalTime(retryInterval: Long) {
this.retryInterval = retryInterval
}
override fun setMaxNumberOfRetires(maxNumberOfRetries: Int) {
this.maxNumberOfRetries = maxNumberOfRetries
}
private fun resetTimer() {
retryCount = 0
timerReconnect?.let {
it.cancel()
it.purge()
}
timerReconnect = null
}
private fun retry() {
if (timerReconnect == null) {
timerReconnect = fixedRateTimer("mqtt_reconnect_timer", true, 0, retryInterval) {
retryCount++
Timber.w("MQTT reconnect retry $retryCount")
if (mqttClient?.isConnected == true || retryCount > maxNumberOfRetries) {
sendConnectionStatus(isMqttClientConnected)
cancel()
}
val loggedIn = accountManager.currentUser != null
if (loggedIn) connect(mqttClient?.serverURI ?: "", topics, qos)
else disconnect()
}
}
}
} | app/src/main/java/ro/cluj/totemz/mqtt/TotemzMqttManager.kt | 226639045 |
package com.ddu.ui.fragment.study.material
import android.os.Bundle
import com.ddu.R
import com.ddu.icore.ui.fragment.DefaultFragment
import com.iannotation.IElement
/**
* Created by yzbzz on 16/4/14.
*/
@IElement("MD")
class CardViewFragment : DefaultFragment() {
override fun getLayoutId(): Int {
return R.layout.fragment_study_md_card_view
}
override fun initView() {
}
companion object {
fun newInstance(taskId: String): CardViewFragment {
val arguments = Bundle()
arguments.putString(ARGUMENT_TASK_ID, taskId)
val fragment = CardViewFragment()
fragment.arguments = arguments
return fragment
}
}
}
| app/src/main/java/com/ddu/ui/fragment/study/material/CardViewFragment.kt | 2423981583 |
package com.empowerops.sojourn
import org.testng.annotations.Test
class IntegrationFixture {
@Test fun `commandLineP118`(){
val params = P118.inputs.flatMap { listOf("--input", it.toCLIString()) }
val expressions = P118.constraints.flatMap { listOf("&&", it.expressionLiteral) }.drop(1)
val args = (params + expressions).toTypedArray()
main(args)
TODO("use jvm fork? get from standard output? add kotlinx.exec and getoptk?")
}
}
fun InputVariable.toCLIString(): String = "$name:{lower:$lowerBound,step:$stepsize,upper:$upperBound}" | src/test/kotlin/com/empowerops/sojourn/IntegrationFixture.kt | 3445952609 |
/*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.testutils.ActivityList
import com.ichi2.testutils.ActivityList.ActivityLaunchParam
import com.ichi2.utils.KotlinCleanup
import org.hamcrest.MatcherAssert
import org.hamcrest.Matchers
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
import java.util.stream.Collectors
import kotlin.Throws
@RunWith(AndroidJUnit4::class)
class ActivityStartupMetaTest : RobolectricTest() {
@Test
@Throws(PackageManager.NameNotFoundException::class)
@KotlinCleanup("remove throws; remove stream(), remove : String")
@Suppress("deprecation") // getPackageInfo
fun ensureAllActivitiesAreTested() {
// if this fails, you may need to add the missing activity to ActivityList.allActivitiesAndIntents()
// we can't access this in a static context
val pm = targetContext.packageManager
val packageInfo = pm.getPackageInfo(targetContext.packageName, PackageManager.GET_ACTIVITIES)
val manifestActivities = packageInfo.activities
val testedActivityClassNames = ActivityList.allActivitiesAndIntents().stream().map { obj: ActivityLaunchParam -> obj.className }.collect(Collectors.toSet())
val manifestActivityNames = Arrays.stream(manifestActivities)
.map { x: ActivityInfo -> x.name }
.filter { x: String -> x != "com.ichi2.anki.TestCardTemplatePreviewer" }
.filter { x: String -> x != "com.ichi2.anki.AnkiCardContextMenuAction" }
.filter { x: String -> x != "com.ichi2.anki.analytics.AnkiDroidCrashReportDialog" }
.filter { x: String -> !x.startsWith("androidx") }
.filter { x: String -> !x.startsWith("org.acra") }
.filter { x: String -> !x.startsWith("leakcanary.internal") }
.toArray()
MatcherAssert.assertThat(testedActivityClassNames, Matchers.containsInAnyOrder(*manifestActivityNames))
}
}
| AnkiDroid/src/test/java/com/ichi2/anki/ActivityStartupMetaTest.kt | 2024243577 |
package com.yuyashuai.frameanimation.drawer
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
/**
* @author yuyashuai 2019-05-05.
* the animation drawer
*/
interface BitmapDrawer {
/**
* draw bitmap
* @param matrix the matrix
* @return canvas if draw success otherwise return null
*/
fun draw(bitmap: Bitmap,matrix: Matrix):Canvas?
fun unlockAndPost(canvas: Canvas)
/**
* clear draw content
*/
fun clear()
} | frameanimation/src/main/java/com/yuyashuai/frameanimation/drawer/BitmapDrawer.kt | 3933277444 |
package com.recurly.androidsdk.data.network
import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest
import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Here should be all the calls to the api with retrofit
*/
interface RecurlyApiClient {
@FormUrlEncoded
@POST("js/v1/tokens")
suspend fun recurlyTokenization(
@Field(value = "first_name", encoded = true) first_name: String,
@Field(value = "last_name", encoded = true) last_name: String,
@Field(value = "company", encoded = true) company: String,
@Field(value = "address1", encoded = true) address1: String,
@Field(value = "address2", encoded = true) address2: String,
@Field(value = "city", encoded = true) city: String,
@Field(value = "state", encoded = true) state: String,
@Field(value = "postal_code", encoded = true) postal_code: String,
@Field(value = "country", encoded = true) country: String,
@Field(value = "phone", encoded = true) phone: String,
@Field(value = "vat_number", encoded = true) vat_number: String,
@Field(value = "tax_identifier", encoded = true) tax_identifier: String,
@Field(value = "tax_identifier_type", encoded = true) tax_identifier_type: String,
@Field(value = "number", encoded = true) number: Long,
@Field(value = "month", encoded = true) month: Int,
@Field(value = "year", encoded = true) year: Int,
@Field(value = "cvv", encoded = true) cvv: Int,
@Field(value = "version", encoded = true) version: String,
@Field(value = "key", encoded = true) key: String,
@Field(value = "deviceId", encoded = true) deviceId: String,
@Field(value = "sessionId", encoded = true) sessionId: String
): Response<TokenizationResponse>
} | AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/RecurlyApiClient.kt | 1274907230 |
/*
* Copyright (C) 2020-2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.domain.interactor.forms
import kotlinx.coroutines.withContext
import org.akvo.flow.domain.executor.CoroutineDispatcher
import org.akvo.flow.domain.repository.FormInstanceRepository
import javax.inject.Inject
class GetRecentSubmittedFormInstance @Inject constructor(
private val formInstanceRepository: FormInstanceRepository,
private val coroutineDispatcher: CoroutineDispatcher,
) {
suspend fun execute(parameters: Map<String, Any>): Long {
if (!parameters.containsKey(PARAM_FORM_ID) || !parameters.containsKey(PARAM_DATAPOINT_ID)) {
throw IllegalArgumentException("Missing form id")
}
return withContext(coroutineDispatcher.getDispatcher()) {
try {
val formId = parameters[PARAM_FORM_ID] as String
val datapointId = parameters[PARAM_DATAPOINT_ID] as String
formInstanceRepository.getLatestSubmittedFormInstance(formId, datapointId)
} catch (e: Exception) {
-1L
}
}
}
companion object {
const val PARAM_FORM_ID = "form_id"
const val PARAM_DATAPOINT_ID = "datapoint_id"
}
}
| domain/src/main/java/org/akvo/flow/domain/interactor/forms/GetRecentSubmittedFormInstance.kt | 347303304 |
package com.seventh_root.guildfordgamejam.system
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.graphics.Color
import com.seventh_root.guildfordgamejam.component.*
class PlayerColorSystem: IteratingSystem(Family.all(PlayerComponent::class.java, ColorComponent::class.java, PositionComponent::class.java).get()) {
val grappleFamily: Family = Family.all(GrappleComponent::class.java, PositionComponent::class.java, ColorComponent::class.java).get()
override fun processEntity(entity: Entity, deltaTime: Float) {
var closestGrapple: Entity? = null
var shortestDistSq: Float? = null
var secondClosestGrapple: Entity? = null
var secondShortestDistSq: Float? = null
for (grapple in engine.getEntitiesFor(grappleFamily)) {
if (shortestDistSq == null) {
closestGrapple = grapple
val xDist = position.get(entity).x - position.get(grapple).x
val yDist = position.get(entity).y - position.get(grapple).y
shortestDistSq = (xDist * xDist) + (yDist * yDist)
} else if (secondShortestDistSq == null) {
secondClosestGrapple = grapple
val xDist = position.get(entity).x - position.get(grapple).x
val yDist = position.get(entity).y - position.get(grapple).y
secondShortestDistSq = (xDist * xDist) + (yDist * yDist)
} else {
val xDist = position.get(entity).x - position.get(grapple).x
val yDist = position.get(entity).y - position.get(grapple).y
val distSq = (xDist * xDist) + (yDist * yDist)
if (distSq < shortestDistSq) {
secondClosestGrapple = closestGrapple
secondShortestDistSq = shortestDistSq
closestGrapple = grapple
shortestDistSq = distSq
} else if (distSq < secondShortestDistSq) {
secondClosestGrapple = grapple
secondShortestDistSq = distSq
}
}
}
if (closestGrapple != null && secondClosestGrapple != null && shortestDistSq != null && secondShortestDistSq != null) {
val bias = shortestDistSq / (shortestDistSq + secondShortestDistSq)
val playerColor = Color(
((1 - bias) * color.get(closestGrapple).color.r) + (bias * color.get(secondClosestGrapple).color.r),
((1 - bias) * color.get(closestGrapple).color.g) + (bias * color.get(secondClosestGrapple).color.g),
((1 - bias) * color.get(closestGrapple).color.b) + (bias * color.get(secondClosestGrapple).color.b),
255F
)
color.get(entity).color = playerColor
}
}
} | core/src/main/kotlin/com/seventh_root/guildfordgamejam/system/PlayerColorSystem.kt | 3284524598 |
package coffee.cypher.kotlinexamples
fun main(args: Array<String>) {
println("Hello World (Kt)")
}
| src/coffee/cypher/kotlinexamples/HelloWorld.kt | 1916083022 |
package com.jtechme.jumpgo.adblock
/**
* Created by joeho on 9/8/2017.
*/
import javax.inject.Inject
import javax.inject.Singleton
/**
* A no-op ad blocker implementation. Always returns false for [isAd].
*/
@Singleton
class NoOpAdBlocker @Inject internal constructor() : AdBlocker {
override fun isAd(url: String?) = false
} | app/src/main/java/com/jtechme/jumpgo/adblock/NoOpAdBlocker.kt | 1234253055 |
package com.gmail.pasquarelli.brandon.setlist
import android.app.Application
import com.gmail.pasquarelli.brandon.setlist.tab_setlists.viewmodel.SetListsViewModel
import com.gmail.pasquarelli.brandon.setlist.tab_songs.new_song.viewmodel.NewSongViewModel
import com.gmail.pasquarelli.brandon.setlist.tab_songs.viewmodel.SongsViewModel
import timber.log.Timber
class SetListApplication : Application() {
val setListsViewModel = SetListsViewModel()
val songsViewModel = SongsViewModel()
val newSongViewModel = NewSongViewModel()
init {
if(BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else {
// Initialize Crashlytics
}
}
} | app/src/main/java/com/gmail/pasquarelli/brandon/setlist/SetListApplication.kt | 2955976752 |
package de.westnordost.streetcomplete.quests.camera_type
import android.os.Bundle
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AImageListQuestAnswerFragment
import de.westnordost.streetcomplete.quests.camera_type.CameraType.*
import de.westnordost.streetcomplete.view.image_select.Item
class AddCameraTypeForm : AImageListQuestAnswerFragment<CameraType, CameraType>() {
override val items = listOf(
Item(DOME, R.drawable.ic_camera_type_dome, R.string.quest_camera_type_dome),
Item(FIXED, R.drawable.ic_camera_type_fixed, R.string.quest_camera_type_fixed),
Item(PANNING, R.drawable.ic_camera_type_panning, R.string.quest_camera_type_panning)
)
override val itemsPerRow = 3
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
imageSelector.cellLayoutId = R.layout.cell_icon_select_with_label_below
}
override fun onClickOk(selectedItems: List<CameraType>) {
applyAnswer(selectedItems.single())
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/camera_type/AddCameraTypeForm.kt | 2312081577 |
package app.youkai.util
import android.support.annotation.IntegerRes
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import app.youkai.App
/**
* Convenience function to get colors from anywhere
*/
fun color(@IntegerRes res: Int) = App.context.resources.getColor(res)
/**
* Convenience function to get strings from anywhere
*/
fun string(@IntegerRes res: Int): String = App.context.resources.getString(res)
/**
* Colors a given span in a string and returns a SpannableString
*/
fun coloredSpannableString(text: String, color: Int, start: Int, end: Int): SpannableString {
val spannable = SpannableString(text)
spannable.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
return spannable
} | app/src/main/kotlin/app/youkai/util/Utils.kt | 3377850384 |
// This file was automatically generated from formats.md by Knit tool. Do not edit.
package example.exampleFormats16
import kotlinx.serialization.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.modules.*
import kotlinx.serialization.encoding.*
import java.io.*
private val byteArraySerializer = serializer<ByteArray>()
class DataOutputEncoder(val output: DataOutput) : AbstractEncoder() {
override val serializersModule: SerializersModule = EmptySerializersModule()
override fun encodeBoolean(value: Boolean) = output.writeByte(if (value) 1 else 0)
override fun encodeByte(value: Byte) = output.writeByte(value.toInt())
override fun encodeShort(value: Short) = output.writeShort(value.toInt())
override fun encodeInt(value: Int) = output.writeInt(value)
override fun encodeLong(value: Long) = output.writeLong(value)
override fun encodeFloat(value: Float) = output.writeFloat(value)
override fun encodeDouble(value: Double) = output.writeDouble(value)
override fun encodeChar(value: Char) = output.writeChar(value.code)
override fun encodeString(value: String) = output.writeUTF(value)
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) = output.writeInt(index)
override fun beginCollection(descriptor: SerialDescriptor, collectionSize: Int): CompositeEncoder {
encodeInt(collectionSize)
return this
}
override fun encodeNull() = encodeBoolean(false)
override fun encodeNotNullMark() = encodeBoolean(true)
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
if (serializer.descriptor == byteArraySerializer.descriptor)
encodeByteArray(value as ByteArray)
else
super.encodeSerializableValue(serializer, value)
}
private fun encodeByteArray(bytes: ByteArray) {
encodeCompactSize(bytes.size)
output.write(bytes)
}
private fun encodeCompactSize(value: Int) {
if (value < 0xff) {
output.writeByte(value)
} else {
output.writeByte(0xff)
output.writeInt(value)
}
}
}
fun <T> encodeTo(output: DataOutput, serializer: SerializationStrategy<T>, value: T) {
val encoder = DataOutputEncoder(output)
encoder.encodeSerializableValue(serializer, value)
}
inline fun <reified T> encodeTo(output: DataOutput, value: T) = encodeTo(output, serializer(), value)
class DataInputDecoder(val input: DataInput, var elementsCount: Int = 0) : AbstractDecoder() {
private var elementIndex = 0
override val serializersModule: SerializersModule = EmptySerializersModule()
override fun decodeBoolean(): Boolean = input.readByte().toInt() != 0
override fun decodeByte(): Byte = input.readByte()
override fun decodeShort(): Short = input.readShort()
override fun decodeInt(): Int = input.readInt()
override fun decodeLong(): Long = input.readLong()
override fun decodeFloat(): Float = input.readFloat()
override fun decodeDouble(): Double = input.readDouble()
override fun decodeChar(): Char = input.readChar()
override fun decodeString(): String = input.readUTF()
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int = input.readInt()
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (elementIndex == elementsCount) return CompositeDecoder.DECODE_DONE
return elementIndex++
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder =
DataInputDecoder(input, descriptor.elementsCount)
override fun decodeSequentially(): Boolean = true
override fun decodeCollectionSize(descriptor: SerialDescriptor): Int =
decodeInt().also { elementsCount = it }
override fun decodeNotNullMark(): Boolean = decodeBoolean()
@Suppress("UNCHECKED_CAST")
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>, previousValue: T?): T =
if (deserializer.descriptor == byteArraySerializer.descriptor)
decodeByteArray() as T
else
super.decodeSerializableValue(deserializer, previousValue)
private fun decodeByteArray(): ByteArray {
val bytes = ByteArray(decodeCompactSize())
input.readFully(bytes)
return bytes
}
private fun decodeCompactSize(): Int {
val byte = input.readByte().toInt() and 0xff
if (byte < 0xff) return byte
return input.readInt()
}
}
fun <T> decodeFrom(input: DataInput, deserializer: DeserializationStrategy<T>): T {
val decoder = DataInputDecoder(input)
return decoder.decodeSerializableValue(deserializer)
}
inline fun <reified T> decodeFrom(input: DataInput): T = decodeFrom(input, serializer())
fun ByteArray.toAsciiHexString() = joinToString("") {
if (it in 32..127) it.toInt().toChar().toString() else
"{${it.toUByte().toString(16).padStart(2, '0').uppercase()}}"
}
@Serializable
data class Project(val name: String, val attachment: ByteArray)
fun main() {
val data = Project("kotlinx.serialization", byteArrayOf(0x0A, 0x0B, 0x0C, 0x0D))
val output = ByteArrayOutputStream()
encodeTo(DataOutputStream(output), data)
val bytes = output.toByteArray()
println(bytes.toAsciiHexString())
val input = ByteArrayInputStream(bytes)
val obj = decodeFrom<Project>(DataInputStream(input))
println(obj)
}
| guide/example/example-formats-16.kt | 287359108 |
/*
* 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.text
import net.kyori.adventure.text.serializer.ComponentSerializer
import org.lanternpowered.api.Lantern
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.serializer.TextSerializer
import org.spongepowered.api.util.locale.Locales
import java.util.Locale
open class LanternLiteralTextSerializer(
private val serializer: ComponentSerializer<Text, out Text, String>
) : TextSerializer {
private val renderer = LiteralTextRenderer(Translators.GlobalAndMinecraft)
override fun serialize(text: Text): String =
this.serialize(text, Locales.DEFAULT)
override fun serialize(text: Text, locale: Locale): String {
val rendered = this.renderer.render(text,
FormattedTextRenderContext(locale, scoreboard = Lantern.server.serverScoreboard.get()))
return this.serializer.serialize(rendered)
}
override fun deserialize(input: String): Text = this.serializer.deserialize(input)
}
| src/main/kotlin/org/lanternpowered/server/text/LanternLiteralTextSerializer.kt | 3570194337 |
package template
import android.content.Context
import androidx.annotation.WorkerThread
import androidx.core.util.lruCache
import common.FileConstants
import template.Template.Default
import template.Template.Version1
import template.Template.Version2
import template.Template.Version3
import template.Template.VersionHtz
import template.TemplateConstants.DEFAULT_TEMPLATE_ID
import template.TemplateConstants.TEMPLATE_CFG
import template.converter.HtzConverter
import template.converter.HtzConverterImpl
import template.factory.DefaultFactory
import template.factory.Factory
import template.factory.Version1Factory
import template.factory.Version2Factory
import template.factory.Version3Factory
import template.factory.VersionHtzFactory
import template.model.ModelHtz
import template.serialize.ModelSerialize
import template.serialize.ModelSerializeImpl
import java.io.File
import java.util.Locale
import java.util.zip.ZipFile
@WorkerThread
class TemplateFactoryManagerImpl constructor(
private val appContext: Context,
fileConstants: FileConstants
) : TemplateFactoryManager, ModelSerialize by ModelSerializeImpl {
private val cache = lruCache<String, Template>(maxSize = 64)
private val htzDir: () -> File = (fileConstants::htzDir)
private val savedDir: () -> File = (fileConstants::savedDir)
private val htzConverter: HtzConverter by lazy {
HtzConverterImpl(appContext, htzDir, ::encodeModelHtz)
}
override fun default(): Default = DEFAULT_TEMPLATE_ID cacheOrNewBy DefaultFactory(appContext)
override fun version1(name: String, installed: Long): Version1 =
name cacheOrNewBy Version1Factory(appContext, name, installed, ::decodeModelV1)
override fun version2(name: String, installed: Long): Version2 =
name cacheOrNewBy Version2Factory(appContext, name, installed, ::decodeModelV2)
override fun version3(name: String, installed: Long): Version3 =
name cacheOrNewBy Version3Factory(appContext, name, installed, ::decodeModelV3)
override fun versionHtz(path: String, installed: Long): VersionHtz =
path cacheOrNewBy VersionHtzFactory(htzDir(), path, installed, ::decodeModelHtz)
override fun importHtz(file: File): VersionHtz {
val id = ZipFile(file).entryInputStream(TEMPLATE_CFG)
.use(::decodeModelHtz).run { generatorHtzId(this) }
decompressHtz(file, File(htzDir(), id))
return versionHtz(id, System.currentTimeMillis())
}
override fun convertHtz(template: Template): VersionHtz {
val id = htzConverter.convert(template, ::generatorHtzId)
return versionHtz(id, System.currentTimeMillis())
}
override fun exportHtz(versionHtz: VersionHtz): File {
val src = File(htzDir(), versionHtz.id)
check(src.exists() && src.isDirectory) { "src must exist and its dir, ${src.absolutePath}" }
val dst = File(savedDir(), "${versionHtz.name}.htz")
compressHtz(src, dst)
return dst
}
override fun removeHtz(versionHtz: VersionHtz): String {
File(htzDir(), versionHtz.id).deleteRecursively()
return versionHtz.name
}
private fun generatorHtzId(modelHtz: ModelHtz): String = modelHtz.run {
"${author.hashCode()}_${name.toLowerCase(Locale.ROOT)}"
.replace("[^\\w]".toRegex(), "") // removing non word char
.trim().take(32) // limit
}
private inline infix fun <reified T : Template> String.cacheOrNewBy(factory: Factory<T>): T =
cache.get(this) as? T? ?: factory.newTemplate().also { cache.put(this, it) }
}
| template/src/main/java/template/TemplateFactoryManagerImpl.kt | 2696043608 |
package br.com.insanitech.spritekit.actions
import android.content.Context
import android.support.annotation.IdRes
import br.com.insanitech.spritekit.SKNode
import br.com.insanitech.spritekit.SKTexture
import br.com.insanitech.spritekit.core.SKBlock
import br.com.insanitech.spritekit.graphics.SKPoint
import br.com.insanitech.spritekit.graphics.SKSize
import java.util.*
abstract class SKAction {
private var started = false
internal var key = ""
internal var completion: SKBlock? = null
internal var startedTime: Long = 0
private set
var speed = 1f
var duration: Long = 1000
var timingMode = defaultTiming
internal fun start(node: SKNode) {
if (!this.started) {
this.started = true
this.startedTime = System.currentTimeMillis()
this.computeStart(node)
}
}
protected fun restart() {
this.started = false
}
internal abstract fun computeStart(node: SKNode)
internal abstract fun computeAction(node: SKNode, elapsed: Long)
internal abstract fun computeFinish(node: SKNode)
internal open fun hasCompleted(elapsed: Long) : Boolean = elapsed >= this.duration
internal fun dispatchCompletion() {
this.completion?.invoke()
}
companion object {
private var defaultTiming = SKActionTimingMode.EaseOut
fun moveBy(deltaPosition: SKPoint, duration: Long): SKAction =
moveBy(deltaPosition.x, deltaPosition.y, duration)
fun moveBy(deltaX: Float, deltaY: Float, duration: Long): SKAction {
val action = SKActionMoveBy(SKPoint(deltaX, deltaY))
action.duration = duration
return action
}
fun moveTo(toX: Float, toY: Float, duration: Long): SKAction =
moveTo(SKPoint(toX, toY), duration)
fun moveTo(position: SKPoint, duration: Long): SKAction {
val action = SKActionMoveTo(position)
action.duration = duration
return action
}
fun rotateBy(radians: Float, duration: Long): SKAction {
val action = SKActionRotateBy(radians)
action.duration = duration
return action
}
fun rotateTo(radians: Float, duration: Long): SKAction {
val action = SKActionRotateTo(radians)
action.duration = duration
return action
}
fun resizeBy(width: Float, height: Float, duration: Long): SKAction =
resizeBy(SKSize(width, height), duration)
fun resizeBy(size: SKSize, duration: Long): SKAction {
val action = SKActionResizeBy(size)
action.duration = duration
return action
}
fun resizeTo(width: Float, height: Float, duration: Long): SKAction =
resizeTo(SKSize(width, height), duration)
fun resizeTo(size: SKSize, duration: Long): SKAction {
val action = SKActionResizeTo(size)
action.duration = duration
return action
}
fun playSoundFile(context: Context, @IdRes resId: Int): SKAction {
val action = SKActionPlaySoundFile(context, resId)
action.duration = 0
return action
}
fun sequence(sequence: List<SKAction>): SKAction = SKActionSequence(LinkedList(sequence))
fun group(group: List<SKAction>): SKAction = SKActionGroup(ArrayList(group))
fun waitFor(duration: Long): SKAction {
val action = SKActionWaitFor()
action.duration = duration
return action
}
fun waitFor(duration: Long, range: Long): SKAction {
val action = SKActionWaitFor()
val random = Random()
val sum = random.nextInt(range.toInt()).toLong()
action.duration = duration + sum
return action
}
fun fadeIn(duration: Long): SKAction {
val action = SKActionFadeIn()
action.duration = duration
return action
}
fun fadeOut(duration: Long): SKAction {
val action = SKActionFadeOut()
action.duration = duration
return action
}
fun fadeAlphaTo(alpha: Float, duration: Long): SKAction {
val action = SKActionFadeAlphaTo(alpha)
action.duration = duration
return action
}
fun fadeAlphaBy(alpha: Float, duration: Long): SKAction {
val action = SKActionFadeAlphaBy(alpha)
action.duration = duration
return action
}
fun scaleTo(scale: Float, duration: Long): SKAction = scaleTo(scale, scale, duration)
fun scaleTo(x: Float, y: Float, duration: Long): SKAction {
val action = SKActionScaleTo(x, y)
action.duration = duration
return action
}
fun scaleBy(scale: Float, duration: Long): SKAction = scaleBy(scale, scale, duration)
fun scaleBy(x: Float, y: Float, duration: Long): SKAction {
val action = SKActionScaleBy(x, y)
action.duration = duration
return action
}
fun setTexture(texture: SKTexture): SKAction {
val action = SKActionSetTexture(texture)
action.duration = 0
return action
}
fun run(completion: SKBlock): SKAction {
val action = SKActionRun(completion)
action.duration = 0
return action
}
fun removeFromParent(): SKAction {
val action = SKActionRemoveFromParent()
action.duration = 0
return action
}
}
} | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKAction.kt | 3096133290 |
package com.deanveloper.overcraft.item
import com.deanveloper.overcraft.util.Interaction
import org.bukkit.entity.Player
/**
* @author Dean
*/
abstract class Weapon : Interactive() {
override val slot = 0
abstract fun onUse(e: Interaction)
override final fun onClick(e: Interaction) {
if (!cooldowns[e.player]) {
onUse(e)
}
}
/**
* When the item is equipped
*
* @return whether to keep the cursor on the item
*/
override fun onEquip(p: Player) = false
/**
* When the item is unequipped
*
* @return whether to move the cursor back to the main weapon
*/
override fun onUnEquip(p: Player): Boolean = false
} | src/main/java/com/deanveloper/overcraft/item/Weapon.kt | 469886905 |
package com.mercadopago.android.px.internal.features.payment_result.remedies
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.HighRiskRemedy
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.RetryPaymentFragment
import com.mercadopago.android.px.model.ExpressMetadata
internal sealed class RemedyState {
internal data class ShowRetryPaymentRemedy(val data: Pair<RetryPaymentFragment.Model, ExpressMetadata?>): RemedyState()
internal data class ShowKyCRemedy(val model: HighRiskRemedy.Model): RemedyState()
internal data class GoToKyc(val deepLink: String): RemedyState()
internal object ChangePaymentMethod: RemedyState()
} | px-checkout/src/main/java/com/mercadopago/android/px/internal/features/payment_result/remedies/RemedyState.kt | 3840020912 |
/*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("Lengths")
package debop4k.units
import java.io.Serializable
const val MILLIMETER_IN_METER = 1.0e-3
const val CENTIMETER_IN_METER = 1.0e-2
const val METER_IN_METER = 1.0
const val KILOMETER_IN_METER = 1.0e3
const val INCH_IN_METER = 39.37
const val FEET_IN_METER = 3.2809
const val YARD_IN_METER = 1.0936
const val MILE_IN_METER = 1609.344
fun Double.millimeter(): Length = Length.of(this, LengthUnit.MILLIMETER)
fun Double.centimeter(): Length = Length.of(this, LengthUnit.CENTIMETER)
fun Double.meter(): Length = Length.of(this)
fun Double.kilometer(): Length = Length.of(this, LengthUnit.KILOMETER)
//fun Double.inch(): Length = Length.of(this, LengthUnit.INCH)
//fun Double.feet(): Length = Length.of(this, LengthUnit.FEET)
//fun Double.yard(): Length = Length.of(this, LengthUnit.YARD)
//fun Double.mile(): Length = Length.of(this, LengthUnit.MILE)
/**
* 길이(Length)의 단위
*/
enum class LengthUnit(val unitName: String, val factor: Double) {
MILLIMETER("mm", MILLIMETER_IN_METER),
CENTIMETER("cm", CENTIMETER_IN_METER),
METER("m", METER_IN_METER),
KILOMETER("km", KILOMETER_IN_METER);
// INCH("inch", INCH_IN_METER),
// FEET("ft", FEET_IN_METER),
// YARD("yd", YARD_IN_METER),
// MILE("ml", MILE_IN_METER);
companion object {
@JvmStatic
fun parse(str: String): LengthUnit {
val lower = str.toLowerCase()
return LengthUnit.values().find { it.unitName == lower }
?: throw UnsupportedOperationException("Unknwon Length unit string. str=$str")
}
}
}
/**
* 길이를 나타내는 클래스
*/
data class Length(val meter: Double = 0.0) : Comparable<Length>, Serializable {
operator final fun plus(other: Length): Length = Length(meter + other.meter)
operator final fun minus(other: Length): Length = Length(meter - other.meter)
operator final fun times(scalar: Double): Length = Length(meter * scalar)
operator final fun times(other: Length): Area = Area(meter * other.meter)
operator final fun div(scalar: Double): Length = Length(meter / scalar)
operator final fun unaryMinus(): Length = Length(-meter)
fun inMillimeter(): Double = meter / LengthUnit.MILLIMETER.factor
fun inCentimeter(): Double = meter / LengthUnit.CENTIMETER.factor
fun inMeter(): Double = meter
fun inKilometer(): Double = meter / LengthUnit.KILOMETER.factor
// fun inInch(): Double = meter / LengthUnit.INCH.factor
// fun inFeet(): Double = meter / LengthUnit.FEET.factor
// fun inYard(): Double = meter / LengthUnit.YARD.factor
// fun inMile(): Double = meter / LengthUnit.MILE.factor
override fun compareTo(other: Length): Int = meter.compareTo(other.meter)
override fun toString(): String = "%.1f %s".format(meter, LengthUnit.METER.factor)
fun toHuman(): String {
val value = Math.abs(meter)
val displayUnit = LengthUnit.values().last { value / it.factor > 1.0 }
return "%.1f %s".format(meter / displayUnit.factor, displayUnit.unitName)
}
fun toHuman(unit: LengthUnit): String {
return "%.1f %s".format(meter / unit.factor, unit.unitName)
}
companion object {
@JvmField val ZERO = Length(0.0)
@JvmField val MIN_VALUE = Length(Double.MIN_VALUE)
@JvmField val MAX_VALUE = Length(Double.MAX_VALUE)
@JvmField val POSITIVE_INF = Length(Double.POSITIVE_INFINITY)
@JvmField val NEGATIVE_INF = Length(Double.NEGATIVE_INFINITY)
@JvmField val NaN = Length(Double.NaN)
@JvmOverloads
@JvmStatic
fun of(length: Double = 0.0, unit: LengthUnit = LengthUnit.METER): Length =
Length(length * unit.factor)
/**
* 문자열을 파싱하여 [Length] 인스턴스를 빌드합니다
*/
@JvmStatic
fun parse(str: String?): Length {
if (str.isNullOrBlank()) {
return ZERO
}
try {
val (length, unit) = str!!.split(" ", limit = 2)
return of(length.toDouble(), LengthUnit.parse(unit))
} catch(e: Exception) {
throw NumberFormatException("Invalid Length string. str=$str")
}
}
}
} | debop4k-units/src/main/kotlin/debop4k/units/Lengths.kt | 3364342892 |
package nl.hannahsten.texifyidea.editor.postfix
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.lang.LatexPackage
import nl.hannahsten.texifyidea.util.insertUsepackage
abstract class LatexPostfixTemplateFromPackageProvider(private val pack: LatexPackage) : PostfixTemplateProvider {
abstract override fun getTemplates(): MutableSet<PostfixTemplate>
override fun isTerminalSymbol(currentChar: Char): Boolean = (currentChar == '.' || currentChar == ',')
override fun afterExpand(file: PsiFile, editor: Editor) {
file.insertUsepackage(pack)
}
override fun preCheck(copyFile: PsiFile, realEditor: Editor, currentOffset: Int): PsiFile =
copyFile
override fun preExpand(file: PsiFile, editor: Editor) {}
companion object {
fun getProvider(pack: LatexPackage?): PostfixTemplateProvider {
return when (pack) {
LatexPackage.AMSMATH -> LatexPostfixTemplateFromAmsMathProvider
LatexPackage.AMSFONTS -> LatexPostfixTemplateFromAmsFontsProvider
LatexPackage.BM -> LatexPostfixTemplateFromBmProvider
else -> LatexPostFixTemplateProvider
}
}
}
}
object LatexPostfixTemplateFromAmsMathProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.AMSMATH) {
override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf(
LatexWrapWithTextPostfixTemplate
)
}
object LatexPostfixTemplateFromAmsFontsProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.AMSFONTS) {
override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf(
LatexWrapWithMathbbPostfixTemplate
)
}
object LatexPostfixTemplateFromBmProvider : LatexPostfixTemplateFromPackageProvider(LatexPackage.BM) {
override fun getTemplates(): MutableSet<PostfixTemplate> = mutableSetOf(
LatexWrapWithBmPostfixTemplate
)
} | src/nl/hannahsten/texifyidea/editor/postfix/LatexPostfixTemplateFromPackageProvider.kt | 182415296 |
/*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* 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 debop4k.timeperiod.calendars
import debop4k.core.kodatimes.asDate
import debop4k.core.loggerOf
import debop4k.timeperiod.*
import debop4k.timeperiod.timeranges.*
/**
* Created by debop
*/
open class CalendarPeriodCollector @JvmOverloads constructor(
filter: CalendarPeriodCollectorFilter,
limits: ITimePeriod,
seekDir: SeekDirection = SeekDirection.Forward,
calendar: ITimeCalendar = DefaultTimeCalendar)
: CalendarVisitor<CalendarPeriodCollectorFilter, CalendarPeriodCollectorContext>(
filter, limits, seekDir, calendar) {
private val log = loggerOf(javaClass)
companion object {
@JvmStatic
@JvmOverloads
fun of(filter: CalendarPeriodCollectorFilter,
limits: ITimePeriod,
seekDir: SeekDirection = SeekDirection.Forward,
calendar: ITimeCalendar = DefaultTimeCalendar): CalendarPeriodCollector {
return CalendarPeriodCollector(filter, limits, seekDir, calendar)
}
}
val periods: ITimePeriodCollection = TimePeriodCollection()
fun collectYears(): Unit = collectByScope(CollectKind.Year)
fun collectMonths(): Unit = collectByScope(CollectKind.Month)
fun collectDays(): Unit = collectByScope(CollectKind.Day)
fun collectHours(): Unit = collectByScope(CollectKind.Hour)
fun collectMinutes(): Unit = collectByScope(CollectKind.Minute)
private fun collectByScope(scope: CollectKind): Unit {
val context = CalendarPeriodCollectorContext(scope)
startPeriodVisit(context)
}
override fun enterYears(years: YearRangeCollection, context: CalendarPeriodCollectorContext): Boolean {
return context.scope.value > CollectKind.Year.value
}
override fun enterMonths(year: YearRange, context: CalendarPeriodCollectorContext): Boolean {
return context.scope.value > CollectKind.Month.value
}
override fun enterDays(month: MonthRange, context: CalendarPeriodCollectorContext): Boolean {
return context.scope.value > CollectKind.Day.value
}
override fun enterHours(day: DayRange, context: CalendarPeriodCollectorContext): Boolean {
return context.scope.value > CollectKind.Hour.value
}
override fun enterMinutes(hour: HourRange, context: CalendarPeriodCollectorContext): Boolean {
return context.scope.value > CollectKind.Minute.value
}
override fun onVisitYears(years: YearRangeCollection, context: CalendarPeriodCollectorContext): Boolean {
log.trace("visit years ... years={}, context={}", years, context)
if (context.scope != CollectKind.Year) {
return true
}
years.years()
.filter { isMatchingYear(it, context) && checkLimits(it) }
.forEach { periods.add(it) }
return false
}
override fun onVisitYear(year: YearRange, context: CalendarPeriodCollectorContext): Boolean {
log.trace("visit year ... year={}, context={}", year, context)
if (context.scope != CollectKind.Month) {
return true
}
val monthFilter: (MonthRange) -> Boolean = { isMatchingMonth(it, context) && checkLimits(it) }
if (filter.collectingMonths.isEmpty) {
year.months().filter(monthFilter).forEach { periods.add(it) }
} else {
filter.collectingMonths.forEach { m ->
if (m.isSingleMonth) {
val mr = MonthRange(asDate(year.year, m.startMonthOfYear), year.calendar)
if (monthFilter(mr)) {
periods.add(mr)
}
} else {
val mc = MonthRangeCollection(year.year,
m.startMonthOfYear,
m.endMonthOfYear - m.startMonthOfYear,
year.calendar)
val months = mc.months()
val isMatch = months.all { isMatchingMonth(it, context) }
if (isMatch && checkLimits(mc)) {
periods.addAll(months)
}
}
}
}
return false
}
override fun onVisitMonth(month: MonthRange, context: CalendarPeriodCollectorContext): Boolean {
log.trace("visit month... month={}, context={}", month, context)
if (context.scope != CollectKind.Day) {
return true
}
val dayFilter: (DayRange) -> Boolean = { isMatchingDay(it, context) && checkLimits(it) }
if (filter.collectingDays.isEmpty) {
month.days().filter(dayFilter).forEach { periods.add(it) }
} else {
filter.collectingDays.forEach { day ->
val startTime = asDate(month.year, month.monthOfYear, day.startDayOfMonth)
if (day.isSingleDay) {
val dayRange = DayRange(startTime, month.calendar)
if (dayFilter(dayRange)) {
periods.add(dayRange)
}
} else {
val dc = DayRangeCollection(startTime,
day.endDayOfMonth - day.startDayOfMonth,
month.calendar)
val days = dc.days()
val isMatch = days.all { isMatchingDay(it, context) }
if (isMatch && checkLimits(dc)) {
periods.addAll(days)
}
}
}
}
return false
}
override fun onVisitDay(day: DayRange, context: CalendarPeriodCollectorContext): Boolean {
log.trace("visit day... day={}, context={}", day, context)
if (filter.collectingHours.isEmpty) {
day.hours()
.filter { isMatchingHour(it, context) && checkLimits(it) }
.forEach { periods.add(it) }
} else if (isMatchingDay(day, context)) {
filter.collectingHours.forEach { h ->
val start = h.start.toDateTime(day.start)
val end = h.endExclusive.toDateTime(day.start)
val hc = CalendarTimeRange(start, end, day.calendar)
if (checkExcludePeriods(hc) && checkLimits(hc)) {
periods.add(hc)
}
}
}
return false
}
} | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/calendars/CalendarPeriodCollector.kt | 1377313920 |
package com.andreapivetta.blu.ui.login
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.settings.AppSettingsFactory
import com.andreapivetta.blu.ui.main.MainActivity
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity(), LoginMvpView {
private val presenter = LoginPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
presenter.attachView(this)
loginButton.setOnClickListener { presenter.performLogin() }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == LoginPresenter.CODE_OAUTH)
if (resultCode == RESULT_OK)
presenter.onResultOk()
else
presenter.onResultCanceled()
}
override fun showOauthActivity(requestCode: Int) {
startActivityForResult(Intent(this, TwitterOAuthActivity::class.java), requestCode)
}
override fun showLoginError() {
Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show()
}
override fun showLoginCanceled() {
Toast.makeText(this, getString(R.string.cancellation), Toast.LENGTH_LONG).show()
}
override fun moveOn() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
override fun isUserLoggedIn() = AppSettingsFactory.getAppSettings(this).isUserLoggedIn()
}
| app/src/main/java/com/andreapivetta/blu/ui/login/LoginActivity.kt | 85876053 |
package com.pr0gramm.app.ui.intro.slides
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.annotation.ColorRes
import com.pr0gramm.app.R
import com.pr0gramm.app.ui.base.BaseFragment
import com.pr0gramm.app.util.find
import com.pr0gramm.app.util.findOptional
/**
*/
abstract class ActionItemsSlide(name: String) : BaseFragment(name) {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(layoutId, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val titleView = view.findOptional<TextView>(R.id.title)
titleView?.text = introTitle
val descriptionView = view.findOptional<TextView>(R.id.description)
descriptionView?.text = introDescription
val actionItems = introActionItems
val listView = view.find<ListView>(R.id.recycler_view)
listView.choiceMode = if (singleChoice) ListView.CHOICE_MODE_SINGLE else ListView.CHOICE_MODE_MULTIPLE
listView.adapter = ArrayAdapter(requireContext(),
android.R.layout.simple_list_item_multiple_choice, android.R.id.text1,
actionItems)
listView.setOnItemClickListener { _, _, position, _ ->
val item = actionItems[position]
if (listView.isItemChecked(position)) {
item.activate()
} else {
item.deactivate()
}
}
for (idx in actionItems.indices) {
if (actionItems[idx].enabled()) {
listView.setItemChecked(idx, true)
}
}
introBackgroundResource?.let { res -> view.setBackgroundResource(res) }
}
open val singleChoice: Boolean = false
open val layoutId: Int = R.layout.intro_fragment_items
@ColorRes
open val introBackgroundResource: Int? = null
abstract val introTitle: String
abstract val introDescription: String
abstract val introActionItems: List<ActionItem>
}
| app/src/main/java/com/pr0gramm/app/ui/intro/slides/ActionItemsSlide.kt | 3960414887 |
package com.duopoints.android.rest.models.dbobjects
import android.annotation.SuppressLint
import android.os.Parcelable
import com.duopoints.android.rest.models.Timestamp
import kotlinx.android.parcel.Parcelize
import java.util.*
@SuppressLint("ParcelCreator")
@Parcelize
data class ReportedContent(val reportedContentContentUuid: UUID, val reportedContentType: String,
val reportedContentReason: String, val reportedUserUuid: UUID) : Timestamp(), Parcelable | app/src/main/java/com/duopoints/android/rest/models/dbobjects/ReportedContent.kt | 2552054594 |
package io.gitlab.arturbosch.detekt.core.processors
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.internal.McCabeVisitor
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.psi.KtFile
class ProjectComplexityProcessor : AbstractProcessor() {
override val visitor = ComplexityVisitor()
override val key = complexityKey
}
val complexityKey = Key<Int>("complexity")
class ComplexityVisitor : DetektVisitor() {
override fun visitKtFile(file: KtFile) {
with(McCabeVisitor()) {
file.accept(this)
file.putUserData(complexityKey, mcc)
}
}
}
| detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/processors/ProjectComplexityProcessor.kt | 1618643473 |
package bob.clean.domain.interactor
import bob.clean.domain.User
import bob.clean.domain.repository.UserRepository
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class LoginTest {
val repository = mock<UserRepository>()
val login = Login(repository)
val name = "name"
val pass = "pass"
@Test
fun testSuccess() {
whenever(repository.login(name, pass)).thenReturn(User(""))
assertNotNull(login.execute(Login.Params(name, pass)))
verify(repository).login(name, pass)
}
@Test
fun testFail() {
whenever(repository.login(name, pass)).thenReturn(null)
assertNull(login.execute(Login.Params(name, pass)))
verify(repository).login(name, pass)
}
@Test(expected = Exception::class)
fun testException() {
val exception = Exception()
whenever(repository.login(name, pass)).thenThrow(exception)
login.execute(Login.Params(name, pass))
}
}
| domain/src/test/kotlin/bob/clean/domain/interactor/LoginTest.kt | 3400901771 |
package com.cout970.statistics.tileentity
import com.cout970.statistics.block.BlockCable
import com.cout970.statistics.block.BlockController
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.ITickable
import net.minecraft.util.math.BlockPos
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.items.CapabilityItemHandler
import net.minecraftforge.items.IItemHandler
import java.util.*
/**
* Created by cout970 on 05/08/2016.
*/
class TileInventoryConnector : TileBase(), ITickable {
val inventory = Inventory()
override fun update() {
if ((worldObj.totalWorldTime + pos.hashCode()) % 20 == 0L) {
inventory.subInventories.clear()
inventory.subInventories.addAll(getInventories().filter { it !is Inventory })
}
}
override fun getInventories(): List<IItemHandler> {
val list = mutableSetOf<IItemHandler>()
val forbiden = setOf(pos.offset(EnumFacing.DOWN), pos.offset(EnumFacing.UP), pos.offset(EnumFacing.NORTH), pos.offset(EnumFacing.SOUTH),
pos.offset(EnumFacing.EAST), pos.offset(EnumFacing.WEST))
val queue = LinkedList<Pair<BlockPos, EnumFacing>>()
val map = HashSet<Pair<BlockPos, EnumFacing>>()
for (dir in EnumFacing.VALUES) {
queue.add(pos to dir)
map.add(pos to dir)
}
while (!queue.isEmpty()) {
val pair = queue.pop()
val pos = pair.first.offset(pair.second)
val block = worldObj.getBlockState(pos).block
if (block == BlockCable || block == BlockController) {
for (dir in EnumFacing.VALUES) {
if ((pos to dir) !in map) {
queue.add(pos to dir)
map.add(pos to dir)
}
}
} else if (pos !in forbiden) {
val tile = worldObj.getTileEntity(pos)
if (tile != null) {
val inventory = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, pair.second.opposite)
if (inventory != null) {
list.add(inventory)
}
}
}
}
return LinkedList(list)
}
override fun <T : Any?> getCapability(capability: Capability<T>?, facing: EnumFacing?): T {
@Suppress("UNCHECKED_CAST")
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return inventory as T
return super.getCapability(capability, facing)
}
override fun hasCapability(capability: Capability<*>?, facing: EnumFacing?): Boolean {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return true
return super.hasCapability(capability, facing)
}
inner class Inventory : IItemHandler {
val subInventories = mutableListOf<IItemHandler>()
fun getSlot(index: Int): Pair<Int, IItemHandler>? {
var acum = 0
for (i in subInventories) {
val slots = i.slots
if (index >= acum + slots) {
acum += i.slots
} else {
return (index - acum) to i
}
}
return null
}
override fun getStackInSlot(slot: Int): ItemStack? {
val pair = getSlot(slot) ?: return null
return pair.second.getStackInSlot(pair.first)
}
override fun insertItem(slot: Int, stack: ItemStack?, simulate: Boolean): ItemStack? {
val pair = getSlot(slot) ?: return stack
return pair.second.insertItem(pair.first, stack, simulate)
}
override fun getSlots(): Int = subInventories.sumBy { it.slots }
override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? {
val pair = getSlot(slot) ?: return null
return pair.second.extractItem(pair.first, amount, simulate)
}
}
} | src/main/kotlin/com/cout970/statistics/tileentity/TileInventoryConnector.kt | 2578162299 |
package com.hea3ven.dulcedeleche.modules.redstone
import com.hea3ven.dulcedeleche.config.BaseModuleConfig
data class RedstoneModuleConfig(val dispenserPlantBehaviorEnabled: Boolean,
val dispenserBreedingBehaviorEnabled: Boolean) : BaseModuleConfig() {
constructor() : this(true, true)
} | src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/RedstoneModuleConfig.kt | 2697385562 |
import org.junit.jupiter.api.Test
interface File {
fun read(name: String)
}
class NormalFile : File {
override fun read(name: String) = println("Reading file: $name")
}
//Proxy:
class SecuredFile(private val normalFile: File) : File {
var password: String = ""
override fun read(name: String) {
if (password == "secret") {
println("Password is correct: $password")
normalFile.read(name)
} else {
println("Incorrect password. Access denied!")
}
}
}
class ProtectionProxyTest {
@Test
fun `Protection Proxy`() {
val securedFile = SecuredFile(NormalFile())
with(securedFile) {
read("readme.md")
password = "secret"
read("readme.md")
}
}
} | patterns/src/test/kotlin/ProtectionProxy.kt | 1534212439 |
package ademar.study.reddit.core.model.internal
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
@JsonObject
class Comment {
@JsonField(name = arrayOf("replies"))
var replies: PostDetailDataReply? = null
@JsonField(name = arrayOf("author"))
lateinit var author: String
@JsonField(name = arrayOf("body"))
lateinit var text: String
@JsonField(name = arrayOf("downs"))
var downs: Long = 0L
@JsonField(name = arrayOf("ups"))
var ups: Long = 0L
}
| Projects/Reddit/core/src/main/java/ademar/study/reddit/core/model/internal/Comment.kt | 750021079 |
package uk.co.nickthecoder.paratask.util
import org.junit.Assert.assertEquals
import org.junit.Test
class StringExtensionsTest {
@Test
fun escapeTest() {
assertEquals( "Hello\\nWorld", "Hello\nWorld".escapeNL() )
assertEquals( "Hello\\n\\nWorld", "Hello\n\nWorld".escapeNL() )
assertEquals( "Hello\\\\World", "Hello\\World".escapeNL() )
}
@Test
fun unescapeNLTest() {
assertEquals( "Hello\nWorld", "Hello\\nWorld".unescapeNL())
assertEquals( "Hello\n\nWorld", "Hello\\n\\nWorld".unescapeNL())
assertEquals( "Hello\\World", "Hello\\\\World".unescapeNL())
}
@Test
fun uncamelTest() {
assertEquals( "Hello", "hello".uncamel() )
assertEquals( "Hello World", "helloWorld".uncamel() )
assertEquals( "Hello World Again", "helloWorldAgain".uncamel() )
assertEquals( "Url", "url".uncamel() )
assertEquals( "URL", "URL".uncamel() )
assertEquals( "URLString", "URLString".uncamel() )
}
}
| paratask-app/src/test/kotlin/uk/co/nickthecoder/paratask/util/StringExtensionsTest.kt | 2515595031 |
package gsonpath.adapter.standard.adapter
import com.squareup.javapoet.ClassName
import gsonpath.adapter.standard.adapter.read.ReadParams
import gsonpath.adapter.standard.adapter.write.WriteParams
import gsonpath.adapter.standard.model.GsonField
import gsonpath.adapter.standard.model.GsonObject
data class AdapterModelMetadata(
val modelClassName: ClassName,
val adapterGenericTypeClassNames: List<ClassName>,
val adapterClassName: ClassName,
val isModelInterface: Boolean,
val rootGsonObject: GsonObject,
val readParams: ReadParams,
val writeParams: WriteParams
) | compiler/standard/src/main/java/gsonpath/adapter/standard/adapter/AdapterModelMetadata.kt | 2517167341 |
/*
* Copyright 2000-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.concurrency
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Getter
import com.intellij.util.Consumer
import com.intellij.util.Function
import org.jetbrains.concurrency.Promise.State
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference
private val LOG = Logger.getInstance(AsyncPromise::class.java)
open class AsyncPromise<T> : Promise<T>, Getter<T> {
private val doneRef = AtomicReference<Consumer<in T>?>()
private val rejectedRef = AtomicReference<Consumer<in Throwable>?>()
private val stateRef = AtomicReference(State.PENDING)
// result object or error message
@Volatile private var result: Any? = null
override fun getState() = stateRef.get()!!
override fun done(done: Consumer<in T>): Promise<T> {
if (isObsolete(done)) {
return this
}
when (state) {
State.PENDING -> {
setHandler(doneRef, done, State.FULFILLED)
}
State.FULFILLED -> {
@Suppress("UNCHECKED_CAST")
done.consume(result as T?)
}
State.REJECTED -> {
}
}
return this
}
override fun rejected(rejected: Consumer<Throwable>): Promise<T> {
if (isObsolete(rejected)) {
return this
}
when (state) {
State.PENDING -> {
setHandler(rejectedRef, rejected, State.REJECTED)
}
State.FULFILLED -> {
}
State.REJECTED -> {
rejected.consume(result as Throwable?)
}
}
return this
}
@Suppress("UNCHECKED_CAST")
override fun get() = if (state == State.FULFILLED) result as T? else null
override fun <SUB_RESULT> then(handler: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> {
@Suppress("UNCHECKED_CAST")
when (state) {
State.PENDING -> {
}
State.FULFILLED -> return DonePromise<SUB_RESULT>(
handler.`fun`(result as T?))
State.REJECTED -> return rejectedPromise(result as Throwable)
}
val promise = AsyncPromise<SUB_RESULT>()
addHandlers(Consumer({ result ->
promise.catchError {
if (handler is Obsolescent && handler.isObsolete) {
promise.cancel()
}
else {
promise.setResult(handler.`fun`(result))
}
}
}), Consumer({ promise.setError(it) }))
return promise
}
override fun notify(child: AsyncPromise<in T>) {
LOG.assertTrue(child !== this)
when (state) {
State.PENDING -> {
addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) }))
}
State.FULFILLED -> {
@Suppress("UNCHECKED_CAST")
child.setResult(result as T)
}
State.REJECTED -> {
child.setError((result as Throwable?)!!)
}
}
}
override fun <SUB_RESULT> thenAsync(handler: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> {
@Suppress("UNCHECKED_CAST")
when (state) {
State.PENDING -> {
}
State.FULFILLED -> return handler.`fun`(result as T?)
State.REJECTED -> return rejectedPromise(result as Throwable)
}
val promise = AsyncPromise<SUB_RESULT>()
val rejectedHandler = Consumer<Throwable>({ promise.setError(it) })
addHandlers(Consumer({
promise.catchError {
handler.`fun`(it)
.done { promise.catchError { promise.setResult(it) } }
.rejected(rejectedHandler)
}
}), rejectedHandler)
return promise
}
override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> {
when (state) {
State.PENDING -> {
addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) }))
}
State.FULFILLED -> {
@Suppress("UNCHECKED_CAST")
fulfilled.setResult(result as T)
}
State.REJECTED -> {
fulfilled.setError((result as Throwable?)!!)
}
}
return this
}
private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) {
setHandler(doneRef, done, State.FULFILLED)
setHandler(rejectedRef, rejected, State.REJECTED)
}
fun setResult(result: T?) {
if (!stateRef.compareAndSet(State.PENDING, State.FULFILLED)) {
return
}
this.result = result
val done = doneRef.getAndSet(null)
rejectedRef.set(null)
if (done != null && !isObsolete(done)) {
done.consume(result)
}
}
fun setError(error: String) = setError(createError(error))
fun cancel() {
setError(OBSOLETE_ERROR)
}
open fun setError(error: Throwable): Boolean {
if (!stateRef.compareAndSet(State.PENDING, State.REJECTED)) {
return false
}
result = error
val rejected = rejectedRef.getAndSet(null)
doneRef.set(null)
if (rejected == null) {
LOG.errorIfNotMessage(error)
}
else if (!isObsolete(rejected)) {
rejected.consume(error)
}
return true
}
override fun processed(processed: Consumer<in T>): Promise<T> {
done(processed)
rejected { processed.consume(null) }
return this
}
override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? {
val latch = CountDownLatch(1)
processed { latch.countDown() }
if (!latch.await(timeout.toLong(), timeUnit)) {
throw TimeoutException()
}
@Suppress("UNCHECKED_CAST")
if (isRejected) {
throw (result as Throwable)
}
else {
return result as T?
}
}
private fun <T> setHandler(ref: AtomicReference<Consumer<in T>?>, newConsumer: Consumer<in T>, targetState: State) {
while (true) {
val oldConsumer = ref.get()
val newEffectiveConsumer = when (oldConsumer) {
null -> newConsumer
is CompoundConsumer<*> -> {
@Suppress("UNCHECKED_CAST")
val compoundConsumer = oldConsumer as CompoundConsumer<T>
var executed = true
synchronized(compoundConsumer) {
compoundConsumer.consumers?.let {
it.add(newConsumer)
executed = false
}
}
// clearHandlers was called - just execute newConsumer
if (executed) {
if (state == targetState) {
@Suppress("UNCHECKED_CAST")
newConsumer.consume(result as T?)
}
return
}
compoundConsumer
}
else -> CompoundConsumer(oldConsumer, newConsumer)
}
if (ref.compareAndSet(oldConsumer, newEffectiveConsumer)) {
break
}
}
if (state == targetState) {
ref.getAndSet(null)?.let {
@Suppress("UNCHECKED_CAST")
it.consume(result as T?)
}
}
}
}
private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> {
var consumers: MutableList<Consumer<in T>>? = ArrayList()
init {
synchronized(this) {
consumers!!.add(c1)
consumers!!.add(c2)
}
}
override fun consume(t: T) {
val list = synchronized(this) {
val list = consumers
consumers = null
list
} ?: return
for (consumer in list) {
if (!isObsolete(consumer)) {
consumer.consume(t)
}
}
}
fun add(consumer: Consumer<in T>) {
synchronized(this) {
consumers.let {
if (it == null) {
// it means that clearHandlers was called
}
consumers?.add(consumer)
}
}
}
}
internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete
inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? {
try {
return runnable()
}
catch (e: Throwable) {
setError(e)
return null
}
} | platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt | 2829527447 |
package net.nemerosa.ontrack.graphql.schema
import graphql.Scalars.GraphQLInt
import graphql.schema.GraphQLArgument.newArgument
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLFieldDefinition.newFieldDefinition
import graphql.schema.GraphQLNonNull
import net.nemerosa.ontrack.model.exceptions.PromotionLevelNotFoundException
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.PromotionLevel
import net.nemerosa.ontrack.model.structure.StructureService
import org.springframework.stereotype.Component
/**
* Root query to get a [PromotionLevel] using its ID.
*/
@Component
class GQLRootQueryPromotionLevel(
private val structureService: StructureService,
private val promotionLevel: GQLTypePromotionLevel
) : GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition {
return newFieldDefinition()
.name("promotionLevel")
.type(promotionLevel.typeRef)
.argument(
newArgument()
.name("id")
.description("ID of the promotion level to look for (required)")
.type(GraphQLNonNull(GraphQLInt))
.build()
)
.dataFetcher { env ->
// Gets the ID
val id = env.getArgument<Int>("id") ?: throw IllegalStateException("`id` argument is required")
// Gets the promotion level
try {
structureService.getPromotionLevel(ID.of(id))
} catch (ignored: PromotionLevelNotFoundException) {
null
}
}
.build()
}
}
| ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLRootQueryPromotionLevel.kt | 3287371611 |
package net.nemerosa.ontrack.extension.scm.catalog.api
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLObjectType
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog
import net.nemerosa.ontrack.graphql.schema.GQLRootQuery
import net.nemerosa.ontrack.graphql.schema.GQLType
import net.nemerosa.ontrack.graphql.schema.GQLTypeCache
import net.nemerosa.ontrack.graphql.support.intField
import net.nemerosa.ontrack.graphql.support.listType
import org.springframework.stereotype.Component
@Component
class GQLRootQuerySCMCatalogTeamStats(
private val scmCatalog: SCMCatalog,
private val gqlTypeSCMCatalogTeamStats: GQLTypeSCMCatalogTeamStats
) : GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition()
.name("scmCatalogTeamStats")
.description("Counts of SCM catalog entries having N teams")
.type(listType(gqlTypeSCMCatalogTeamStats.typeRef))
.dataFetcher {
// Collecting team counts
val teamCounts = mutableMapOf<Int, Int>()
scmCatalog.catalogEntries.forEach { entry ->
val teamCount = entry.teams?.size ?: 0
val currentCount = teamCounts[teamCount]
if (currentCount != null) {
teamCounts[teamCount] = currentCount + 1
} else {
teamCounts[teamCount] = 1
}
}
// OK
teamCounts.map { (teamCount, entryCount) ->
SCMCatalogTeamStats(teamCount, entryCount)
}.sortedByDescending { it.teamCount }
}
.build()
}
@Component
class GQLTypeSCMCatalogTeamStats : GQLType {
override fun getTypeName(): String = SCMCatalogTeamStats::class.java.simpleName
override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject()
.name(typeName)
.description("Number of entries in the SCM catalog having this number of teams")
.intField(SCMCatalogTeamStats::teamCount, "Number of teams")
.intField(SCMCatalogTeamStats::entryCount, "Number of entries having this number of teams")
.build()
}
data class SCMCatalogTeamStats(
val teamCount: Int,
val entryCount: Int,
)
| ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/api/GQLRootQuerySCMCatalogTeamStats.kt | 2117129780 |
package net.nemerosa.ontrack.extension.dm.tse
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.convert.DurationUnit
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.temporal.ChronoUnit
@Component
@ConfigurationProperties(prefix = "ontrack.extension.delivery-metrics.tse")
class TimeSinceEventConfigurationProperties {
/**
* Is the "time since event" metric enabled?
*/
var enabled: Boolean = true
/**
* Interval between two scans for "time since events"
*/
@DurationUnit(ChronoUnit.MINUTES)
var interval: Duration = Duration.ofMinutes(30)
}
| ontrack-extension-delivery-metrics/src/main/java/net/nemerosa/ontrack/extension/dm/tse/TimeSinceEventConfigurationProperties.kt | 4285833711 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.