content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package pt.joaomneto.titancompanion.adventure.impl class SOSAdventure : TFODAdventure()
src/main/java/pt/joaomneto/titancompanion/adventure/impl/SOSAdventure.kt
3183848216
package io.kotest.data import io.kotest.mpp.reflection import kotlin.jvm.JvmName suspend fun <A, B> forAll(vararg rows: Row2<A, B>, testfn: suspend (A, B) -> Unit) { val params = reflection.paramNames(testfn) ?: emptyList<String>() val paramA = params.getOrElse(0) { "a" } val paramB = params.getOrElse(1) { "b" } table(headers(paramA, paramB), *rows).forAll { a, b -> testfn(a, b) } } @JvmName("forall2") inline fun <A, B> forAll(table: Table2<A, B>, testfn: (A, B) -> Unit) = table.forAll(testfn) inline fun <A, B> Table2<A, B>.forAll(fn: (A, B) -> Unit) { val collector = ErrorCollector() for (row in rows) { try { fn(row.a, row.b) } catch (e: Throwable) { collector.append(error(e, headers.values(), row.values())) } } collector.assertAll() } suspend fun <A, B> forNone(vararg rows: Row2<A, B>, testfn: suspend (A, B) -> Unit) { val params = reflection.paramNames(testfn) ?: emptyList<String>() val paramA = params.getOrElse(0) { "a" } val paramB = params.getOrElse(1) { "b" } table(headers(paramA, paramB), *rows).forNone { a, b -> testfn(a, b) } } @JvmName("fornone2") inline fun <A, B> forNone(table: Table2<A, B>, testfn: (A, B) -> Unit) = table.forNone(testfn) inline fun <A, B> Table2<A, B>.forNone(fn: (A, B) -> Unit) { for (row in rows) { try { fn(row.a, row.b) } catch (e: AssertionError) { continue } throw forNoneError(headers.values(), row.values()) } }
kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/data/forAll2.kt
3447243927
package io.kotest.assertions.json sealed class JsonNode { fun type() = when (this) { is ObjectNode -> "object" is ArrayNode -> "array" is BooleanNode -> "boolean" is StringNode -> "string" is LongNode -> "long" is DoubleNode -> "double" is IntNode -> "int" is FloatNode -> "float" NullNode -> "null" } data class ObjectNode(val elements: Map<String, JsonNode>) : JsonNode() data class ArrayNode(val elements: List<JsonNode>) : JsonNode() interface ValueNode data class BooleanNode(val value: Boolean) : JsonNode(), ValueNode data class StringNode(val value: String) : JsonNode(), ValueNode data class FloatNode(val value: Float) : JsonNode(), ValueNode data class LongNode(val value: Long) : JsonNode(), ValueNode data class DoubleNode(val value: Double) : JsonNode(), ValueNode data class IntNode(val value: Int) : JsonNode(), ValueNode object NullNode : JsonNode(), ValueNode }
kotest-assertions/kotest-assertions-json/src/commonMain/kotlin/io/kotest/assertions/json/nodes.kt
1906321695
package {{ cookiecutter.package_name }}.base interface IBaseView{ }
{{cookiecutter.repo_name}}/app/src/main/kotlin/base/IBaseView.kt
2241385370
package com.jiangKlijna.web.control import com.jiangKlijna.web.app.ContextWrapper import com.jiangKlijna.web.bean.Result import org.springframework.web.bind.annotation.ModelAttribute import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpSession import java.io.IOException open class BaseControl : ContextWrapper() { protected var request: HttpServletRequest? = null protected var response: HttpServletResponse? = null protected var session: HttpSession? = null @ModelAttribute fun setReqAndRes(request: HttpServletRequest, response: HttpServletResponse) { this.request = request this.response = response this.session = request.session } protected fun response(contentType: String, content: String) { try { response!!.contentType = contentType val w = response!!.writer w.print(content) w.flush() w.close() } catch (e: IOException) { e.printStackTrace() } } companion object { @JvmStatic protected val errorParameterResult = Result(1, "invalid parameter", "") @JvmStatic protected fun testParameter(vararg strs: String?): Boolean { for (s in strs) if (s == null || s.isEmpty()) return false return true } } }
springmvc/spring-springmvc-springdatajpa-kotlin/src/main/java/com/jiangKlijna/web/control/BaseControl.kt
2661183208
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.transform import com.android.tools.build.jetifier.core.config.Config import com.android.tools.build.jetifier.core.pom.PomDependency import com.android.tools.build.jetifier.core.pom.PomRewriteRule import com.android.tools.build.jetifier.processor.Processor import com.google.common.truth.Truth import org.junit.Test class DependencyMappingTest { @Test fun mapTest_oneToOne_shouldMap() { MappingTester.testRewrite( from = "hello:world:1.0.0", to = "hi:all:2.0.0", rules = setOf( PomRewriteRule( from = PomDependency(groupId = "hello", artifactId = "world"), to = PomDependency(groupId = "hi", artifactId = "all", version = "2.0.0") )) ) } object MappingTester { fun testRewrite(from: String, to: String?, rules: Set<PomRewriteRule>) { val config = Config.fromOptional( pomRewriteRules = rules ) val processor = Processor.createProcessor(config) val result = processor.mapDependency(from) if (to == null) { Truth.assertThat(result).isNull() } else { Truth.assertThat(result).isEqualTo(to) } } } }
jetifier/jetifier/processor/src/test/kotlin/com/android/tools/build/jetifier/processor/transform/DependencyMappingTest.kt
806801932
package com.ivanovsky.passnotes.domain.usecases import com.ivanovsky.passnotes.data.ObserverBus import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.data.entity.Template import com.ivanovsky.passnotes.data.entity.TemplateField import com.ivanovsky.passnotes.data.entity.TemplateFieldType import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository import com.ivanovsky.passnotes.domain.DispatcherProvider import kotlinx.coroutines.withContext import java.util.UUID class AddTemplatesUseCase( private val dbRepo: EncryptedDatabaseRepository, private val dispatchers: DispatcherProvider, private val observerBus: ObserverBus ) { suspend fun addTemplates(): OperationResult<Boolean> { return withContext(dispatchers.IO) { val isAdd = dbRepo.templateRepository.addTemplates(createDefaultTemplates()) if (isAdd.isSucceededOrDeferred) { observerBus.notifyGroupDataSetChanged() val templateGroupUid = dbRepo.templateRepository.templateGroupUid if (templateGroupUid != null) { observerBus.notifyNoteDataSetChanged(templateGroupUid) } } isAdd } } private fun createDefaultTemplates(): List<Template> { return listOf( Template( uid = UUID.randomUUID(), title = "ID card", fields = listOf( TemplateField( title = "Number", position = 0, type = TemplateFieldType.INLINE ), TemplateField( title = "Name", position = 1, type = TemplateFieldType.INLINE ), TemplateField( title = "Place of issue", position = 2, type = TemplateFieldType.INLINE ), TemplateField( title = "Date of issue", position = 3, type = TemplateFieldType.INLINE ), TemplateField( title = "@exp_date", position = 4, type = TemplateFieldType.DATE_TIME ) ) ), Template( uid = UUID.randomUUID(), title = "E-Mail", fields = listOf( TemplateField( title = "E-Mail", position = 0, type = TemplateFieldType.INLINE ), TemplateField( title = "URL", position = 1, type = TemplateFieldType.INLINE ), TemplateField( title = "Password", position = 2, type = TemplateFieldType.PROTECTED_INLINE ) ) ), Template( uid = UUID.randomUUID(), title = "Wireless LAN", fields = listOf( TemplateField( title = "SSID", position = 0, type = TemplateFieldType.INLINE ), TemplateField( title = "Password", position = 1, type = TemplateFieldType.PROTECTED_INLINE ) ) ), Template( uid = UUID.randomUUID(), title = "Secure note", fields = listOf( TemplateField( title = "Notes", position = 0, type = TemplateFieldType.INLINE ) ) ), Template( uid = UUID.randomUUID(), title = "Credit card", fields = listOf( TemplateField( title = "Number", position = 0, type = TemplateFieldType.INLINE ), TemplateField( title = "CVV", position = 1, type = TemplateFieldType.PROTECTED_INLINE ), TemplateField( title = "PIN", position = 2, type = TemplateFieldType.PROTECTED_INLINE ), TemplateField( title = "Card holder", position = 3, type = TemplateFieldType.INLINE ), TemplateField( title = "@exp_date", position = 4, type = TemplateFieldType.DATE_TIME ) ) ), Template( uid = UUID.randomUUID(), title = "Membership", fields = listOf( TemplateField( title = "Number", position = 0, type = TemplateFieldType.INLINE ), TemplateField( title = "URL", position = 1, type = TemplateFieldType.INLINE ), TemplateField( title = "@exp_date", position = 2, type = TemplateFieldType.DATE_TIME ) ) ) ) } }
app/src/main/kotlin/com/ivanovsky/passnotes/domain/usecases/AddTemplatesUseCase.kt
891334865
/* * Copyright 2017, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.integration.kotlintestapp.vo import androidx.room.TypeConverter import java.util.Date class DateConverter { @TypeConverter fun toDate(timestamp: Long?): Date? { return if (timestamp == null) null else Date(timestamp) } @TypeConverter fun toTimestamp(date: Date?): Long? { return date?.time } }
room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/vo/DateConverter.kt
216762510
import kotlin.math.PI import kotlin.math.asin import kotlin.math.sqrt import kotlin.random.Random import kotlin.system.measureTimeMillis fun main() { val n = 2_000_000 val rands = DoubleArray(n) val gen = Random(321) // 1st variant val duration1 = measureTimeMillis { var i = 0 while (i < n) { val r1 = gen.nextDouble() val r2 = gen.nextDouble() if (r2 < asin(sqrt(r1)) / (PI / 2)) { rands.set(i, r1) i++ } } } var sum = 0.0 for (r in rands) { sum += r } println("1st variant:") println("average = ${sum / n}") println("generation takes ${1e-3 * duration1} s") // 2nd variant // Park-Miller RNG val a: Long = 48_271 val m: Long = 2_147_483_647 fun pm(state: Long): Long { return state * a % m } fun toD(state: Long): Double { return state.toDouble() / m.toDouble() } val duration2 = measureTimeMillis { var i = 0 var s: Long = 42 while (i < n) { s = pm(s) val r1 = toD(s) s = pm(s) val r2 = toD(s) if (r2 < asin(sqrt(r1)) / (PI / 2)) { rands.set(i, r1) i++ } } } sum = 0.0 for (r in rands) { sum += r } println("2nd variant:") println("average = ${sum / n}") println("generation takes ${1e-3 * duration2} s") // 3rd variant val duration3 = measureTimeMillis { var i = 0 var s: Long = 142 sum = 0.0 while (i < n) { s = pm(s) val r1 = toD(s) s = pm(s) val r2 = toD(s) if (r2 < asin(sqrt(r1)) / (PI / 2)) { sum += r1 i++ } } } println("3nd variant:") println("average = ${sum / n}") println("generation takes ${1e-3 * duration3} s") }
Kotlin/generation.kt
976743486
/* * Copyright 2000-2022 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. */ import io.mockk.* import jetbrains.buildServer.clouds.CloudInstanceUserData import jetbrains.buildServer.clouds.InstanceStatus import jetbrains.buildServer.clouds.azure.arm.* import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector import jetbrains.buildServer.clouds.azure.arm.connector.AzureInstance import kotlinx.coroutines.* import org.jmock.MockObjectTestCase import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import java.util.concurrent.CyclicBarrier import kotlin.concurrent.thread class AzureCloudImageTest : MockObjectTestCase() { private lateinit var myJob: CompletableJob private lateinit var myImageDetails: AzureCloudImageDetails private lateinit var myApiConnector: AzureApiConnector private lateinit var myScope: CoroutineScope @BeforeMethod fun beforeMethod() { MockKAnnotations.init(this) myApiConnector = mockk(); coEvery { myApiConnector.createInstance(any(), any()) } answers { Unit } every { myApiConnector.fetchInstances<AzureInstance>(any<AzureCloudImage>()) } returns emptyMap() myImageDetails = AzureCloudImageDetails( mySourceId = null, deployTarget = AzureCloudDeployTarget.SpecificGroup, regionId = "regionId", groupId = "groupId", imageType = AzureCloudImageType.Image, imageUrl = null, imageId = "imageId", instanceId = null, osType = null, networkId = null, subnetId = null, vmNamePrefix = "vm", vmSize = null, vmPublicIp = null, myMaxInstances = 2, username = null, storageAccountType = null, template = null, numberCores = null, memory = null, storageAccount = null, registryUsername = null, agentPoolId = null, profileId = null, myReuseVm = false, customEnvironmentVariables = null, spotVm = null, enableSpotPrice = null, spotPrice = null, enableAcceleratedNetworking = null ) myJob = SupervisorJob() myScope = CoroutineScope(myJob + Dispatchers.IO) } @Test fun shouldCreateNewInstance() { // Given myScope = CoroutineScope(Dispatchers.Unconfined) val instance = createInstance() val userData = CloudInstanceUserData( "agentName", "authToken", "", 0, "profileId", "profileDescr", emptyMap() ) // When instance.startNewInstance(userData) // Then coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } } @Test fun shouldCreateSecondInstance() { // Given myScope = CoroutineScope(Dispatchers.Unconfined) val instance = createInstance() val userData = CloudInstanceUserData( "agentName", "authToken", "", 0, "profileId", "profileDescr", emptyMap() ) instance.startNewInstance(userData) // When instance.startNewInstance(userData) // Then coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } } @Test(invocationCount = 30) fun shouldCreateSecondInstanceInParallel() { // Given val instance = createInstance() val userData = CloudInstanceUserData( "agentName", "authToken", "", 0, "profileId", "profileDescr", emptyMap() ) val barrier = CyclicBarrier(3) // When val thread1 = thread(start = true) { barrier.await(); instance.startNewInstance(userData) } val thread2 = thread(start = true) { barrier.await(); instance.startNewInstance(userData) } barrier.await() thread1.join() thread2.join() myJob.complete() runBlocking { myJob.join() } // Then coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } } @Test(invocationCount = 30) fun shouldCheckInstanceLimitWhenCreateInstanceInParallel() { // Given val instance = createInstance() val userData = CloudInstanceUserData( "agentName", "authToken", "", 0, "profileId", "profileDescr", emptyMap() ) val barrier = CyclicBarrier(4) // When val thread1 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } } val thread2 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } } val thread3 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } } barrier.await() thread1.join() thread2.join() thread3.join() myJob.complete() runBlocking { myJob.join() } // Then coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } coVerify { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } coVerify(exactly = 0) { myApiConnector.createInstance( match { i -> i.imageId == instance.id && i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "3" && i.image == instance && i.status == InstanceStatus.STARTING }, match { userData -> userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "3" && userData.profileId == "profileId" && userData.profileDescription == "profileDescr" }) } } private fun createInstance() : AzureCloudImage { return AzureCloudImage(myImageDetails, myApiConnector, myScope) } }
plugin-azure-server/src/test/kotlin/jetbrains/buildServer/clouds/azure/arm/AzureCloudImageTest.kt
1591223125
package arma.ark.cartograph.mission.date import arma.ark.cartograph.config.DATE_FORMAT import arma.ark.cartograph.util.arma.parseIntSqfArray import org.joda.time.DateTimeConstants import org.joda.time.LocalDateTime import org.joda.time.format.DateTimeFormat const val SESSION_END_HOUR = 6; val DATE_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT) data class DateTimeDescription( val hour: Int, val minute: Int, val description: String ) val DATE_TIME_DESCRIPTIONS = arrayOf( DateTimeDescription(4, 50, "Dawn"), DateTimeDescription(5, 50, "Early Morning"), DateTimeDescription(9, 0, "Morning"), DateTimeDescription(12, 0, "Noon"), DateTimeDescription(15, 0, "Afternoon"), DateTimeDescription(17, 50, "Evening"), DateTimeDescription(18, 50, "Dusk"), DateTimeDescription(0, 0, "Night") ) data class Session( val week: Int, val day: String ) data class DateTime( val description: String, val year: Int, val month: Int, val day: Int, val hour: Int, val minute: Int ) data class Duration( val hour: Int, val minute: Int, val second: Int ) fun parseNullDate(dateStr: String?): LocalDateTime { return if (dateStr != null) DATE_FORMATTER.parseLocalDateTime(dateStr) else LocalDateTime.now() } fun getSession(created: LocalDateTime): Session { val day = when { created.dayOfWeek == DateTimeConstants.SATURDAY || created.dayOfWeek == DateTimeConstants.SUNDAY && created.hourOfDay <= SESSION_END_HOUR -> "Saturday" created.dayOfWeek == DateTimeConstants.SUNDAY || created.dayOfWeek == DateTimeConstants.MONDAY && created.hourOfDay <= SESSION_END_HOUR -> "Sunday" else -> "Unknown" } return Session(created.weekOfWeekyear, day) } fun getDateTime(dateStr: String?, timeStr: String?): DateTime { val date = parseIntSqfArray(dateStr) val time = parseIntSqfArray(timeStr) val finalDate = if (date.size != 3) IntArray(3){0} else date val finalTime = if (time.size != 2) IntArray(2){0} else time return DateTime(getDateTimeDescription(finalTime[0], finalTime[1]), finalDate[0], finalDate[1], finalDate[2], finalTime[0], finalTime[1]) } fun getDuration(duration: Float?): Duration { val finalDuration = (duration ?: 0f).toInt() return Duration(finalDuration / 3600, finalDuration % 3600 / 60, finalDuration % 60) } fun getDateTimeDescription(hour: Int, minute: Int): String { if (DATE_TIME_DESCRIPTIONS.isEmpty()) return "Noon" val time = hour * 60 + minute; val dtds = DATE_TIME_DESCRIPTIONS.plus(DATE_TIME_DESCRIPTIONS[0]) for (idx in (0..DATE_TIME_DESCRIPTIONS.size - 1)) { val dtd = dtds[idx] val nextDtd = dtds[idx + 1] if (time in (dtd.hour * 60 + dtd.minute .. nextDtd.hour * 60 + nextDtd.minute - 1)) return dtd.description } return "Noon" }
src/main/kotlin/arma/ark/cartograph/mission/date/Date.kt
772556189
package com.almasb.zeph.character import java.util.* /** * Character classes with base hp/sp. * * @author Almas Baimagambetov ([email protected]) */ enum class CharacterClass(val hp: Int, val sp: Int, val description: String) { MONSTER (50, 50, ""), NOVICE (10, 10, "You've only started your adventure! You have many great opportunities before you!"), // Warrior tree WARRIOR (40, 20, "Warriors are strong, tough and fearless. They will fight until their last breath and against all odds, will often emerge victorious."), CRUSADER (60, 35, "Crusaders are guardians of light. By using divine armor and weapons, they become virtually indestructible."), PALADIN (90, 50, "TODO"), GLADIATOR(65, 30, "Gladiators train their whole life to be the unstoppable force they are. Their raw strength can turn the tides of any battle."), KNIGHT (100, 35, "TODO"), // Scout tree SCOUT (30, 35, "Scouts are nimble experts with a bow. They often use unconventional tactics to surprise and, ultimately, defeat their opponents."), ROGUE (50, 40, "Rogues are shameless combatants who prefer daggers to execute their swift and deadly attacks. No matter who their enemies are, a rogue will always find a chink in their armor."), ASSASSIN (75, 45, "Assassins have mastered the art of killing. Always walking in the shadows, their enemies will never know what hit them."), RANGER (40, 40, "TODO"), HUNTER (50, 55, "TODO"), // Mage tree MAGE (25, 45, "Mages are adepts at manipulating the elements themselves. By tapping into the nature's powers, they can defeat their enemies with a single thought."), WIZARD (35, 60, "Wizards have gained the knowledge to blend elements together, multiplying their skill power. They are able to penetrate even most powerful magic barriers."), ARCHMAGE (45, 75, "Archmages' arcane powers are second to none. Only few exist who can withstand their full destructive power."), ENCHANTER(30, 65, "TODO"), SAGE (40, 90, "TODO"); } /** * Enemies can be one of 3 types. */ enum class CharacterType { NORMAL, MINIBOSS, BOSS } object CharacterClassChanger { private val reqList = HashMap<CharacterClass, Ascension>() init { reqList[CharacterClass.NOVICE] = Ascension(2, 2, CharacterClass.WARRIOR, CharacterClass.SCOUT, CharacterClass.MAGE) reqList[CharacterClass.WARRIOR] = Ascension(3, 3, CharacterClass.CRUSADER, CharacterClass.GLADIATOR) reqList[CharacterClass.SCOUT] = Ascension(3, 3, CharacterClass.ROGUE, CharacterClass.RANGER) reqList[CharacterClass.MAGE] = Ascension(3, 3, CharacterClass.WIZARD, CharacterClass.ENCHANTER) reqList[CharacterClass.CRUSADER] = Ascension(5, 5, CharacterClass.PALADIN) reqList[CharacterClass.GLADIATOR] = Ascension(5, 5, CharacterClass.KNIGHT) reqList[CharacterClass.ROGUE] = Ascension(5, 5, CharacterClass.ASSASSIN) reqList[CharacterClass.RANGER] = Ascension(5, 5, CharacterClass.HUNTER) reqList[CharacterClass.WIZARD] = Ascension(5, 5, CharacterClass.ARCHMAGE) reqList[CharacterClass.ENCHANTER] = Ascension(5, 5, CharacterClass.SAGE) } // fun canChangeClass(player: Entity): Boolean { // val r = reqList[player.charClass.value] // return r != null && player.baseLevel.value >= r.baseLevel && player.jobLevel.value >= r.jobLevel // } // // fun getAscensionClasses(player: Entity) = reqList[player.charClass.value]!!.classesTo private class Ascension(val baseLevel: Int, val jobLevel: Int, vararg classes: CharacterClass) { val classesTo = classes as Array<CharacterClass> } }
src/main/kotlin/com/almasb/zeph/character/CharacterClass.kt
3280477360
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.browser.behavior import android.content.Context import android.util.AttributeSet import android.view.View import com.google.android.material.appbar.AppBarLayout import jp.hazuki.yuzubrowser.browser.R import jp.hazuki.yuzubrowser.legacy.browser.BrowserController import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData import jp.hazuki.yuzubrowser.ui.widget.PaddingFrameLayout import jp.hazuki.yuzubrowser.webview.CustomWebView class WebViewBehavior(context: Context, attrs: AttributeSet) : AppBarLayout.ScrollingViewBehavior(context, attrs) { private var isInitialized = false private lateinit var topToolBar: View private lateinit var bottomBar: View private lateinit var paddingFrame: View private lateinit var overlayPaddingFrame: PaddingFrameLayout private lateinit var controller: BrowserController private var webView: CustomWebView? = null private var prevY: Int = 0 private var paddingHeight = 0 var isImeShown = false override fun layoutDependsOn(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View): Boolean { if (dependency is AppBarLayout) { topToolBar = parent.findViewById(R.id.topToolbar) bottomBar = parent.findViewById(R.id.bottomOverlayLayout) paddingFrame = child.findViewById(R.id.toolbarPadding) overlayPaddingFrame = child.findViewById(R.id.bottomAlwaysOverlayToolbarPadding) isInitialized = true return true } return false } override fun onDependentViewChanged(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View): Boolean { val bottom = dependency.bottom val webView = webView if (webView != null) { webView.isToolbarShowing = dependency.top == 0 if (!webView.isTouching && webView.webScrollY != 0) { webView.scrollBy(0, bottom - prevY) } val data = controller.getTabOrNull(webView) if (data != null) { adjustWebView(data, topToolBar.height + bottomBar.height) } } prevY = bottom return super.onDependentViewChanged(parent, child, dependency) } fun adjustWebView(data: MainTabData, height: Int) { if (!isInitialized) return if (paddingHeight != height) { paddingHeight = height val params = paddingFrame.layoutParams params.height = height paddingFrame.layoutParams = params data.mWebView.computeVerticalScrollRangeMethod() } if (data.isFinished && !data.mWebView.isScrollable && !isImeShown) { controller.expandToolbar() data.mWebView.isNestedScrollingEnabledMethod = false paddingFrame.visibility = View.VISIBLE overlayPaddingFrame.forceHide = true data.mWebView.computeVerticalScrollRangeMethod() } else { paddingFrame.visibility = View.GONE overlayPaddingFrame.forceHide = false data.mWebView.computeVerticalScrollRangeMethod() } } fun setWebView(webView: CustomWebView?) { this.webView = webView } fun setController(browserController: BrowserController) { controller = browserController } }
browser/src/main/java/jp/hazuki/yuzubrowser/browser/behavior/WebViewBehavior.kt
455922846
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 2015 Zhang Hai <[email protected]> * All Rights Reserved. */ package jp.hazuki.yuzubrowser.ui.widget.progress import android.content.Context /** * A backported `Drawable` for determinate horizontal `ProgressBar`. */ /** * Create a new `HorizontalProgressDrawable`. * * @param context the `Context` for retrieving style information. */ internal class HorizontalProgressDrawable(context: Context) : BaseProgressLayerDrawable<SingleHorizontalProgressDrawable, HorizontalProgressBarDrawable>( arrayOf( SingleHorizontalProgressDrawable(), HorizontalProgressBarDrawable(), HorizontalProgressBarDrawable() ), context )
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/HorizontalProgressDrawable.kt
1492316496
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.testFramework.fixtures import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.MAIN import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.InspectionTestUtil import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.createGlobalContextForTool import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.intellij.lang.annotations.Language abstract class LightJava9ModulesCodeInsightFixtureTestCase : LightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = MultiModuleJava9ProjectDescriptor override fun tearDown() { MultiModuleJava9ProjectDescriptor.cleanupSourceRoots() super.tearDown() } protected fun addFile(path: String, text: String, module: ModuleDescriptor = MAIN): VirtualFile = VfsTestUtil.createFile(module.root(), path, text) protected fun addTestFile(path: String, text: String): VirtualFile = VfsTestUtil.createFile(MAIN.testRoot()!!, path, text) /** * @param classNames is like <code>arrayOf("foo.api.Api", "foo.impl.Impl")</code>; the file's directory path is created based on FQN */ protected fun addJavaFiles(testDirPath: String, classNames: Array<out String>, module: ModuleDescriptor = MAIN) { classNames.map { val dot = it.lastIndexOf('.') val name = if (dot >= 0) it.substring(dot + 1) else it val sourceFile = FileUtil.findFirstThatExist("$testDirPath/$name.java") val text = String(FileUtil.loadFileText(sourceFile!!)) addFile("${it.replace('.', '/')}.java", text, module) } } protected fun moduleInfo(@Language("JAVA") text: String, module: ModuleDescriptor = MAIN) = addFile("module-info.java", text, module) protected fun doGlobalInspectionTest(testDirPath: String, toolWrapper: InspectionToolWrapper<*, *>) { val scope = AnalysisScope(project) val globalContext = createGlobalContextForTool(scope, project, listOf(toolWrapper)) InspectionTestUtil.runTool(toolWrapper, scope, globalContext) InspectionTestUtil.compareToolResults(globalContext, toolWrapper, true, testDirPath) } }
java/java-tests/testSrc/com/intellij/java/testFramework/fixtures/LightJava9ModulesCodeInsightFixtureTestCase.kt
1043473224
/*** * Copyright (c) 2018 CommonsWare, 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. * * Covered in detail in the book _The Busy Coder's Guide to Android Development_ * https://commonsware.com/Android */ package com.commonsware.android.auth.note import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import com.commonsware.cwac.saferoom.SafeHelperFactory import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.ObservableOnSubscribe import java.util.* private const val SCHEMA = 1 private const val DATABASE_NAME = "note.db" val EMPTY = Note(-1, null) class NoteRepository private constructor(ctxt: Context, passphrase: CharArray) { private val db: SupportSQLiteDatabase init { val factory = SafeHelperFactory(passphrase) val cfgBuilder = SupportSQLiteOpenHelper.Configuration.builder(ctxt) cfgBuilder .name(DATABASE_NAME) .callback(object : SupportSQLiteOpenHelper.Callback(SCHEMA) { override fun onCreate(db: SupportSQLiteDatabase) { db.execSQL("CREATE TABLE note (_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);") } override fun onUpgrade( db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int ) { throw RuntimeException("How did we get here?") } }) db = factory.create(cfgBuilder.build()).writableDatabase } private class LoadObservable(ctxt: Context, private val passphrase: CharArray) : ObservableOnSubscribe<Note> { private val app: Context = ctxt.applicationContext @Throws(Exception::class) override fun subscribe(e: ObservableEmitter<Note>) { val c = NoteRepository.init(app, passphrase).db.query("SELECT _id, content FROM note") if (c.isAfterLast) { e.onNext(EMPTY) } else { c.moveToFirst() e.onNext(Note(c.getLong(0), c.getString(1))) Arrays.fill(passphrase, '\u0000') } c.close() } } companion object { @Volatile private var INSTANCE: NoteRepository? = null @Synchronized private fun init(ctxt: Context, passphrase: CharArray): NoteRepository { return INSTANCE ?: NoteRepository(ctxt.applicationContext, passphrase).apply { INSTANCE = this } } @Synchronized private fun get(): NoteRepository { return INSTANCE!! } fun load(ctxt: Context, passphrase: CharArray): Observable<Note> { return Observable.create(LoadObservable(ctxt, passphrase)) } fun save(note: Note, content: String): Note { val cv = ContentValues(1) cv.put("content", content) return if (note === EMPTY) { val id = NoteRepository.get().db.insert("note", SQLiteDatabase.CONFLICT_ABORT, cv) Note(id, content) } else { NoteRepository.get().db.update( "note", SQLiteDatabase.CONFLICT_REPLACE, cv, "_id=?", arrayOf(note.id.toString()) ) Note(note.id, content) } } } }
demo/src/main/java/com/commonsware/android/auth/note/NoteRepository.kt
579913932
package com.google.firebase.quickstart.auth.kotlin import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.facebook.AccessToken import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.login.LoginManager import com.facebook.login.LoginResult import com.google.firebase.auth.FacebookAuthProvider import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.auth.R import com.google.firebase.quickstart.auth.databinding.FragmentFacebookBinding /** * Demonstrate Firebase Authentication using a Facebook access token. */ class FacebookLoginFragment : BaseFragment() { private lateinit var auth: FirebaseAuth private var _binding: FragmentFacebookBinding? = null private val binding: FragmentFacebookBinding get() = _binding!! private lateinit var callbackManager: CallbackManager override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentFacebookBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setProgressBar(binding.progressBar) binding.buttonFacebookSignout.setOnClickListener { signOut() } // Initialize Firebase Auth auth = Firebase.auth // Initialize Facebook Login button callbackManager = CallbackManager.Factory.create() binding.buttonFacebookLogin.setPermissions("email", "public_profile") binding.buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { Log.d(TAG, "facebook:onSuccess:$loginResult") handleFacebookAccessToken(loginResult.accessToken) } override fun onCancel() { Log.d(TAG, "facebook:onCancel") updateUI(null) } override fun onError(error: FacebookException) { Log.d(TAG, "facebook:onError", error) updateUI(null) } }) } override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) } private fun handleFacebookAccessToken(token: AccessToken) { Log.d(TAG, "handleFacebookAccessToken:$token") showProgressBar() val credential = FacebookAuthProvider.getCredential(token.token) auth.signInWithCredential(credential) .addOnCompleteListener(requireActivity()) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.exception) Toast.makeText(context, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } hideProgressBar() } } fun signOut() { auth.signOut() LoginManager.getInstance().logOut() updateUI(null) } private fun updateUI(user: FirebaseUser?) { hideProgressBar() if (user != null) { binding.status.text = getString(R.string.facebook_status_fmt, user.displayName) binding.detail.text = getString(R.string.firebase_status_fmt, user.uid) binding.buttonFacebookLogin.visibility = View.GONE binding.buttonFacebookSignout.visibility = View.VISIBLE } else { binding.status.setText(R.string.signed_out) binding.detail.text = null binding.buttonFacebookLogin.visibility = View.VISIBLE binding.buttonFacebookSignout.visibility = View.GONE } } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { private const val TAG = "FacebookLogin" } }
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginFragment.kt
2283935440
package com.github.prologdb.runtime.module import com.github.prologdb.runtime.PrologRuntimeEnvironment /** * Throws an exception when attempting to load any module. */ object NoopModuleLoader : ModuleLoader { /** * @throws ModuleNotFoundException */ override fun initiateLoading(reference: ModuleReference, runtime: PrologRuntimeEnvironment): Nothing { throw ModuleNotFoundException(reference) } }
core/src/main/kotlin/com/github/prologdb/runtime/module/NoopModuleLoader.kt
381518796
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int): Comparable<MyDate> { override fun compareTo(other: MyDate): Int { val result = 2000*(other.year - this.year) + 31*(other.month - this.month) + other.dayOfMonth - this.dayOfMonth return when { result == 0 -> 0 result > 0 -> -1 else -> 1 } } operator fun plus(interval: TimeInterval): MyDate { return this.addTimeIntervals(interval, 1) } operator fun plus(repeatedTimeInterval: RepeatedTimeInterval): MyDate { return this.addTimeIntervals(repeatedTimeInterval.ti, repeatedTimeInterval.n) } } operator fun MyDate.rangeTo(other: MyDate): DateRange { return DateRange(this, other) } enum class TimeInterval { DAY, WEEK, YEAR; operator fun times(i: Int): RepeatedTimeInterval { return RepeatedTimeInterval(this, i) } } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) class DateRange(val start: MyDate, val endInclusive: MyDate): Iterator<MyDate> { private var currentDate: MyDate = start override fun hasNext(): Boolean { return currentDate <= endInclusive } override fun next(): MyDate { val result = currentDate currentDate = currentDate.nextDay() return result } operator fun contains(date: MyDate): Boolean { if ((date >= start) && (date <= endInclusive)) { return true } return false } }
src/iii_conventions/MyDate.kt
1064305660
package org.nield.kotlinstatistics fun <T> Sequence<T>.mode() = countBy() .entries .asSequence() .sortedByDescending { it.value } .toList().let { list -> list.asSequence() .takeWhile { list[0].value == it.value } .map { it.key } } fun <T> Iterable<T>.mode() = asSequence().mode() fun <T> Array<out T>.mode() = asIterable().mode() fun ByteArray.mode() = asIterable().mode() fun ShortArray.mode() = asIterable().mode() fun IntArray.mode() = asIterable().mode() fun LongArray.mode() = asIterable().mode() fun FloatArray.mode() = asIterable().mode() fun DoubleArray.mode() = asIterable().mode() //AGGREGATION OPERATORS /** * Groups each distinct value with the number counts it appeared */ fun <T> Sequence<T>.countBy() = groupApply({ it }, {it.count()}) /** * Groups each distinct value with the number counts it appeared */ fun <T> Iterable<T>.countBy() = asSequence().countBy() /** * Groups each distinct key with the number counts it appeared */ inline fun <T,K> Sequence<T>.countBy(crossinline keySelector: (T) -> K) = groupApply(keySelector) { it.count() } /** * Groups each distinct key with the number counts it appeared */ inline fun <T,K> Iterable<T>.countBy(crossinline keySelector: (T) -> K) = asSequence().countBy(keySelector)
src/main/kotlin/org/nield/kotlinstatistics/CategoricalStatistics.kt
1239426891
/* Copyright 2022 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.example.makeitso import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.ExperimentalMaterialApi import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint @ExperimentalMaterialApi class MakeItSoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MakeItSoApp() } } }
app/src/main/java/com/example/makeitso/MakeItSoActivity.kt
2934062875
package org.cups4j /** * Copyright (C) 2009 Harald Weyhing * * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of * the GNU Lesser General Public License along with this program; if not, see * <http:></http:>//www.gnu.org/licenses/>. */ /*Notice * This file has been modified. It is not the original. * Jon Freeman - 2013 */ import android.content.Context import org.cups4j.operations.cups.CupsGetDefaultOperation import org.cups4j.operations.cups.CupsGetPrintersOperation import org.cups4j.operations.cups.CupsMoveJobOperation import org.cups4j.operations.ipp.IppCancelJobOperation import org.cups4j.operations.ipp.IppGetJobAttributesOperation import org.cups4j.operations.ipp.IppGetJobsOperation import org.cups4j.operations.ipp.IppHoldJobOperation import org.cups4j.operations.ipp.IppReleaseJobOperation import java.net.URL import java.security.cert.X509Certificate import timber.log.Timber /** * Main Client for accessing CUPS features like * - get printers * - print documents * - get job attributes * - ... */ class CupsClient @JvmOverloads constructor( val context: Context, private val url: URL = URL(DEFAULT_URL), private val userName: String = DEFAULT_USER ) { var serverCerts: Array<X509Certificate>? = null private set // Storage for server certificates if they're not trusted var lastResponseCode: Int = 0 private set /** * Path to list of printers, like xxx://ip:port/printers/printer_name => will contain '/printers/' * seen in issue: https://github.com/BenoitDuffez/AndroidCupsPrint/issues/40 */ private var path = "/printers/" // add default printer if available @Throws(Exception::class) fun getPrinters(firstName: String? = null, limit: Int? = null): List<CupsPrinter> { val cupsGetPrintersOperation = CupsGetPrintersOperation(context) val printers: List<CupsPrinter> try { printers = cupsGetPrintersOperation.getPrinters(url, path, firstName, limit) } finally { serverCerts = cupsGetPrintersOperation.serverCerts lastResponseCode = cupsGetPrintersOperation.lastResponseCode } val defaultPrinter = defaultPrinter for (p in printers) { if (defaultPrinter != null && p.printerURL.toString() == defaultPrinter.printerURL.toString()) { p.isDefault = true } } return printers } private val defaultPrinter: CupsPrinter? @Throws(Exception::class) get() = CupsGetDefaultOperation(context).getDefaultPrinter(url, path) val host: String get() = url.host @Throws(Exception::class) fun getPrinter(printerURL: URL): CupsPrinter? { // Extract the printer name var name = printerURL.path val pos = name.indexOf('/', 1) if (pos > 0) { name = name.substring(pos + 1) } val printers = getPrinters(name, 1) Timber.d("getPrinter: Found ${printers.size} possible CupsPrinters") for (p in printers) { if (p.printerURL.path == printerURL.path) return p } return null } @Throws(Exception::class) fun getJobAttributes(jobID: Int): PrintJobAttributes = getJobAttributes(url, userName, jobID) @Throws(Exception::class) fun getJobAttributes(userName: String, jobID: Int): PrintJobAttributes = getJobAttributes(url, userName, jobID) @Throws(Exception::class) private fun getJobAttributes(url: URL, userName: String, jobID: Int): PrintJobAttributes = IppGetJobAttributesOperation(context).getPrintJobAttributes(url, userName, jobID) @Throws(Exception::class) fun getJobs(printer: CupsPrinter, whichJobs: WhichJobsEnum, userName: String, myJobs: Boolean): List<PrintJobAttributes> = IppGetJobsOperation(context).getPrintJobs(printer, whichJobs, userName, myJobs) @Throws(Exception::class) fun cancelJob(jobID: Int): Boolean = IppCancelJobOperation(context).cancelJob(url, userName, jobID) @Throws(Exception::class) fun cancelJob(url: URL, userName: String, jobID: Int): Boolean = IppCancelJobOperation(context).cancelJob(url, userName, jobID) @Throws(Exception::class) fun holdJob(jobID: Int): Boolean = IppHoldJobOperation(context).holdJob(url, userName, jobID) @Throws(Exception::class) fun holdJob(url: URL, userName: String, jobID: Int): Boolean = IppHoldJobOperation(context).holdJob(url, userName, jobID) @Throws(Exception::class) fun releaseJob(jobID: Int): Boolean = IppReleaseJobOperation(context).releaseJob(url, userName, jobID) @Throws(Exception::class) fun releaseJob(url: URL, userName: String, jobID: Int): Boolean = IppReleaseJobOperation(context).releaseJob(url, userName, jobID) @Throws(Exception::class) fun moveJob(jobID: Int, userName: String, currentPrinter: CupsPrinter, targetPrinter: CupsPrinter): Boolean { val currentHost = currentPrinter.printerURL.host return CupsMoveJobOperation(context).moveJob(currentHost, userName, jobID, targetPrinter.printerURL) } /** * Ensure path starts and ends with a slash * * @param path Path to printers on server * @return Self for easy chained calls */ fun setPath(path: String): CupsClient { this.path = path if (!path.startsWith("/")) { this.path = "/$path" } if (!path.endsWith("/")) { this.path += "/" } return this } companion object { const val DEFAULT_USER = "anonymous" private const val DEFAULT_URL = "http://localhost:631" } }
app/src/main/java/org/cups4j/CupsClient.kt
1163940851
package io.hammerhead.mocha.api.uiactions.espresso import android.support.test.espresso.Espresso import android.support.test.espresso.ViewInteraction import io.hammerhead.mocha.api.expectations.espresso.EspressoAssertion import org.hamcrest.core.AllOf class EspressoExpectDelegator { private var viewInteraction: ViewInteraction? = null internal fun onDelegate(init: EspressoUiAction.() -> Unit) = delegate(init) internal fun assertDelegate(init: EspressoAssertion.() -> Unit) = EspressoAssertion(init, viewInteraction) private fun delegate(init: EspressoUiAction.() -> Unit) { viewInteraction = EspressoUiAction(init, { Espresso.onView(AllOf.allOf(it)) }).invoke() } }
mocha-api/src/main/kotlin/io/hammerhead/mocha/api/uiactions/espresso/EspressoExpectDelegator.kt
4271465986
/* * Copyright 2022 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.chat.bukkit.discord interface DiscordButtonClickEvent { fun reply(message: String) }
bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/discord/DiscordButtonClickEvent.kt
1583430502
package fr.free.nrw.commons.media import android.net.Uri import com.facebook.imagepipeline.common.BytesRange import com.facebook.imagepipeline.image.EncodedImage import com.facebook.imagepipeline.producers.Consumer import com.facebook.imagepipeline.producers.NetworkFetcher import com.facebook.imagepipeline.producers.ProducerContext import com.facebook.imagepipeline.request.ImageRequest import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.CommonsApplication import fr.free.nrw.commons.kvstore.JsonKvStore import okhttp3.* import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.jupiter.api.Assertions import org.mockito.Mock import org.mockito.MockitoAnnotations import org.powermock.reflect.Whitebox import java.lang.reflect.Method import java.util.concurrent.Executor class CustomOkHttpNetworkFetcherUnitTest { private lateinit var fetcher: CustomOkHttpNetworkFetcher private lateinit var okHttpClient: OkHttpClient private lateinit var state: CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState @Mock private lateinit var callback: NetworkFetcher.Callback @Mock private lateinit var defaultKvStore: JsonKvStore @Mock private lateinit var consumer: Consumer<EncodedImage> @Mock private lateinit var context: ProducerContext @Mock private lateinit var imageRequest: ImageRequest @Mock private lateinit var uri: Uri @Mock private lateinit var mCacheControl: CacheControl @Mock private lateinit var bytesRange: BytesRange @Mock private lateinit var executor: Executor @Mock private lateinit var call: Call @Mock private lateinit var response: Response @Mock private lateinit var body: ResponseBody @Before @Throws(Exception::class) fun setUp() { MockitoAnnotations.initMocks(this) okHttpClient = OkHttpClient() fetcher = CustomOkHttpNetworkFetcher(okHttpClient, defaultKvStore) whenever(context.imageRequest).thenReturn(imageRequest) whenever(imageRequest.sourceUri).thenReturn(uri) whenever(imageRequest.bytesRange).thenReturn(bytesRange) whenever(bytesRange.toHttpRangeHeaderValue()).thenReturn("bytes 200-1000/67589") whenever(uri.toString()).thenReturn("https://example.com") state = fetcher.createFetchState(consumer, context) } @Test @Throws(Exception::class) fun checkNotNull() { Assert.assertNotNull(fetcher) } @Test @Throws(Exception::class) fun testFetchCaseReturn() { whenever( defaultKvStore.getBoolean( CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED, false ) ).thenReturn(true) fetcher.fetch(state, callback) verify(callback).onFailure(any()) } @Test @Throws(Exception::class) fun testFetch() { Whitebox.setInternalState(fetcher, "mCacheControl", mCacheControl) whenever( defaultKvStore.getBoolean( CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED, false ) ).thenReturn(false) fetcher.fetch(state, callback) fetcher.onFetchCompletion(state, 0) verify(bytesRange).toHttpRangeHeaderValue() } @Test @Throws(Exception::class) fun testFetchCaseException() { whenever(uri.toString()).thenReturn("") whenever( defaultKvStore.getBoolean( CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED, false ) ).thenReturn(false) fetcher.fetch(state, callback) verify(callback).onFailure(any()) } @Test @Throws(Exception::class) fun testGetExtraMap() { val map = fetcher.getExtraMap(state, 40) Assertions.assertEquals(map!!["image_size"], 40.toString()) } @Test @Throws(Exception::class) fun testOnFetchCancellationRequested() { Whitebox.setInternalState(fetcher, "mCancellationExecutor", executor) val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod( "onFetchCancellationRequested", Call::class.java, ) method.isAccessible = true method.invoke(fetcher, call) verify(executor).execute(any()) } @Test @Throws(Exception::class) fun testOnFetchResponseCaseReturn() { whenever(response.body()).thenReturn(body) whenever(response.isSuccessful).thenReturn(false) whenever(call.isCanceled).thenReturn(true) val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod( "onFetchResponse", CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java, Call::class.java, Response::class.java, NetworkFetcher.Callback::class.java, ) method.isAccessible = true method.invoke(fetcher, state, call, response, callback) verify(callback).onCancellation() } @Test @Throws(Exception::class) fun testOnFetchResponse() { whenever(response.body()).thenReturn(body) whenever(response.isSuccessful).thenReturn(true) whenever(response.header("Content-Range")).thenReturn("bytes 200-1000/67589") whenever(call.isCanceled).thenReturn(true) whenever(body.contentLength()).thenReturn(-1) val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod( "onFetchResponse", CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java, Call::class.java, Response::class.java, NetworkFetcher.Callback::class.java, ) method.isAccessible = true method.invoke(fetcher, state, call, response, callback) verify(callback).onResponse(null, 0) } @Test @Throws(Exception::class) fun testOnFetchResponseCaseException() { whenever(response.body()).thenReturn(body) whenever(response.isSuccessful).thenReturn(true) whenever(response.header("Content-Range")).thenReturn("test") whenever(call.isCanceled).thenReturn(false) whenever(body.contentLength()).thenReturn(-1) val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod( "onFetchResponse", CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java, Call::class.java, Response::class.java, NetworkFetcher.Callback::class.java, ) method.isAccessible = true method.invoke(fetcher, state, call, response, callback) verify(callback).onFailure(any()) } }
app/src/test/kotlin/fr/free/nrw/commons/media/CustomOkHttpNetworkFetcherUnitTest.kt
1612567368
package com.github.ajalt.clikt.samples.plugins import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.options.* import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.setBinding data class Repo(var home: String, val config: MutableMap<String, String>, var verbose: Boolean) class Cli : CliktCommand( help = """Repo is a command line tool that showcases how to build complex command line interfaces with Clikt. This tool is supposed to look like a distributed version control system to show how something like this can be structured.""") { init { versionOption("1.0") } val repoHome: String by option(help = "Changes the repository folder location.") .default(".repo") val config: List<Pair<String, String>> by option(help = "Overrides a config key/value pair.") .pair() .multiple() val verbose: Boolean by option("-v", "--verbose", help = "Enables verbose mode.") .flag() override fun run() { val repo = Repo(repoHome, HashMap(), verbose) for ((k, v) in config) { repo.config[k] = v } currentContext.obj = repo } } fun main(args: Array<String>) { val kodein = Kodein { bind() from setBinding<CliktCommand>() import(cloneModule) import(deleteModule) import(setuserModule) import(commitModule) } val commands: Set<CliktCommand> by kodein.instance() Cli().subcommands(commands).main(args) }
samples/plugins/src/main/kotlin/com/github/ajalt/clikt/samples/plugins/main.kt
254185485
// Copyright 2021 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.google.maps.android.rx import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.Marker import com.google.maps.android.rx.shared.MainThreadObservable import io.reactivex.rxjava3.android.MainThreadDisposable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Observer /** * Creates an [Observable] that emits whenever a marker's info window is closed. * * The created [Observable] uses [GoogleMap.setOnInfoWindowCloseListener] to listen to info window * close events. Since only one listener at a time is allowed, only one Observable at a time can be * used. */ public fun GoogleMap.infoWindowCloseEvents(): Observable<Marker> = GoogleMapInfoWindowCloseObservable(this) private class GoogleMapInfoWindowCloseObservable( private val googleMap: GoogleMap ) : MainThreadObservable<Marker>() { override fun subscribeMainThread(observer: Observer<in Marker>) { val listener = InfoWindowCloseListener(googleMap, observer) observer.onSubscribe(listener) googleMap.setOnInfoWindowCloseListener(listener) } private class InfoWindowCloseListener( private val googleMap: GoogleMap, private val observer: Observer<in Marker> ) : MainThreadDisposable(), GoogleMap.OnInfoWindowCloseListener { override fun onDispose() { googleMap.setOnInfoWindowCloseListener(null) } override fun onInfoWindowClose(marker: Marker) { if (!isDisposed) { observer.onNext(marker) } } } }
maps-rx/src/main/java/com/google/maps/android/rx/GoogleMapInfoWindowCloseObservable.kt
3916915855
package net.oschina.git.roland.wimm.main import android.app.AlertDialog import android.support.design.widget.BottomNavigationView import android.support.v4.app.FragmentManager import android.util.SparseArray import android.view.KeyEvent import net.oschina.git.roland.wimm.R import net.oschina.git.roland.wimm.common.base.BaseActivity import net.oschina.git.roland.wimm.common.view.HeaderFragment import net.oschina.git.roland.wimm.module.function.FunctionsFragment import net.oschina.git.roland.wimm.module.runningaccount.RunningAccountFragment import net.oschina.git.roland.wimm.settings.SettingsFragment import net.oschina.git.roland.wimm.module.statistics.StatisticsFragment import kotlinx.android.synthetic.main.activity_main.* /** * Created by Roland on 2017/4/10. */ class MainActivity : BaseActivity() { private var fragments: SparseArray<HeaderFragment>? = null private var fragmentManager: FragmentManager? = null private var displayingFragment: HeaderFragment? = null override fun getContentViewLayout(): Int { return R.layout.activity_main } override fun initComp() { fragments = SparseArray<HeaderFragment>() fragments!!.put(R.id.home, StatisticsFragment().setHeader(header)) fragments!!.put(R.id.running_account, RunningAccountFragment().setHeader(header)) fragments!!.put(R.id.functions, FunctionsFragment().setHeader(header)) fragments!!.put(R.id.settings, SettingsFragment().setHeader(header)) navigation!!.itemIconTintList = null fragmentManager = supportFragmentManager showFragment(R.id.home) } override fun initListener() { navigation!!.setOnNavigationItemSelectedListener(navigationItemSelectedListener) } override fun initData() { } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { confirmExit() return true } return super.onKeyUp(keyCode, event) } private fun confirmExit() { val dialog = AlertDialog.Builder(this) dialog.setMessage(R.string.confirm_exit) dialog.setNegativeButton(R.string.str_cancel, null) dialog.setPositiveButton(R.string.str_confirm) { dialog, which -> finish() } dialog.show() } private val navigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> showFragment(item.itemId) true } private fun showFragment(menuId: Int) { displayingFragment = fragments!!.get(menuId) if (displayingFragment != null) { fragmentManager!!.beginTransaction().replace(R.id.content, displayingFragment).commit() displayingFragment!!.refreshHeader() } } }
app/src/main/java/net/oschina/git/roland/wimm/main/MainActivity.kt
3424471653
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package chattime.api.plugin /** * Represents an entry in the plugin load order list. * * @constructor The primary constructor. * * @property id the other plugin * @property isRequired set to true if the other plugin is required */ sealed class LoadOrder( val id: String, val isRequired: Boolean) { /** * Loads this plugin before the other plugin. * * @constructor The primary constructor. * * @param id the other plugin * @param isRequired set to true if the other plugin is required */ class Before(id: String, isRequired: Boolean = false) : LoadOrder(id, isRequired) /** * Loads this plugin after the other plugin. * * @constructor The primary constructor. * * @param id the other plugin * @param isRequired set to true if the other plugin is required */ class After(id: String, isRequired: Boolean = false) : LoadOrder(id, isRequired) }
api/src/main/kotlin/chattime/api/plugin/LoadOrder.kt
2301838271
package com.saanx.configurator.data.entity import com.fasterxml.jackson.annotation.JsonIgnore import org.hibernate.validator.constraints.URL import org.springframework.data.rest.core.annotation.RestResource import java.math.BigDecimal import javax.persistence.* /** * @author sandjelkovic * @date 20.7.17. */ @Entity class SlotEntryKt(@Id @GeneratedValue val id: Long = 0, val name: String = "", val data: String = "", @URL val url: String = "", val value: BigDecimal = BigDecimal.ZERO, val selected: Boolean = false, val position: Int = 0, @JsonIgnore @ManyToOne @RestResource(exported = false) val slot: SlotKt = SlotKt(), @Version @JsonIgnore val version: Long = 0)
src/main/java/com/saanx/configurator/data/entity/SlotEntryKt.kt
1428138188
package com.github.kittinunf.reactiveandroid.reactive class Reactive<out T>(val item: T)
reactiveandroid/src/main/kotlin/com/github/kittinunf/reactiveandroid/reactive/Reactive.kt
2772012311
package com.zj.example.kotlin.basicsknowledge /** * Created by zhengjiong * date: 2017/9/15 11:37 */ /** * 如果不是abstract, C类要继承B需要C是open的, * 如果是abstract就不需要加open */ private abstract class B{ /** * plus必须要是open的, 才可以被重写 */ open fun plus(){ } /** * abstract不需要加open就可以被重写 */ abstract fun sum() } /** * 因为B有一个默认构造函数, 所以B后面需要加括号() */ private class C: B() { override fun plus(){ } override fun sum() { } }
src/main/kotlin/com/zj/example/kotlin/basicsknowledge/23.AbstractExample.kt
165890107
package com.netflix.spinnaker.cats.sql import com.netflix.spinnaker.cats.agent.CacheResult import com.netflix.spinnaker.cats.cache.CacheData import com.netflix.spinnaker.cats.cache.CacheFilter import com.netflix.spinnaker.cats.cache.DefaultCacheData import com.netflix.spinnaker.cats.cache.WriteableCache import com.netflix.spinnaker.cats.provider.ProviderCache import com.netflix.spinnaker.cats.sql.cache.SqlCache import com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.* import org.slf4j.LoggerFactory import org.slf4j.MDC import kotlin.contracts.ExperimentalContracts @ExperimentalContracts class SqlProviderCache(private val backingStore: WriteableCache) : ProviderCache { private val log = LoggerFactory.getLogger(javaClass) companion object { private const val ALL_ID = "_ALL_" // this implementation ignores this entirely } init { if (backingStore !is SqlCache) { throw IllegalStateException("SqlProviderCache must be wired with a SqlCache backingStore") } } /** * Filters the supplied list of identifiers to only those that exist in the cache. * * @param type the type of the item * @param identifiers the identifiers for the items * @return the list of identifiers that are present in the cache from the provided identifiers */ override fun existingIdentifiers(type: String, identifiers: MutableCollection<String>): MutableCollection<String> { return backingStore.existingIdentifiers(type, identifiers) } /** * Returns the identifiers for the specified type that match the provided glob. * * @param type The type for which to retrieve identifiers * @param glob The glob to match against the identifiers * @return the identifiers for the type that match the glob */ override fun filterIdentifiers(type: String?, glob: String?): MutableCollection<String> { return backingStore.filterIdentifiers(type, glob) } /** * Retrieves all the items for the specified type * * @param type the type for which to retrieve items * @return all the items for the type */ override fun getAll(type: String): MutableCollection<CacheData> { return getAll(type, null as CacheFilter?) } override fun getAll(type: String, identifiers: MutableCollection<String>?): MutableCollection<CacheData> { return getAll(type, identifiers, null) } override fun getAll(type: String, cacheFilter: CacheFilter?): MutableCollection<CacheData> { validateTypes(type) return backingStore.getAll(type, cacheFilter) } override fun getAll( type: String, identifiers: MutableCollection<String>?, cacheFilter: CacheFilter? ): MutableCollection<CacheData> { validateTypes(type) return backingStore.getAll(type, identifiers, cacheFilter) } override fun supportsGetAllByApplication(): Boolean { return true } override fun getAllByApplication(type: String, application: String): Map<String, MutableCollection<CacheData>> { return getAllByApplication(type, application, null) } override fun getAllByApplication( type: String, application: String, cacheFilter: CacheFilter? ): Map<String, MutableCollection<CacheData>> { validateTypes(type) return backingStore.getAllByApplication(type, application, cacheFilter) } override fun getAllByApplication( types: Collection<String>, application: String, filters: Map<String, CacheFilter?> ): Map<String, MutableCollection<CacheData>> { validateTypes(types) return backingStore.getAllByApplication(types, application, filters) } /** * Retrieves the items for the specified type matching the provided identifiers * * @param type the type for which to retrieve items * @param identifiers the identifiers * @return the items matching the type and identifiers */ override fun getAll(type: String, vararg identifiers: String): MutableCollection<CacheData> { return getAll(type, identifiers.toMutableList()) } /** * Gets a single item from the cache by type and id * * @param type the type of the item * @param id the id of the item * @return the item matching the type and id */ override fun get(type: String, id: String?): CacheData? { return get(type, id, null) } override fun get(type: String, id: String?, cacheFilter: CacheFilter?): CacheData? { if (ALL_ID == id) { log.warn("Unexpected request for $ALL_ID for type: $type, cacheFilter: $cacheFilter") return null } validateTypes(type) return backingStore.get(type, id, cacheFilter) ?: return null } override fun evictDeletedItems(type: String, ids: Collection<String>) { try { MDC.put("agentClass", "evictDeletedItems") backingStore.evictAll(type, ids) } finally { MDC.remove("agentClass") } } /** * Retrieves all the identifiers for a type * * @param type the type for which to retrieve identifiers * @return the identifiers for the type */ override fun getIdentifiers(type: String): MutableCollection<String> { validateTypes(type) return backingStore.getIdentifiers(type) } override fun putCacheResult( source: String, authoritativeTypes: MutableCollection<String>, cacheResult: CacheResult ) { try { MDC.put("agentClass", "$source putCacheResult") // This is a hack because some types are global and a single agent // can't be authoritative for cleanup but can supply enough // information to create the entity. For those types we need an out // of band cleanup so they should be cached as authoritative but // without cleanup // // TODO Consider adding a GLOBAL type for supported data types to // allow caching agents to explicitly opt into this rather than // encoding them in here.. val globalTypes = getGlobalTypes(source, authoritativeTypes, cacheResult) cacheResult.cacheResults .filter { it.key.contains(ON_DEMAND.ns, ignoreCase = true) } .forEach { authoritativeTypes.add(it.key) } val cachedTypes = mutableSetOf<String>() // Update resource table from Authoritative sources only when { // OnDemand agents should only be treated as authoritative and don't use standard eviction logic source.contains(ON_DEMAND.ns, ignoreCase = true) -> cacheResult.cacheResults // And OnDemand agents shouldn't update other resource type tables .filter { it.key.contains(ON_DEMAND.ns, ignoreCase = true) } .forEach { cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false) } authoritativeTypes.isNotEmpty() -> cacheResult.cacheResults .filter { authoritativeTypes.contains(it.key) || globalTypes.contains(it.key) } .forEach { cacheDataType(it.key, source, it.value, authoritative = true, cleanup = !globalTypes.contains(it.key)) cachedTypes.add(it.key) } else -> // If there are no authoritative types in cacheResult, override all as authoritative without cleanup cacheResult.cacheResults .forEach { cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false) cachedTypes.add(it.key) } } // Update relationships for non-authoritative types if (!source.contains(ON_DEMAND.ns, ignoreCase = true)) { cacheResult.cacheResults .filter { !cachedTypes.contains(it.key) } .forEach { cacheDataType(it.key, source, it.value, authoritative = false) } } if (cacheResult.evictions.isNotEmpty()) { cacheResult.evictions.forEach { evictDeletedItems(it.key, it.value) } } } finally { MDC.remove("agentClass") } } override fun addCacheResult( source: String, authoritativeTypes: MutableCollection<String>, cacheResult: CacheResult ) { try { MDC.put("agentClass", "$source putCacheResult") authoritativeTypes.addAll(getGlobalTypes(source, authoritativeTypes, cacheResult)); val cachedTypes = mutableSetOf<String>() if (authoritativeTypes.isNotEmpty()) { cacheResult.cacheResults .filter { authoritativeTypes.contains(it.key) } .forEach { cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false) cachedTypes.add(it.key) } } cacheResult.cacheResults .filter { !cachedTypes.contains(it.key) } .forEach { cacheDataType(it.key, source, it.value, authoritative = false, cleanup = false) } } finally { MDC.remove("agentClass") } } override fun putCacheData(type: String, cacheData: CacheData) { try { MDC.put("agentClass", "putCacheData") backingStore.merge(type, cacheData) } finally { MDC.remove("agentClass") } } fun cleanOnDemand(maxAgeMs: Long): Int { return (backingStore as SqlCache).cleanOnDemand(maxAgeMs) } private fun validateTypes(type: String) { validateTypes(listOf(type)) } private fun validateTypes(types: Collection<String>) { val invalid = types .asSequence() .filter { it.contains(":") } .toSet() if (invalid.isNotEmpty()) { throw IllegalArgumentException("Invalid types: $invalid") } } private fun cacheDataType(type: String, agent: String, items: Collection<CacheData>, authoritative: Boolean) { cacheDataType(type, agent, items, authoritative, cleanup = true) } private fun cacheDataType( type: String, agent: String, items: Collection<CacheData>, authoritative: Boolean, cleanup: Boolean ) { val toStore = ArrayList<CacheData>(items.size + 1) items.forEach { toStore.add(uniqueifyRelationships(it, agent)) } // OnDemand agents are always updated incrementally and should not trigger auto-cleanup at the WriteableCache layer val cleanupOverride = if (agent.contains(ON_DEMAND.ns, ignoreCase = true) || type.contains(ON_DEMAND.ns, ignoreCase = true)) { false } else { cleanup } (backingStore as SqlCache).mergeAll(type, agent, toStore, authoritative, cleanupOverride) } private fun uniqueifyRelationships(source: CacheData, sourceAgentType: String): CacheData { val relationships = HashMap<String, Collection<String>>(source.relationships.size) for ((key, value) in source.relationships) { relationships["$key:$sourceAgentType"] = value } return DefaultCacheData(source.id, source.ttlSeconds, source.attributes, relationships) } private fun getGlobalTypes(source: String, authoritativeTypes: Collection<String>, cacheResult: CacheResult): Set<String> = when { (source.contains("clustercaching", ignoreCase = true) || source.contains("titusstreaming", ignoreCase = true)) && !authoritativeTypes.contains(CLUSTERS.ns) && cacheResult.cacheResults .any { it.key.startsWith(CLUSTERS.ns) } -> setOf(CLUSTERS.ns, APPLICATIONS.ns) else -> emptySet() } }
cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/cats/sql/SqlProviderCache.kt
158901024
/* * Copyright 2016 Nicolas Fränkel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.frankel.kaadin.common import ch.frankel.kaadin.* import com.vaadin.server.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.* import java.net.URI class PageTest { @BeforeMethod private fun setUp() { initializeAndSetCurrentUI() } @Test fun `page should be configurable`() { val fragment = "a fragment" page { uriFragment = fragment } assertThat(Page.getCurrent().uriFragment).isEqualTo(fragment) } @Test fun `page location can be set with string`() { val location = "http://localhost:8080" location(location) assertThat(Page.getCurrent().location).isEqualTo(URI(location)) } @Test fun `page location can be set with URI`() { val location = URI("http://localhost:8080") location(location) assertThat(Page.getCurrent().location).isEqualTo(location) } @Test fun `page uri fragment can be set`() { val uriFragment = "a fragment" uriFragment(uriFragment) assertThat(Page.getCurrent().uriFragment).isEqualTo(uriFragment) } }
kaadin-core/src/test/kotlin/ch/frankel/kaadin/common/PageTest.kt
1040249207
package net.perfectdreams.loritta.embededitor.editors import kotlinx.html.classes import kotlinx.html.js.onClickFunction import net.perfectdreams.loritta.embededitor.EmbedEditor import net.perfectdreams.loritta.embededitor.data.DiscordEmbed import net.perfectdreams.loritta.embededitor.utils.lovelyButton object EmbedTitleEditor : EditorBase { val isNotNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo -> currentElement.classes += "clickable" currentElement.onClickFunction = { titlePopup(discordMessage.embed!!, m) } } val isNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo -> lovelyButton( "fas fa-heading", "Adicionar Título" ) { titlePopup(discordMessage.embed!!, m) } } fun titlePopup(embed: DiscordEmbed, m: EmbedEditor) = genericPopupTextAreaWithSaveAndDelete( m, { m.activeMessage!!.copy( embed = m.activeMessage!!.embed!!.copy(title = it) ) }, { m.activeMessage!!.copy( embed = m.activeMessage!!.embed!!.copy(title = null) ) }, embed.title ?: "Loritta é muito fofa!", DiscordEmbed.MAX_DESCRIPTION_LENGTH ) }
web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedTitleEditor.kt
4176072555
package xyz.thecodeside.tradeapp.helpers import android.app.Activity import android.content.IntentFilter import android.net.ConnectivityManager import android.net.NetworkInfo import io.reactivex.Flowable import io.reactivex.processors.BehaviorProcessor import javax.inject.Inject class InternetConnectionManager @Inject internal constructor( private val service: ConnectivityManager){ private val connectionState : BehaviorProcessor<Status> = BehaviorProcessor.create() private val onConnectionChanged : OnConnectionChanged = object : OnConnectionChanged{ override fun onChange() = connectionState.onNext(isOnline()) } private val receiver = InternetConnectionReceiver(onConnectionChanged) fun isOnline(): Status = if(service.activeNetworkInfo?.state == NetworkInfo.State.CONNECTED) Status.ONLINE else Status.OFFLINE fun observe(activity: Activity?): Flowable<Status> { val intentFilter = IntentFilter() intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, intentFilter) return connectionState } fun stopObserve(activity: Activity?){ activity?.unregisterReceiver(receiver) } interface OnConnectionChanged{ fun onChange() } enum class Status{ ONLINE, OFFLINE } }
app/src/main/java/xyz/thecodeside/tradeapp/helpers/InternetConnectionManager.kt
1458500617
package eu.kanade.tachiyomi.extension.ru.mintmanga import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern class Mintmanga : ParsedHttpSource() { override val id: Long = 6 override val name = "Mintmanga" override val baseUrl = "http://mintmanga.com" override val lang = "ru" override val supportsLatest = true override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/list?sortType=rate&offset=${70 * (page - 1)}&max=70", headers) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/list?sortType=updated&offset=${70 * (page - 1)}&max=70", headers) override fun popularMangaSelector() = "div.tile" override fun latestUpdatesSelector() = "div.tile" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("img.lazy").first().attr("data-original") element.select("h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun popularMangaNextPageSelector() = "a.nextLink" override fun latestUpdatesNextPageSelector() = "a.nextLink" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val genres = filters.filterIsInstance<Genre>().joinToString("&") { it.id + arrayOf("=", "=in", "=ex")[it.state] } return GET("$baseUrl/search/advanced?q=$query&$genres", headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) // max 200 results override fun searchMangaNextPageSelector() = null override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.leftContent").first() val manga = SManga.create() manga.author = infoElement.select("span.elem_author").first()?.text() manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",") manga.description = infoElement.select("div.manga-description").text() manga.status = parseStatus(infoElement.html()) manga.thumbnail_url = infoElement.select("img").attr("data-full") return manga } private fun parseStatus(element: String): Int = when { element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> SManga.LICENSED element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> SManga.COMPLETED element.contains("<b>Перевод:</b> продолжается") -> SManga.ONGOING else -> SManga.UNKNOWN } override fun chapterListSelector() = "div.chapters-link tbody tr" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val urlText = urlElement.text() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mtr=1") if (urlText.endsWith(" новое")) { chapter.name = urlText.dropLast(6) } else { chapter.name = urlText } chapter.date_upload = element.select("td.hidden-xxs").last()?.text()?.let { SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time } ?: 0 return chapter } override fun prepareNewChapter(chapter: SChapter, manga: SManga) { val basic = Regex("""\s*([0-9]+)(\s-\s)([0-9]+)\s*""") val extra = Regex("""\s*([0-9]+\sЭкстра)\s*""") val single = Regex("""\s*Сингл\s*""") when { basic.containsMatchIn(chapter.name) -> { basic.find(chapter.name)?.let { val number = it.groups[3]?.value!! chapter.chapter_number = number.toFloat() } } extra.containsMatchIn(chapter.name) -> // Extra chapters doesn't contain chapter number chapter.chapter_number = -2f single.containsMatchIn(chapter.name) -> // Oneshoots, doujinshi and other mangas with one chapter chapter.chapter_number = 1f } } override fun pageListParse(response: Response): List<Page> { val html = response.body()!!.string() val beginIndex = html.indexOf("rm_h.init( [") val endIndex = html.indexOf("], 0, false);", beginIndex) val trimmedHtml = html.substring(beginIndex, endIndex) val p = Pattern.compile("'.*?','.*?',\".*?\"") val m = p.matcher(trimmedHtml) val pages = mutableListOf<Page>() var i = 0 while (m.find()) { val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',') pages.add(Page(i++, "", urlParts[1] + urlParts[0] + urlParts[2])) } return pages } override fun pageListParse(document: Document): List<Page> { throw Exception("Not used") } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { val imgHeader = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)") add("Referer", baseUrl) }.build() return GET(page.imageUrl!!, imgHeader) } private class Genre(name: String, val id: String) : Filter.TriState(name) /* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")] * .map(el => `Genre("${el.textContent.trim()}", $"{el.getAttribute('onclick') * .substr(31,el.getAttribute('onclick').length-33)"})`).join(',\n') * on http://mintmanga.com/search/advanced */ override fun getFilterList() = FilterList( Genre("арт", "el_2220"), Genre("бара", "el_1353"), Genre("боевик", "el_1346"), Genre("боевые искусства", "el_1334"), Genre("вампиры", "el_1339"), Genre("гарем", "el_1333"), Genre("гендерная интрига", "el_1347"), Genre("героическое фэнтези", "el_1337"), Genre("детектив", "el_1343"), Genre("дзёсэй", "el_1349"), Genre("додзинси", "el_1332"), Genre("драма", "el_1310"), Genre("игра", "el_5229"), Genre("история", "el_1311"), Genre("киберпанк", "el_1351"), Genre("комедия", "el_1328"), Genre("меха", "el_1318"), Genre("мистика", "el_1324"), Genre("научная фантастика", "el_1325"), Genre("омегаверс", "el_5676"), Genre("повседневность", "el_1327"), Genre("постапокалиптика", "el_1342"), Genre("приключения", "el_1322"), Genre("психология", "el_1335"), Genre("романтика", "el_1313"), Genre("самурайский боевик", "el_1316"), Genre("сверхъестественное", "el_1350"), Genre("сёдзё", "el_1314"), Genre("сёдзё-ай", "el_1320"), Genre("сёнэн", "el_1326"), Genre("сёнэн-ай", "el_1330"), Genre("спорт", "el_1321"), Genre("сэйнэн", "el_1329"), Genre("трагедия", "el_1344"), Genre("триллер", "el_1341"), Genre("ужасы", "el_1317"), Genre("фантастика", "el_1331"), Genre("фэнтези", "el_1323"), Genre("школа", "el_1319"), Genre("эротика", "el_1340"), Genre("этти", "el_1354"), Genre("юри", "el_1315"), Genre("яой", "el_1336") ) }
src/ru/mintmanga/src/eu/kanade/tachiyomi/extension/ru/mintmanga/Mintmanga.kt
749398098
package info.izumin.android.sunazuri.data.action.user; import info.izumin.android.droidux.Action import info.izumin.android.droidux.Dispatcher import info.izumin.android.sunazuri.data.action.common.BaseAction import info.izumin.android.sunazuri.data.action.common.BaseAsyncAction import info.izumin.android.sunazuri.domain.repository.UsersRepository import rx.Observable /** * Created by izumin on 5/25/2016 AD. */ class LoadLoginInfoAction constructor( val repo: UsersRepository, val userActionCreator: UserActionCreator ) : BaseAsyncAction<LoadLoginInfoAction.RequestValue>() { override fun call(dispatcher: Dispatcher): Observable<Action> { return repo.loginInfo.defaultIfEmpty(null) .map { userActionCreator.createSetLoginInfo(it) } } class RequestValue : BaseAction.RequestValue }
app/src/main/java/info/izumin/android/sunazuri/data/action/user/LoadLoginInfoAction.kt
2423097561
/* 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 model import android.content.Context import android.content.res.AssetManager import android.database.SQLException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.util.Log import java.io.* // thanks to http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ // for the code here. IMPORTANT: Follow code at top for create/insert and _id class DataBaseHelper(context: Context, private val m_DBName: String, dbVersion: Int) : SQLiteOpenHelper(context, m_DBName, null, dbVersion) { private var myDataBase: SQLiteDatabase? = null private val mDBFileName: String = context.getDatabasePath(m_DBName).absolutePath private val mFilesDir: String = context.filesDir.path private val mAssetManager: AssetManager = context.assets /** * Creates a empty database on the system and rewrites it with your own * database. */ @Throws(Error::class) fun createDataBase() { val dbExist = checkDataBase() var dbRead: SQLiteDatabase? = null if (!dbExist) { // By calling this method and empty database will be created into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. try { dbRead = this.readableDatabase } catch (e: Exception) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e)) } finally { if (dbRead != null && dbRead.isOpen) dbRead.close() } try { copyDataBase() } catch (e: IOException) { throw Error("Error copying database" + e.message) } } } /** * Check if the database already exist to avoid re-copying the file each * time you open the application. * * @return true if it exists, false if it doesn't */ private fun checkDataBase(): Boolean { var checkDB: SQLiteDatabase? = null try { checkDB = SQLiteDatabase.openDatabase(mDBFileName, null, SQLiteDatabase.OPEN_READONLY) } catch (e: SQLiteException) { // database does't exist yet. } finally { checkDB?.close() } return checkDB != null } /** * Copies your database from your local assets-folder to the just created * empty database in the system folder, from where it can be accessed and * handled. This is done by transfering bytestream. */ @Throws(IOException::class) private fun copyDataBase() { // Open your local db as the input stream val myInput: InputStream // Ensure that the directory exists. var f = File(mFilesDir) if (!f.exists()) { if (f.mkdir()) Log.v(MFBConstants.LOG_TAG, "Database Directory created") } // Open the empty db as the output stream val szFileName = mDBFileName f = File(szFileName) if (f.exists()) { if (!f.delete()) Log.v(MFBConstants.LOG_TAG, "Delete failed for copydatabase") } val myOutput: OutputStream = FileOutputStream(szFileName) try { // now put the pieces of the DB together (see above) val szAsset = if (m_DBName.compareTo(DB_NAME_MAIN) == 0) szDBNameMain else szDBNameAirports myInput = mAssetManager.open(szAsset) // transfer bytes from the inputfile to the outputfile val buffer = ByteArray(1024) var length: Int while (myInput.read(buffer).also { length = it } > 0) { myOutput.write(buffer, 0, length) } myInput.close() } catch (ex: Exception) { Log.e(MFBConstants.LOG_TAG, "Error copying database: " + ex.message) } finally { // Close the streams try { myOutput.flush() myOutput.close() } catch (ex: Exception) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(ex)) } } } @Throws(SQLException::class) fun openDataBase() { // Open the database myDataBase = SQLiteDatabase.openDatabase( mDBFileName, null, SQLiteDatabase.OPEN_READONLY ) } @Synchronized override fun close() { if (myDataBase != null) myDataBase!!.close() super.close() } override fun onCreate(db: SQLiteDatabase) {} override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (m_DBName.compareTo(DB_NAME_MAIN) == 0) { Log.e( MFBConstants.LOG_TAG, String.format("Upgrading main DB from %d to %d", oldVersion, newVersion) ) // below will attempt to migrate version to version, step by step // Initial release was (I believe) version 3, so anything less than that if (oldVersion < newVersion) { Log.e(MFBConstants.LOG_TAG, "Slamming new main database") try { copyDataBase() // just force an upgrade, always. We need to force a download of aircraft again anyhow } catch (e: IOException) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e)) } } } else // else it is the airport DB. This is read-only, so we can ALWAYS just slam in a new copy. { try { Log.e( MFBConstants.LOG_TAG, String.format("Upgrading airport DB from %d to %d", oldVersion, newVersion) ) copyDataBase() } catch (e: IOException) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e)) } } } companion object { // The Android's default system path of your application database. // private static String DB_PATH = "/data/data/com.myflightbook.android/databases/"; const val DB_NAME_MAIN = "mfbAndroid.sqlite" const val DB_NAME_AIRPORTS = "mfbAirports.sqlite" private const val szDBNameMain = "mfbAndroid.sqlite" private const val szDBNameAirports = "mfbAirport.sqlite" } }
app/src/main/java/model/DataBaseHelper.kt
2254658888
package be.digitalia.fosdem import android.app.Application import android.content.Context import android.content.SharedPreferences import androidx.multidex.MultiDex import be.digitalia.fosdem.alarms.AppAlarmManager import be.digitalia.fosdem.utils.ThemeManager import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject import javax.inject.Named @HiltAndroidApp class FosdemApplication : Application() { // Injected for automatic initialization on app startup @Inject lateinit var themeManager: ThemeManager @Inject lateinit var alarmManager: AppAlarmManager // Preload UI State SharedPreferences for faster initial access @Inject @Named("UIState") lateinit var preferences: SharedPreferences override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) MultiDex.install(this) } }
app/src/main/java/be/digitalia/fosdem/FosdemApplication.kt
4085960015
package at.cpickl.gadsu.mail import at.cpickl.gadsu.appointment.Appointment import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.firstNotEmpty import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.service.TemplateData import at.cpickl.gadsu.service.TemplateDeclaration import at.cpickl.gadsu.service.TemplatingEngine import com.google.common.annotations.VisibleForTesting import javax.inject.Inject interface AppointmentConfirmationer { fun sendConfirmation(client: Client, appointment: Appointment) } class AppointmentConfirmationerImpl @Inject constructor( private val templating: TemplatingEngine, private val mailSender: MailSender, private val prefs: Prefs ) : AppointmentConfirmationer { // see: GCalSyncService override fun sendConfirmation(client: Client, appointment: Appointment) { client.validateTemplateData() val subjectTemplate = prefs.preferencesData.templateConfirmSubject ?: throw GadsuException("confirm subject not set!") val bodyTemplate = prefs.preferencesData.templateConfirmBody?: throw GadsuException("confirm body not set!") mailSender.send(buildMail(subjectTemplate, bodyTemplate, client, appointment)) } @VisibleForTesting fun buildMail(subjectTemplate: String, bodyTemplate: String, client: Client, appointment: Appointment): Mail { val data = AppointmentConfirmationTemplateDeclaration.process(client to appointment) val subject = templating.process(subjectTemplate, data) val body = templating.process(bodyTemplate, data) return Mail(client.contact.mail, subject, body, recipientsAsBcc = false) } private fun Client.validateTemplateData() { if (contact.mail.isEmpty()) { throw AppointmentConfirmationException("Client mail is not configured for: $this") } if (firstName.isEmpty()) { throw AppointmentConfirmationException("Client mail is not configured for: $this") } } } class AppointmentConfirmationException(message: String, cause: Exception? = null) : GadsuException(message, cause) object AppointmentConfirmationTemplateDeclaration : TemplateDeclaration<Pair<Client, Appointment>> { override val data = listOf( TemplateData<Pair<Client, Appointment>>("name", "Der externe Spitzname bzw. Vorname falls nicht vorhanden, zB: \${name?lower_case}") { firstNotEmpty(it.first.nickNameExt, it.first.firstName) }, TemplateData("dateStart", "Z.B.: termin am \${dateStart?string[\"EEEE 'der' d. MMMMM\"]?lower_case} von \${dateStart?string[\"HH:mm\"]}") { it.second.start.toDate() }, TemplateData("dateEnd", "Z.B.: bis \${dateEnd?string[\"HH:mm\"]} uhr") { it.second.end.toDate() }, TemplateData("gender", "Z.B.: hallo <#if gender == \"M\">lieber <#elseif gender == \"F\">liebe </#if>") { it.first.gender.sqlCode } ) }
src/main/kotlin/at/cpickl/gadsu/mail/appointment_confirmation.kt
1790307378
package com.angcyo.uiview.dialog import android.view.Gravity import com.angcyo.uiview.R import com.angcyo.uiview.recycler.RBaseItemDecoration import com.angcyo.uiview.recycler.RBaseViewHolder import com.angcyo.uiview.recycler.adapter.RExBaseAdapter /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述: * 创建人员:Robi * 创建时间:2018/02/24 16:51 * 修改人员:Robi * 修改时间:2018/02/24 16:51 * 修改备注: * Version: 1.0.0 */ class UIItemSelectorDialog<T>(val items: List<T>) : UIRecyclerDialog<String, T, String>() { var onItemSelector: ((position: Int, bean: T) -> Unit)? = null var onInitItemLayout: ((holder: RBaseViewHolder, posInData: Int, dataBean: T) -> Unit)? = null override fun getGravity(): Int { return Gravity.BOTTOM } override fun createAdapter(): RExBaseAdapter<String, T, String> = object : RExBaseAdapter<String, T, String>(mActivity, items) { override fun onBindDataView(holder: RBaseViewHolder, posInData: Int, dataBean: T) { super.onBindDataView(holder, posInData, dataBean) if (dataBean is String) { holder.tv(R.id.base_text_view).text = dataBean } holder.click(R.id.base_item_root_layout) { finishDialog { onItemSelector?.invoke(posInData, dataBean) } } onInitItemLayout?.invoke(holder, posInData, dataBean) } override fun getItemLayoutId(viewType: Int): Int { return R.layout.base_text_item_selector_layout } } override fun initRecyclerView() { super.initRecyclerView() recyclerView.addItemDecoration(RBaseItemDecoration(getDimensionPixelOffset(R.dimen.base_line), getColor(R.color.base_chat_bg_color))) } }
uiview/src/main/java/com/angcyo/uiview/dialog/UIItemSelectorDialog.kt
3747061736
package com.ghstudios.android /** * Interface for objects that can be displayed as icons */ interface ITintedIcon { /** * Returns the name of the resource file associated with this icon. */ fun getIconResourceString(): String /** * Returns the associated color array id. * If it returns 0, that means this icon should not be tinted. */ fun getColorArrayId(): Int = 0 /** * Returns the position in the color array for tinting this icon. */ fun getIconColorIndex():Int = 0 }
app/src/main/java/com/ghstudios/android/ITintedIcon.kt
1566776400
package uk.co.appsbystudio.geoshare.friends.profile.staticmap import uk.co.appsbystudio.geoshare.utils.firebase.DatabaseLocations interface ProfileStaticMapInteractor { interface OnFirebaseListener { fun setImage(location: DatabaseLocations) fun error(error: String) } fun getLocation(uid: String, listener: OnFirebaseListener) }
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/staticmap/ProfileStaticMapInteractor.kt
1470063281
package com.sksamuel.kotest.matchers.reflection.annotations @Target( AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER ) @Retention(AnnotationRetention.RUNTIME) annotation class Fancy(val cost: Int = 1000)
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/reflection/annotations/Fancy.kt
3136442105
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.5.1-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.database.models import org.ktorm.dsl.* import org.ktorm.schema.* import org.ktorm.database.Database import .* /** * * @param name * @param propertySize * @param url * @param propertyClass */ object PipelinelatestRunartifactss : BaseTable<PipelinelatestRunartifacts>("PipelinelatestRunartifacts") { val name = text("name") /* null */ val propertySize = int("size") /* null */ val url = text("url") /* null */ val propertyClass = text("_class") /* null */ /** * Create an entity of type PipelinelatestRunartifacts from the model */ override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = PipelinelatestRunartifacts( name = row[name] /* kotlin.String? */, propertySize = row[propertySize] /* kotlin.Int? */, url = row[url] /* kotlin.String? */, propertyClass = row[propertyClass] /* kotlin.String? */ ) /** * Assign all the columns from the entity of type PipelinelatestRunartifacts to the DML expression. * * Usage: * * ```kotlin * let entity = PipelinelatestRunartifacts() * database.update(PipelinelatestRunartifactss, { * assignFrom(entity) * }) * ``` * @return the builder with the columns for the update or insert. */ fun AssignmentsBuilder.assignFrom(entity: PipelinelatestRunartifacts) { this.apply { set(PipelinelatestRunartifactss.name, entity.name) set(PipelinelatestRunartifactss.propertySize, entity.propertySize) set(PipelinelatestRunartifactss.url, entity.url) set(PipelinelatestRunartifactss.propertyClass, entity.propertyClass) } } }
clients/ktorm-schema/generated/src/main/kotlin/org/openapitools/database/models/PipelinelatestRunartifacts.kt
1170837286
package itaka.intellij.plugin.json.navigator import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State( name = "JsonFilePathNavigatorState", storages = arrayOf(Storage("JsonFilePathNavigatorState.xml")) ) class FilePathNavigatorState : PersistentStateComponent<FilePathNavigatorState> { var searchFilePaths: String? = null override fun loadState(state: FilePathNavigatorState) { XmlSerializerUtil.copyBean(state, this) } override fun getState(): FilePathNavigatorState? { return this } fun getPaths(): List<String> { return searchFilePaths.orEmpty() .split(",") .map { it.trim() } } companion object { fun getInstance(): FilePathNavigatorState { return ServiceManager.getService(FilePathNavigatorState::class.java) } } }
src/main/kotlin/itaka/intellij/plugin/json/navigator/FilePathNavigatorState.kt
2814831393
package com.rogalabs.lib.facebook import android.content.Intent import android.os.Bundle import android.support.v4.app.FragmentActivity import com.facebook.* import com.facebook.login.LoginManager import com.facebook.login.LoginResult import com.rogalabs.lib.Callback import com.rogalabs.lib.LoginContract import com.rogalabs.lib.model.Hometown import com.rogalabs.lib.model.SocialUser import org.json.JSONObject import java.util.* /** * Created by roga on 14/07/16. */ class LoginFacebookPresenter(val view: LoginContract.View) : LoginContract.FacebookPresenter, FacebookCallback<LoginResult>, GraphRequest.GraphJSONObjectCallback { private var callback: Callback? = null private var callbackManager: CallbackManager? = null private var activity: FragmentActivity? = null private val profileFields = "id, name, email, birthday, hometown" override fun activityResult(requestCode: Int, resultCode: Int, data: Intent) { callbackManager?.onActivityResult(requestCode, resultCode, data) } override fun create(activity: FragmentActivity?) { this.activity = activity callbackManager = com.facebook.CallbackManager.Factory.create() registerFacebookCallback(callbackManager) } override fun pause() { } override fun destroy() { } private fun registerFacebookCallback(callbackManager: CallbackManager?) { LoginManager.getInstance().registerCallback(callbackManager, this) } override fun onCancel() { } override fun onError(error: FacebookException?) { callback?.onError(error?.cause!!) } override fun onSuccess(result: LoginResult?) { sendGraphRequest() } override fun signIn(callback: Callback) { this.callback = callback LoginManager.getInstance().logInWithReadPermissions(activity, Arrays.asList( "public_profile", "email", "user_birthday", "user_hometown")) } override fun signIn(callback: Callback, readPermissions: List<String>) { this.callback = callback LoginManager.getInstance().logInWithReadPermissions(activity, readPermissions) } override fun signOut() { LoginManager.getInstance().logOut() } override fun onCompleted(jsonResponse: JSONObject?, response: GraphResponse?) { callback?.onSuccess(buildSocialUser(jsonResponse)) } private fun sendGraphRequest() { val graphRequest: GraphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), this) val parameters = Bundle() parameters.putString("fields", profileFields) graphRequest.setParameters(parameters) graphRequest.executeAsync() } private fun buildSocialUser(jsonObject: JSONObject?): SocialUser { var hometown: Hometown = Hometown() var birthday: String = "" try { val hometownObj = jsonObject?.getJSONObject("hometown") birthday = jsonObject?.getString("birthday") as String hometown = Hometown(hometownObj?.getString("id"), hometownObj?.getString("name")) } finally { val user: SocialUser = SocialUser(jsonObject?.getString("id"), jsonObject?.getString("name"), jsonObject?.getString("email"), birthday, userPicture(jsonObject?.getString("id")), hometown, AccessToken.getCurrentAccessToken().token) return user } } private fun userPicture(id: String?): String { return "https://graph.facebook.com/${id}/picture?type=large" } }
lib/src/main/java/com/rogalabs/lib/facebook/LoginFacebookPresenter.kt
1568050457
package com.lasthopesoftware.bluewater.client.stored.library.items.files.GivenAMediaFile.ThatIsInAnotherLibrary import androidx.test.core.app.ApplicationProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.stored.library.items.files.StoredFileAccess import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import io.mockk.mockk import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class WhenAddingTheFile { companion object { private val storedFile by lazy { StoredFileAccess(ApplicationProvider.getApplicationContext(), mockk()) .addMediaFile( Library().setId(13), ServiceFile(3), 14, "a-test-path" ) .toFuture() .get() val storedFileAccess = StoredFileAccess(ApplicationProvider.getApplicationContext(), mockk()) storedFileAccess .addMediaFile( Library().setId(15), ServiceFile(3), 14, "a-test-path" ) .toFuture() .get() storedFileAccess .getStoredFile(Library().setId(15), ServiceFile(3)) .toFuture() .get()!! } } @Test fun thenTheLibraryIdIsCorrect() { assertThat(storedFile.libraryId).isEqualTo(15) } @Test fun thenThisLibraryDoesNotOwnTheFile() { assertThat(storedFile.isOwner).isFalse } @Test fun thenTheDownloadIsMarkedComplete() { assertThat(storedFile.isDownloadComplete).isTrue } @Test fun thenTheStoredFileHasTheCorrectMediaFileId() { assertThat(storedFile.storedMediaId).isEqualTo(14) } @Test fun thenTheStoredFileHasTheCorrectPath() { assertThat(storedFile.path).isEqualTo("a-test-path") } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/items/files/GivenAMediaFile/ThatIsInAnotherLibrary/WhenAddingTheFile.kt
1523625827
package org.DUCodeWars.framework.server.net.packets abstract class Packet(val action: String) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } }
src/main/java/org/DUCodeWars/framework/server/net/packets/Packet.kt
2387544295
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm.service import android.app.IntentService import android.app.Service import android.content.Intent import android.location.Location import android.os.Bundle import androidx.core.os.bundleOf import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.LocationListener import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import gc.david.dfm.map.LocationUtils class GeofencingService : IntentService("GeofencingService"), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private var googleApiClient: GoogleApiClient? = null private var locationRequest: LocationRequest? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { createGoogleApiClient() googleApiClient?.connect() createLocationRequest() return Service.START_STICKY } override fun onHandleIntent(intent: Intent?) { // nothing } override fun onConnected(bundle: Bundle?) { val lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient) if (lastKnownLocation != null) { sendUpdate(lastKnownLocation) } startLocationUpdates() } override fun onConnectionSuspended(cause: Int) { // nothing } override fun onConnectionFailed(connectionResult: ConnectionResult) { // nothing } override fun onLocationChanged(location: Location) { sendUpdate(location) } @Synchronized private fun createGoogleApiClient() { googleApiClient = GoogleApiClient.Builder(this).addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build() } private fun stopLocationUpdates() { if (googleApiClient?.isConnected == true) { LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this) } } private fun createLocationRequest() { locationRequest = LocationRequest.create().apply { priority = LocationRequest.PRIORITY_HIGH_ACCURACY interval = LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS // Set the interval ceiling to one minute fastestInterval = LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS } } private fun startLocationUpdates() { val googleApiClient = googleApiClient ?: return val locationRequest = locationRequest ?: return if (googleApiClient.isConnected) { LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this) } } private fun sendUpdate(location: Location) { val locationIntent = Intent(GEOFENCE_RECEIVER_ACTION).apply { val bundle = bundleOf( GEOFENCE_RECEIVER_LATITUDE_KEY to location.latitude, GEOFENCE_RECEIVER_LONGITUDE_KEY to location.longitude ) putExtras(bundle) } applicationContext.sendBroadcast(locationIntent) } override fun onDestroy() { super.onDestroy() stopLocationUpdates() googleApiClient?.disconnect() } companion object { const val GEOFENCE_RECEIVER_ACTION = "geofence.receiver.action" const val GEOFENCE_RECEIVER_LATITUDE_KEY = "geofence.receiver.latitude.key" const val GEOFENCE_RECEIVER_LONGITUDE_KEY = "geofence.receiver.longitude.key" } }
app/src/main/java/gc/david/dfm/service/GeofencingService.kt
1638024671
package com.cout970.magneticraft.proxy import com.cout970.magneticraft.Debug import com.cout970.magneticraft.MOD_ID import com.cout970.magneticraft.Magneticraft import com.cout970.magneticraft.misc.* import com.cout970.magneticraft.registry.blocks import com.cout970.magneticraft.registry.items import com.cout970.magneticraft.registry.registerSounds import com.cout970.magneticraft.systems.blocks.BlockBase import com.cout970.magneticraft.systems.gui.components.CompBookRenderer import com.cout970.magneticraft.systems.items.ItemBase import com.cout970.magneticraft.systems.tileentities.TileBase import com.cout970.magneticraft.systems.tilerenderers.TileRenderer import com.cout970.modelloader.api.DefaultBlockDecorator import com.cout970.modelloader.api.ModelLoaderApi import net.minecraft.client.renderer.block.model.ModelResourceLocation import net.minecraft.util.SoundEvent import net.minecraftforge.client.event.ModelBakeEvent import net.minecraftforge.client.model.ModelLoader import net.minecraftforge.client.model.obj.OBJLoader import net.minecraftforge.event.RegistryEvent import net.minecraftforge.fml.client.registry.ClientRegistry import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.relauncher.Side /** * This class extends the functionality of CommonProxy but adds * thing only for the client: sounds, models, textures and renders */ @Suppress("unused") class ClientProxy : CommonProxy() { // List of registered TileEntityRenderers val tileRenderers = mutableListOf<TileRenderer<out TileBase>>() @SubscribeEvent fun initSoundsEvent(event: RegistryEvent.Register<SoundEvent>) { logTime("Task registerSounds:") { registerSounds(event.registry) } } override fun postItemRegister() { super.postItemRegister() //Item renders logTime("Task registerItemModels:") { registerItemModels() } //ItemBlock renders logTime("Task registerBlockAndItemBlockModels:") { registerBlockAndItemBlockModels() } //TileEntity renderers logTime("Task registerTileEntityRenderers:") { registerTileEntityRenderers() } } override fun preInit() { super.preInit() //Model loaders OBJLoader.INSTANCE.addDomain(MOD_ID) // Preload guidebook logTime("Task loadGuideBookPages:") { CompBookRenderer.book } } fun registerItemModels() { items.forEach { i -> (i as? ItemBase)?.let { item -> item.variants.forEach { variant -> ModelLoader.setCustomModelResourceLocation( item, variant.key, item.registryName!!.toModel(variant.value) ) } item.customModels.forEach { (state, location) -> ModelLoaderApi.registerModelWithDecorator( ModelResourceLocation(item.registryName!!, state), location, DefaultBlockDecorator ) } } } } fun registerBlockAndItemBlockModels() { blocks.forEach { (block, itemBlock) -> if (itemBlock == null) return@forEach (block as? BlockBase)?.let { blockBase -> if (blockBase.generateDefaultItemModel) { blockBase.inventoryVariants.forEach { ModelLoader.setCustomModelResourceLocation( itemBlock, it.key, itemBlock.registryName!!.toModel(it.value) ) } } else { ModelLoader.setCustomModelResourceLocation( itemBlock, 0, itemBlock.registryName!!.toModel("inventory") ) } val mapper = blockBase.getCustomStateMapper() if (mapper != null) { ModelLoader.setCustomStateMapper(blockBase, mapper) } blockBase.customModels.forEach { (state, location) -> if (state == "inventory" || blockBase.forceModelBake) { ModelLoaderApi.registerModelWithDecorator( modelId = ModelResourceLocation(blockBase.registryName!!, state), modelLocation = location, decorator = DefaultBlockDecorator ) } else { ModelLoaderApi.registerModel( modelId = ModelResourceLocation(blockBase.registryName!!, state), modelLocation = location, bake = false ) } } } } } @Suppress("UNCHECKED_CAST") fun registerTileEntityRenderers() { val data = Magneticraft.asmData.getAll(RegisterRenderer::class.java.canonicalName) data.forEach { try { val clazz = Class.forName(it.className).kotlin val annotation = clazz.annotations.find { it is RegisterRenderer } as RegisterRenderer val tile = annotation.tileEntity.java as Class<TileBase> val renderer = clazz.objectInstance as TileRenderer<TileBase> register(tile, renderer) if (Debug.DEBUG) { info("Registering TESR: Tile = ${clazz.simpleName}, Renderer = ${renderer.javaClass.simpleName}") } } catch (e: Exception) { logError("Unable to register class with @RegisterRenderer: $it") e.printStackTrace() } } } override fun getSide() = Side.CLIENT /** * Updates all the TileEntityRenderers to reload models */ @Suppress("unused", "UNUSED_PARAMETER") @SubscribeEvent fun onModelRegistryReload(event: ModelBakeEvent) { tileRenderers.forEach { it.onModelRegistryReload() } } /** * Binds a TileEntity class with a TileEntityRenderer and * registers the TileEntityRenderer to update it when ModelBakeEvent is fired */ private fun <T : TileBase> register(tileEntityClass: Class<T>, specialRenderer: TileRenderer<T>) { ClientRegistry.bindTileEntitySpecialRenderer(tileEntityClass, specialRenderer) tileRenderers.add(specialRenderer) } }
src/main/kotlin/com/cout970/magneticraft/proxy/ClientProxy.kt
1289170840
package com.fastaccess.ui.modules.repos.wiki import android.content.Intent import com.fastaccess.BuildConfig import com.fastaccess.R import com.fastaccess.data.dao.wiki.FirebaseWikiConfigModel import com.fastaccess.data.dao.wiki.WikiContentModel import com.fastaccess.data.dao.wiki.WikiSideBarModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.RxHelper import com.fastaccess.provider.rest.jsoup.JsoupProvider import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.github.b3er.rxfirebase.database.RxFirebaseDatabase import com.google.firebase.database.FirebaseDatabase import io.reactivex.Observable import org.jsoup.Jsoup import org.jsoup.nodes.Document import retrofit2.HttpException import java.util.* /** * Created by Kosh on 13 Jun 2017, 8:14 PM */ class WikiPresenter : BasePresenter<WikiMvp.View>(), WikiMvp.Presenter { @com.evernote.android.state.State var repoId: String? = null @com.evernote.android.state.State var login: String? = null private var firebaseWikiConfigModel: FirebaseWikiConfigModel? = null override fun onActivityCreated(intent: Intent?) { if (intent != null) { val bundle = intent.extras repoId = bundle?.getString(BundleConstant.ID) login = bundle?.getString(BundleConstant.EXTRA) val page = bundle?.getString(BundleConstant.EXTRA_TWO) if (!page.isNullOrEmpty()) { sendToView { it.onSetPage(page) } } if (!repoId.isNullOrEmpty() && !login.isNullOrEmpty()) { onSidebarClicked(WikiSideBarModel("Home", "$login/$repoId/wiki" + if (!page.isNullOrEmpty()) "/$page" else "")) } } } override fun onSidebarClicked(sidebar: WikiSideBarModel) { if (firebaseWikiConfigModel == null) { manageDisposable( RxHelper.getSingle(RxFirebaseDatabase.data(FirebaseDatabase.getInstance().reference.child("github_wiki"))) .doOnSubscribe { sendToView { it.showProgress(0) } } .map { firebaseWikiConfigModel = FirebaseWikiConfigModel.map(it.value as? HashMap<String, String>) return@map firebaseWikiConfigModel } .subscribe( { callApi(sidebar) }, { callApi(sidebar) } ) ) } else { callApi(sidebar) } } private fun callApi(sidebar: WikiSideBarModel) { manageViewDisposable(RxHelper.getObservable(JsoupProvider.getWiki().getWiki(sidebar.link)) .flatMap { s -> RxHelper.getObservable(getWikiContent(s)) } .doOnSubscribe { sendToView { it.showProgress(0) } } .subscribe( { response -> sendToView { view -> view.onLoadContent(response) } }, { throwable -> if (throwable is HttpException) { if (throwable.code() == 404) { sendToView { it.showPrivateRepoError() } return@subscribe } } onError(throwable) }, { sendToView { it.hideProgress() } } ) ) } private fun getWikiContent(body: String?): Observable<WikiContentModel> { return Observable.fromPublisher { s -> val document: Document = Jsoup.parse(body, "") val firebaseWikiConfigModel = firebaseWikiConfigModel ?: kotlin.run { s.onNext(WikiContentModel("<h2 align='center'>No Wiki</h4>", "", arrayListOf())) s.onComplete() return@fromPublisher } val wikiWrapper = document.select(firebaseWikiConfigModel.wikiWrapper) if (!wikiWrapper.isNullOrEmpty()) { val header = wikiWrapper.select(firebaseWikiConfigModel.wikiHeader)?.text() val subHeaderText = wikiWrapper.select(firebaseWikiConfigModel.wikiSubHeader)?.text() val wikiContent = wikiWrapper.select(firebaseWikiConfigModel.wikiContent) val wikiBody = wikiContent?.select(firebaseWikiConfigModel.wikiBody)?.html() val rightBarList = wikiContent?.select(firebaseWikiConfigModel.sideBarUl)?.select(firebaseWikiConfigModel.sideBarList) val headerHtml = "<div class='gh-header-meta'><h1>$header</h1><p>$subHeaderText</p></div>" val content = "$headerHtml $wikiBody" s.onNext(WikiContentModel(content, null, rightBarList?.map { WikiSideBarModel( it.select(firebaseWikiConfigModel.sideBarListTitle).text(), it.select(firebaseWikiConfigModel.sideBarListTitle).attr(firebaseWikiConfigModel.sideBarListLink) ) } ?: listOf())) } else { s.onNext(WikiContentModel("<h2 align='center'>No Wiki</h4>", "", arrayListOf())) } s.onComplete() } } }
app/src/main/java/com/fastaccess/ui/modules/repos/wiki/WikiPresenter.kt
808002115
package com.github.shynixn.petblocks.api.business.proxy /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ interface EntityPetProxy { /** * Removes this entity. */ fun deleteFromWorld() }
petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/business/proxy/EntityPetProxy.kt
3644409237
/* * Copyright (c) 2017 Andrei Heidelbacher <[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 com.andreihh.algostorm.systems import com.andreihh.algostorm.core.drivers.audio.AudioStream import com.andreihh.algostorm.core.drivers.graphics2d.Color import com.andreihh.algostorm.core.drivers.io.Resource import com.andreihh.algostorm.core.ecs.Component import com.andreihh.algostorm.core.ecs.EntityPool import com.andreihh.algostorm.core.ecs.EntityRef import com.andreihh.algostorm.core.ecs.EntityRef.Id import com.andreihh.algostorm.systems.graphics2d.TileSet import kotlin.properties.Delegates class MapObject private constructor( val width: Int, val height: Int, val tileWidth: Int, val tileHeight: Int, val tileSets: List<TileSet>, val sounds: List<Resource<AudioStream>>, val entities: EntityPool, val backgroundColor: Color?, val version: String ) { class Builder { companion object { fun mapObject(init: Builder.() -> Unit): MapObject = Builder().apply(init).build() } var width: Int by Delegates.notNull() var height: Int by Delegates.notNull() var tileWidth: Int by Delegates.notNull() var tileHeight: Int by Delegates.notNull() private val tileSets = arrayListOf<TileSet>() private val sounds = arrayListOf<Resource<AudioStream>>() private val initialEntities = hashMapOf<Id, Collection<Component>>() private val entities = arrayListOf<Collection<Component>>() var backgroundColor: Color? = null var version: String = "1.0" fun tileSet(init: TileSet.Builder.() -> Unit) { tileSets += TileSet.Builder().apply(init).build() } fun tileSet(tileSet: TileSet) { tileSets += tileSet } fun sound(resource: String) { sounds += Resource(resource) } fun sound(resource: Resource<AudioStream>) { sounds += resource } fun entity(id: Id, init: EntityRef.Builder.() -> Unit) { initialEntities[id] = EntityRef.Builder().apply(init).build() } fun entity(id: Id, components: Collection<Component>) { initialEntities[id] = components } fun entity(init: EntityRef.Builder.() -> Unit) { entities += EntityRef.Builder().apply(init).build() } fun entity(components: Collection<Component>) { entities += components } fun build(): MapObject = MapObject( width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, tileSets = tileSets.toList(), sounds = sounds.toList(), entities = EntityPool.of(initialEntities) .apply { entities.forEach { create(it) } }, backgroundColor = backgroundColor, version = version ) } }
algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/MapObject.kt
1003660428
package com.waz.zclient.storage.db.conversations import androidx.room.Dao import androidx.room.Query import com.waz.zclient.storage.db.BatchDao @Dao interface ConversationRoleActionDao : BatchDao<ConversationRoleActionEntity> { @Query("SELECT * FROM ConversationRoleAction") suspend fun allConversationRoleActions(): List<ConversationRoleActionEntity> @Query("SELECT * FROM ConversationRoleAction ORDER BY conv_id LIMIT :batchSize OFFSET :start") override suspend fun nextBatch(start: Int, batchSize: Int): List<ConversationRoleActionEntity>? @Query("SELECT COUNT(*) FROM ConversationRoleAction") override suspend fun count(): Int }
storage/src/main/kotlin/com/waz/zclient/storage/db/conversations/ConversationRoleActionDao.kt
1352031120
package moe.cuebyte.rendition.query import moe.cuebyte.rendition.mock.PostStr import moe.cuebyte.rendition.query.method.batchInsert import moe.cuebyte.rendition.query.method.delete import moe.cuebyte.rendition.query.method.findBy import moe.cuebyte.rendition.util.Connection import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import redis.clients.jedis.Jedis import kotlin.test.assertTrue object ResultSetDeleteSpec : Spek({ describe("ResultSetDeleteSpec") { beforeGroup { Connection.set(Jedis("localhost")) Connection.get().select(4) } afterGroup { Connection.get().flushDB() } on("delete results") { PostStr.batchInsert(listOf( mapOf("id" to "1", "name" to "A", "amount" to 1) , mapOf("id" to "2", "name" to "A", "amount" to 2) , mapOf("id" to "6", "name" to "A", "amount" to 4) , mapOf("id" to "3", "name" to "B", "amount" to 3) , mapOf("id" to "4", "name" to "C", "amount" to 3) , mapOf("id" to "5", "name" to "D", "amount" to 3) )) it("should be ok with string index.") { PostStr.findBy("name", "A").delete() assertTrue { PostStr.findBy("name", "A").isEmpty() } assertTrue { PostStr.findBy("amount", 1).isEmpty() } assertTrue { PostStr.findBy("amount", 2).isEmpty() } assertTrue { PostStr.findBy("amount", 4).isEmpty() } } it("should be ok with number index.") { PostStr.findBy("amount", 3).delete() val b = PostStr.findBy("name", "B") val c = PostStr.findBy("name", "C") val d = PostStr.findBy("name", "D") assertTrue { PostStr.findBy("amount", 3).isEmpty() } assertTrue { b.isEmpty() } assertTrue { c.isEmpty() } assertTrue { d.isEmpty() } } } } })
src/test/kotlin/moe/cuebyte/rendition/query/method/ResultSetDeleteSpec.kt
1350687931
package xyz.roolurker.colorbot /** * Created with love by rooLurk on 1/5/17. */ /** * Copyright (c) 2017 Markus "rooLurk" Isberg * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ fun main(args: Array<String>) { if (args.isEmpty()) { println("No token specified!") return } val bot: ColorBot = ColorBot(args[0]) bot.run() }
src/xyz/roolurker/colorbot/Main.kt
891321138
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.horologist.compose.tools import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.Colors public data class ThemeValues(val name: String, val index: Int, val colors: Colors) { val safeName: String get() = name.replace("[^A-Za-z0-9]".toRegex(), "") } public val themeValues: List<ThemeValues> = listOf( ThemeValues("Blue (Default - AECBFA)", 0, Colors()), ThemeValues( "Blue (7FCFFF)", 1, Colors( primary = Color(0xFF7FCFFF), primaryVariant = Color(0xFF3998D3), secondary = Color(0xFF6DD58C), secondaryVariant = Color(0xFF1EA446) ) ), ThemeValues( "Lilac (D0BCFF)", 2, Colors( primary = Color(0xFFD0BCFF), primaryVariant = Color(0xFF9A82DB), secondary = Color(0xFF7FCFFF), secondaryVariant = Color(0xFF3998D3) ) ), ThemeValues( "Green (6DD58C)", 3, Colors( primary = Color(0xFF6DD58C), primaryVariant = Color(0xFF1EA446), secondary = Color(0xFFFFBB29), secondaryVariant = Color(0xFFD68400) ) ), ThemeValues( "Blue with Text (7FCFFF)", 4, Colors( primary = Color(0xFF7FCFFF), primaryVariant = Color(0xFF3998D3), onPrimary = Color(0xFF003355), secondary = Color(0xFF6DD58C), secondaryVariant = Color(0xFF1EA446), onSecondary = Color(0xFF0A3818), surface = Color(0xFF303030), onSurface = Color(0xFFE3E3E3), onSurfaceVariant = Color(0xFFC4C7C5), background = Color.Black, onBackground = Color.White, error = Color(0xFFF2B8B5), onError = Color(0xFF370906) ) ), ThemeValues( "Orange-y", 5, Colors( secondary = Color(0xFFED612B), // Used for RSB surface = Color(0xFF202124), // Used for Device Chip onPrimary = Color(0xFFED612B), onSurface = Color(0xFFED612B) ) ), ThemeValues( "Uamp", 6, Colors( primary = Color(0xFF981F68), primaryVariant = Color(0xFF66003d), secondary = Color(0xFF981F68), error = Color(0xFFE24444), onPrimary = Color.White, onSurfaceVariant = Color(0xFFDADCE0), surface = Color(0xFF303133), onError = Color.Black ) ) )
compose-tools/src/main/java/com/google/android/horologist/compose/tools/ThemeValues.kt
3114851527
package info.papdt.express.helper.view import android.content.Context import com.google.android.material.appbar.AppBarLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.recyclerview.widget.RecyclerView import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import com.scwang.smartrefresh.layout.SmartRefreshLayout import info.papdt.express.helper.R class ScrollingViewWithBottomBarBehavior(context: Context, attrs: AttributeSet?) : AppBarLayout.ScrollingViewBehavior(context, attrs) { private var bottomMargin = 0 private fun isBottomBar(view: View): Boolean { return view.id == R.id.bottom_bar && view is LinearLayout } override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean { return super.layoutDependsOn(parent, child, dependency) || isBottomBar(dependency) } override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean { val result = super.onDependentViewChanged(parent, child, dependency) if (isBottomBar(dependency) && dependency.height != bottomMargin) { bottomMargin = dependency.height var targetChild = child if (child is SmartRefreshLayout) { for (index in 0 until child.childCount) { val view = child.getChildAt(index) if (view is RecyclerView) { targetChild = view break } } } val layout = targetChild.layoutParams as ViewGroup.MarginLayoutParams layout.bottomMargin = bottomMargin targetChild.requestLayout() return true } else { return result } } }
mobile/src/main/kotlin/info/papdt/express/helper/view/ScrollingViewWithBottomBarBehavior.kt
2574162326
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.matching /** * Matching certainty. **The order of declaration is important!** */ enum class ResultCertainty : Comparable<ResultCertainty> { /** * The input did not match at least one unique part of the pattern. */ NOT_RECOGNIZED, /** * At least one unique property of the pattern was fulfilled by the input */ MATCHED, /** * All unique properties of the pattern were fulfilled by the input; however, errors were still encountered. */ OPTIMISTIC, /** * The input did fulfill all requirements. */ DEFINITIVE }
src/compiler/matching/ResultCertainty.kt
2659310680
package com.denysnovoa.nzbmanager.radarr.movie.release.repository.mapper import com.denysnovoa.nzbmanager.radarr.movie.release.repository.MovieReleaseEntity import com.denysnovoa.nzbmanager.radarr.movie.release.repository.entity.ReleaseQualityEntity import com.denysnovoa.nzbmanager.radarr.movie.release.repository.entity.ReleaseQualityResponse import com.denysnovoa.nzbmanager.radarr.movie.release.repository.entity.RevisionEntity import com.denysnovoa.nzbmanager.radarr.movie.release.repository.model.MovieReleaseModel class MovieReleaseMapperImpl : MovieReleaseMapper { override fun transform(movie: MovieReleaseEntity) = with(movie) { MovieReleaseModel(title, size, indexerId, indexer, rejected, downloadAllowed, age, seeders, leechers, guid, downloadUrl, infoUrl, quality = quality.quality.name) } override fun transform(movie: MovieReleaseModel) = with(movie) { MovieReleaseEntity(title, size, indexerId, indexer, rejected, downloadAllowed, age, seeders, leechers, guid, downloadUrl, infoUrl, ReleaseQualityResponse(ReleaseQualityEntity(0, ""), RevisionEntity(0, 0))) } }
app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/repository/mapper/MovieReleaseMapperImpl.kt
1444335153
package org.wordpress.android.fluxc.list import androidx.paging.DataSource.InvalidatedCallback import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.fluxc.model.list.PagedListFactory internal class PagedListFactoryTest { @Test fun `create factory triggers create data source`() { val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>() whenever(mockCreateDataSource.invoke()).thenReturn(mock()) val pagedListFactory = PagedListFactory(mockCreateDataSource) pagedListFactory.create() verify(mockCreateDataSource, times(1)).invoke() } @Test fun `invalidate triggers create data source`() { val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>() whenever(mockCreateDataSource.invoke()).thenReturn(mock()) val invalidatedCallback = mock<InvalidatedCallback>() val pagedListFactory = PagedListFactory(mockCreateDataSource) val currentSource = pagedListFactory.create() currentSource.addInvalidatedCallback(invalidatedCallback) pagedListFactory.invalidate() verify(invalidatedCallback, times(1)).onInvalidated() } }
example/src/test/java/org/wordpress/android/fluxc/list/PagedListFactoryTest.kt
3463782970
package fr.corenting.edcompanion.models import fr.corenting.edcompanion.models.apis.EDAPIV4.CommodityWithPriceResponse data class CommodityDetailsResult(val name: String, val id: Long, val isRare: Boolean, val category: String, val averageSellPrice: Long, val averageBuyPrice: Long, val maximumSellPrice: Long, val minimumBuyPrice: Long) { companion object { fun fromEDApiCommodityDetails(res: CommodityWithPriceResponse): CommodityDetailsResult { return CommodityDetailsResult(res.Commodity.Name, res.Commodity.Id, res.Commodity.IsRare, res.Commodity.Category, res.AverageSellPrice, res.AverageBuyPrice, res.MaximumSellPrice, res.MinimumBuyPrice) } } }
app/src/main/java/fr/corenting/edcompanion/models/CommodityDetailsResult.kt
2978623068
package br.com.codeteam.ctanywhere.view.webview import android.annotation.TargetApi import android.graphics.Bitmap import android.os.Build import android.os.Handler import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient abstract class WebViewClient(private var timeout: Long = 30000) : WebViewClient() { private var isTimeout = true abstract fun handleUri(url: String): Boolean abstract fun handleTimeout() override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) Handler().postDelayed({ if (isTimeout) { handleTimeout() } }, timeout) } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) isTimeout = false } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { if (this.handleUri(request?.url.toString())) { return true } view?.loadUrl(request?.url.toString()) return true } @Suppress("OverridingDeprecatedMember") override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (this.handleUri(url)) { return true } view.loadUrl(url) return true } }
app/src/main/java/br/com/codeteam/ctanywhere/view/webview/WebViewClient.kt
3484000150
package com.eden.orchid.posts import com.eden.orchid.posts.utils.PostsUtils import com.eden.orchid.testhelpers.BaseOrchidTest import org.junit.jupiter.api.DisplayName import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import strikt.api.expectThat import strikt.assertions.isEqualTo import strikt.assertions.isNotNull import strikt.assertions.isNull @DisplayName("Tests the formatting accepted by the LatestPostsCollection") class PostsCollectionTest : BaseOrchidTest() { @ParameterizedTest @CsvSource( "':latestBlogPost ', , 1", "':latestBlogPost() ', , 1", "':latestBlogPost(programming) ', programming, 1", "':latestBlogPost(3) ', , 3", "':latestBlogPost(programming, 3)', programming, 3", "':latestBlogPost(3, programming)', programming, 3", "':latestBlogPosts ', , 1", "':latestBlogPosts() ', , 1", "':latestBlogPosts(programming) ', programming, 1", "':latestBlogPosts(3) ', , 3", "':latestBlogPosts(programming, 3)', programming, 3", "':latestBlogPosts(3, programming)', programming, 3" ) fun testValidPostCollectionPatterns(input: String, expectedCategory: String?, expectedCount: Int) { expectThat(PostsUtils.parseLatestPostCollectionId(input.trim())) .isNotNull() .and { get { this.first }.isEqualTo(expectedCategory?.trim()) } .and { get { this.second }.isEqualTo(expectedCount) } } @ParameterizedTest @CsvSource( "'latestBlogPost'", "'latestBlogPosts'", "':latestBlogPosts(a,1,f)'", "':latestBlogPosts(,a)'", "':latestBlogPosts(a,)'", "':latestBlogPosts(,1)'", "':latestBlogPosts(1,)'", "':latestBlogPosts('", "':latestBlogPosts)'" ) fun testInvalidPostCollectionPatterns(input: String) { expectThat(PostsUtils.parseLatestPostCollectionId(input.trim())) .isNull() } }
plugins/OrchidPosts/src/test/kotlin/com/eden/orchid/posts/PostsCollectionTest.kt
1610780210
package de.msal.muzei.nationalgeographic import com.google.gson.* import com.google.gson.JsonParseException import de.msal.muzei.nationalgeographic.model.Image import java.lang.reflect.Type /** * "Flattens" the Json as the relevant data is nested deeply */ class ImageDeserializer : JsonDeserializer<Image> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Image { val image = Gson().fromJson(json, Image::class.java) // change /files/screenshot-2021-03-04-at-11.17.05.png // to https://static.nationalgeographic.co.uk/files/styles/image_3200/public/screenshot-2021-03-04-at-11.17.05.png.webp image.url = image.url ?.replace("/files/", "https://static.nationalgeographic.co.uk/files/styles/image_3200/public/") ?.replace(".png", ".png.webp") ?.replace(".jpg", ".webp") return image } }
muzei-nationalgeographic/src/main/kotlin/de/msal/muzei/nationalgeographic/ImageDeserializer.kt
2355997294
package com.octo.mob.octomeuh.transversal interface HumanlyReadableDurationsConverter { fun getReadableStringFromValueInSeconds(secondsDuration: Int): String } abstract class HumanlyReadableDurationsConverterImpl : HumanlyReadableDurationsConverter { private companion object { val SECONDS_IN_ONE_MINUTE = 60 val MINUTES_IN_ONE_HOUR = 60 val SECONDS_IN_ONE_HOUR = MINUTES_IN_ONE_HOUR * SECONDS_IN_ONE_MINUTE } protected fun getSecondsValue(secondsDuration: Int) = secondsDuration % SECONDS_IN_ONE_MINUTE protected fun getMinutesValue(hourValue: Int, secondsDuration: Int) = (secondsDuration - hourValue * SECONDS_IN_ONE_HOUR) / MINUTES_IN_ONE_HOUR protected fun getHourValue(secondsDuration: Int) = secondsDuration / (SECONDS_IN_ONE_HOUR) } class CompactDurationConverterImpl : HumanlyReadableDurationsConverterImpl() { override fun getReadableStringFromValueInSeconds(secondsDuration: Int): String { val hourValue = getHourValue(secondsDuration) val minutesValue = getMinutesValue(hourValue, secondsDuration) val secondsValue = getSecondsValue(secondsDuration) val hourString = getCompactReadableHours(hourValue) val minutesString = getCompactReadableMinutes(hourValue, minutesValue) val secondsString = getCompactReadableSeconds(hourValue, minutesValue, secondsValue) return hourString + minutesString + secondsString } private fun getCompactReadableHours(hourValue: Int) = if (hourValue > 0) "$hourValue:" else "" private fun getCompactReadableMinutes(hourValue: Int, minutesValue: Int): String { if (minutesValue > 0) { return String.format("%02d:", minutesValue) } else if (hourValue > 0) { return "00:" } else { return "" } } private fun getCompactReadableSeconds(hourValue: Int, minutesValue: Int, secondsValue: Int): String { if (secondsValue > 0) { return String.format("%02d", secondsValue) } else if (hourValue == 0 && minutesValue == 0) { return "0" } else { return "00" } } } class ExpandedDurationConverterImpl : HumanlyReadableDurationsConverterImpl() { override fun getReadableStringFromValueInSeconds(secondsDuration: Int): String { val hourValue = getHourValue(secondsDuration) val minutesValue = getMinutesValue(hourValue, secondsDuration) val secondsValue = getSecondsValue(secondsDuration) val hourString = getReadableHours(hourValue) val minutesString = getReadableMinutes(minutesValue) val secondsString = getReadableSeconds(hourValue, minutesValue, secondsValue) return hourString + minutesString + secondsString } private fun getReadableSeconds(hourValue: Int, minutesValue: Int, secondsValue: Int) = if (secondsValue > 0) "${secondsValue}s" else if (hourValue == 0 && minutesValue == 0) "0s" else "" private fun getReadableMinutes(minutesValue: Int) = if (minutesValue > 0) "${minutesValue}min " else "" private fun getReadableHours(hourValue: Int) = if (hourValue > 0) "${hourValue}h " else "" }
app/src/main/kotlin/com/octo/mob/octomeuh/transversal/HumanlyReadableDurationsConverter.kt
817787047
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.presentation.recentactivity import android.database.Cursor import com.doctoror.fuckoffmusicplayer.domain.albums.COLUMN_ALBUM import com.doctoror.fuckoffmusicplayer.domain.albums.COLUMN_ALBUM_ART import com.doctoror.fuckoffmusicplayer.domain.albums.COLUMN_ID import java.util.* class AlbumItemsFactory { fun itemsFromCursor(c: Cursor): List<AlbumItem> { val items = ArrayList<AlbumItem>(c.count) if (c.moveToFirst()) { while (!c.isAfterLast) { items.add(itemFromCursor(c)) c.moveToNext() } } return items } private fun itemFromCursor(c: Cursor) = AlbumItem( c.getLong(COLUMN_ID), c.getString(COLUMN_ALBUM), c.getString(COLUMN_ALBUM_ART)) }
presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/recentactivity/AlbumItemsFactory.kt
1335445665
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.symbol.impl.synthetic import com.google.devtools.ksp.processing.impl.findAnnotationFromUseSiteTarget import com.google.devtools.ksp.symbol.* abstract class KSPropertyAccessorSyntheticImpl(ksPropertyDeclaration: KSPropertyDeclaration) : KSPropertyAccessor { override val annotations: Sequence<KSAnnotation> by lazy { this.findAnnotationFromUseSiteTarget() } override val location: Location by lazy { ksPropertyDeclaration.location } override val modifiers: Set<Modifier> = emptySet() override val origin: Origin = Origin.SYNTHETIC override val receiver: KSPropertyDeclaration = ksPropertyDeclaration override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitPropertyAccessor(this, data) } }
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/synthetic/KSPropertyAccessorSyntheticImpl.kt
3629842758
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.psi.PsiElement import com.intellij.psi.stubs.StubElement import com.intellij.psi.tree.IElementType import com.vladsch.md.nav.psi.util.BasicTextMapElementTypeProvider import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.md.nav.psi.util.TextMapElementType import com.vladsch.md.nav.psi.util.TextMapMatch class MdJekyllFrontMatterBlockStubElementType(debugName: String) : MdPlainTextStubElementType<MdJekyllFrontMatterBlock, MdJekyllFrontMatterBlockStub>(debugName) { override fun createPsi(stub: MdJekyllFrontMatterBlockStub) = MdJekyllFrontMatterBlockImpl(stub, this) override fun getExternalId(): String = "markdown.plain-text-referenceable.jekyll-front-matter" override fun createStub(parentStub: StubElement<PsiElement>, textMapType: TextMapElementType, textMapMatches: Array<TextMapMatch>, referenceableOffsetInParent: Int): MdJekyllFrontMatterBlockStub = MdJekyllFrontMatterBlockStubImpl(parentStub, textMapType, textMapMatches, referenceableOffsetInParent) override fun getReferenceableTextType(): IElementType = MdTypes.JEKYLL_FRONT_MATTER_BLOCK override fun getTextMapType(): TextMapElementType = BasicTextMapElementTypeProvider.JEKYLL_FRONT_MATTER }
src/main/java/com/vladsch/md/nav/psi/element/MdJekyllFrontMatterBlockStubElementType.kt
2503134219
package org.ozinger.ika.serialization.serializer import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.encoding.encodeStructure import org.ozinger.ika.definition.MemberMode import org.ozinger.ika.definition.ModeChangelist import org.ozinger.ika.serialization.ModeStringDescriptor import org.ozinger.ika.state.ModeDefinitions object ChannelMemberDeclarationSerializer : KSerializer<ModeChangelist<MemberMode>> { override val descriptor = ModeStringDescriptor("ChannelMemberDeclaration", trailing = true) override fun serialize(encoder: Encoder, value: ModeChangelist<MemberMode>) = encoder.encodeStructure(descriptor) { val memberModes = mutableMapOf<String, MutableSet<Char>>() value.adding.forEach { mode -> val set = memberModes.getOrPut(mode.target.value, ::mutableSetOf) mode.mode?.let { set.add(it) } } val memberString = memberModes.map { (uuid, modes) -> StringBuilder().apply { modes.map(::append) append(",") append(uuid) }.toString() }.joinToString(" ") encodeStringElement(descriptor, 0, memberString) } override fun deserialize(decoder: Decoder): ModeChangelist<MemberMode> { val adding = mutableSetOf<MemberMode>() val members = decoder.decodeString().split(" ") for (member in members) { val (modes, uuid) = member.split(",") for (mode in modes) { if (mode !in ModeDefinitions.member.parameterized) { throw SerializationException("Invalid member mode: $mode") } adding.add(MemberMode(uuid, mode)) } if (modes.isEmpty()) { adding.add(MemberMode(uuid)) } } return ModeChangelist(adding = adding) } }
app/src/main/kotlin/org/ozinger/ika/serialization/serializer/ChannelMemberDeclarationSerializer.kt
220112235
package iii_properties import junit.framework.Assert import org.junit.Test as test import ii_conventions.MyDate class _21_Delegates_How_It_Works { @test fun testDate() { val d = D() d.date = MyDate(2014, 1, 13) Assert.assertEquals(2014, d.date.year) Assert.assertEquals(1, d.date.month) Assert.assertEquals(13, d.date.dayOfMonth) } }
test/iii_properties/_21_Delegates_How_It_Works.kt
2297643477
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.actions.styling import com.intellij.openapi.editor.Document import com.intellij.psi.PsiElement import com.vladsch.flexmark.util.sequence.RepeatedSequence import com.vladsch.md.nav.actions.handlers.util.PsiEditAdjustment import com.vladsch.md.nav.psi.element.MdHeaderElement import com.vladsch.md.nav.psi.element.MdParagraph import com.vladsch.md.nav.psi.element.MdSetextHeader import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.plugin.util.rangeLimit class HeaderLevelUpAction : HeaderAction() { override fun canPerformAction(element: PsiElement): Boolean { return element is MdHeaderElement && element.headerLevel < 6 || element is MdParagraph } override fun cannotPerformActionReason(element: PsiElement): String { return if (element is MdHeaderElement && element.canIncreaseLevel) "Cannot increase level heading beyond 6" else "Not Heading or Text element" } override fun headerAction(element: PsiElement, document: Document, caretOffset: Int, editContext: PsiEditAdjustment): Int? { if (element is MdHeaderElement) { if (element.canIncreaseLevel) { if (element is MdSetextHeader && element.headerLevel == 1) { val markerElement = element.headerMarkerNode ?: return null document.replaceString(markerElement.startOffset, markerElement.startOffset + markerElement.textLength, RepeatedSequence.repeatOf('-', element.headerText.length)) } else { element.setHeaderLevel(element.headerLevel + 1, editContext) } } else if (element.headerLevel < 6) { // change to ATX and increase level val offset = (caretOffset - element.headerTextElement!!.node.startOffset).rangeLimit(0, element.headerTextElement!!.node.textLength) return MdPsiImplUtil.changeHeaderType(element, element.headerLevel + 1, document, offset, editContext) } } else if (element is MdParagraph) { // add # before start of line without prefixes val startLine = document.getLineNumber(element.node.startOffset) val caretLine = document.getLineNumber(caretOffset) - startLine val lines = MdPsiImplUtil.linesForWrapping(element, false, false, false, editContext) // disabled because it is not undoable by heading down //if (false && MdCodeStyleSettings.getInstance(element.project).HEADING_PREFERENCE_TYPE().isSetextPreferred) { // val offset = lines[caretLine].trackedSourceLocation(0).offset + lines[caretLine].trimEnd().length // document.insertString(offset, "\n" + prefixes.childPrefix + RepeatedSequence.of('=', unPrefixedLines[caretLine].trimEnd().length)) // // if (caretLine > 0) { // // insert blank line or all preceding lines will be treated as part of heading // val startOffset = unPrefixedLines[caretLine].trackedSourceLocation(0).offset // document.insertString(startOffset, prefixes.childPrefix + "\n") // } //} else { // diagnostics/2556, index out of bounds val offset = if (caretLine >= lines.lineCount) document.textLength else lines[caretLine].text.startOffset return if (offset > 0 && document.charsSequence[offset - 1] != '\n') { document.insertString(offset, "\n# ") offset + 3 } else { document.insertString(offset, "# ") offset + 2 } //} } return null } }
src/main/java/com/vladsch/md/nav/actions/styling/HeaderLevelUpAction.kt
2407676452
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.ui.view import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun KeyValueField(key: String, value: String) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = key) Text( color = MaterialTheme.colorScheme.onBackground, text = value ) } }
lib_ui/src/main/java/no/nordicsemi/android/ui/view/KeyValueField.kt
952614376
package com.garpr.android.preferences.persistent import com.garpr.android.preferences.KeyValueStore class PersistentLongPreference( key: String, defaultValue: Long?, keyValueStore: KeyValueStore ) : BasePersistentPreference<Long>( key, defaultValue, keyValueStore ) { override fun get(): Long? { return if (hasValueInStore) { // at this point, returning the fallback value is impossible keyValueStore.getLong(key, 0L) } else { defaultValue } } override fun performSet(newValue: Long) { keyValueStore.setLong(key, newValue) } }
smash-ranks-android/app/src/main/java/com/garpr/android/preferences/persistent/PersistentLongPreference.kt
329123409
package com.garpr.android.extensions import android.os.Bundle import android.os.Parcelable fun <T : Parcelable> Bundle?.requireParcelable(key: String): T { checkNotNull(this) { "Bundle is null" } if (containsKey(key)) { return getParcelable(key) ?: throw NullPointerException( "Bundle Parcelable \"$key\" is null") } throw NoSuchElementException("Bundle does not contain Parcelable: \"$key\"") } fun Bundle?.requireString(key: String): String { checkNotNull(this) { "Bundle is null" } if (containsKey(key)) { return getString(key) ?: throw NullPointerException("Bundle String \"$key\" is null") } throw NoSuchElementException("Bundle does not contain String: \"$key\"") }
smash-ranks-android/app/src/main/java/com/garpr/android/extensions/BundleExt.kt
3549144332
package com.garpr.android.repositories import com.garpr.android.data.models.FullPlayer import com.garpr.android.data.models.MatchesBundle import com.garpr.android.data.models.PlayerMatchesBundle import com.garpr.android.data.models.Region import io.reactivex.Single import io.reactivex.functions.BiFunction class PlayerMatchesRepositoryImpl( private val matchesRepository: MatchesRepository, private val playersRepository: PlayersRepository ) : PlayerMatchesRepository { override fun getPlayerAndMatches(region: Region, playerId: String): Single<PlayerMatchesBundle> { return Single.zip( matchesRepository.getMatches(region, playerId), playersRepository.getPlayer(region, playerId), BiFunction<MatchesBundle, FullPlayer, PlayerMatchesBundle> { t1, t2 -> PlayerMatchesBundle(fullPlayer = t2, matchesBundle = t1) }) } }
smash-ranks-android/app/src/main/java/com/garpr/android/repositories/PlayerMatchesRepositoryImpl.kt
3644544437
package com.openlattice.users.processors.aggregators import com.auth0.json.mgmt.users.User import com.hazelcast.aggregation.Aggregator data class UsersWithConnectionsAggregator( val connections: Set<String>, val users: MutableSet<User> ) : Aggregator<MutableMap.MutableEntry<String, User>, Set<User>> { override fun accumulate(input: MutableMap.MutableEntry<String, User>) { if (input.value.identities.any { connections.contains(it.connection) }) { users.add(input.value) } } override fun combine(aggregator: Aggregator<*, *>) { if (aggregator is UsersWithConnectionsAggregator) { users.addAll(aggregator.users) } } override fun aggregate(): Set<User> { return users } }
src/main/kotlin/com/openlattice/users/processors/aggregators/UsersWithConnectionsAggregator.kt
3028245317
/* * #%L * Lincheck * %% * Copyright (C) 2015 - 2018 Devexperts, LLC * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package com.devexperts.dxlab.lincheck.test.verifier.quantitative import com.devexperts.dxlab.lincheck.LinChecker import com.devexperts.dxlab.lincheck.Result import com.devexperts.dxlab.lincheck.annotations.Operation import com.devexperts.dxlab.lincheck.annotations.Param import com.devexperts.dxlab.lincheck.paramgen.IntGen import com.devexperts.dxlab.lincheck.strategy.stress.StressCTest import com.devexperts.dxlab.lincheck.verifier.quantitative.* import com.devexperts.dxlab.lincheck.verifier.quantitative.PathCostFunction.* import org.junit.Test @StressCTest(threads = 2, actorsPerThread = 10, actorsBefore = 5, actorsAfter = 5, invocationsPerIteration = 10, iterations = 1000, verifier = QuantitativeRelaxationVerifier::class) @QuantitativeRelaxationVerifierConf( factor = 2, pathCostFunc = PHI_INTERVAL_RESTRICTED_MAX, costCounter = KPriorityQueueTest.CostCounter::class ) @Param(name = "push-value", gen = IntGen::class, conf = "1:20") class KPriorityQueueTest { private val pq = KPriorityQueueSimulation(2) @Operation(params = ["push-value"]) fun push(x: Int) = pq.push(x) @QuantitativeRelaxed @Operation fun poll(): Int? = pq.poll() @Test fun test() = LinChecker.check(KPriorityQueueTest::class.java) data class CostCounter @JvmOverloads constructor( private val k: Int, private val pq: List<Int> = emptyList() ) { fun push(value: Int, result: Result): CostCounter { check(result.type == Result.Type.VOID) val pqNew = ArrayList(pq) pqNew.add(0, value) pqNew.sort() return CostCounter(k, pqNew) } fun poll(result: Result): List<CostWithNextCostCounter<CostCounter>> { if (pq.isEmpty()) { return if (result.value == null) listOf(CostWithNextCostCounter(this, 0, false)) else emptyList() } else { val edges: MutableList<CostWithNextCostCounter<CostCounter>> = mutableListOf() val predicate = result.value != pq[0] val it = pq.iterator() var cost = 0 while (it.hasNext() && cost < k) { val value = it.next() if (value == result.value) { val pqNew = ArrayList(pq) pqNew.remove(value) edges.add(CostWithNextCostCounter(CostCounter(k, pqNew), cost, predicate)) } cost++ } return edges } } } }
lincheck/src/test/java/com/devexperts/dxlab/lincheck/test/verifier/quantitative/KPriorityQueueTest.kt
250743314
package edu.cs4730.recyclerviewdemo3_kt import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.DefaultItemAnimator /** * A "simple" version of the recyclerview with layout. * There is no simple layout or adapter, so both have to be created. * Everything is labeled, simple1_ that goes with this one. */ class Simple1_Fragment : Fragment() { lateinit var mRecyclerView: RecyclerView lateinit var mAdapter: Simple1_myAdapter var values = arrayOf( "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.simple1_fragment, container, false) //setup the RecyclerView mRecyclerView = myView.findViewById(R.id.list) mRecyclerView.layoutManager = LinearLayoutManager(requireContext()) mRecyclerView.itemAnimator = DefaultItemAnimator() //setup the adapter, which is myAdapter, see the code. mAdapter = Simple1_myAdapter(values, R.layout.simple1_rowlayout, requireContext()) //add the adapter to the recyclerview mRecyclerView.adapter = mAdapter return myView } }
RecyclerViews/RecyclerViewDemo3_kt/app/src/main/java/edu/cs4730/recyclerviewdemo3_kt/Simple1_Fragment.kt
3778751662
package org.http4k.contract.openapi.v3 import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import org.junit.jupiter.api.Test class FieldRetrievalTest { private val blowUp = FieldRetrieval { p1, p2 -> throw NoFieldFound(p2, p1) } private val result = Field("hello", true, FieldMetadata.empty) private val findIt = FieldRetrieval { _, _ -> result } data class Beany(val nonNullable: String = "hello", val aNullable: String? = "aNullable") @Test fun `bombs if can't find field anywhere`() { assertThat({ FieldRetrieval.compose(blowUp, blowUp)(Beany(), "foo") }, throws<NoFieldFound>()) } @Test fun `field retrieval falls back if none found`() { assertThat(FieldRetrieval.compose(blowUp, findIt)(Beany(), "foo"), equalTo(Field("hello", true, FieldMetadata.empty))) } }
http4k-contract/src/test/kotlin/org/http4k/contract/openapi/v3/FieldRetrievalTest.kt
2794043751
package org.http4k.server import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.present import org.http4k.client.ApacheClient import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.Random class KtorCIOTest : ServerContract({ KtorCIO(Random().nextInt(1000) + 8745) }, ApacheClient()) { @BeforeEach fun sleepForABitBecauseStartupIsCrushinglySlow() { Thread.sleep(1000) } @Test override fun `ok when length already set`() { } @Test override fun `can start on port zero and then get the port`() { } override fun clientAddress(): Matcher<String?> = present() override fun requestScheme(): Matcher<String?> = equalTo("http") }
http4k-server/ktorcio/src/test/kotlin/org/http4k/server/KtorCIOTest.kt
3473824905
package fr.letroll.kotlinandroidlib import android.app.Activity import android.content.res.Configuration import android.util.Log import android.view.View //public fun Activity.findView<T: View>(id: Int): T? = findViewById(id) as? T public fun Activity.findView<T : View>(id : Int) : T { val view : View? = findViewById(id) ?: throw IllegalArgumentException("Given ID could not be found in current layout!") return view as T } fun Activity.isLandscape(): Boolean { return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE } fun Activity.isPortrait(): Boolean { return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT } public fun Activity.log(txt: String?) { if (txt == null) Log.d("debug", "text null") else Log.d("debug", txt) } public fun Activity.loge(txt: String?) { if (txt == null) Log.e("error", "text null") else Log.e("error", txt) }
kotlinandroidlib/src/main/kotlin/fr/letroll/kotlinandroidlib/KotlinActivity.kt
2643378620
package com.binarymonks.jj.core.audio import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.JJ class EffectsController { private var singletonMap = ObjectMap<String, SingletonWindow>() var volume = 0.2f var isMute = false fun addSingletonSound(singletonTimeWindow: Float, vararg soundpaths: String) { val window = SingletonWindow(singletonTimeWindow) for (soundpath in soundpaths) { singletonMap.put(soundpath, window) } } fun canTriggerSingleton(soundpath: String): Boolean { if (!singletonMap.containsKey(soundpath)) { return true } return singletonMap.get(soundpath).elapsed() } private inner class SingletonWindow(window: Float) { var window: Double = 0.toDouble() var lastTrigger = 0.0 init { this.window = window.toDouble() } fun elapsed(): Boolean { val currentT = JJ.B.clock.time val elapsed = currentT - lastTrigger > window if (elapsed) { lastTrigger = currentT } return elapsed } } }
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/audio/EffectsController.kt
4938458
@file:JsModule("rxjs") package kodando.rxjs.scheduler @JsName("queue") external val queueScheduler: Scheduler
kodando-rxjs/src/main/kotlin/kodando/rxjs/scheduler/QueueScheduler.kt
2689821896
package fr.vbastien.mycoincollector.db import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.ForeignKey import android.arch.persistence.room.PrimaryKey /** * Created by vbastien on 03/07/2017. */ @Entity(tableName = "coin", foreignKeys = arrayOf(ForeignKey(entity = Country::class, parentColumns = arrayOf("country_id"), childColumns = arrayOf("coin_id"), onDelete = ForeignKey.CASCADE))) data class Coin ( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "coin_id") var coinId : Int = 0, @ColumnInfo(name = "country_id") var countryId : Int = 0, var value: Double = 0.0, var img: String? = null, var description: String? = null )
app/src/main/java/fr/vbastien/mycoincollector/db/Coin.kt
3883286866
package lt.vilnius.tvarkau.dagger import android.content.Context import android.support.v4.app.Fragment import android.support.v7.preference.PreferenceFragmentCompat import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.AndroidSupportInjection import dagger.android.support.HasSupportFragmentInjector import javax.inject.Inject abstract class PreferenceDaggerFragment : PreferenceFragmentCompat(), HasSupportFragmentInjector { @Inject lateinit var childFragmentInjector: DispatchingAndroidInjector<Fragment> override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun supportFragmentInjector(): AndroidInjector<Fragment>? { return childFragmentInjector } }
app/src/main/java/lt/vilnius/tvarkau/dagger/PreferenceDaggerFragment.kt
3910569148
package com.infinum.dbinspector.domain.pragma.models internal enum class IndexListColumns { SEQ, NAME, UNIQUE; companion object { operator fun invoke(index: Int) = values().single { it.ordinal == index } } }
dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/pragma/models/IndexListColumns.kt
4006619221
/* * Copyright (c) 2020 Arthur Milchior <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.RobolectricTest import com.ichi2.utils.KotlinCleanup import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @KotlinCleanup("IDE lint") class ExportingTest : RobolectricTest() { @KotlinCleanup("lateinit") private var mCol: Collection? = null /***************** * Exporting * */ private fun setup() { mCol = col var note = mCol!!.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar<br>") note.setTagsFromStr("tag, tag2") mCol!!.addNote(note) // with a different col note = mCol!!.newNote() note.setItem("Front", "baz") note.setItem("Back", "qux") note.model().put("did", addDeck("new col")) mCol!!.addNote(note) } /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */ @Test fun empty_test() { // A test should occurs in the file, otherwise travis rejects. This remains here until we can uncomment the real tests. } /* TODO @Test public void test_export_anki(){ // create a new col with its own conf to test conf copying long did = addDeck("test"); Deck dobj = col.getDecks().get(did); long confId = col.getDecks().add_config_returning_id("newconf"); DeckConfig conf = col.getDecks().getConf(confId); conf.getJSONObject("new").put("perDay", 5); col.getDecks().save(conf); col.getDecks().setConf(dobj, confId); // export AnkiPackageExporter e = AnkiExporter(col); fd, newname = tempfile.mkstemp(prefix="ankitest", suffix=".anki2"); newname = str(newname); os.close(fd); os.unlink(newname); e.exportInto(newname); // exporting should not have changed conf for original deck conf = col.getDecks().confForDid(did); assertNotEquals(conf.getLong("id") != 1); // connect to new deck Collection col2 = aopen(newname); assertEquals(2, col2.cardCount()); // as scheduling was reset, should also revert decks to default conf long did = col2.getDecks().id("test", create=false); assertTrue(did); conf2 = col2.getDecks().confForDid(did); assertTrue(conf2.getJSONObject("new").put("perDay",= 20)); Deck dobj = col2.getDecks().get(did); // conf should be 1 assertTrue(dobj.put("conf",= 1)); // try again, limited to a deck fd, newname = tempfile.mkstemp(prefix="ankitest", suffix=".anki2"); newname = str(newname); os.close(fd); os.unlink(newname); e.setDid(1); e.exportInto(newname); col2 = aopen(newname); assertEquals(1, col2.cardCount()); } @Test public void test_export_ankipkg(){ // add a test file to the media directory with open(os.path.join(col.getMedia().dir(), "今日.mp3"), "w") as note: note.write("test"); Note n = col.newNote(); n.setItem("Front", "[sound:今日.mp3]"); col.addNote(n); AnkiPackageExporter e = AnkiPackageExporter(col); fd, newname = tempfile.mkstemp(prefix="ankitest", suffix=".apkg"); String newname = str(newname); os.close(fd); os.unlink(newname); e.exportInto(newname); } @errorsAfterMidnight @Test public void test_export_anki_due(){ Collection col = getCol(); Note note = col.newNote(); note.setItem("Front","foo"); col.addNote(note); col.crt -= SECONDS_PER_DAY * 10; col.flush(); col.getSched().reset(); Card c = col.getSched().getCard(); col.getSched().answerCard(c, 3); col.getSched().answerCard(c, 3); // should have ivl of 1, due on day 11 assertEquals(1, c.getIvl()); assertEquals(11, c.getDue()); assertEquals(10, col.getSched().getToday()); assertEquals(1, c.getDue() - col.getSched().getToday()); // export AnkiPackageExporter e = AnkiExporter(col); e.includeSched = true; fd, newname = tempfile.mkstemp(prefix="ankitest", suffix=".anki2"); String newname = str(newname); os.close(fd); os.unlink(newname); e.exportInto(newname); // importing into a new deck, the due date should be equivalent col2 = getCol(); imp = Anki2Importer(col2, newname); imp.run(); c = col2.getCard(c.getId()); col2.getSched().reset(); assertEquals(1, c.getDue() - col2.getSched().getToday()); } @Test public void test_export_textcard(){ // e = TextCardExporter(col) // Note note = unicode(tempfile.mkstemp(prefix="ankitest")[1]) // os.unlink(note) // e.exportInto(note) // e.includeTags = true // e.exportInto(note) } @Test public void test_export_textnote(){ Collection col = setup1(); e = TextNoteExporter(col); fd, Note note = tempfile.mkstemp(prefix="ankitest"); Note note = str(note); os.close(fd); os.unlink(note); e.exportInto(note); with open(note) as file: assertEquals("foo\tbar<br>\ttag tag2\n", file.readline()); e.includeTags = false; e.includeHTML = false; e.exportInto(note); with open(note) as file: assertEquals("foo\tbar\n", file.readline()); } @Test public void test_exporters(){ assertThat(str(exporters()), containsString("*.apkg")); */ }
AnkiDroid/src/test/java/com/ichi2/libanki/ExportingTest.kt
1458433000
/* * 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.preferences import android.content.Context import android.text.method.LinkMovementMethod import android.util.AttributeSet import android.widget.TextView import androidx.core.text.parseAsHtml import androidx.preference.Preference import androidx.preference.PreferenceViewHolder import com.ichi2.anki.R /** * Non-clickable preference that shows help text. * * The summary is parsed as a format string containing HTML, * and may contain up to three format specifiers as understood by `Sting.format()`, * arguments for which can be specified using XML attributes such as `app:substitution1`. * * <com.ichi2.preferences.HtmlHelpPreference * android:summary="@string/format_string" * app:substitution1="@string/substitution1" * /> * * The summary HTML can contain all tags that TextViews can display, * including new lines and links. Raw HTML can be entered using the CDATA tag, e.g. * * <string name="format_string"><![CDATA[<b>Hello, %s</b>]]></string> */ class HtmlHelpPreference(context: Context, attrs: AttributeSet?) : Preference(context, attrs) { init { isSelectable = false isPersistent = false } private val substitutions = context.usingStyledAttributes(attrs, R.styleable.HtmlHelpPreference) { arrayOf( getString(R.styleable.HtmlHelpPreference_substitution1), getString(R.styleable.HtmlHelpPreference_substitution2), getString(R.styleable.HtmlHelpPreference_substitution3), ) } override fun getSummary() = super.getSummary() .toString() .format(*substitutions) .parseAsHtml() override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) val summary = holder.findViewById(android.R.id.summary) as TextView summary.movementMethod = LinkMovementMethod.getInstance() summary.maxHeight = Int.MAX_VALUE } }
AnkiDroid/src/main/java/com/ichi2/preferences/HtmlHelpPreference.kt
3772672887
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.custom import android.content.Context import android.graphics.PorterDuff import android.support.design.widget.AppBarLayout import android.util.AttributeSet import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import com.toshi.R import com.toshi.extensions.getColorById import kotlinx.android.synthetic.main.view_dapp_header.view.closeButton import kotlinx.android.synthetic.main.view_dapp_header.view.collapsingToolbar import kotlinx.android.synthetic.main.view_dapp_header.view.headerImage import kotlinx.android.synthetic.main.view_dapp_header.view.headerImageWrapper import kotlinx.android.synthetic.main.view_dapp_header.view.toolbar class DappHeaderView : AppBarLayout { private var prevOffset = -1 var offsetChangedListener: ((Float) -> Unit)? = null constructor(context: Context): super(context) { init() } constructor(context: Context, attrs: AttributeSet?): super(context, attrs) { init() } private fun init() { inflate(context, R.layout.view_dapp_header, this) initListeners() } private fun initListeners() { addOnOffsetChangedListener { appBarLayout, verticalOffset -> handleOffsetChanged(appBarLayout, verticalOffset) } } private fun handleOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { if (prevOffset == verticalOffset) return prevOffset = verticalOffset val absVerticalOffset = Math.abs(verticalOffset).toFloat() val scrollRange = appBarLayout.totalScrollRange.toFloat() val percentage = 1f - (absVerticalOffset / scrollRange) setHeaderImageAlpha(percentage) offsetChangedListener?.invoke(percentage) } private fun setHeaderImageAlpha(percentage: Float) { headerImageWrapper.alpha = percentage headerImage.alpha = percentage } fun enableCollapsing() { setExpanded(true) setDarkToolbar() } fun disableCollapsing() { setExpanded(false) setLightToolbar() val lp = collapsingToolbar.layoutParams as AppBarLayout.LayoutParams lp.height = WRAP_CONTENT } private fun setLightToolbar() { collapsingToolbar.setBackgroundColor(getColorById(R.color.windowBackground)) toolbar.setBackgroundColor(getColorById(R.color.windowBackground)) toolbar.closeButton.setColorFilter(getColorById(R.color.textColorSecondary), PorterDuff.Mode.SRC_IN) } private fun setDarkToolbar() { collapsingToolbar.setBackgroundColor(getColorById(R.color.colorPrimary)) toolbar.closeButton.setColorFilter(getColorById(R.color.textColorContrast), PorterDuff.Mode.SRC_IN) } }
app/src/main/java/com/toshi/view/custom/DappHeaderView.kt
361092857
package de.westnordost.streetcomplete.quests.construction import de.westnordost.streetcomplete.data.meta.SURVEY_MARK_KEY import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder fun deleteTagsDescribingConstruction(changes: StringMapChangesBuilder) { changes.deleteIfExists("construction") changes.deleteIfExists("source:construction") changes.deleteIfExists("opening_date") changes.deleteIfExists("source:opening_date") changes.deleteIfExists(SURVEY_MARK_KEY) changes.deleteIfExists("source:$SURVEY_MARK_KEY") }
app/src/main/java/de/westnordost/streetcomplete/quests/construction/MarkCompletedConstructionUtils.kt
436920887
/* * Copyright (C) 2018,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.presentation.form import org.akvo.flow.domain.QuestionResponse import org.akvo.flow.domain.Survey import java.util.HashMap interface FormView { fun showLoading() fun hideLoading() fun dismiss() fun showErrorExport() fun showMobileUploadSetting(surveyInstanceId: Long) fun startSync(isMobileSyncAllowed: Boolean) fun goToListOfForms() fun showFormUpdated() fun trackDraftFormVersionUpdated() fun showErrorLoadingForm() fun displayFormAndResponses(form: Survey, responses: HashMap<String, QuestionResponse>) }
app/src/main/java/org/akvo/flow/presentation/form/FormView.kt
2362567834
package jgappsandgames.smartreminderslite.home // Android OS import android.os.Bundle import android.text.Editable import android.text.TextWatcher // Views import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity // Anko import org.jetbrains.anko.alert import org.jetbrains.anko.button import org.jetbrains.anko.customView import org.jetbrains.anko.matchParent import org.jetbrains.anko.verticalLayout import org.jetbrains.anko.wrapContent import org.jetbrains.anko.sdk25.coroutines.onClick // App import jgappsandgames.smartreminderslite.R import jgappsandgames.smartreminderslite.adapter.TaskAdapter import jgappsandgames.smartreminderslite.utility.* // KotlinX import kotlinx.android.synthetic.main.activity_home.* // Save Library import jgappsandgames.smartreminderssave.MasterManager import jgappsandgames.smartreminderssave.tasks.Task import jgappsandgames.smartreminderssave.tasks.TaskManager /** * HomeActivity * Created by joshua on 12/13/2017. */ class HomeActivity: AppCompatActivity(), TaskAdapter.OnTaskChangedListener { // LifeCycle Methods --------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) setTitle(R.string.app_name) // Handle the Data loadClass(this) // Set Click Listeners home_add_task.setOnClickListener { home_fab.close(true) startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_TASK).save(), true)))) } home_add_folder.setOnClickListener { home_fab.close(true) startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_FOLDER).save(), true)))) } home_add_note.setOnClickListener { home_fab.close(true) startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_NOTE).save(), true)))) } home_bottom_bar_search.setOnClickListener { if (home_bottom_bar_search_text.visibility == View.VISIBLE) searchVisibility(false) else searchVisibility(true) } home_bottom_bar_more.setOnClickListener { alert { title = [email protected](R.string.sort_options) customView { verticalLayout { button { text = context.getString(R.string.sort_by_tags) onClick { startActivity(buildTagsIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) button { text = context.getString(R.string.sort_by_status) onClick { startActivity(buildStatusIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) button { text = context.getString(R.string.sort_by_priority) onClick { startActivity(buildPriorityIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) button { text = context.getString(R.string.sort_by_days) onClick { startActivity(buildDayIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) button { text = context.getString(R.string.sort_by_week) onClick { startActivity(buildWeekIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) button { text = context.getString(R.string.sort_by_month) onClick { startActivity(buildMonthIntent(this@HomeActivity, IntentOptions())) } }.lparams(matchParent, wrapContent) }.layoutParams = ViewGroup.LayoutParams(matchParent, matchParent) } }.show() } home_bottom_bar_search_text.addTextChangedListener(object: TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { if (home_bottom_bar_search_text.visibility == View.VISIBLE) home_tasks_list.adapter = TaskAdapter(this@HomeActivity, this@HomeActivity, TaskManager.getHome(), home_bottom_bar_search_text.text.toString()) } }) } override fun onResume() { super.onResume() home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "") } override fun onPause() { super.onPause() save() } // Menu Methods -------------------------------------------------------------------------------- override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_home, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean = onOptionsItemSelected(this, item!!, object: Save { override fun save() = [email protected]() }) // Task Listener ------------------------------------------------------------------------------- override fun onTaskChanged() = onResume() // Auxiliary Methods --------------------------------------------------------------------------- fun save() = MasterManager.save() // Search Methods ------------------------------------------------------------------------------ private fun searchVisibility(visible: Boolean = true) { if (visible) { home_bottom_bar_search_text.visibility = View.VISIBLE home_bottom_bar_search_text.setText("") home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "") } else { home_bottom_bar_search_text.visibility = View.INVISIBLE home_bottom_bar_search_text.setText("") home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "") } } }
app/src/main/java/jgappsandgames/smartreminderslite/home/HomeActivity.kt
152108309
package coursework.kiulian.com.freerealestate.view.dialogs import android.app.Activity import android.support.v7.app.AlertDialog import android.content.pm.PackageManager import android.support.annotation.NonNull import coursework.kiulian.com.freerealestate.R import android.content.Intent /** * Created by User on 30.03.2017. */ class ImagePickDialog(activity: Activity) { interface OnAvatarPickListener { fun onMethodSelected(requestCode: Int) } private val items = arrayOf("Take Photo", "Choose from Library") private val onAvatarPickListener: OnAvatarPickListener init { onAvatarPickListener = activity as OnAvatarPickListener val builder = AlertDialog.Builder(activity) builder.setTitle("Add Photo") builder.setItems(items, { dialog, item -> if (items[item] == "Take Photo") { onAvatarPickListener.onMethodSelected(TAKE_PHOTO) } else if (items[item] == "Choose from Library") { onAvatarPickListener.onMethodSelected(PICK_IMAGE) } }) builder.show() } companion object { val TAKE_PHOTO = 1023 val PICK_IMAGE = 2340 } }
app/src/main/java/coursework/kiulian/com/freerealestate/view/dialogs/ImagePickDialog.kt
2467397804
package org.strykeforce.trapper import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonWriter import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okio.Buffer import okio.BufferedSource private val traceJsonAdapter = TraceJsonAdapter(moshi) @JsonClass(generateAdapter = true) data class Trace(val time: Int) : Postable { var id: Int? = null var action: Int? = null var data: List<Double> = mutableListOf() override fun endpoint(baseUrl: String) = "$baseUrl/traces/".toHttpUrl() override fun asRequestBody(): RequestBody { val buffer = Buffer() traceJsonAdapter.toJson(buffer, this) return buffer.readUtf8().toRequestBody(MEDIA_TYPE_JSON) } @Suppress("UNCHECKED_CAST") override fun <T : Postable> fromJson(source: BufferedSource): T = traceJsonAdapter.fromJson(source)!! as T } internal fun requestBodyFromList(traces: List<Trace>): RequestBody { val buffer = Buffer() val writer: JsonWriter = JsonWriter.of(buffer) writer.beginArray() traces.forEach { traceJsonAdapter.toJson(writer, it) } writer.endArray() return buffer.readUtf8().toRequestBody(MEDIA_TYPE_JSON) }
src/main/kotlin/org/strykeforce/trapper/Trace.kt
1907561512
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.adapter.viewholder import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.toshi.model.local.dapp.DappCategory class SearchDappCategoryViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { fun setCategory(category: DappCategory) { val view = itemView as TextView view.text = category.category } }
app/src/main/java/com/toshi/view/adapter/viewholder/SearchDappCategoryViewHolder.kt
3964768845
// Copyright 2021 [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 avb.desc import org.apache.commons.codec.binary.Hex import org.junit.Test import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream class UnknownDescriptorTest { private val log = LoggerFactory.getLogger(UnknownDescriptorTest::class.java) @Test fun readDescriptors() { //output by "xxd -p <file>" val descStr = "000000000000000200000000000000b800000000017b9000736861323536" + "000000000000000000000000000000000000000000000000000000000004" + "000000200000002000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000626f6f7428f6d60b554d9532bd45874ab0cd" + "cb2219c4f437c9350f484fa189a881878ab6156408cd763ff119635ec9db" + "2a9656e220fa1dc27e26e59bd3d85025b412ffc3" val descBA = Hex.decodeHex(descStr + descStr) val descList = UnknownDescriptor.parseDescriptors(ByteArrayInputStream(descBA), descBA.size.toLong()) descList.forEach{ log.info(it.toString()) } } }
bbootimg/src/test/kotlin/avb/desc/UnknownDescriptorTest.kt
3138011671
package org.wordpress.android.fluxc.persistence import com.wellsql.generated.ListItemModelTable import com.wellsql.generated.ListModelTable import com.yarolegovich.wellsql.SelectQuery import com.yarolegovich.wellsql.WellSql import org.wordpress.android.fluxc.model.list.ListItemModel import javax.inject.Inject import javax.inject.Singleton @Singleton class ListItemSqlUtils @Inject constructor() { /** * This function inserts the [itemList] in the [ListItemModelTable]. * * Unique constraint in [ListItemModel] will ignore duplicate records which is what we want. That'll ensure that * the order of the items will not be altered while the user is browsing the list. The order will fix itself * once the list data is refreshed. */ fun insertItemList(itemList: List<ListItemModel>) { WellSql.insert(itemList).asSingleTransaction(true).execute() } /** * This function returns a list of [ListItemModel] records for the given [listId]. */ fun getListItems(listId: Int): List<ListItemModel> = getListItemsQuery(listId).asModel /** * This function returns the number of records a list has for the given [listId]. */ fun getListItemsCount(listId: Int): Long = getListItemsQuery(listId).count() /** * A helper function that returns the select query for a list of [ListItemModel] records for the given [listId]. */ private fun getListItemsQuery(listId: Int): SelectQuery<ListItemModel> = WellSql.select(ListItemModel::class.java) .where() .equals(ListItemModelTable.LIST_ID, listId) .endWhere() .orderBy(ListModelTable.ID, SelectQuery.ORDER_ASCENDING) /** * This function deletes [ListItemModel] records for the [listIds]. */ fun deleteItem(listIds: List<Int>, remoteItemId: Long) { WellSql.delete(ListItemModel::class.java) .where() .isIn(ListItemModelTable.LIST_ID, listIds) .equals(ListItemModelTable.REMOTE_ITEM_ID, remoteItemId) .endWhere() .execute() } /** * This function deletes all [ListItemModel]s for a specific [listId]. */ fun deleteItems(listId: Int) { WellSql.delete(ListItemModel::class.java) .where() .equals(ListItemModelTable.LIST_ID, listId) .endWhere() .execute() } /** * This function deletes [ListItemModel]s for [remoteItemIds] in every lists with [listIds] */ fun deleteItemsFromLists(listIds: List<Int>, remoteItemIds: List<Long>) { // Prevent a crash caused by either of these lists being empty if (listIds.isEmpty() || remoteItemIds.isEmpty()) { return } WellSql.delete(ListItemModel::class.java) .where() .isIn(ListItemModelTable.LIST_ID, listIds) .isIn(ListItemModelTable.REMOTE_ITEM_ID, remoteItemIds) .endWhere() .execute() } }
fluxc/src/main/java/org/wordpress/android/fluxc/persistence/ListItemSqlUtils.kt
1944528722