content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package org.kkanojia.tasks.teamcity.common
interface InterruptionChecker {
val isInterrupted: Boolean
}
| tasks-teamcity-plugin-common/src/main/kotlin/org/kkanojia/tasks/teamcity/common/InterruptionChecker.kt | 1695612259 |
package at.phatbl.swiftpm.tasks
/**
* Generates an Xcode project for the package.
*/
open class GenerateXcodeTask : AbstractExecTask() {
init {
description = "Generates an Xcode project for the package."
command = "swift package generate-xcodeproj"
}
}
| src/main/kotlin/at/phatbl/swiftpm/tasks/GenerateXcodeTask.kt | 2792777078 |
// MOVE: down
fun foo(x: Boolean) {
<caret>while (x) {
}
if (x) {
}
}
| plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/whileToBlock1.kt | 2298265017 |
TODO("not implemented") | .idea/fileTemplates/code/New Kotlin Property Initializer.kt | 1779042683 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.kdoc
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.psi.KtFile
class KDocTypedHandler : TypedHandlerDelegate() {
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
if (overwriteClosingBracket(c, editor, file)) {
EditorModificationUtil.moveCaretRelatively(editor, 1)
return Result.STOP
}
return Result.CONTINUE
}
override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result =
if (handleBracketTyped(c, project, editor, file)) Result.STOP else Result.CONTINUE
private fun overwriteClosingBracket(c: Char, editor: Editor, file: PsiFile): Boolean {
if (c != ']' && c != ')') return false
if (file !is KtFile) return false
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return false
val offset = editor.caretModel.offset
val document = editor.document
val chars = document.charsSequence
if (offset < document.textLength && chars[offset] == c) {
val iterator = (editor as EditorEx).highlighter.createIterator(offset)
val elementType = iterator.tokenType
if (iterator.start == 0) return false
iterator.retreat()
val prevElementType = iterator.tokenType
return when (c) {
']' -> {
// if the bracket is not part of a link, it will be part of KDOC_TEXT, not a separate RBRACKET element
prevElementType in KDocTokens.KDOC_HIGHLIGHT_TOKENS && (elementType == KDocTokens.MARKDOWN_LINK || (offset > 0 && chars[offset - 1] == '['))
}
')' -> elementType == KDocTokens.MARKDOWN_INLINE_LINK
else -> false
}
}
return false
}
private fun handleBracketTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Boolean {
if (c != '[' && c != '(') return false
if (file !is KtFile) return false
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return false
val offset = editor.caretModel.offset
if (offset == 0) return false
val document = editor.document
PsiDocumentManager.getInstance(project).commitDocument(document)
val element = file.findElementAt(offset - 1) ?: return false
if (element.node.elementType != KDocTokens.TEXT) return false
when (c) {
'[' -> {
document.insertString(offset, "]")
return true
}
'(' -> {
if (offset > 1 && document.charsSequence[offset - 2] == ']') {
document.insertString(offset, ")")
return true
}
}
}
return false
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KDocTypedHandler.kt | 376947832 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
abstract class FindFirstProcessor<out T : GroovyResolveResult>(protected val name: String) : ProcessorWithHints(), GrResolverProcessor<T> {
init {
hint(NameHint.KEY, NameHint { name })
}
private var result: T? = null
final override val results: List<T> get() = result?.let { listOf(it) } ?: emptyList()
final override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (shouldStop()) return false
assert(result == null)
result = result(element, state)
return !shouldStop() && result == null
}
protected abstract fun result(element: PsiElement, state: ResolveState): T?
protected open fun shouldStop(): Boolean = false
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/FindFirstProcessor.kt | 2798865457 |
// INTENTION_CLASS: org.jetbrains.kotlin.android.intention.AddActivityToManifest
// NOT_AVAILABLE
package com.myapp
import android.app.Activity
class <caret>MyActivity : Activity() | plugins/kotlin/idea/tests/testData/android/intention/addActivityToManifest/alreadyExists.kt | 484411767 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.presentation.impl
import com.intellij.model.presentation.SymbolPresentation
import org.jetbrains.annotations.Nls
import javax.swing.Icon
internal class DefaultSymbolPresentation(
private val icon: Icon?,
@Nls private val typeString: String,
@Nls private val shortNameString: String,
@Nls private val longNameString: String? = shortNameString
) : SymbolPresentation {
override fun getIcon(): Icon? = icon
override fun getShortNameString(): String = shortNameString
override fun getShortDescription(): String = "$typeString '$shortNameString'"
override fun getLongDescription(): String = "$typeString '$longNameString'"
}
| platform/lang-impl/src/com/intellij/model/presentation/impl/DefaultSymbolPresentation.kt | 283175709 |
// "Create property 'foo'" "true"
// ERROR: Property must be initialized or be abstract
// ERROR: Variable 'foo' must be initialized
class A<T> {
var x: A<Int> by <caret>foo
}
| plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/property/memberVarDelegateRuntime.kt | 3163876138 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.util
import android.arch.lifecycle.LiveData
/**
* A LiveData class that has `null` value.
*/
class AbsentLiveData<T> private constructor() : LiveData<T>() {
init {
postValue(null)
}
companion object {
fun <T> create(): LiveData<T> {
return AbsentLiveData()
}
}
} | domain/src/main/java/com/sinyuk/fanfou/domain/util/AbsentLiveData.kt | 2480044767 |
package org.livingdoc.repositories.file
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class FileRepositoryTest {
val cut = FileRepository("", FileRepositoryConfig())
@Test fun `exception is thrown if document could not be found`() {
assertThrows<FileDocumentNotFoundException> {
cut.getDocument("foo-bar.md")
}
}
}
| livingdoc-repository-file/src/test/kotlin/org/livingdoc/repositories/file/FileRepositoryTest.kt | 2545841320 |
package fr.free.nrw.commons.nearby.fragments
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import fr.free.nrw.commons.R
import fr.free.nrw.commons.Utils
import fr.free.nrw.commons.auth.LoginActivity
import fr.free.nrw.commons.contributions.ContributionController
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.utils.ActivityUtils
import fr.free.nrw.commons.wikidata.WikidataConstants
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class CommonPlaceClickActions @Inject constructor(
@Named("default_preferences") private val applicationKvStore: JsonKvStore,
private val activity: Activity,
private val contributionController: ContributionController
) {
fun onCameraClicked(): (Place) -> Unit = {
if (applicationKvStore.getBoolean("login_skipped", false)) {
showLoginDialog()
} else {
Timber.d("Camera button tapped. Image title: ${it.getName()}Image desc: ${it.longDescription}")
storeSharedPrefs(it)
contributionController.initiateCameraPick(activity)
}
}
fun onGalleryClicked(): (Place) -> Unit = {
if (applicationKvStore.getBoolean("login_skipped", false)) {
showLoginDialog()
} else {
Timber.d("Gallery button tapped. Image title: ${it.getName()}Image desc: ${it.getLongDescription()}")
storeSharedPrefs(it)
contributionController.initiateGalleryPick(activity, false)
}
}
fun onOverflowClicked(): (Place, View) -> Unit = { place, view ->
PopupMenu(view.context, view).apply {
inflate(R.menu.nearby_info_dialog_options)
enableBy(R.id.nearby_info_menu_commons_article, place.hasCommonsLink())
enableBy(R.id.nearby_info_menu_wikidata_article, place.hasWikidataLink())
enableBy(R.id.nearby_info_menu_wikipedia_article, place.hasWikipediaLink())
setOnMenuItemClickListener { item: MenuItem ->
when (item.itemId) {
R.id.nearby_info_menu_commons_article -> openWebView(place.siteLinks.commonsLink)
R.id.nearby_info_menu_wikidata_article -> openWebView(place.siteLinks.wikidataLink)
R.id.nearby_info_menu_wikipedia_article -> openWebView(place.siteLinks.wikipediaLink)
else -> false
}
}
}.show()
}
fun onDirectionsClicked(): (Place) -> Unit = {
Utils.handleGeoCoordinates(activity, it.getLocation())
}
private fun storeSharedPrefs(selectedPlace: Place) {
Timber.d("Store place object %s", selectedPlace.toString())
applicationKvStore.putJson(WikidataConstants.PLACE_OBJECT, selectedPlace)
}
private fun openWebView(link: Uri): Boolean {
Utils.handleWebUrl(activity, link)
return true;
}
private fun PopupMenu.enableBy(menuId: Int, hasLink: Boolean) {
menu.findItem(menuId).isEnabled = hasLink
}
private fun showLoginDialog() {
AlertDialog.Builder(activity)
.setMessage(R.string.login_alert_message)
.setPositiveButton(R.string.login) { dialog, which ->
ActivityUtils.startActivityWithFlags(
activity,
LoginActivity::class.java,
Intent.FLAG_ACTIVITY_CLEAR_TOP,
Intent.FLAG_ACTIVITY_SINGLE_TOP
)
applicationKvStore.putBoolean("login_skipped", false)
activity.finish()
}
.show()
}
}
| app/src/main/java/fr/free/nrw/commons/nearby/fragments/CommonPlaceClickActions.kt | 1408784426 |
package stan.androiddemo.project.petal.API
import retrofit2.http.*
import rx.Observable
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Module.ImageDetail.GatherInfoBean
import stan.androiddemo.project.petal.Module.ImageDetail.GatherResultBean
import stan.androiddemo.project.petal.Module.ImageDetail.LikePinsOperateBean
import stan.androiddemo.project.petal.Module.UserInfo.FollowUserOperateBean
import stan.androiddemo.project.petal.Module.UserInfo.UserBoardSingleBean
/**
* Created by stanhu on 14/8/2017.
*/
interface OperateAPI{
@POST("pins/{pinId}/{operate}")
fun httpsLikeOperate(@Header(Config.Authorization)
authorization: String, @Path("pinId") pinsId: String,
@Path("operate") operate: String): Observable<LikePinsOperateBean>
//对某个图片进行采集前网络访问 判断是否被采集过
//https://api.huaban.com/pins/707907583/repin/?check=true
@GET("pins/{viaId}/repin/")
abstract fun httpsGatherInfo(@Header(Config.Authorization) authorization: String,
@Path("viaId") viaId: String, @Query("check") check: Boolean): Observable<GatherInfoBean>
@FormUrlEncoded
@POST("pins/")
fun httpsGatherPins(@Header(Config.Authorization) authorization: String,
@Field("board_id") boardId: String,
@Field("text") describe: String,
@Field("via") PinsIda: String): Observable<GatherResultBean>
//关注某个用户
//https://api.huaban.com/users/17037199/follow 或者unfollow POST方法 统一成一个接口
@POST("users/{userId}/{operate}")
abstract fun httpsFollowUserOperate(@Header(Config.Authorization) authorization: String,
@Path("userId") userId: String, @Path("operate") operate: String): Observable<FollowUserOperateBean>
//修改某个画板的信息
//https://api.huaban.com/boards/29646779 category=photography&description=%E6%B7%BB%E5%8A%A0%E6%8F%8F%E8%BF%B0&title=%E6%B7%BB%E5%8A%A0
@FormUrlEncoded
@POST("boards/{boardId}")
fun httpsEditBoard(@Header(Config.Authorization) authorization: String,@Path("boardId") boardId: String,
@Field("title") title: String, @Field("description") description: String,
@Field("category") category: String): Observable<UserBoardSingleBean>
@FormUrlEncoded
@POST("boards/{boardId}")
abstract fun httpsDeleteBoard(@Header(Config.Authorization) authorization: String, @Path("boardId") boardId: String,
@Field("_method") operate: String): Observable<UserBoardSingleBean>
} | app/src/main/java/stan/androiddemo/project/petal/API/OperateAPI.kt | 3729279952 |
package stan.androiddemo.project.petal.HttpUtiles
/**
* Created by stanhu on 11/8/2017.
*/
class ProgressBean{
var bytesRead: Long = 0
var contentLength: Long = 0
var done: Boolean = false
} | app/src/main/java/stan/androiddemo/project/petal/HttpUtiles/ProgressBean.kt | 3811935488 |
package kscript.examples
import kscript.util.OneLinerContext
import kscript.text.add
import kscript.text.print
import kscript.text.split
/**
* One-liner kscript example. To ease development simply extend [OneLinerContext] as shown, which will provide
* the same context as `kscript` when running in single line mode.
*
* @author Holger Brandl
*/
fun main(args: Array<String>) {
object : OneLinerContext(args) {
override fun apply(lines: Sequence<String>) {
lines.split().drop(1).filter { it[9] == "UA" }.add { it[3] + ":" + it[3] }.print()
// kscript 'lines.split().drop(1).filter { it[9] == "UA" }.add { it[3] + ":" + it[3] }.print()'
}
}
} | src/test/kotlin/kscript/examples/OneLinerExample.kt | 2776926337 |
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.security.config.annotation.web.oauth2.resourceserver
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenAuthenticationConverter
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector
/**
* A Kotlin DSL to configure opaque token Resource Server Support using idiomatic Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
* @property introspectionUri the URI of the Introspection endpoint.
* @property introspector the [OpaqueTokenIntrospector] to use.
* @property authenticationManager the [AuthenticationManager] used to determine if the provided
* [Authentication] can be authenticated.
*/
@OAuth2ResourceServerSecurityMarker
class OpaqueTokenDsl {
private var _introspectionUri: String? = null
private var _introspector: OpaqueTokenIntrospector? = null
private var clientCredentials: Pair<String, String>? = null
var authenticationManager: AuthenticationManager? = null
var introspectionUri: String?
get() = _introspectionUri
set(value) {
_introspectionUri = value
_introspector = null
}
var introspector: OpaqueTokenIntrospector?
get() = _introspector
set(value) {
_introspector = value
_introspectionUri = null
clientCredentials = null
}
var authenticationConverter: OpaqueTokenAuthenticationConverter? = null
/**
* Configures the credentials for Introspection endpoint.
*
* @param clientId the clientId part of the credentials.
* @param clientSecret the clientSecret part of the credentials.
*/
fun introspectionClientCredentials(clientId: String, clientSecret: String) {
clientCredentials = Pair(clientId, clientSecret)
_introspector = null
}
internal fun get(): (OAuth2ResourceServerConfigurer<HttpSecurity>.OpaqueTokenConfigurer) -> Unit {
return { opaqueToken ->
introspectionUri?.also { opaqueToken.introspectionUri(introspectionUri) }
introspector?.also { opaqueToken.introspector(introspector) }
authenticationConverter?.also { opaqueToken.authenticationConverter(authenticationConverter) }
clientCredentials?.also { opaqueToken.introspectionClientCredentials(clientCredentials!!.first, clientCredentials!!.second) }
authenticationManager?.also { opaqueToken.authenticationManager(authenticationManager) }
}
}
}
| config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDsl.kt | 1486786110 |
package io.heapy.komodo.config.dotenv
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* Wrapper for [System.getenv], for easy testing and extensibility.
*
* @author Ruslan Ibragimov
* @since 1.0
*/
interface Env {
/**
* Throws exception, if env not found
*/
fun get(env: String): String {
return getOrNull(env)
?: throw EnvNotDefinedException("$env not defined.")
}
/**
* Returns null, if env not found
*/
fun getOrNull(env: String): String?
}
class EnvNotDefinedException(message: String) : RuntimeException(message)
class Dotenv(
/**
* Env file location
*/
private val file: Path = Paths.get(".env"),
/**
* Env variable that overrides env file location
*/
private val fileEnv: String = "KOMODO_DOTENV_FILE",
/**
* Ignore file if it doesn't exists
*/
private val ignoreIfMissing: Boolean = true,
/**
* System env variables
*/
private val system: Map<String, String> = System.getenv()
) : Env {
private val vars = getEnvironmentVariables()
override fun getOrNull(env: String): String? {
return vars[env]
}
internal fun getEnvironmentVariables(): Map<String, String> {
val resolvedFile = system[fileEnv]?.let { Paths.get(it) } ?: file
return if (Files.exists(resolvedFile)) {
Files.readAllLines(resolvedFile)
.filterNot { it.startsWith("#") }
.filterNot { it.isNullOrEmpty() }
.map {
val (name, value) = it.split("=", limit = 2)
name to value
}
.toMap()
.plus(system)
} else {
if (ignoreIfMissing) {
mapOf<String, String>().plus(system)
} else {
throw DotenvFileNotFoundException("File ${resolvedFile.toAbsolutePath()} not exists")
}
}
}
}
class DotenvFileNotFoundException(message: String) : RuntimeException(message)
| komodo-config-dotenv/src/main/kotlin/io/heapy/komodo/config/dotenv/Dotenv.kt | 1406613273 |
package com.sksamuel.kotest.engine.spec.unfinished
import io.kotest.core.spec.Isolate
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.style.scopes.TestDslState
import io.kotest.engine.KotestEngineLauncher
import io.kotest.engine.listener.NoopTestEngineListener
import io.kotest.inspectors.forAtLeastOne
import io.kotest.matchers.string.shouldContain
@Isolate
class UnfinishedTestDefinitionTest : FunSpec() {
init {
afterEach {
TestDslState.reset()
}
test("fun spec") {
val result = KotestEngineLauncher()
.withListener(NoopTestEngineListener)
.withSpec(FunSpecUnfinishedTestDefinitionTest::class)
.launch()
result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished test") }
}
test("describe spec") {
val result = KotestEngineLauncher()
.withListener(NoopTestEngineListener)
.withSpec(DescribeSpecUnfinishedTestDefinitionTest::class)
.launch()
result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished it") }
}
test("should spec") {
val result = KotestEngineLauncher()
.withListener(NoopTestEngineListener)
.withSpec(ShouldSpecUnfinishedTestDefinitionTest::class)
.launch()
result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished should") }
}
test("feature spec") {
val result = KotestEngineLauncher()
.withListener(NoopTestEngineListener)
.withSpec(FeatureSpecUnfinishedTestDefinitionTest::class)
.launch()
result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished scenario") }
}
test("expect spec") {
val result = KotestEngineLauncher()
.withListener(NoopTestEngineListener)
.withSpec(ExpectSpecUnfinishedTestDefinitionTest::class)
.launch()
result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished expect") }
}
}
}
| kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/unfinished/UnfinishedTestDefinitionTest.kt | 1502780506 |
import java.io.File
// 2463
fun main(args: Array<String>) {
assert(score(".#....##....#####...#######....#.#..##.", 3) == 325)
val regex = Regex(".* => .*")
val margin = 3
val lines = File(args[0]).readLines()
var leftPots = 0
var state = StringBuilder(lines[0].split(":")[1].trim())
val transitions = lines.filter { it.matches(regex) }.map { line ->
val split = line.split("=>")
Pair(split[0].trim(), split[1].trim()[0])
}.toMap()
println("0 -> $state")
for (gen in 1..20) {
val leftEmptyPots = CharArray(maxOf(margin - state.indexOf('#'), 0)) { '.' }
state.insert(0, leftEmptyPots)
leftPots += leftEmptyPots.size
val rightEmptyPots = CharArray(maxOf(margin - (state.length - state.lastIndexOf('#')), 0) + 1) { '.' }
state.append(rightEmptyPots)
val nextState = StringBuilder(state)
transitions.forEach { t, u ->
var patternIndex = state.indexOf(t, 0)
while (patternIndex != -1) {
nextState[patternIndex + 2] = u
patternIndex = state.indexOf(t, patternIndex + 1)
}
}
state = nextState
println("$gen -> $state")
}
val sum = score(state.toString(), leftPots)
println(sum)
}
private fun score(state: String, leftPots: Int): Int =
(0 until state.length)
.filter { state[it] == '#' }
.sumBy { it - leftPots }
| advent_of_code/2018/solutions/day_12_a.kt | 1797723198 |
/*
* Copyright (C) 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.core.graphics
import android.graphics.Color
import android.graphics.ColorSpace
import android.support.test.filters.SdkSuppress
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ColorTest {
@SdkSuppress(minSdkVersion = 26)
@Test fun destructuringColor() {
val (r, g, b, a) = 0x337f3010.toColor()
assertEquals(0.5f, r, 1e-2f)
assertEquals(0.19f, g, 1e-2f)
assertEquals(0.06f, b, 1e-2f)
assertEquals(0.2f, a, 1e-2f)
}
@Test fun destructuringInt() {
val (a, r, g, b) = 0x337f3010
assertEquals(0x33, a)
assertEquals(0x7f, r)
assertEquals(0x30, g)
assertEquals(0x10, b)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun intToColor() = assertEquals(Color.valueOf(0x337f3010), 0x337f3010.toColor())
@SdkSuppress(minSdkVersion = 26)
@Test fun intToColorLong() = assertEquals(Color.pack(0x337f3010), 0x337f3010.toColorLong())
@Test fun alpha() = assertEquals(0x33, 0x337f3010.alpha)
@Test fun red() = assertEquals(0x7f, 0x337f3010.red)
@Test fun green() = assertEquals(0x30, 0x337f3010.green)
@Test fun blue() = assertEquals(0x10, 0x337f3010.blue)
@SdkSuppress(minSdkVersion = 26)
@Test fun luminance() = assertEquals(0.212f, 0xff7f7f7f.toInt().luminance, 1e-3f)
@SdkSuppress(minSdkVersion = 26)
@Test fun longToColor() {
assertEquals(Color.valueOf(0x337f3010), Color.pack(0x337f3010).toColor())
}
@SdkSuppress(minSdkVersion = 26)
@Test fun longToColorInt() = assertEquals(0x337f3010, Color.pack(0x337f3010).toColorInt())
@SdkSuppress(minSdkVersion = 26)
@Test fun destructuringLong() {
val (r, g, b, a) = Color.pack(0x337f3010)
assertEquals(0.20f, a, 1e-2f)
assertEquals(0.50f, r, 1e-2f)
assertEquals(0.19f, g, 1e-2f)
assertEquals(0.06f, b, 1e-2f)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun alphaLong() = assertEquals(0.20f, Color.pack(0x337f3010).alpha, 1e-2f)
@SdkSuppress(minSdkVersion = 26)
@Test fun redLong() = assertEquals(0.50f, Color.pack(0x337f3010).red, 1e-2f)
@SdkSuppress(minSdkVersion = 26)
@Test fun greenLong() = assertEquals(0.19f, Color.pack(0x337f3010).green, 1e-2f)
@SdkSuppress(minSdkVersion = 26)
@Test fun blueLong() = assertEquals(0.06f, Color.pack(0x337f3010).blue, 1e-2f)
@SdkSuppress(minSdkVersion = 26)
@Test fun luminanceLong() {
assertEquals(0.212f, Color.pack(0xff7f7f7f.toInt()).luminance, 1e-3f)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun isSrgb() {
assertTrue(0x337f3010.toColorLong().isSrgb)
val c = Color.pack(1.0f, 0.0f, 0.0f, 1.0f, ColorSpace.get(ColorSpace.Named.BT2020))
assertFalse(c.isSrgb)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun isWideGamut() {
assertFalse(0x337f3010.toColorLong().isWideGamut)
val c = Color.pack(1.0f, 0.0f, 0.0f, 1.0f, ColorSpace.get(ColorSpace.Named.BT2020))
assertTrue(c.isWideGamut)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun getColorSpace() {
val sRGB = ColorSpace.get(ColorSpace.Named.SRGB)
assertEquals(sRGB, 0x337f3010.toColorLong().colorSpace)
val bt2020 = ColorSpace.get(ColorSpace.Named.BT2020)
val c = Color.pack(1.0f, 0.0f, 0.0f, 1.0f, bt2020)
assertEquals(bt2020, c.colorSpace)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun addColorsSameColorSpace() {
val (r, g, b, a) = 0x7f7f0000.toColor() + 0x7f007f00.toColor()
assertEquals(0.16f, r, 1e-2f)
assertEquals(0.33f, g, 1e-2f)
assertEquals(0.00f, b, 1e-2f)
assertEquals(0.75f, a, 1e-2f)
}
@Test fun stringToColorInt() = assertEquals(Color.GREEN, "#00ff00".toColorInt())
}
| core/ktx/src/androidTest/java/androidx/core/graphics/ColorTest.kt | 1921688748 |
package fi.lasicaine.navigationdrawer
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("fi.lasicaine.navigationdrawer", appContext.packageName)
}
}
| NavigationDrawer/app/src/androidTest/java/fi/lasicaine/navigationdrawer/ExampleInstrumentedTest.kt | 3732296787 |
package com.jakewharton.diffuse.diff
import com.jakewharton.diffuse.ApiMapping
import com.jakewharton.diffuse.Apk
import com.jakewharton.diffuse.diff.lint.resourcesArscCompression
import com.jakewharton.diffuse.report.DiffReport
import com.jakewharton.diffuse.report.text.ApkDiffTextReport
internal class ApkDiff(
val oldApk: Apk,
val oldMapping: ApiMapping,
val newApk: Apk,
val newMapping: ApiMapping
) : BinaryDiff {
val archive = ArchiveFilesDiff(oldApk.files, newApk.files)
val signatures = SignaturesDiff(oldApk.signatures, newApk.signatures)
val dex = DexDiff(oldApk.dexes, oldMapping, newApk.dexes, newMapping)
val arsc = ArscDiff(oldApk.arsc, newApk.arsc)
val manifest = ManifestDiff(oldApk.manifest, newApk.manifest)
val lintMessages = listOfNotNull(
archive.resourcesArscCompression())
override fun toTextReport(): DiffReport = ApkDiffTextReport(this)
}
| diffuse/src/main/kotlin/com/jakewharton/diffuse/diff/ApkDiff.kt | 1564601310 |
package it.achdjian.paolo.temperaturemonitor.rajawali
import android.util.SparseIntArray
/**
* Created by Paolo Achdjian on 07/09/16.
*/
object TemperatureColorMap {
private val MAP_TEMP_COLOR = SparseIntArray()
init {
MAP_TEMP_COLOR.put(13, 0xFF0000E0.toInt())
MAP_TEMP_COLOR.put(14, 0xFF0000C0.toInt())
MAP_TEMP_COLOR.put(15, 0xFF0000A0.toInt())
MAP_TEMP_COLOR.put(16, 0xFF000080.toInt())
MAP_TEMP_COLOR.put(17, 0xFF000060.toInt())
MAP_TEMP_COLOR.put(18, 0xFF000040.toInt())
MAP_TEMP_COLOR.put(19, 0xFF008020.toInt())
MAP_TEMP_COLOR.put(20, 0xFF00FA00.toInt())
MAP_TEMP_COLOR.put(21, 0xFF19E100.toInt())
MAP_TEMP_COLOR.put(22, 0xFF32C800.toInt())
MAP_TEMP_COLOR.put(23, 0xFF4BAF00.toInt())
MAP_TEMP_COLOR.put(24, 0xFF649600.toInt())
MAP_TEMP_COLOR.put(25, 0xFF7D7D00.toInt())
MAP_TEMP_COLOR.put(26, 0xFF966400.toInt())
MAP_TEMP_COLOR.put(27, 0xFFAF4B00.toInt())
MAP_TEMP_COLOR.put(28, 0xFFC83200.toInt())
MAP_TEMP_COLOR.put(29, 0xFFE11900.toInt())
MAP_TEMP_COLOR.put(30, 0xFFFA0000.toInt())
}
fun getColor(temperature: Int): Int {
val temp = temperature / 100
val color: Int
if (temp < 13) {
color = 0xFF0000FF.toInt()
} else if (temp > 30) {
color = 0xFFFF0000.toInt()
} else {
color = MAP_TEMP_COLOR[temp]
}
return color
}
}
| temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/rajawali/TemperatureColorMap.kt | 3968214596 |
/*
* Copyright 2019 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.players.bukkit.servlet
import com.rpkit.core.web.Alert
import com.rpkit.core.web.Alert.Type.DANGER
import com.rpkit.core.web.RPKServlet
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_OK
class ProfileSignInServlet(private val plugin: RPKPlayersBukkit): RPKServlet() {
override val url = "/profiles/signin/"
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val activeProfile = profileProvider.getActiveProfile(req)
if (activeProfile != null) {
resp.sendRedirect("/profiles/")
return
}
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/signin.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("alerts", listOf<Alert>())
Velocity.evaluate(velocityContext, resp.writer, "/web/signin.html", templateBuilder.toString())
}
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
val name = req.getParameter("name")
val password = req.getParameter("password")
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = profileProvider.getProfile(name)
val alerts = mutableListOf<Alert>()
if (profile != null) {
if (profile.checkPassword(password.toCharArray())) {
profileProvider.setActiveProfile(req, profile)
resp.sendRedirect("/profiles/")
return
} else {
alerts.add(Alert(DANGER, "Incorrect username or password."))
}
} else {
alerts.add(Alert(DANGER, "Incorrect username or password."))
}
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/signin.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("alerts", alerts)
Velocity.evaluate(velocityContext, resp.writer, "/web/signin.html", templateBuilder.toString())
}
} | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/ProfileSignInServlet.kt | 2868931081 |
package com.orgzly.android.usecase
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.BookView
class BookRename(val bookView: BookView, val name: String) : UseCase() {
override fun run(dataRepository: DataRepository): UseCaseResult {
dataRepository.renameBook(bookView, name)
return UseCaseResult(
modifiesLocalData = true,
triggersSync = SYNC_DATA_MODIFIED
)
}
} | app/src/main/java/com/orgzly/android/usecase/BookRename.kt | 866267990 |
package com.yohaq.titan.ui.createWorkoutScreen
import com.jakewharton.rxrelay.PublishRelay
import com.yohaq.titan.data.interactors.CreateWorkoutInteractor
import com.yohaq.titan.data.models.Exercise
import com.yohaq.titan.data.models.WorkoutSet
import rx.Observable
import rx.functions.Action1
import java.util.*
import javax.inject.Inject
/**
* Created by yousufhaque on 6/8/16.
*/
class CreateWorkoutViewModel
@Inject constructor(private val createWorkoutInteractor: CreateWorkoutInteractor) {
val onDateUpdate : Action1<Date>
val onExerciseUpdate : Action1<Exercise>
val onSetListUpdate: Action1<List<WorkoutSet>>
val onCreateWorkout: Action1<Unit>
private val dateObservable : Observable<Date>
private val exerciseObservable : Observable<Exercise>
private val setListObservable : Observable<List<WorkoutSet>>
private val createWorkoutObservable : Observable<Unit>
init {
val dateRelay = PublishRelay.create<Date>()
val exerciseRelay = PublishRelay.create<Exercise>()
val setListRelay = PublishRelay.create<List<WorkoutSet>>()
val createWorkoutRelay = PublishRelay.create<Unit>()
onDateUpdate = dateRelay.asAction()
onExerciseUpdate = exerciseRelay.asAction()
onSetListUpdate = setListRelay.asAction()
onCreateWorkout = createWorkoutRelay.asAction()
dateObservable = dateRelay.asObservable()
exerciseObservable = exerciseRelay.asObservable()
setListObservable = setListRelay.asObservable()
createWorkoutObservable = createWorkoutRelay.asObservable()
}
fun createWorkout(dateCreated: Date, exercise: Exercise, sets: List<WorkoutSet>) {
createWorkoutInteractor.createWorkout(dateCreated, exercise, sets)
}
} | app/src/main/kotlin/com/yohaq/titan/ui/createWorkoutScreen/CreateWorkoutViewModel.kt | 862935068 |
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins.update.downloader
import com.netflix.spinnaker.kork.annotations.VisibleForTesting
import com.netflix.spinnaker.kork.plugins.config.Configurable
import com.netflix.spinnaker.kork.plugins.update.downloader.internal.DefaultProcessRunner
import java.io.FileNotFoundException
import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import org.pf4j.update.FileDownloader
import org.slf4j.LoggerFactory
/**
* Runs a local process to handle the downloading of a plugin binary.
*/
@Configurable(ProcessFileDownloaderConfig::class)
class ProcessFileDownloader(
@VisibleForTesting internal val config: ProcessFileDownloaderConfig,
private val processRunner: ProcessRunner
) : FileDownloader {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
/**
* For satisfying the [Configurable] functionality.
*/
constructor(config: ProcessFileDownloaderConfig) : this(config, DefaultProcessRunner())
override fun downloadFile(fileUrl: URL): Path {
log.debug("Downloading plugin binary: $fileUrl")
val builder = ProcessBuilder().apply {
directory(Files.createTempDirectory("plugin-downloads").toFile())
environment().putAll(config.env)
command(*config.command.split(" ").toTypedArray())
}
val path = Paths.get(processRunner.completeOrTimeout(builder))
log.debug("Received downloaded plugin path: $path (from $fileUrl)")
if (!path.toFile().exists()) {
throw FileNotFoundException("The downloaded file could not be found on the file system")
}
return path
}
/**
* Allows for switching out the actual process execution logic. This is primarily for
* the purposes of mocking process execution during unit tests.
*/
interface ProcessRunner {
/**
* Run the given [processBuilder], waiting for completion or timing out after the configured time.
*/
fun completeOrTimeout(processBuilder: ProcessBuilder): String
}
}
| kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/update/downloader/ProcessFileDownloader.kt | 3664458893 |
package com.squareup.sqldelight.runtime.coroutines
import app.cash.turbine.test
import com.squareup.sqldelight.Query
import com.squareup.sqldelight.internal.copyOnWriteList
import com.squareup.sqldelight.runtime.coroutines.Employee.Companion.MAPPER
import com.squareup.sqldelight.runtime.coroutines.Employee.Companion.SELECT_EMPLOYEES
import com.squareup.sqldelight.runtime.coroutines.TestDb.Companion.TABLE_EMPLOYEE
import kotlinx.coroutines.flow.take
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.test.fail
class MappingTest : DbTest {
override suspend fun setupDb(): TestDb = TestDb(testDriver())
@Test
fun mapToOne() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", MAPPER)
.asFlow()
.mapToOne()
.test {
assertEquals(Employee("alice", "Alice Allison"), expectItem())
cancel()
}
}
@Test fun mapToOneThrowsFromMapFunction() = runTest { db ->
val expected = IllegalStateException("test exception")
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", { throw expected })
.asFlow()
.mapToOne()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneThrowsFromQueryExecute() = runTest { db ->
val expected = IllegalStateException("test exception")
val query = object : Query<Any>(copyOnWriteList(), { fail() }) {
override fun execute() = throw expected
}
query.asFlow()
.mapToOne()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneThrowsOnMultipleRows() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 2", MAPPER)
.asFlow()
.mapToOne()
.test {
val message = expectError().message!!
assertTrue("ResultSet returned more than 1 row" in message, message)
}
}
@Test fun mapToOneOrDefault() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", MAPPER)
.asFlow()
.mapToOneOrDefault(Employee("fred", "Fred Frederson"))
.test {
assertEquals(Employee("alice", "Alice Allison"), expectItem())
cancel()
}
}
@Test fun mapToOneOrDefaultThrowsFromMapFunction() = runTest { db ->
val expected = IllegalStateException("test exception")
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", { throw expected })
.asFlow()
.mapToOneOrDefault(Employee("fred", "Fred Frederson"))
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneOrDefaultThrowsFromQueryExecute() = runTest {
val expected = IllegalStateException("test exception")
val query = object : Query<Any>(copyOnWriteList(), { fail() }) {
override fun execute() = throw expected
}
query.asFlow()
.mapToOneOrDefault(Employee("fred", "Fred Frederson"))
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneOrDefaultThrowsOnMultipleRows() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 2", MAPPER) //
.asFlow()
.mapToOneOrDefault(Employee("fred", "Fred Frederson"))
.test {
val message = expectError().message!!
assertTrue("ResultSet returned more than 1 row" in message, message)
}
}
@Test fun mapToOneOrDefaultReturnsDefaultWhenNoResults() = runTest { db ->
val defaultEmployee = Employee("fred", "Fred Frederson")
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 0", MAPPER) //
.asFlow()
.mapToOneOrDefault(defaultEmployee)
.test {
assertSame(defaultEmployee, expectItem())
cancel()
}
}
@Test fun mapToList() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asFlow()
.mapToList()
.test {
assertEquals(
listOf(
Employee("alice", "Alice Allison"), //
Employee("bob", "Bob Bobberson"), //
Employee("eve", "Eve Evenson")
),
expectItem()
)
cancel()
}
}
@Test fun mapToListThrowsFromMapFunction() = runTest { db ->
val expected = IllegalStateException("test exception")
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, { throw expected })
.asFlow()
.mapToList()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToListThrowsFromQueryExecute() = runTest {
val expected = IllegalStateException("test exception")
val query = object : Query<Any>(copyOnWriteList(), { fail() }) {
override fun execute() = throw expected
}
query.asFlow()
.mapToList()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToListEmptyWhenNoRows() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES WHERE 1=2", MAPPER)
.asFlow()
.mapToList()
.test {
assertEquals(emptyList(), expectItem())
cancel()
}
}
@Test fun mapToOneOrNull() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", MAPPER)
.asFlow()
.mapToOneOrNull()
.test {
assertEquals(Employee("alice", "Alice Allison"), expectItem())
cancel()
}
}
@Test fun mapToOneOrNullThrowsFromMapFunction() = runTest { db ->
val expected = IllegalStateException("test exception")
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", { throw expected })
.asFlow()
.mapToOneOrNull()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneOrNullThrowsFromQueryExecute() = runTest {
val expected = IllegalStateException("test exception")
val query = object : Query<Any>(copyOnWriteList(), { fail() }) {
override fun execute() = throw expected
}
query.asFlow()
.mapToOneOrNull()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneOrNullThrowsOnMultipleRows() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 2", MAPPER) //
.asFlow()
.mapToOneOrNull()
.test {
val message = expectError().message!!
assertTrue("ResultSet returned more than 1 row" in message, message)
}
}
@Test fun mapToOneOrNullEmptyWhenNoResults() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 0", MAPPER) //
.asFlow()
.mapToOneOrNull()
.test {
assertNull(expectItem())
cancel()
}
}
@Test fun mapToOneNonNull() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", MAPPER)
.asFlow()
.mapToOneNotNull()
.test {
assertEquals(Employee("alice", "Alice Allison"), expectItem())
cancel()
}
}
@Test fun mapToOneNonNullThrowsFromMapFunction() = runTest { db ->
val expected = IllegalStateException("test exception")
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 1", { throw expected })
.asFlow()
.mapToOneNotNull()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneNonNullThrowsFromQueryExecute() = runTest {
val expected = IllegalStateException("test exception")
val query = object : Query<Any>(copyOnWriteList(), { fail() }) {
override fun execute() = throw expected
}
query.asFlow()
.mapToOneNotNull()
.test {
// We can't assertSame because coroutines break exception referential transparency.
val actual = expectError()
assertEquals(IllegalStateException::class, actual::class)
assertEquals(expected.message, actual.message)
}
}
@Test fun mapToOneNonNullDoesNotEmitForNoResults() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES LIMIT 0", MAPPER)
.asFlow()
.take(1) // Ensure we have an event (complete) that the script can validate.
.mapToOneNotNull()
.test {
expectComplete()
}
}
}
| extensions/coroutines-extensions/src/commonTest/kotlin/com/squareup/sqldelight/runtime/coroutines/MappingTest.kt | 1077305037 |
package wiki.depasquale.mcachepreview
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.rxkotlin.addTo
import kotlinx.android.synthetic.main.activity_main.*
import wiki.depasquale.mcache.BuildConfig
import wiki.depasquale.mcache.Cache
import java.util.Locale
class MainActivity : AppCompatActivity(), Consumer<User> {
private var startTime: Long = 0
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
et.setText("diareuse")
et.post { fab.performClick() }
plugin.text = BuildConfig.VERSION_NAME
fab.setOnClickListener {
message.text = null
user.text = null
responseTime.text = null
val username = et.text.toString()
if (username.isEmpty()) {
input.error = "Please fill this field :)"
input.isErrorEnabled = true
} else {
when {
username.equals(
"clean",
ignoreCase = true
) -> Cache.obtain(User::class.java).build().delete()
username.equals("removeall", ignoreCase = true) -> removeAll()
else -> retrieveUser(username)
}
}
}
}
private fun removeAll() {
startTime = System.nanoTime()
Cache.obtain(Cache::class.java)
.build()
.deleteLater()
.subscribe({ success ->
responseTime.append(if (responseTime.text.isNotEmpty()) "\n" else "")
responseTime.append(
String.format(
Locale.getDefault(), "%d ms",
(System.nanoTime() - startTime) / 1000000
)
)
message.text = if (success) "OK" else "FAILED"
})
.addTo(disposables)
}
private fun retrieveUser(username: String) {
input.isErrorEnabled = false
user.text = String.format("/users/%s", username)
startTime = System.nanoTime()
Github.user(username)
.subscribe(this,
Consumer<Throwable> { error ->
error.printStackTrace()
Toast.makeText(this, error.message, Toast.LENGTH_SHORT).show()
})
.addTo(disposables)
}
@Throws(Exception::class)
override fun accept(user: User) {
Logger.d("User@${user.login} accepted")
responseTime.append(if (responseTime.text.isNotEmpty()) "\n" else "")
responseTime.append(
String.format(
Locale.getDefault(), "%d ms",
(System.nanoTime() - startTime) / 1000000
)
)
message.text = Gson().toJson(user)
}
override fun onDestroy() {
disposables.dispose()
super.onDestroy()
}
}
| app/src/main/java/wiki/depasquale/mcachepreview/MainActivity.kt | 1701202822 |
package org.evomaster.core.problem.util.inference.model
import org.evomaster.core.problem.util.StringSimilarityComparator
import kotlin.math.min
/**
* the class is used when applying parser to derive possible relationship between two named entities (e.g., resource with table name)
* @property input for matching
* @property targetMatched presents what are matched regarding a target
* @property similarity presents a degree of similarity
* @property inputIndicator presents a depth-level of input, e.g., token on resource path is level 0, token on description is level 1
* @property outputIndicator presents a depth-level of target to match, e.g., name of table is level 0, name of a column of a table is level 1
*/
open class MatchedInfo(val input : String, val targetMatched : String, var similarity : Double, var inputIndicator : Int = 0, var outputIndicator : Int = 0){
fun modifySimilarity(times : Double = 0.9){
similarity *= times
if (similarity > 1.0) similarity = 1.0
}
fun setMax(){
similarity = 1.0
}
fun setMin(){
similarity = min(similarity, StringSimilarityComparator.SimilarityThreshold)
}
}
| core/src/main/kotlin/org/evomaster/core/problem/util/inference/model/MatchedInfo.kt | 997318279 |
// Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch
// TODO Incomplete implementation
/**
* Bonded class to enable delayed serialization.
*/
class Bonded<RefT>
| core/src/main/kotlin/net/dummydigit/qbranch/Bonded.kt | 2981407656 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Austin Donovan (addonovan)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.addonovan.ftcext.hardware
import com.qualcomm.robotcore.hardware.*
import kotlin.reflect.KClass
/**
* An annotation for hardware class that are build on top of another hardware device.
* Valid classes for the [hardwareMapType] are as follows:
* * [DcMotorController]
* * [DcMotor]
* * [ServoController]
* * [Servo]
* * [LegacyModule]
* * [TouchSensorMultiplexer]
* * [DeviceInterfaceModule]
* * [AnalogInput]
* * [AnalogOutput]
* * [DigitalChannel]
* * [LED]
* * [OpticalDistanceSensor]
* * [TouchSensor]
* * [PWMOutput]
* * [I2cDevice]
* * [ColorSensor]
* * [AccelerationSensor]
* * [CompassSensor]
* * [GyroSensor]
* * [IrSeekerSensor]
* * [LightSensor]
* * [UltrasonicSensor]
* * [VoltageSensor]
*
* @param[hardwareMapType]
* The type of [HardwareDevice] that the class is based around. See the list
* above for valid classes.
*
* @author addonovan
* @since 6/26/16
*
* @see [HardwareMap]
*/
@Target( AnnotationTarget.CLASS )
@Retention( AnnotationRetention.RUNTIME )
@MustBeDocumented
annotation class HardwareExtension( val hardwareMapType: KClass< out HardwareDevice > );
//
// Extension functions
//
/**
* An extension method for checking if the current class has the
* [HardwareExtension] annotation on it.
*
* @return `true` if this class has the `HardwareExtension` annotation on it.
*/
fun Class< * >.isHardwareExtension() = isAnnotationPresent( HardwareExtension::class.java );
/**
* @return The `hardwareMapType` value from the [HardwareExtension] annotation
* on this class.
*/
fun Class< * >.getHardwareMapType() =
if ( !this.isHardwareExtension() ) throw IllegalArgumentException( "No @HardwareExtension annotation on class \"$simpleName\"" );
else getAnnotation( HardwareExtension::class.java ).hardwareMapType; | ftc-ext/src/main/java/com/addonovan/ftcext/hardware/HardwareExtension.kt | 42931727 |
package com.andreadev.poikotlin.ui.base
/**
* Created by andrea on 18/08/2017.
*/
open class BaseMvpPresenter<V : BaseMvpView> : BasePresenter<V> {
protected var mView : V? = null
override fun attachView(view: V) {
mView = view
}
override fun detachView() {
mView = null
}
fun getView() : V?{
return mView
}
} | app/src/main/java/com/andreadev/kotlinmvp/ui/base/presenter/BaseMvpPresenter.kt | 2035132171 |
package com.leaguechampions.features.champions.presentation.champions
import com.leaguechampions.features.champions.domain.model.Champion
data class ChampionsUiModel(
val champions: List<ChampionUiModel>
)
data class ChampionUiModel(
val id: String,
val name: String,
val version: String
)
fun List<Champion>.toChampionsUiModel(): ChampionsUiModel {
return ChampionsUiModel(map { ChampionUiModel(it.id, it.name, it.version) })
}
| features/champions/src/main/java/com/leaguechampions/features/champions/presentation/champions/ChampionsUiModel.kt | 1057032590 |
package ru.ustimov.weather.ui.forecast
import android.location.Location
import com.arellomobile.mvp.InjectViewState
import io.reactivex.Flowable
import ru.ustimov.weather.AppState
@InjectViewState
class CityLocationPresenter(appState: AppState, private val cityId: Long) : LocationPresenter(appState) {
override fun onFirstViewAttach() {
super.onFirstViewAttach()
queryCityById(cityId)
.doOnError({ viewState.onLocationNotFound() })
.onErrorResumeNext(Flowable.empty())
.subscribe({ viewState.onLocationFound(it) })
}
override fun onLocationChanged(location: Location) {
throw IllegalStateException("Presenter does not support location changes")
}
} | app/src/main/java/ru/ustimov/weather/ui/forecast/CityLocationPresenter.kt | 3125736584 |
/*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.ui
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.text.format.DateFormat.getDateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.TimePicker.OnTimeChangedListener
import androidx.fragment.app.DialogFragment
import de.grobox.transportr.R
import kotlinx.android.synthetic.main.fragment_time_date.*
import java.util.*
import java.util.Calendar.*
class TimeDateFragment : DialogFragment(), OnDateSetListener, OnTimeChangedListener {
private var listener: TimeDateListener? = null
private lateinit var calendar: Calendar
companion object {
@JvmField
val TAG: String = TimeDateFragment::class.java.simpleName
private val CALENDAR = "calendar"
@JvmStatic
fun newInstance(calendar: Calendar): TimeDateFragment {
val f = TimeDateFragment()
val args = Bundle()
args.putSerializable(CALENDAR, calendar)
f.arguments = args
return f
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
calendar = if (savedInstanceState == null) {
arguments?.let {
it.getSerializable(CALENDAR) as Calendar
} ?: throw IllegalArgumentException("Arguments missing")
} else {
savedInstanceState.getSerializable(CALENDAR) as Calendar
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_time_date, container)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Time
timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(context))
timePicker.setOnTimeChangedListener(this)
showTime(calendar)
// Date
dateView.setOnClickListener {
DatePickerDialog(context!!, this@TimeDateFragment, calendar.get(YEAR), calendar.get(MONTH), calendar.get(DAY_OF_MONTH))
.show()
}
showDate(calendar)
// Previous and Next Date
prevDateButton.setOnClickListener {
calendar.add(DAY_OF_MONTH, -1)
showDate(calendar)
}
nextDateButton.setOnClickListener {
calendar.add(DAY_OF_MONTH, 1)
showDate(calendar)
}
// Buttons
okButton.setOnClickListener {
listener?.onTimeAndDateSet(calendar)
dismiss()
}
nowButton.setOnClickListener {
listener?.onTimeAndDateSet(Calendar.getInstance())
dismiss()
}
cancelButton.setOnClickListener {
dismiss()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putSerializable(CALENDAR, calendar)
}
override fun onTimeChanged(timePicker: TimePicker, hourOfDay: Int, minute: Int) {
calendar.set(HOUR_OF_DAY, hourOfDay)
calendar.set(MINUTE, minute)
}
override fun onDateSet(datePicker: DatePicker, year: Int, month: Int, day: Int) {
calendar.set(YEAR, year)
calendar.set(MONTH, month)
calendar.set(DAY_OF_MONTH, day)
showDate(calendar)
}
fun setTimeDateListener(listener: TimeDateListener) {
this.listener = listener
}
@Suppress("DEPRECATION")
private fun showTime(c: Calendar) {
timePicker.currentHour = c.get(HOUR_OF_DAY)
timePicker.currentMinute = c.get(MINUTE)
}
private fun showDate(c: Calendar) {
val now = Calendar.getInstance()
dateView.text = when {
c.isYesterday(now) -> getString(R.string.yesterday)
c.isToday(now) -> getString(R.string.today)
c.isTomorrow(now) -> getString(R.string.tomorrow)
else -> getDateFormat(context?.applicationContext).format(calendar.time)
}
}
private fun Calendar.isSameMonth(c: Calendar) = c.get(YEAR) == get(YEAR) && c.get(MONTH) == get(MONTH)
private fun Calendar.isYesterday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) - 1
private fun Calendar.isToday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH)
private fun Calendar.isTomorrow(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) + 1
interface TimeDateListener {
fun onTimeAndDateSet(calendar: Calendar)
}
}
| app/src/main/java/de/grobox/transportr/ui/TimeDateFragment.kt | 1314436169 |
/*
* This file is part of JuniperBot.
*
* JuniperBot 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.
* JuniperBot 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 JuniperBot. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.juniperbot.module.ranking.service
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import ru.juniperbot.common.model.RankingInfo
import ru.juniperbot.module.ranking.model.MemberVoiceState
interface RankingService {
companion object {
val COOKIE_EMOTE = "\uD83C\uDF6A"
}
fun onMessage(event: GuildMessageReceivedEvent)
fun giveCookie(senderMember: Member, recipientMember: Member)
fun addVoiceActivity(member: Member, state: MemberVoiceState)
fun updateRewards(member: Member)
fun getRankingInfo(guildId: Long, userId: String): RankingInfo?
}
| modules/jb-module-ranking/src/main/java/ru/juniperbot/module/ranking/service/RankingService.kt | 1311332701 |
package com.texasgamer.zephyr.util.resource
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
/**
* Implementation of [IResourceProvider] which uses [Context] to resolve resources.
*/
class ResourceProvider(private val mContext: Context) : IResourceProvider {
override fun getString(@StringRes stringRes: Int): String {
return mContext.getString(stringRes)
}
override fun getString(@StringRes stringRes: Int, vararg formatArgs: Any): String {
return mContext.getString(stringRes, *formatArgs)
}
override fun getDrawable(@DrawableRes drawableRes: Int): Drawable? {
return ContextCompat.getDrawable(mContext, drawableRes)
}
} | android/app/src/main/java/com/texasgamer/zephyr/util/resource/ResourceProvider.kt | 19149109 |
package com.battlelancer.seriesguide.dataliberation
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import android.content.OperationApplicationException
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.annotation.VisibleForTesting
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.dataliberation.DataLiberationFragment.LiberationResultEvent
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgEpisodeForImport
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgSeasonForImport
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgShowForImport
import com.battlelancer.seriesguide.dataliberation.JsonExportTask.BackupType
import com.battlelancer.seriesguide.dataliberation.JsonExportTask.ListItemTypesExport
import com.battlelancer.seriesguide.dataliberation.model.List
import com.battlelancer.seriesguide.dataliberation.model.Movie
import com.battlelancer.seriesguide.dataliberation.model.Season
import com.battlelancer.seriesguide.dataliberation.model.Show
import com.battlelancer.seriesguide.provider.SeriesGuideContract
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItemTypes
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItems
import com.battlelancer.seriesguide.provider.SeriesGuideDatabase
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.shows.database.SgEpisode2
import com.battlelancer.seriesguide.shows.database.SgEpisode2Helper
import com.battlelancer.seriesguide.shows.database.SgSeason2Helper
import com.battlelancer.seriesguide.shows.database.SgShow2Helper
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.battlelancer.seriesguide.util.DBUtils
import com.battlelancer.seriesguide.util.Errors.Companion.logAndReport
import com.battlelancer.seriesguide.util.LanguageTools
import com.battlelancer.seriesguide.util.TaskManager
import com.google.gson.Gson
import com.google.gson.JsonParseException
import com.google.gson.stream.JsonReader
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStreamReader
/**
* Imports shows, lists or movies from a human-readable JSON file replacing existing data.
*/
class JsonImportTask(
context: Context,
importShows: Boolean,
importLists: Boolean,
importMovies: Boolean,
private val database: SgRoomDatabase,
private val sgShow2Helper: SgShow2Helper,
private val sgSeason2Helper: SgSeason2Helper,
private val sgEpisode2Helper: SgEpisode2Helper
) {
private val context: Context = context.applicationContext
private val languageCodes: Array<String> =
this.context.resources.getStringArray(R.array.content_languages)
private var isImportingAutoBackup: Boolean
private val isImportShows: Boolean
private val isImportLists: Boolean
private val isImportMovies: Boolean
@VisibleForTesting
var errorCause: String? = null
private set
/**
* If set will use this file instead of opening via URI, which seems broken with Robolectric
* (openFileDescriptor throws FileNotFoundException).
*/
@VisibleForTesting
var testBackupFile: File? = null
init {
isImportingAutoBackup = false
isImportShows = importShows
isImportLists = importLists
isImportMovies = importMovies
}
constructor(
context: Context,
importShows: Boolean,
importLists: Boolean,
importMovies: Boolean
) : this(
context,
importShows,
importLists,
importMovies,
SgRoomDatabase.getInstance(context),
SgRoomDatabase.getInstance(context).sgShow2Helper(),
SgRoomDatabase.getInstance(context).sgSeason2Helper(),
SgRoomDatabase.getInstance(context).sgEpisode2Helper()
)
constructor(context: Context) : this(context, true, true, true) {
isImportingAutoBackup = true
}
suspend fun run(): Int {
return withContext(Dispatchers.IO) {
val result = doInBackground(this)
onPostExecute(result)
return@withContext result
}
}
private fun doInBackground(coroutineScope: CoroutineScope): Int {
// Ensure no large database ops are running
val tm = TaskManager.getInstance()
if (SgSyncAdapter.isSyncActive(context, false) || tm.isAddTaskRunning) {
return ERROR_LARGE_DB_OP
}
// last chance to abort
if (!coroutineScope.isActive) {
return ERROR
}
var result: Int
if (isImportShows) {
result = importData(JsonExportTask.BACKUP_SHOWS)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
if (isImportLists) {
result = importData(JsonExportTask.BACKUP_LISTS)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
if (isImportMovies) {
result = importData(JsonExportTask.BACKUP_MOVIES)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
// Renew search table
SeriesGuideDatabase.rebuildFtsTable(context)
return SUCCESS
}
private fun onPostExecute(result: Int) {
val messageId: Int
val showIndefinite: Boolean
when (result) {
SUCCESS -> {
messageId = R.string.import_success
showIndefinite = false
}
ERROR_STORAGE_ACCESS -> {
messageId = R.string.import_failed_nosd
showIndefinite = true
}
ERROR_FILE_ACCESS -> {
messageId = R.string.import_failed_nofile
showIndefinite = true
}
ERROR_LARGE_DB_OP -> {
messageId = R.string.update_inprogress
showIndefinite = false
}
else -> {
messageId = R.string.import_failed
showIndefinite = true
}
}
EventBus.getDefault().post(
LiberationResultEvent(
context.getString(messageId), errorCause, showIndefinite
)
)
}
private fun importData(@BackupType type: Int): Int {
if (!isImportingAutoBackup) {
val testBackupFile = testBackupFile
var pfd: ParcelFileDescriptor? = null
if (testBackupFile == null) {
// make sure we have a file uri...
val backupFileUri = getDataBackupFile(type) ?: return ERROR_FILE_ACCESS
// ...and the file actually exists
try {
pfd = context.contentResolver.openFileDescriptor(backupFileUri, "r")
} catch (e: FileNotFoundException) {
Timber.e(e, "Backup file not found.")
errorCause = e.message
return ERROR_FILE_ACCESS
} catch (e: SecurityException) {
Timber.e(e, "Backup file not found.")
errorCause = e.message
return ERROR_FILE_ACCESS
}
if (pfd == null) {
Timber.e("File descriptor is null.")
return ERROR_FILE_ACCESS
}
}
if (!clearExistingData(type)) {
return ERROR
}
// Access JSON from backup file and try to import data
val inputStream = if (testBackupFile == null) {
FileInputStream(pfd!!.fileDescriptor)
} else FileInputStream(testBackupFile)
try {
importFromJson(type, inputStream)
// let the document provider know we're done.
pfd?.close()
} catch (e: JsonParseException) {
// the given Json might not be valid or unreadable
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IOException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IllegalStateException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: Exception) {
// Only report unexpected errors.
logAndReport("Import failed", e)
errorCause = e.message
return ERROR
}
} else {
// Restoring latest auto backup.
val (backupFile) = AutoBackupTools.getLatestBackupOrNull(type, context)
?: // There is no backup file to restore from.
return ERROR_FILE_ACCESS
val inputStream: FileInputStream // Closed by reader after importing.
try {
if (!backupFile.canRead()) {
return ERROR_FILE_ACCESS
}
inputStream = FileInputStream(backupFile)
} catch (e: Exception) {
Timber.e(e, "Unable to open backup file.")
errorCause = e.message
return ERROR_FILE_ACCESS
}
// Only clear data after backup file could be opened.
if (!clearExistingData(type)) {
return ERROR
}
// Access JSON from backup file and try to import data
try {
importFromJson(type, inputStream)
} catch (e: JsonParseException) {
// the given Json might not be valid or unreadable
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IOException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IllegalStateException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: Exception) {
// Only report unexpected errors.
logAndReport("Import failed", e)
errorCause = e.message
return ERROR
}
}
return SUCCESS
}
private fun getDataBackupFile(@BackupType type: Int): Uri? {
return BackupSettings.getImportFileUriOrExportFileUri(context, type)
}
private fun clearExistingData(@BackupType type: Int): Boolean {
val batch = ArrayList<ContentProviderOperation>()
when (type) {
JsonExportTask.BACKUP_SHOWS -> {
database.runInTransaction {
// delete episodes and seasons first to prevent violating foreign key constraints
sgEpisode2Helper.deleteAllEpisodes()
sgSeason2Helper.deleteAllSeasons()
sgShow2Helper.deleteAllShows()
}
}
JsonExportTask.BACKUP_LISTS -> {
// delete list items before lists to prevent violating foreign key constraints
batch.add(
ContentProviderOperation.newDelete(ListItems.CONTENT_URI).build()
)
batch.add(
ContentProviderOperation.newDelete(SeriesGuideContract.Lists.CONTENT_URI)
.build()
)
}
JsonExportTask.BACKUP_MOVIES -> {
batch.add(
ContentProviderOperation.newDelete(SeriesGuideContract.Movies.CONTENT_URI)
.build()
)
}
}
try {
DBUtils.applyInSmallBatches(context, batch)
} catch (e: OperationApplicationException) {
errorCause = e.message
Timber.e(e, "clearExistingData")
return false
}
return true
}
@Throws(JsonParseException::class, IOException::class, IllegalArgumentException::class)
private fun importFromJson(@BackupType type: Int, inputStream: FileInputStream) {
if (inputStream.channel.size() == 0L) {
Timber.i("Backup file is empty, nothing to import.")
inputStream.close()
return // File is empty, nothing to import.
}
val gson = Gson()
val reader = JsonReader(InputStreamReader(inputStream, "UTF-8"))
reader.beginArray()
when (type) {
JsonExportTask.BACKUP_SHOWS -> {
while (reader.hasNext()) {
val show = gson.fromJson<Show>(reader, Show::class.java)
addShowToDatabase(show)
}
}
JsonExportTask.BACKUP_LISTS -> {
while (reader.hasNext()) {
val list = gson.fromJson<List>(reader, List::class.java)
addListToDatabase(list)
}
}
JsonExportTask.BACKUP_MOVIES -> {
while (reader.hasNext()) {
val movie = gson.fromJson<Movie>(reader, Movie::class.java)
context.contentResolver.insert(
SeriesGuideContract.Movies.CONTENT_URI,
movie.toContentValues()
)
}
}
}
reader.endArray()
reader.close()
}
private fun addShowToDatabase(show: Show) {
if ((show.tmdb_id == null || show.tmdb_id!! <= 0)
&& (show.tvdb_id == null || show.tvdb_id!! <= 0)) {
// valid id required
return
}
// Map legacy language codes.
if (!show.language.isNullOrEmpty()) {
show.language = LanguageTools.mapLegacyShowCode(show.language)
}
// Reset language if it is not supported.
val languageSupported = languageCodes.find { it == show.language } != null
if (!languageSupported) {
show.language = null
}
val sgShow = show.toSgShowForImport()
val showId = sgShow2Helper.insertShow(sgShow)
if (showId == -1L) {
return // Insert failed.
}
if (show.seasons == null || show.seasons.isEmpty()) {
// no seasons (or episodes)
return
}
// Parse and insert seasons and episodes.
insertSeasonsAndEpisodes(show, showId)
}
private fun insertSeasonsAndEpisodes(show: Show, showId: Long) {
for (season in show.seasons) {
if ((season.tmdb_id == null || season.tmdb_id!!.isEmpty())
&& (season.tvdbId == null || season.tvdbId!! <= 0)) {
// valid id is required
continue
}
if (season.episodes == null || season.episodes.isEmpty()) {
// episodes required
continue
}
// Insert season.
val sgSeason = season.toSgSeasonForImport(showId)
val seasonId = sgSeason2Helper.insertSeason(sgSeason)
// If inserted, insert episodes.
if (seasonId != -1L) {
val episodes = buildEpisodeBatch(season, showId, seasonId)
sgEpisode2Helper.insertEpisodes(episodes)
}
}
}
private fun buildEpisodeBatch(
season: Season,
showId: Long,
seasonId: Long
): ArrayList<SgEpisode2> {
val episodeBatch = ArrayList<SgEpisode2>()
for (episode in season.episodes) {
if ((episode.tmdb_id == null || episode.tmdb_id!! <= 0)
&& (episode.tvdbId == null || episode.tvdbId!! <= 0)) {
// valid id is required
continue
}
episodeBatch.add(episode.toSgEpisodeForImport(showId, seasonId, season.season))
}
return episodeBatch
}
private fun addListToDatabase(list: List) {
if (list.name.isNullOrEmpty()) {
return // required
}
if (list.listId.isNullOrEmpty()) {
// rebuild from name
list.listId = SeriesGuideContract.Lists.generateListId(list.name)
}
// Insert the list
context.contentResolver.insert(
SeriesGuideContract.Lists.CONTENT_URI,
list.toContentValues()
)
if (list.items == null || list.items.isEmpty()) {
return
}
// Insert the lists items
val items = ArrayList<ContentValues>()
for (item in list.items) {
// Note: DO import legacy types (seasons and episodes),
// as e.g. older backups can still contain legacy show data to allow displaying them.
val type: Int = if (ListItemTypesExport.SHOW == item.type) {
ListItemTypes.TVDB_SHOW
} else if (ListItemTypesExport.TMDB_SHOW == item.type) {
ListItemTypes.TMDB_SHOW
} else if (ListItemTypesExport.SEASON == item.type) {
ListItemTypes.SEASON
} else if (ListItemTypesExport.EPISODE == item.type) {
ListItemTypes.EPISODE
} else {
// Unknown item type, skip
continue
}
var externalId: String? = null
if (item.externalId != null && item.externalId.isNotEmpty()) {
externalId = item.externalId
} else if (item.tvdbId > 0) {
externalId = item.tvdbId.toString()
}
if (externalId == null) continue // No external ID, skip
// Generate list item ID from values, do not trust given item ID
// (e.g. encoded list ID might not match)
item.listItemId = ListItems.generateListItemId(externalId, type, list.listId)
val itemValues = ContentValues()
itemValues.put(ListItems.LIST_ITEM_ID, item.listItemId)
itemValues.put(SeriesGuideContract.Lists.LIST_ID, list.listId)
itemValues.put(ListItems.ITEM_REF_ID, externalId)
itemValues.put(ListItems.TYPE, type)
items.add(itemValues)
}
context.contentResolver.bulkInsert(ListItems.CONTENT_URI, items.toTypedArray())
}
companion object {
const val SUCCESS = 1
private const val ERROR_STORAGE_ACCESS = 0
private const val ERROR = -1
private const val ERROR_LARGE_DB_OP = -2
private const val ERROR_FILE_ACCESS = -3
}
} | app/src/main/java/com/battlelancer/seriesguide/dataliberation/JsonImportTask.kt | 3153137992 |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CancelExecution
import com.netflix.spinnaker.orca.q.RescheduleExecution
import com.netflix.spinnaker.orca.q.ResumeStage
import com.netflix.spinnaker.q.Queue
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
@Component
class CancelExecutionHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher")private val publisher: ApplicationEventPublisher
) : OrcaMessageHandler<CancelExecution> {
override val messageType = CancelExecution::class.java
override fun handle(message: CancelExecution) {
message.withExecution { execution ->
repository.cancel(execution.type, execution.id, message.user, message.reason)
// Resume any paused stages so that their RunTaskHandler gets executed
// and handles the `canceled` flag.
execution
.stages
.filter { it.status == PAUSED }
.forEach { stage ->
queue.push(ResumeStage(stage))
}
// then, make sure those runTask messages get run right away
queue.push(RescheduleExecution(execution))
publisher.publishEvent(ExecutionComplete(this, message.executionType, message.executionId, CANCELED))
}
}
}
| orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CancelExecutionHandler.kt | 3336237419 |
package ca.josephroque.bowlingcompanion.statistics.impl.firstball
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.lane.Deck
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.statistics.PercentageStatistic
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame
/**
* Copyright (C) 2018 Joseph Roque
*
* Parent class for statistics which are calculated based on the user throwing at a
* full deck of pins.
*/
abstract class FirstBallStatistic(override var numerator: Int = 0, override var denominator: Int = 0) : PercentageStatistic {
override fun isModifiedBy(frame: StatFrame) = true
override val category = StatisticsCategory.FirstBall
override val secondaryGraphDataLabelId = R.string.statistic_total_shots_at_middle
// MARK: Statistic
override fun modify(frame: StatFrame) {
// This function has a similar construction to `StrikeMiddleHitsStatistic.modify(StatFrame)
// and the two should remain aligned
// Every frame adds 1 possible hit
denominator++
numerator += if (isModifiedBy(frame.pinState[0])) 1 else 0
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
// In the 10th frame, for each time the first or second ball cleared the lane, add
// another middle hit chance, and check if the statistic is modified
if (frame.pinState[0].arePinsCleared) {
denominator++
numerator += if (isModifiedBy(frame.pinState[1])) 1 else 0
}
if (frame.pinState[1].arePinsCleared) {
denominator++
numerator += if (isModifiedBy(frame.pinState[2])) 1 else 0
}
}
}
// MARK: FirstBallStatistic
abstract fun isModifiedBy(deck: Deck): Boolean
}
| app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/FirstBallStatistic.kt | 2710206873 |
package de.roamingthings.devworkbench.category.repository
import de.roamingthings.devworkbench.category.domain.Category
import de.roamingthings.devworkbench.link.api.CategoryDto
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import javax.transaction.Transactional
/**
*
*
* @author Alexander Sparkowsky [[email protected]]
* @version 2017/07/08
*/
@Repository
@Transactional(Transactional.TxType.MANDATORY)
internal interface CategoryRepository : JpaRepository<Category, Long> {
fun findOneByCode(code: String): Category?
} | dev-workbench-backend/src/main/kotlin/de/roamingthings/devworkbench/category/repository/CategoryRepository.kt | 463808334 |
/*
* 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.irc
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService
import com.rpkit.chat.bukkit.chatchannel.undirected.IRCComponent
import com.rpkit.core.service.Services
import com.rpkit.permissions.bukkit.group.hasPermission
import com.rpkit.permissions.bukkit.permissions.RPKPermissionsService
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileName
import com.rpkit.players.bukkit.profile.RPKProfileService
import com.rpkit.players.bukkit.profile.irc.RPKIRCNick
import com.rpkit.players.bukkit.profile.irc.RPKIRCProfileService
import org.pircbotx.Channel
import org.pircbotx.PircBotX
import org.pircbotx.User
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class IRCWhitelistValidator(private val plugin: RPKChatBukkit) {
fun enforceWhitelist(user: User, nick: RPKIRCNick, bot: PircBotX, channel: Channel) {
val verified = user.isVerified
val chatChannelService = Services[RPKChatChannelService::class.java] ?: return
val chatChannel = chatChannelService.getChatChannelFromIRCChannel(IRCChannel(channel.name)) ?: return
if (chatChannel.undirectedPipeline
.firstNotNullOfOrNull { component -> component as? IRCComponent }
?.isIRCWhitelisted != true) return
if (!verified) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but you are not verified.",
"${nick.value} attempted to join, but was not verified."
)
}
val permissionsService = Services[RPKPermissionsService::class.java]
if (permissionsService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the permissions service could not be found.",
"${nick.value} attempted to join, but no permissions service could be found and the channel is whitelisted."
)
return
}
val profileService = Services[RPKProfileService::class.java]
if (profileService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the profile service could not be found.",
"${nick.value} attempted to join, but no profile service could be found and the channel is whitelisted."
)
return
}
val ircProfileService = Services[RPKIRCProfileService::class.java]
if (ircProfileService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the IRC profile service could not be found.",
"${nick.value} attempted to join, but no IRC profile service could be found and the channel is whitelisted."
)
return
}
CompletableFuture.runAsync {
val ircProfile = ircProfileService.getIRCProfile(nick).join() ?: ircProfileService.createIRCProfile(
profileService.createThinProfile(RPKProfileName(nick.value)),
nick
).join()
val profile = ircProfile.profile
if (profile !is RPKProfile) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but this IRC account has not been linked to a profile.",
"${nick.value} attempted to join, but their IRC account was not linked to a profile."
)
return@runAsync
}
if (!profile.hasPermission("rpkit.chat.listen.${chatChannel.name.value}").join()) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, you do not have permission to view it.",
"${nick.value} attempted to join, but does not have permission to view the channel."
)
}
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to check IRC profile", exception)
throw exception
}
}
private fun kick(
bot: PircBotX,
channel: Channel,
nick: String,
kickMessage: String,
channelMessage: String
) {
bot.sendIRC().message(channel.name, "/kick ${channel.name} $nick $kickMessage")
channel.send().message(channelMessage)
}
} | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/IRCWhitelistValidator.kt | 208647397 |
/*
* 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.example.compose.rally.ui.components
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
private const val DividerLengthInDegrees = 1.8f
/**
* A donut chart that animates when loaded.
*/
@Composable
fun AnimatedCircle(
proportions: List<Float>,
colors: List<Color>,
modifier: Modifier = Modifier
) {
val currentState = remember {
MutableTransitionState(AnimatedCircleProgress.START)
.apply { targetState = AnimatedCircleProgress.END }
}
val stroke = with(LocalDensity.current) { Stroke(5.dp.toPx()) }
val transition = updateTransition(currentState)
val angleOffset by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = LinearOutSlowInEasing
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
360f
}
}
val shift by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = CubicBezierEasing(0f, 0.75f, 0.35f, 0.85f)
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
30f
}
}
Canvas(modifier) {
val innerRadius = (size.minDimension - stroke.width) / 2
val halfSize = size / 2.0f
val topLeft = Offset(
halfSize.width - innerRadius,
halfSize.height - innerRadius
)
val size = Size(innerRadius * 2, innerRadius * 2)
var startAngle = shift - 90f
proportions.forEachIndexed { index, proportion ->
val sweep = proportion * angleOffset
drawArc(
color = colors[index],
startAngle = startAngle + DividerLengthInDegrees / 2,
sweepAngle = sweep - DividerLengthInDegrees,
topLeft = topLeft,
size = size,
useCenter = false,
style = stroke
)
startAngle += sweep
}
}
}
private enum class AnimatedCircleProgress { START, END }
| NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/components/RallyAnimatedCircle.kt | 1250595468 |
package io.drakon.uod.di_explained.handlers
import com.google.inject.Inject
import io.drakon.uod.di_explained.stores.IClickerStore
/**
* Clicker Handler.
*/
class ClickerHandler @Inject constructor(private val clickerStore: IClickerStore): IClickerHandler {
override fun click(responder: IResponder, uuid: String) {
clickerStore.incrementScore(uuid)
sendScore(responder, uuid)
}
override fun sendScore(responder: IResponder, uuid: String) {
val score = clickerStore.getScore(uuid)
responder.respond(WSResponseScore(score))
}
} | samples/2/src/main/kotlin/io/drakon/uod/di_explained/handlers/ClickerHandler.kt | 3024288193 |
/*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api.helper
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.OutputStream
class ProcessExecutor {
@Throws(InterruptedException::class, IOException::class)
fun execute(cmd: Array<String>?, stdout: OutputStream?, stderr: OutputStream?): Int {
val rt = Runtime.getRuntime()
val proc = rt.exec(cmd)
val errorGobbler = StreamGobbler(proc.errorStream, stderr)
val outputGobbler = StreamGobbler(proc.inputStream, stdout)
errorGobbler.start()
outputGobbler.start()
return proc.waitFor()
}
companion object {
private val LOG = LoggerFactory.getLogger(ProcessExecutor::class.java)
}
}
| ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/ProcessExecutor.kt | 260880957 |
package io.skygear.plugins.chat.ui.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Environment
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import android.media.ExifInterface
import android.R.attr.path
import java.io.FileOutputStream
/**
* Created by carmenlau on 10/2/17.
*/
private val THUMBNAIL_SIZE = 80.0
private val IMAGE_SIZE = 1600.0
var mCurrentPhotoPath: String = ""
data class ImageData(val thumbnail: Bitmap,
val image: Bitmap)
fun getResizedBitmap(context: Context, uri: Uri): ImageData? {
var input = context.getContentResolver().openInputStream(uri)
val onlyBoundsOptions = BitmapFactory.Options()
onlyBoundsOptions.inJustDecodeBounds = true
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions)
input.close()
if (onlyBoundsOptions.outWidth == -1 || onlyBoundsOptions.outHeight == -1) {
return null
}
// get orientation exif
input = context.getContentResolver().openInputStream(uri)
val file = File.createTempFile("image_tmp", ".jpg", context.getCacheDir())
val fos = FileOutputStream(file)
var len: Int
val buffer = ByteArray(1024)
do {
len = input.read(buffer, 0, 1024)
if (len == -1)
break
fos.write(buffer, 0, len)
} while (true)
input.close()
fos.close()
val ef = ExifInterface(file.toString())
val orientation = ef.getAttributeInt(ExifInterface.TAG_ORIENTATION, 99)
val originalSize = if (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
onlyBoundsOptions.outHeight else onlyBoundsOptions.outWidth
val imgRatio = if (originalSize > IMAGE_SIZE) originalSize / IMAGE_SIZE else 1.0
val bitmap = getBitmap(context, uri, imgRatio, orientation)
val thumbRatio = if (originalSize > THUMBNAIL_SIZE) originalSize / THUMBNAIL_SIZE else 1.0
val thumbBitmap = getBitmap(context, uri, thumbRatio, orientation)
return ImageData(thumbBitmap, bitmap)
}
fun getBitmap(context: Context, uri: Uri, ratio: Double, orientation: Int) : Bitmap {
val bitmapOptions = BitmapFactory.Options()
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio)
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888
val input = context.getContentResolver().openInputStream(uri)
var bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions)
bitmap = rotateBitmap(bitmap, orientation)
input.close()
return bitmap
}
fun bitmapToByteArray(bmp: Bitmap): ByteArray? {
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 70, stream)
return stream.toByteArray()
}
fun rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap? {
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return bitmap
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return bitmap
}
try {
val bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
return bmRotated
} catch (e: OutOfMemoryError) {
e.printStackTrace()
return null
}
}
@Throws(IOException::class)
fun createImageFile(context: Context): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath()
return image
}
private fun getPowerOfTwoForSampleRatio(ratio: Double): Int {
val k = Integer.highestOneBit(Math.floor(ratio).toInt())
return if (k == 0) 1 else k
}
| chat/src/main/java/io/skygear/plugins/chat/ui/utils/ImageUtils.kt | 1673101891 |
/*
* 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
*
* 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.summit.ast
/**
* This interface is for nodes that can print their subtree as an Apex code string.
*
* Not every node corresponds to actual syntax in a well-formed Apex compilation unit. For example,
* anonymous code blocks and special callsites may utilize special name identifiers for internal
* use. These identifiers would never be printed in the code of their parent node, but the child
* nodes may still return a code-like string for testing or debugging.
*/
interface PrintableAsCodeString {
/** Returns the node's subtree printed as an Apex code string. */
fun asCodeString(): String
}
| src/main/java/com/google/summit/ast/PrintableAsCodeString.kt | 3605024525 |
package com.adviser.ipaddress.kotlin
import java.math.BigInteger
/*
interface VtFrom {
fun <Prefix> run(p: Prefix, n: Byte): Result<Prefix>
}
*/
public class Prefix(val num: Int,
val ip_bits: IpBits,
val net_mask: BigInteger,
val vt_from: (p: Prefix, n: Int) -> Result<Prefix>) {
companion object {
fun new_netmask(prefix: Int, bits: Int): BigInteger {
var mask = BigInteger.ZERO
val host_prefix = bits - prefix
for (i in 0 until prefix) {
mask = mask.add((BigInteger.ONE.shiftLeft(host_prefix + i)))
}
return mask
}
}
fun clone(): Prefix {
return Prefix(this.num, this.ip_bits, this.net_mask, this.vt_from)
}
fun equal(other: Prefix): Boolean {
return this.ip_bits.version == other.ip_bits.version &&
this.num == other.num
}
fun inspect(): String {
return "Prefix: ${num}"
}
fun compare(oth: Prefix): Int {
if (this.ip_bits.version < oth.ip_bits.version) {
return -1
} else if (this.ip_bits.version > oth.ip_bits.version) {
return 1
} else {
if (this.num < oth.num) {
return -1
} else if (this.num > oth.num) {
return 1
} else {
return 0
}
}
}
fun from(num: Int): Result<Prefix> {
return this.vt_from(this, num)
}
fun to_ip_str(): String {
return this.ip_bits.vt_as_compressed_string(this.ip_bits, this.netmask())
}
fun size(): BigInteger {
return BigInteger.ONE.shiftLeft(this.ip_bits.bits - this.num)
}
fun netmask(): BigInteger {
return BigInteger.ZERO.add(this.net_mask)
}
fun get_prefix(): Int {
return this.num
}
/// The hostmask is the contrary of the subnet mask,
/// as it shows the bits that can change within the
/// hosts
///
/// prefix = IPAddress::Prefix32.new 24
///
/// prefix.hostmask
/// /// "0.0.0.255"
///
fun host_mask(): BigInteger {
var ret = BigInteger.ZERO
for (i in 0 until this.ip_bits.bits - this.num) {
ret = ret.shiftLeft(1).add(BigInteger.ONE)
}
return ret
}
///
/// Returns the length of the host portion
/// of a netmask.
///
/// prefix = Prefix128.new 96
///
/// prefix.host_prefix
/// /// 128
///
fun host_prefix(): Int {
return this.ip_bits.bits - this.num
}
///
/// Transforms the prefix into a string of bits
/// representing the netmask
///
/// prefix = IPAddress::Prefix128.new 64
///
/// prefix.bits
/// /// "1111111111111111111111111111111111111111111111111111111111111111"
/// "0000000000000000000000000000000000000000000000000000000000000000"
///
fun bits(): String {
return this.netmask().toString(2)
}
fun to_s(): String {
return "${this.get_prefix()}"
}
fun to_i(): Int {
return this.get_prefix()
}
fun add_prefix(other: Prefix): Result<Prefix> {
return this.from(this.get_prefix() + other.get_prefix())
}
fun add(other: Int): Result<Prefix> {
return this.from(this.get_prefix() + other)
}
fun sub_prefix(other: Prefix): Result<Prefix> {
return this.sub(other.get_prefix())
}
fun sub(other: Int): Result<Prefix> {
if (other > this.get_prefix()) {
return this.from(other - this.get_prefix())
}
return this.from(this.get_prefix() - other)
}
}
| kotlin/lib/src/main/kotlin/com/adviser/ipaddress/Prefix.kt | 3191237089 |
package org.luxons.sevenwonders.ui.components.lobby
import com.palantir.blueprintjs.*
import kotlinx.css.*
import kotlinx.css.properties.transform
import kotlinx.css.properties.translate
import org.luxons.sevenwonders.model.api.LobbyDTO
import org.luxons.sevenwonders.model.api.PlayerDTO
import org.luxons.sevenwonders.model.wonders.*
import org.luxons.sevenwonders.ui.components.GlobalStyles
import org.luxons.sevenwonders.ui.redux.*
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import react.dom.h2
import react.dom.h3
import react.dom.h4
import styled.css
import styled.styledDiv
import styled.styledH2
private val BOT_NAMES = listOf("Wall-E", "B-Max", "Sonny", "T-800", "HAL", "GLaDOS")
interface LobbyStateProps : RProps {
var currentGame: LobbyDTO?
var currentPlayer: PlayerDTO?
}
interface LobbyDispatchProps : RProps {
var startGame: () -> Unit
var addBot: (displayName: String) -> Unit
var leaveLobby: () -> Unit
var disbandLobby: () -> Unit
var reorderPlayers: (orderedPlayers: List<String>) -> Unit
var reassignWonders: (wonders: List<AssignedWonder>) -> Unit
}
interface LobbyProps : LobbyDispatchProps, LobbyStateProps
class LobbyPresenter(props: LobbyProps) : RComponent<LobbyProps, RState>(props) {
override fun RBuilder.render() {
val currentGame = props.currentGame
val currentPlayer = props.currentPlayer
if (currentGame == null || currentPlayer == null) {
bpNonIdealState(icon = "error", title = "Error: no current game")
return
}
styledDiv {
css {
padding(1.rem)
+GlobalStyles.fullscreen
}
h2 { +"${currentGame.name} — Lobby" }
radialPlayerList(currentGame.players, currentPlayer)
actionButtons(currentPlayer, currentGame)
if (currentPlayer.isGameOwner) {
setupPanel(currentGame)
}
}
}
private fun RBuilder.actionButtons(currentPlayer: PlayerDTO, currentGame: LobbyDTO) {
styledDiv {
css {
position = Position.fixed
bottom = 2.rem
left = 50.pct
transform { translate((-50).pct) }
}
if (currentPlayer.isGameOwner) {
bpButtonGroup {
startButton(currentGame, currentPlayer)
addBotButton(currentGame)
leaveButton()
disbandButton()
}
} else {
leaveButton()
}
}
}
private fun RBuilder.startButton(currentGame: LobbyDTO, currentPlayer: PlayerDTO) {
val startability = currentGame.startability(currentPlayer.username)
bpButton(
large = true,
intent = Intent.PRIMARY,
icon = "play",
title = startability.tooltip,
disabled = !startability.canDo,
onClick = { props.startGame() },
) {
+"START"
}
}
private fun RBuilder.setupPanel(currentGame: LobbyDTO) {
styledDiv {
css {
position = Position.fixed
top = 2.rem
right = 1.rem
width = 15.rem
}
bpCard(Elevation.TWO) {
styledH2 {
css {
margin(top = 0.px)
}
+"Game setup"
}
bpDivider()
h3 {
+"Players"
}
reorderPlayersButton(currentGame)
h3 {
+"Wonders"
}
randomizeWondersButton(currentGame)
wonderSideSelectionGroup(currentGame)
}
}
}
private fun RBuilder.addBotButton(currentGame: LobbyDTO) {
bpButton(
large = true,
icon = "plus",
rightIcon = "desktop",
title = if (currentGame.maxPlayersReached) "Max players reached" else "Add a bot to this game",
disabled = currentGame.maxPlayersReached,
onClick = { addBot(currentGame) },
)
}
private fun addBot(currentGame: LobbyDTO) {
val availableBotNames = BOT_NAMES.filter { name ->
currentGame.players.all { it.displayName != name }
}
props.addBot(availableBotNames.random())
}
private fun RBuilder.reorderPlayersButton(currentGame: LobbyDTO) {
bpButton(
icon = "random",
rightIcon = "people",
title = "Re-order players randomly",
onClick = { reorderPlayers(currentGame) },
) {
+"Reorder players"
}
}
private fun reorderPlayers(currentGame: LobbyDTO) {
props.reorderPlayers(currentGame.players.map { it.username }.shuffled())
}
private fun RBuilder.randomizeWondersButton(currentGame: LobbyDTO) {
bpButton(
icon = "random",
title = "Re-assign wonders to players randomly",
onClick = { randomizeWonders(currentGame) },
) {
+"Randomize wonders"
}
}
private fun RBuilder.wonderSideSelectionGroup(currentGame: LobbyDTO) {
h4 {
+"Select wonder sides:"
}
bpButtonGroup {
bpButton(
icon = "random",
title = "Re-roll wonder sides randomly",
onClick = { randomizeWonderSides(currentGame) },
)
bpButton(
title = "Choose side A for everyone",
onClick = { setWonderSides(currentGame, WonderSide.A) },
) {
+"A"
}
bpButton(
title = "Choose side B for everyone",
onClick = { setWonderSides(currentGame, WonderSide.B) },
) {
+"B"
}
}
}
private fun randomizeWonders(currentGame: LobbyDTO) {
props.reassignWonders(currentGame.allWonders.deal(currentGame.players.size))
}
private fun randomizeWonderSides(currentGame: LobbyDTO) {
props.reassignWonders(currentGame.players.map { currentGame.findWonder(it.wonder.name).withRandomSide() })
}
private fun setWonderSides(currentGame: LobbyDTO, side: WonderSide) {
props.reassignWonders(currentGame.players.map { currentGame.findWonder(it.wonder.name).withSide(side) })
}
private fun RBuilder.leaveButton() {
bpButton(
large = true,
intent = Intent.WARNING,
icon = "arrow-left",
title = "Leave the lobby and go back to the game browser",
onClick = { props.leaveLobby() },
) {
+"LEAVE"
}
}
private fun RBuilder.disbandButton() {
bpButton(
large = true,
intent = Intent.DANGER,
icon = "delete",
title = "Disband the group and go back to the game browser",
onClick = { props.disbandLobby() },
) {
+"DISBAND"
}
}
}
fun RBuilder.lobby() = lobby {}
private val lobby = connectStateAndDispatch<LobbyStateProps, LobbyDispatchProps, LobbyProps>(
clazz = LobbyPresenter::class,
mapStateToProps = { state, _ ->
currentGame = state.currentLobby
currentPlayer = state.currentPlayer
},
mapDispatchToProps = { dispatch, _ ->
startGame = { dispatch(RequestStartGame()) }
addBot = { name -> dispatch(RequestAddBot(name)) }
leaveLobby = { dispatch(RequestLeaveLobby()) }
disbandLobby = { dispatch(RequestDisbandLobby()) }
reorderPlayers = { orderedPlayers -> dispatch(RequestReorderPlayers(orderedPlayers)) }
reassignWonders = { wonders -> dispatch(RequestReassignWonders(wonders)) }
},
)
| sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/lobby/Lobby.kt | 1032582522 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.views_app
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat
import com.example.views_app.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
const val PREFERENCE_NAME = "shared_preference"
const val PREFERENCE_MODE = Context.MODE_PRIVATE
const val FIRST_TIME_MIGRATION = "first_time_migration"
const val SELECTED_LANGUAGE = "selected_language"
const val STATUS_DONE = "status_done"
}
/**
* This is a sample code that explains the use of getter and setter APIs for Locales introduced
* in the Per-App language preferences. Here is an example use of the AndroidX Support Library
* */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
/* NOTE: If you were handling the locale storage on you own earlier, you will need to add a
one time migration for switching this storage from a custom way to the AndroidX storage.
This can be done in the following manner. Lets say earlier the locale preference was
stored in a SharedPreference */
// Check if the migration has already been done or not
if (getString(FIRST_TIME_MIGRATION) != STATUS_DONE) {
// Fetch the selected language from wherever it was stored. In this case its SharedPref
getString(SELECTED_LANGUAGE)?.let {
// Set this locale using the AndroidX library that will handle the storage itself
val localeList = LocaleListCompat.forLanguageTags(it)
AppCompatDelegate.setApplicationLocales(localeList)
// Set the migration flag to ensure that this is executed only once
putString(FIRST_TIME_MIGRATION, STATUS_DONE)
}
}
// Fetching the current application locale using the AndroidX support Library
val currentLocaleName = if (!AppCompatDelegate.getApplicationLocales().isEmpty) {
// Fetches the current Application Locale from the list
AppCompatDelegate.getApplicationLocales()[0]?.displayName
} else {
// Fetches the default System Locale
Locale.getDefault().displayName
}
// Displaying the selected locale on screen
binding.tvSelectedLanguage.text = currentLocaleName
// Setting app language to "English" in-app using the AndroidX support library
binding.btnSelectEnglish.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("en")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Hindi" in-app using the AndroidX support library
binding.btnSelectHindi.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("hi")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Arabic" in-app using the AndroidX support Library
// NOTE: Here the screen orientation is reversed to RTL
binding.btnSelectArabic.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("ar")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Japanese" in-app using the AndroidX support library
binding.btnSelectJapanese.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("ja")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Spanish" in-app using the AndroidX support library
binding.btnSelectSpanish.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("es")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to Traditional Chinese in-app using the AndroidX support Library
binding.btnSelectXxYy.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("zh-Hant")
AppCompatDelegate.setApplicationLocales(localeList)
}
}
private fun putString(key: String, value: String) {
val editor = getSharedPreferences(PREFERENCE_NAME, PREFERENCE_MODE).edit()
editor.putString(key, value)
editor.apply()
}
private fun getString(key: String): String? {
val preference = getSharedPreferences(PREFERENCE_NAME, PREFERENCE_MODE)
return preference.getString(key, null)
}
}
| PerAppLanguages/views_app/app/src/main/java/com/example/views_app/MainActivity.kt | 864168420 |
/*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.jibri
import com.fasterxml.jackson.annotation.JsonIgnore
import java.util.Objects
/**
* We assume the 'baseUrl' represents a sort of landing page (on the same
* domain) where we can set the necessary local storage values. The call
* url will be created by joining [baseUrl] and [callName] with a "/". If
* set, a list of [urlParams] will be concatenated after the call name with
* a "#" in between.
*/
data class CallUrlInfo(
val baseUrl: String = "",
val callName: String = "",
private val urlParams: List<String> = listOf()
) {
@get:JsonIgnore
val callUrl: String
get() {
return if (urlParams.isNotEmpty()) {
"$baseUrl/$callName#${urlParams.joinToString("&")}"
} else {
"$baseUrl/$callName"
}
}
override fun equals(other: Any?): Boolean {
return when {
other == null -> false
this === other -> true
javaClass != other.javaClass -> false
else -> hashCode() == other.hashCode()
}
}
override fun hashCode(): Int {
// Purposefully ignore urlParams here
return Objects.hash(baseUrl.lowercase(), callName.lowercase())
}
}
| src/main/kotlin/org/jitsi/jibri/CallUrlInfo.kt | 2179822749 |
package com.blankj.utilcode.pkg.feature.span
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Bundle
import android.text.Layout
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.ClickableSpan
import android.text.style.UpdateAppearance
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.annotation.ColorInt
import com.blankj.common.activity.CommonActivity
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.span_activity.*
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/27
* desc : demo about SpanUtils
* ```
*/
class SpanActivity : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, SpanActivity::class.java)
context.startActivity(starter)
}
}
private lateinit var mSpanUtils: SpanUtils
private lateinit var animSsb: SpannableStringBuilder
private var lineHeight: Int = 0
private var textSize: Float = 0f
private lateinit var valueAnimator: ValueAnimator
private lateinit var mShader: Shader
private var mShaderWidth: Float = 0f
private lateinit var matrix: Matrix
private lateinit var mBlurMaskFilterSpan: BlurMaskFilterSpan
private lateinit var mShadowSpan: ShadowSpan
private lateinit var mForegroundAlphaColorSpan: ForegroundAlphaColorSpan
private lateinit var mForegroundAlphaColorSpanGroup: ForegroundAlphaColorSpanGroup
private lateinit var mPrinterString: String
private var density: Float = 0f
override fun bindTitleRes(): Int {
return R.string.demo_span
}
override fun bindLayout(): Int {
return R.layout.span_activity
}
override fun initView(savedInstanceState: Bundle?, contentView: View?) {
super.initView(savedInstanceState, contentView)
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
ToastUtils.showShort("事件触发了")
}
override fun updateDrawState(ds: TextPaint) {
ds.color = Color.BLUE
ds.isUnderlineText = false
}
}
lineHeight = spanAboutTv.lineHeight
textSize = spanAboutTv.textSize
density = resources.displayMetrics.density
SpanUtils.with(spanAboutTv)
.appendLine("SpanUtils").setBackgroundColor(Color.LTGRAY).setBold().setForegroundColor(Color.YELLOW).setHorizontalAlign(Layout.Alignment.ALIGN_CENTER)
.appendLine("前景色").setForegroundColor(Color.GREEN)
// .appendLine("测试哈哈").setForegroundColor(Color.RED).setBackgroundColor(Color.LTGRAY).setFontSize(10).setLineHeight(280, SpanUtils.ALIGN_BOTTOM)
.appendLine("背景色").setBackgroundColor(Color.LTGRAY)
.appendLine("行高居中对齐").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_CENTER).setBackgroundColor(Color.LTGRAY)
.appendLine("行高底部对齐").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_BOTTOM).setBackgroundColor(Color.GREEN)
.appendLine("测试段落缩,首行缩进两字,其他行不缩进").setLeadingMargin(textSize.toInt() * 2, 10).setBackgroundColor(Color.GREEN)
.appendLine("测试引用,后面的字是为了凑到两行的效果").setQuoteColor(Color.GREEN, 10, 10).setBackgroundColor(Color.LTGRAY)
.appendLine("测试列表项,后面的字是为了凑到两行的效果").setBullet(Color.GREEN, 20, 10).setBackgroundColor(Color.LTGRAY).setBackgroundColor(Color.GREEN)
.appendLine("32dp 字体").setFontSize(32, true)
.appendLine("2 倍字体").setFontProportion(2f)
.appendLine("横向 2 倍字体").setFontXProportion(1.5f)
.appendLine("删除线").setStrikethrough()
.appendLine("下划线").setUnderline()
.append("测试").appendLine("上标").setSuperscript()
.append("测试").appendLine("下标").setSubscript()
.appendLine("粗体").setBold()
.appendLine("斜体").setItalic()
.appendLine("粗斜体").setBoldItalic()
.appendLine("monospace 字体").setFontFamily("monospace")
.appendLine("自定义字体").setTypeface(Typeface.createFromAsset(assets, "fonts/dnmbhs.ttf"))
.appendLine("相反对齐").setHorizontalAlign(Layout.Alignment.ALIGN_OPPOSITE)
.appendLine("居中对齐").setHorizontalAlign(Layout.Alignment.ALIGN_CENTER)
.appendLine("正常对齐").setHorizontalAlign(Layout.Alignment.ALIGN_NORMAL)
.append("测试").appendLine("点击事件").setClickSpan(clickableSpan)
.append("测试").appendLine("Url").setUrl("https://github.com/Blankj/AndroidUtilCode")
.append("测试").appendLine("模糊").setBlur(3f, BlurMaskFilter.Blur.NORMAL)
.appendLine("颜色渐变").setShader(LinearGradient(0f, 0f, 64f * density * 4f, 0f, resources.getIntArray(R.array.rainbow), null, Shader.TileMode.REPEAT)).setFontSize(64, true)
.appendLine("图片着色").setFontSize(64, true).setShader(BitmapShader(BitmapFactory.decodeResource(resources, R.drawable.span_cheetah), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT))
.appendLine("阴影效果").setFontSize(64, true).setBackgroundColor(Color.BLACK).setShadow(24f, 8f, 8f, Color.WHITE)
.append("小图").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_TOP)
.append("顶部").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_CENTER)
.append("居中").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BASELINE)
.append("底部").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BOTTOM)
.appendLine("对齐").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.append("大图").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.append("顶部").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.appendLine("对齐").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.append("大图").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.append("居中").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.appendLine("对齐").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.append("大图").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.append("底部").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.appendLine("对齐").setBackgroundColor(Color.LTGRAY)
.append("测试空格").appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN).appendSpace(100).appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN)
.create()
// initAnimSpan();
// startAnim();
}
private fun initAnimSpan() {
mShaderWidth = 64f * density * 4f
mShader = LinearGradient(0f, 0f,
mShaderWidth, 0f,
resources.getIntArray(R.array.rainbow), null,
Shader.TileMode.REPEAT)
matrix = Matrix()
mBlurMaskFilterSpan = BlurMaskFilterSpan(25f)
mShadowSpan = ShadowSpan(8f, 8f, 8f, Color.WHITE)
mForegroundAlphaColorSpan = ForegroundAlphaColorSpan(Color.TRANSPARENT)
mForegroundAlphaColorSpanGroup = ForegroundAlphaColorSpanGroup(0f)
mPrinterString = "打印动画,后面的文字是为了测试打印效果..."
mSpanUtils = SpanUtils()
.appendLine("彩虹动画").setFontSize(64, true).setShader(mShader)
.appendLine("模糊动画").setFontSize(64, true).setSpans(mBlurMaskFilterSpan)
.appendLine("阴影动画").setFontSize(64, true).setBackgroundColor(Color.BLACK).setSpans(mShadowSpan)
.appendLine("透明动画").setFontSize(64, true).setSpans(mForegroundAlphaColorSpan)
var i = 0
val len = mPrinterString.length
while (i < len) {
val span = ForegroundAlphaColorSpan(Color.TRANSPARENT)
mSpanUtils.append(mPrinterString.substring(i, i + 1)).setSpans(span)
mForegroundAlphaColorSpanGroup.addSpan(span)
++i
}
animSsb = mSpanUtils.create()
}
private fun startAnim() {
valueAnimator = ValueAnimator.ofFloat(0f, 1f)
valueAnimator.addUpdateListener { animation ->
// shader
matrix.reset()
matrix.setTranslate(animation.animatedValue as Float * mShaderWidth, 0f)
mShader.setLocalMatrix(matrix)
// blur
mBlurMaskFilterSpan.radius = 25 * (1.00001f - animation.animatedValue as Float)
// shadow
mShadowSpan.dx = 16 * (0.5f - animation.animatedValue as Float)
mShadowSpan.dy = 16 * (0.5f - animation.animatedValue as Float)
// alpha
mForegroundAlphaColorSpan.setAlpha((255 * animation.animatedValue as Float).toInt())
// printer
mForegroundAlphaColorSpanGroup.alpha = animation.animatedValue as Float
// showMsg
spanAboutAnimTv.text = animSsb
}
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = (600 * 3).toLong()
valueAnimator.repeatCount = ValueAnimator.INFINITE
valueAnimator.start()
}
override fun doBusiness() {}
override fun onDebouncingClick(view: View) {}
// override fun onDestroy() {
// if (valueAnimator.isRunning) {
// valueAnimator.cancel()
// }
// super.onDestroy()
// }
}
class BlurMaskFilterSpan(private var mRadius: Float) : CharacterStyle(), UpdateAppearance {
private var mFilter: MaskFilter? = null
var radius: Float
get() = mRadius
set(radius) {
mRadius = radius
mFilter = BlurMaskFilter(mRadius, BlurMaskFilter.Blur.NORMAL)
}
override fun updateDrawState(ds: TextPaint) {
ds.maskFilter = mFilter
}
}
class ForegroundAlphaColorSpan(@param:ColorInt private var mColor: Int) : CharacterStyle(), UpdateAppearance {
fun setAlpha(alpha: Int) {
mColor = Color.argb(alpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor))
}
override fun updateDrawState(ds: TextPaint) {
ds.color = mColor
}
}
class ForegroundAlphaColorSpanGroup(private val mAlpha: Float) {
private val mSpans: ArrayList<ForegroundAlphaColorSpan> = ArrayList()
var alpha: Float
get() = mAlpha
set(alpha) {
val size = mSpans.size
var total = 1.0f * size.toFloat() * alpha
for (index in 0 until size) {
val span = mSpans[index]
if (total >= 1.0f) {
span.setAlpha(255)
total -= 1.0f
} else {
span.setAlpha((total * 255).toInt())
total = 0.0f
}
}
}
fun addSpan(span: ForegroundAlphaColorSpan) {
span.setAlpha((mAlpha * 255).toInt())
mSpans.add(span)
}
}
class ShadowSpan(private val radius: Float, var dx: Float, var dy: Float, private val shadowColor: Int) : CharacterStyle(), UpdateAppearance {
override fun updateDrawState(tp: TextPaint) {
tp.setShadowLayer(radius, dx, dy, shadowColor)
}
} | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/span/SpanActivity.kt | 3735539976 |
package net.perfectdreams.loritta.morenitta.profile.profiles
import dev.kord.common.entity.Snowflake
import net.perfectdreams.loritta.morenitta.dao.Profile
import net.perfectdreams.loritta.morenitta.utils.enableFontAntiAliasing
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.utils.makeRoundedCorners
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.profile.ProfileGuildInfoData
import net.perfectdreams.loritta.morenitta.profile.ProfileUserInfoData
import java.awt.Color
import java.awt.image.BufferedImage
class DebugProfileCreator(loritta: LorittaBot) : StaticProfileCreator(loritta, "debug") {
override suspend fun create(
sender: ProfileUserInfoData,
user: ProfileUserInfoData,
userProfile: Profile,
guild: ProfileGuildInfoData?,
badges: List<BufferedImage>,
locale: BaseLocale,
i18nContext: I18nContext,
background: BufferedImage,
aboutMe: String,
allowedDiscordEmojis: List<Snowflake>?
): BufferedImage {
val base = BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB) // Base
val graphics = base.graphics.enableFontAntiAliasing()
graphics.color = Color.WHITE
graphics.fillRect(0, 0, 800, 600)
graphics.color = Color.BLACK
graphics.drawString("Perfil de $user", 20, 20)
graphics.drawString("Apenas para Testes!!!", 400, 400)
return base.makeRoundedCorners(15)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/profile/profiles/DebugProfileCreator.kt | 2326070816 |
package xyz.thecodeside.tradeapp.repository.remote.socket
import io.reactivex.Flowable
import xyz.thecodeside.tradeapp.helpers.Logger
import xyz.thecodeside.tradeapp.model.BaseSocket
import xyz.thecodeside.tradeapp.model.SocketRequest
import xyz.thecodeside.tradeapp.model.SocketType
class SocketManager(private val socketAddress: String,
private val socket: RxSocketWrapper,
private val packer: SocketItemPacker,
private val logger: Logger) {
companion object {
const val TAG = "SOCKET"
}
fun connect(): Flowable<RxSocketWrapper.Status> = socket
.connect(socketAddress)
.doOnError {
disconnect()
}
private fun isReady(it: RxSocketWrapper.Status) =
it == RxSocketWrapper.Status.READY
fun disconnect() = socket.disconnect()
fun send(item: SocketRequest) = socket.send(packer.pack(item))
fun observe(): Flowable<BaseSocket> = socket
.observeSocketMessages()
.flatMap { unpackItem(it) }
.map {
checkIsReady(it)
it
}
private fun checkIsReady(it: BaseSocket) {
if (isConnected() && isConnectedMessage(it)) {
socket.status = RxSocketWrapper.Status.READY
}
}
private fun isConnectedMessage(it: BaseSocket) =
it.type == SocketType.CONNECT_CONNECTED
private fun isConnected() = socket.status == RxSocketWrapper.Status.CONNECTED
fun unpackItem(envelope: String?): Flowable<BaseSocket> = Flowable
.fromCallable { (packer.unpack(envelope)) }
.onErrorResumeNext { e: Throwable ->
logger.logException(e)
Flowable.never<BaseSocket>()
}
}
| app/src/main/java/xyz/thecodeside/tradeapp/repository/remote/socket/SocketManager.kt | 932788090 |
package com.androidvip.hebf.ui.main.tools
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.androidvip.hebf.*
import com.androidvip.hebf.ui.main.tools.apps.AppsManagerActivity
import com.androidvip.hebf.ui.main.tools.apps.AutoStartDisablerActivity
import com.androidvip.hebf.databinding.FragmentTools2Binding
import com.androidvip.hebf.ui.base.binding.BaseViewBindingFragment
import com.androidvip.hebf.ui.main.LottieAnimViewModel
import com.androidvip.hebf.ui.main.tools.cleaner.CleanerActivity
import com.androidvip.hebf.utils.K
import com.androidvip.hebf.utils.Logger
import com.androidvip.hebf.utils.RootUtils
import com.androidvip.hebf.utils.Utils
import com.google.android.material.behavior.SwipeDismissBehavior
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import java.io.File
class ToolsFragment2 : BaseViewBindingFragment<FragmentTools2Binding>(
FragmentTools2Binding::inflate
) {
private val animViewModel: LottieAnimViewModel by sharedViewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.wifiSettings.setOnClickListener {
findNavController().navigate(R.id.startWiFiTweaksFragment)
}
binding.fstrim.setOnClickListener {
findNavController().navigate(R.id.startFstrimFragment)
}
binding.cleaner.setOnClickListener {
Intent(findContext(), CleanerActivity::class.java).apply {
startActivity(this)
requireActivity().overridePendingTransition(
R.anim.slide_in_right, R.anim.fragment_open_exit
)
}
}
binding.autoStartDisabler.setOnClickListener {
Intent(findContext(), AutoStartDisablerActivity::class.java).apply {
startActivity(this)
}
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.fragment_open_exit)
}
binding.appsManager.setOnClickListener {
Intent(findContext(), AppsManagerActivity::class.java).apply {
startActivity(this)
}
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.fragment_open_exit)
}
lifecycleScope.launch(workerContext) {
val isRooted = isRooted()
val supportsAppOps = !Utils.runCommand(
"which appops",
""
).isNullOrEmpty()
val ipv6File = File("/proc/net/if_inet6")
val supportsIpv6 = ipv6File.exists() || ipv6File.isFile
val ipv6State = RootUtils.executeWithOutput(
"cat /proc/sys/net/ipv6/conf/all/disable_ipv6",
"0",
activity
)
val captivePortalStatus = RootUtils.executeWithOutput(
"settings get global captive_portal_detection_enabled",
"1",
activity
)
val hostnameFound = Utils.runCommand("getprop net.hostname", "")
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val supportsWifi5 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && wifiManager.is5GHzBandSupported
val preferredWifiBand = RootUtils.executeWithOutput(
"settings get global wifi_frequency_band", "null", activity
)
runSafeOnUiThread {
setUpNetControls(isRooted)
setUpControls(isRooted)
setUpSwipes(isRooted)
binding.autoStartDisabler.isEnabled = supportsAppOps && isRooted
binding.hostnameField.apply {
setText(hostnameFound)
isEnabled = isRooted
}
binding.captivePortal.apply {
isEnabled = isRooted
setChecked(captivePortalStatus == "1" || captivePortalStatus == "null")
setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand("settings put global captive_portal_detection_enabled 1")
} else {
runCommand("settings put global captive_portal_detection_enabled 0")
}
}
}
binding.ipv6.apply {
if (!supportsIpv6) {
prefs.putInt(K.PREF.NET_IPV6_STATE, -1)
}
isEnabled = isRooted && supportsIpv6
binding.ipv6.setChecked(ipv6State == "0")
binding.ipv6.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand(arrayOf(
"sysctl -w net.ipv6.conf.all.disable_ipv6=0",
"sysctl -w net.ipv6.conf.wlan0.accept_ra=1")
)
Logger.logInfo("IPv6 enabled", findContext())
prefs.putInt(K.PREF.NET_IPV6_STATE, 1)
} else {
runCommand(arrayOf(
"sysctl -w net.ipv6.conf.all.disable_ipv6=1",
"sysctl -w net.ipv6.conf.wlan0.accept_ra=0")
)
Logger.logInfo("IPv6 disabled", findContext())
prefs.putInt(K.PREF.NET_IPV6_STATE, 0)
}
}
}
binding.prefer5ghz.apply {
isEnabled = supportsWifi5 && isRooted
setChecked(preferredWifiBand == "1")
setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand("settings put global wifi_frequency_band 1")
Logger.logInfo("Set preferred Wi-Fi frequency band to 5GHz", findContext())
} else {
runCommand("settings put global wifi_frequency_band 0")
Logger.logInfo("Set preferred Wi-Fi frequency band to auto", findContext())
}
}
}
binding.zipalign.apply {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { // Real OG's
show()
}
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_ZIPALIGN, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_ZIPALIGN, isChecked)
if (isChecked) {
Logger.logInfo("Zipalign enabled", findContext())
RootUtils.runInternalScriptAsync("zipalign_tweak", findContext())
} else {
Logger.logInfo("Zipalign disabled", findContext())
}
}
}
binding.kernelOptions.apply {
isEnabled = isRooted
setOnClickListener {
findNavController().navigate(R.id.startKernelOptionsFragment)
}
}
}
}
}
override fun onResume() {
super.onResume()
animViewModel.setAnimRes(R.raw.tools_anim)
}
private fun setUpControls(isRooted: Boolean) {
binding.kernelPanic.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_KERNEL_PANIC, true))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_KERNEL_PANIC, isChecked)
if (isChecked) {
runCommands(
"sysctl -w kernel.panic=5",
"sysctl -w kernel.panic_on_oops=1",
"sysctl -w kernel.panic=1",
"sysctl -w vm.panic_on_oom=1"
)
Snackbar.make(this, R.string.done, Snackbar.LENGTH_SHORT).apply {
view.translationY = (54.dp) * -1
show()
}
Logger.logInfo("Kernel panic enabled", findContext())
} else {
runCommands(
"sysctl -w kernel.panic=0",
"sysctl -w kernel.panic_on_oops=0",
"sysctl -w kernel.panic=0",
"sysctl -w vm.panic_on_oom=0"
)
Snackbar.make(this, R.string.panic_off, Snackbar.LENGTH_SHORT).apply {
view.translationY = (54.dp) * -1
show()
}
Logger.logInfo("Kernel panic disabled", findContext())
}
}
}
binding.disableLogging.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_LOGCAT, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_LOGCAT, isChecked)
if (isChecked) {
Logger.logInfo("Android logging disabled", findContext())
runCommand("stop logd")
} else {
Logger.logInfo("Android logging re-enabled", findContext())
runCommand("start logd")
}
}
}
}
private fun setUpNetControls(isRooted: Boolean) {
binding.tcp.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_TCP, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_TCP, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("net", findContext())
Logger.logInfo("TCP tweaks added", findContext())
} else {
Logger.logInfo("TCP tweaks removed", findContext())
}
}
}
binding.signal.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_SIGNAL, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_SIGNAL, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("3g_on", findContext())
Logger.logInfo("Added signal tweaks", findContext())
} else {
Logger.logInfo("Removed signal tweaks", findContext())
}
}
}
binding.browsing.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_BUFFERS, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_BUFFERS, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("buffer_on", findContext())
} else {
Logger.logInfo("Removed buffer tweaks", findContext())
}
}
}
binding.stream.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_STREAM_TWEAKS, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_STREAM_TWEAKS, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("st_on", findContext())
} else {
Logger.logInfo("Removed video streaming tweaks", findContext())
}
}
}
binding.hostnameButton.apply {
isEnabled = isRooted
setOnClickListener {
val hostname = binding.hostnameField.text.toString().trim().replace(" ", "")
if (hostname.isEmpty()) {
Utils.showEmptyInputFieldSnackbar(binding.hostnameField)
} else {
val log = "Hostname set to: $hostname"
runCommand("setprop net.hostname $hostname")
Logger.logInfo(log, applicationContext)
requireContext().toast(log)
userPrefs.putString(K.PREF.NET_HOSTNAME, hostname)
}
}
}
}
private fun setUpSwipes(isRooted: Boolean) {
if (isRooted) return
binding.warningLayout.show()
binding.noRootWarning.updateLayoutParams<CoordinatorLayout.LayoutParams> {
behavior = SwipeDismissBehavior<AppCompatTextView>().apply {
setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_ANY)
listener = object : SwipeDismissBehavior.OnDismissListener {
override fun onDismiss(view: View?) {
if (binding.warningLayout.childCount == 1) {
binding.warningLayout.goAway()
view?.goAway()
} else {
view?.goAway()
}
}
override fun onDragStateChanged(state: Int) {}
}
}
}
}
} | app/src/main/java/com/androidvip/hebf/ui/main/tools/ToolsFragment2.kt | 3329601640 |
package com.ghstudios.android.features.skills.detail
import androidx.lifecycle.Observer
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AppSettings
import com.ghstudios.android.data.classes.Armor
import com.ghstudios.android.BasePagerActivity
import com.ghstudios.android.MenuSection
import com.ghstudios.android.mhgendatabase.R
class SkillTreeDetailPagerActivity : BasePagerActivity() {
companion object {
/**
* A key for passing a monster ID as a long
*/
const val EXTRA_SKILLTREE_ID = "com.daviancorp.android.android.ui.detail.skill_id"
}
/**
* Viewmodel for the entirity of this skill detail, including sub fragments
*/
private val viewModel by lazy {
ViewModelProvider(this).get(SkillDetailViewModel::class.java)
}
override fun onAddTabs(tabs: BasePagerActivity.TabAdder) {
val skillTreeId = intent.getLongExtra(EXTRA_SKILLTREE_ID, -1)
viewModel.setSkillTreeId(skillTreeId, showPenalties=AppSettings.showSkillPenalties)
viewModel.skillTreeData.observe(this, Observer { data ->
if (data != null) {
this.title = data.name
}
})
tabs.addTab(R.string.skill_tab_detail) {
SkillTreeDetailFragment.newInstance(skillTreeId)
}
tabs.addTab(R.string.type_decoration) {
SkillTreeDecorationFragment.newInstance(skillTreeId)
}
tabs.addTab(R.string.skill_tab_head) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_HEAD)
}
tabs.addTab(R.string.skill_tab_body) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_BODY)
}
tabs.addTab(R.string.skill_tab_arms) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_ARMS)
}
tabs.addTab(R.string.skill_tab_waist) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_WAIST)
}
tabs.addTab(R.string.skill_tab_legs) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_LEGS)
}
}
override fun getSelectedSection(): Int {
return MenuSection.SKILL_TREES
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu) // will inflate global actions like search
menuInflater.inflate(R.menu.menu_skill_detail, menu)
menu.findItem(R.id.show_negative).isChecked = AppSettings.showSkillPenalties
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle superclass cases first. If handled, return immediately
val handled = super.onOptionsItemSelected(item)
if (handled) {
return true
}
return when (item.itemId) {
R.id.show_negative -> {
val newSetting = !AppSettings.showSkillPenalties
AppSettings.showSkillPenalties = newSetting
viewModel.setShowPenalties(newSetting)
item.isChecked = newSetting
true
}
else -> false
}
}
}
| app/src/main/java/com/ghstudios/android/features/skills/detail/SkillTreeDetailPagerActivity.kt | 1172057024 |
package ee.lang.fx.view
import ee.task.Task
import javafx.application.Platform
import tornadofx.View
import tornadofx.tab
import tornadofx.tabpane
class OptionsContainerView : View("OptionsContainerView") {
val tasksController: TasksController by inject()
override val root = tabpane {}
fun consoleTab(task: Task): ConsoleView {
val ret = ConsoleView(task.name)
Platform.runLater {
with(root) {
tab(task.name, ret.root)
}
}
return ret
}
}
| ee-lang_fx/src/main/kotlin/ee/lang/fx/view/OptionsContainerView.kt | 2708707401 |
package net.yested.core.html
import net.yested.core.properties.bind
import net.yested.core.properties.Property
import net.yested.core.properties.ReadOnlyProperty
import net.yested.core.properties.map
import net.yested.core.properties.zip
import net.yested.core.utils.*
import org.w3c.dom.*
import kotlin.browser.document
/**
* Property binding to HTML elements.
* @author Eric Pabst ([email protected])
* Date: 2/2/17
* Time: 11:00 PM
*/
fun HTMLInputElement.bind(property: Property<String>) {
var updating = false
property.onNext {
if (!updating) {
value = it
}
}
addEventListener("change", { updating = true; property.set(value); updating = false }, false)
addEventListener("keyup", { updating = true; property.set(value); updating = false }, false)
}
fun HTMLTextAreaElement.bind(property: Property<String>) {
var updating = false
property.onNext {
if (!updating) {
value = it
}
}
addEventListener("change", { updating = true; property.set(value); updating = false }, false)
addEventListener("keyup", { updating = true; property.set(value); updating = false }, false)
}
fun HTMLInputElement.bindChecked(checked: Property<Boolean>) {
val element = this
var updating = false
checked.onNext {
if (!updating) {
element.checked = it
}
}
addEventListener("change", { updating = true; checked.set(element.checked); updating = false }, false)
}
fun <T> HTMLSelectElement.bindMultiselect(selected: Property<List<T>>, options: ReadOnlyProperty<List<T>>, render: HTMLElement.(T)->Unit) {
bindMultiselect(selected, options, { selected.set(it) }, render)
}
fun <T> HTMLSelectElement.bindMultiselect(selected: ReadOnlyProperty<List<T>>, options: ReadOnlyProperty<List<T>>, onSelect: (List<T>) -> Unit, render: HTMLElement.(T)->Unit) {
val selectElement = this
options.onNext {
removeAllChildElements()
it.forEachIndexed { index, item ->
val option: HTMLOptionElement = document.createElement("option").asDynamic()
option.value = "$index"
option.render(item)
appendChild(option)
}
}
var updating = false
selected.zip(options).onNext { (selectedList, options) ->
if (!updating) {
options.forEachIndexed { index, option ->
if (index < selectElement.options.length) {
(selectElement.options.get(index) as HTMLOptionElement).selected = selectedList.contains(option)
}
}
}
}
addEventListener("change", {
val selectOptions = this.options
val selectedValues = (1..selectOptions.length)
.map { selectOptions[it - 1] }
.filter { (it as HTMLOptionElement).selected }
.map { (it as HTMLOptionElement).value }
.map { options.get()[it.toInt()] }
updating = true
onSelect.invoke(selectedValues)
updating = false
}, false)
}
fun <T> HTMLSelectElement.bind(selected: Property<T>, options: ReadOnlyProperty<List<T>>, render: HTMLElement.(T)->Unit) {
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
val multipleSelected = selected.bind({ if (it == null) emptyList<T>() else listOf(it) }, { it.firstOrNull() as T })
bindMultiselect(multipleSelected, options, render)
}
fun <T> HTMLSelectElement.bind(selected: ReadOnlyProperty<T>, options: ReadOnlyProperty<List<T>>, onSelect: (T) -> Unit, render: HTMLElement.(T)->Unit) {
val multiSelected: ReadOnlyProperty<List<T>> = selected.map { if (it == null) emptyList() else listOf(it) }
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
bindMultiselect(multiSelected, options, { onSelect(it.firstOrNull() as T) }, render)
}
fun <T> HTMLSelectElement.bindOptional(selected: ReadOnlyProperty<T?>, options: ReadOnlyProperty<List<T>>, onSelect: (T) -> Unit, render: HTMLElement.(T)->Unit) {
val multiSelected: ReadOnlyProperty<List<T>> = selected.map { if (it == null) emptyList() else listOf(it) }
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
bindMultiselect(multiSelected, options, { onSelect(it.firstOrNull() as T) }, render)
}
fun HTMLElement.setClassPresence(className: String, present: ReadOnlyProperty<Boolean>) {
setClassPresence(className, present, true)
}
fun <T> HTMLElement.setClassPresence(className: String, property: ReadOnlyProperty<T>, presentValue: T) {
property.onNext {
if (it == presentValue) addClass2(className) else removeClass2(className)
}
}
fun HTMLButtonElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLInputElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLTextAreaElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLSelectElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLFieldSetElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLInputElement.setReadOnly(property: ReadOnlyProperty<Boolean>) {
property.onNext { readOnly = it }
}
fun HTMLTextAreaElement.setReadOnly(property: ReadOnlyProperty<Boolean>) {
property.onNext { readOnly = it }
}
/** This exists because Kotlin's ArrayList calls throwCCE() if a non-null Element doesn't extend "Any". */
private data class ElementWrapper(val element: Element?)
private fun HTMLCollection.toWrapperList(): List<ElementWrapper> {
return (0..(this.length - 1)).map { ElementWrapper(item(it)) }
}
fun <C: HTMLElement,T> C.repeatLive(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect, itemInit: C.(T) -> Unit) {
return repeatLive(orderedData, effect, { _, item -> itemInit(item) })
}
fun <C: HTMLElement,T> C.repeatLive(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect, itemInit: C.(Int, T) -> Unit) {
val containerElement = this
val itemsWithoutDelays = mutableListOf<List<ElementWrapper>>()
var operableList : DomOperableList<C,T>? = null
var elementAfter: HTMLElement? = null
orderedData.onNext { values ->
val operableListSnapshot = operableList
if (values == null) {
itemsWithoutDelays.flatten().forEach {
if (it.element?.parentElement == containerElement) {
containerElement.removeChild(it.element)
}
}
itemsWithoutDelays.clear()
operableList = null
} else if (operableListSnapshot == null) {
itemsWithoutDelays.flatten().forEach {
if (it.element?.parentElement == containerElement) {
containerElement.removeChild(it.element)
}
}
itemsWithoutDelays.clear()
val domOperableList = DomOperableList(values.toMutableList(), itemsWithoutDelays, containerElement, effect, elementAfter, itemInit)
values.forEachIndexed { index, item ->
domOperableList.addItemToContainer(containerElement, index, item, itemsWithoutDelays, elementAfter)
}
operableList = domOperableList
} else {
operableListSnapshot.reconcileTo(values.toList())
}
}
elementAfter = span() // create a <span/> to clearly indicate where to insert new elements.
operableList?.elementAfter = elementAfter
}
private class DomOperableList<C : HTMLElement,T>(
initialData: MutableList<T>,
val itemsWithoutDelays: MutableList<List<ElementWrapper>>,
val container: C,
val effect: BiDirectionEffect,
var elementAfter: HTMLElement? = null,
val itemInit: C.(Int, T) -> Unit) : InMemoryOperableList<T>(initialData) {
override fun add(index: Int, item: T) {
addItemToContainer(container, index, item, itemsWithoutDelays, elementAfter).forEach { if (it.element is HTMLElement) effect.applyIn(it.element) }
super.add(index, item)
}
override fun removeAt(index: Int): T {
val elementsForIndex = itemsWithoutDelays.removeAt(index)
elementsForIndex.forEach {
if (it.element is HTMLElement) {
effect.applyOut(it.element) {
if (it.element.parentElement == container) {
container.removeChild(it.element)
}
}
} else if (it.element?.parentElement == container) {
container.removeChild(it.element)
}
}
return super.removeAt(index)
}
override fun move(fromIndex: Int, toIndex: Int) {
val item = removeAt(fromIndex)
add(toIndex, item)
}
fun addItemToContainer(container: C, index: Int, item: T, itemsWithoutDelays: MutableList<List<ElementWrapper>>, elementAfter: HTMLElement?): List<ElementWrapper> {
val nextElement = if (index < itemsWithoutDelays.size) itemsWithoutDelays.get(index).firstOrNull()?.element else elementAfter
val childrenBefore = container.children.toWrapperList()
container.itemInit(index, item)
val childrenLater = container.children.toWrapperList()
val newChildren = childrenLater.filterNot { childrenBefore.contains(it) }
if (nextElement != null && nextElement.parentElement == container) {
newChildren.forEach { it.element?.let { container.insertBefore(it, nextElement) } }
}
itemsWithoutDelays.add(index, newChildren)
return newChildren
}
}
/**
* Bind table content to a Property<Iterable<T>>. The index and value are provided to itemInit.
* Example:<pre>
* table {
* thead {
* th { appendText("Name") }
* th { appendText("Value") }
* }
* tbody(myData, effect = Collapse()) { index, item ->
* tr { className = if (index % 2 == 0) "even" else "odd"
* td { appendText(item.name) }
* td { appendText(item.value) }
* }
* }
* }
* </pre>
*/
fun <T> HTMLTableElement.tbody(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect,
itemInit: HTMLTableSectionElement.(Int, T) -> Unit) {
tbody { repeatLive(orderedData, effect, itemInit) }
}
/**
* Bind table content to a Property<Iterable<T>>. The value is provided to itemInit.
* Example:<pre>
* table {
* thead {
* th { appendText("Name") }
* th { appendText("Value") }
* }
* tbody(myData, effect = Collapse()) { item ->
* tr { className = if (index % 2 == 0) "even" else "odd"
* td { appendText(item.name) }
* td { appendText(item.value) }
* }
* }
* }
* </pre>
*/
fun <T> HTMLTableElement.tbody(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect,
itemInit: HTMLTableSectionElement.(T) -> Unit): HTMLTableSectionElement {
return tbody { repeatLive(orderedData, effect, itemInit) }
}
| src/jsMain/kotlin/net/yested/core/html/htmlbind.kt | 3458676256 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.screens.home
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.homesampleapp.*
import com.google.homesampleapp.databinding.DeviceViewItemBinding
import timber.log.Timber
/**
* ViewHolder for a device item in the devices list, which is backed by RecyclerView. The ViewHolder
* is a wrapper around a View that contains the layout for an individual item in the list.
*
* When the view holder is created, it doesn't have any data associated with it. After the view
* holder is created, the RecyclerView binds it to its data. The RecyclerView requests those views,
* and binds the views to their data, by calling methods in the adapter (see DevicesAdapter).
*/
class DeviceViewHolder(private val binding: DeviceViewItemBinding) :
RecyclerView.ViewHolder(binding.root) {
// TODO: Can't this be cached somewhere?
private val lightBulbIcon = getResourceId("quantum_gm_ic_lights_gha_vd_theme_24")
private val outletIcon = getResourceId("ic_baseline_outlet_24")
private val unknownDeviceIcon = getResourceId("ic_baseline_device_unknown_24")
private val shapeOffDrawable = getDrawable("device_item_shape_off")
private val shapeOnDrawable = getDrawable("device_item_shape_on")
/**
* Binds the Device (DeviceUiModel, the model class) to the UI element (device_view_item.xml) that
* holds the Device view.
*
* TODO: change icon
* https://stackoverflow.com/questions/16906528/change-image-of-imageview-programmatically-in-android
*/
fun bind(deviceUiModel: DeviceUiModel) {
Timber.d("binding device [${deviceUiModel}]")
val iconResourceId =
when (deviceUiModel.device.deviceType) {
Device.DeviceType.TYPE_LIGHT -> lightBulbIcon
Device.DeviceType.TYPE_OUTLET -> outletIcon
else -> unknownDeviceIcon
}
val shapeDrawable =
if (deviceUiModel.isOnline && deviceUiModel.isOn) shapeOnDrawable else shapeOffDrawable
binding.zeicon.setImageResource(iconResourceId)
binding.name.text = deviceUiModel.device.name
binding.zestate.text = stateDisplayString(deviceUiModel.isOnline, deviceUiModel.isOn)
binding.rootLayout.background = shapeDrawable
if (ON_OFF_SWITCH_DISABLED_WHEN_DEVICE_OFFLINE) {
binding.onoffSwitch.isEnabled = deviceUiModel.isOnline
} else {
binding.onoffSwitch.isEnabled = true
}
binding.onoffSwitch.isChecked = deviceUiModel.isOn
}
private fun getDrawable(name: String): Drawable? {
val resources: Resources = itemView.context.resources
val resourceId = resources.getIdentifier(name, "drawable", itemView.context.packageName)
return resources.getDrawable(resourceId)
}
private fun getResourceId(name: String): Int {
val resources: Resources = itemView.context.resources
return resources.getIdentifier(name, "drawable", itemView.context.packageName)
}
companion object {
fun create(parent: ViewGroup): DeviceViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.device_view_item, parent, false)
val binding = DeviceViewItemBinding.bind(view)
return DeviceViewHolder(binding)
}
}
}
| app/src/main/java/com/google/homesampleapp/screens/home/DeviceViewHolder.kt | 2444720430 |
package com.lasthopesoftware.bluewater.settings
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.RadioGroup
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.about.AboutTitleBuilder
import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.BrowserLibrarySelection
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineType
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineTypeSelectionPersistence
import com.lasthopesoftware.bluewater.client.playback.engine.selection.SelectedPlaybackEngineTypeAccess
import com.lasthopesoftware.bluewater.client.playback.engine.selection.broadcast.PlaybackEngineTypeChangedBroadcaster
import com.lasthopesoftware.bluewater.client.playback.engine.selection.defaults.DefaultPlaybackEngineLookup
import com.lasthopesoftware.bluewater.client.playback.engine.selection.view.PlaybackEngineTypeSelectionView
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService
import com.lasthopesoftware.bluewater.client.servers.list.ServerListAdapter
import com.lasthopesoftware.bluewater.client.servers.list.listeners.EditServerClickListener
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.android.notifications.notificationchannel.SharedChannelProperties
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import com.lasthopesoftware.bluewater.tutorials.TutorialManager
import tourguide.tourguide.Overlay
import tourguide.tourguide.Pointer
import tourguide.tourguide.ToolTip
import tourguide.tourguide.TourGuide
class ApplicationSettingsActivity : AppCompatActivity() {
private val channelConfiguration: SharedChannelProperties by lazy { SharedChannelProperties(this) }
private val progressBar = LazyViewFinder<ProgressBar>(this, R.id.recyclerLoadingProgress)
private val serverListView = LazyViewFinder<RecyclerView>(this, R.id.loadedRecyclerView)
private val notificationSettingsContainer = LazyViewFinder<LinearLayout>(this, R.id.notificationSettingsContainer)
private val modifyNotificationSettingsButton = LazyViewFinder<Button>(this, R.id.modifyNotificationSettingsButton)
private val addServerButton = LazyViewFinder<Button>(this, R.id.addServerButton)
private val killPlaybackEngineButton = LazyViewFinder<Button>(this, R.id.killPlaybackEngine)
private val settingsMenu = SettingsMenu(this, AboutTitleBuilder(this))
private val applicationSettingsRepository by lazy { getApplicationSettingsRepository() }
private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) }
private val tutorialManager by lazy { TutorialManager(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_application_settings)
setSupportActionBar(findViewById(R.id.applicationSettingsToolbar))
HandleSyncCheckboxPreference.handle(
applicationSettingsRepository,
{ s -> s.isSyncOnPowerOnly },
{ s -> s::isSyncOnPowerOnly::set },
findViewById(R.id.syncOnPowerCheckbox))
HandleSyncCheckboxPreference.handle(
applicationSettingsRepository,
{ it.isSyncOnWifiOnly },
{ s -> s::isSyncOnWifiOnly::set },
findViewById(R.id.syncOnWifiCheckbox))
HandleCheckboxPreference.handle(
applicationSettingsRepository,
{ it.isVolumeLevelingEnabled },
{ s -> s::isVolumeLevelingEnabled::set },
findViewById(R.id.isVolumeLevelingEnabled))
val selection = PlaybackEngineTypeSelectionPersistence(
applicationSettingsRepository,
PlaybackEngineTypeChangedBroadcaster(MessageBus(LocalBroadcastManager.getInstance(this))))
val selectedPlaybackEngineTypeAccess = SelectedPlaybackEngineTypeAccess(applicationSettingsRepository, DefaultPlaybackEngineLookup())
val playbackEngineTypeSelectionView = PlaybackEngineTypeSelectionView(this)
val playbackEngineOptions = findViewById<RadioGroup>(R.id.playbackEngineOptions)
for (i in 0 until playbackEngineOptions.childCount)
playbackEngineOptions.getChildAt(i).isEnabled = false
for (rb in playbackEngineTypeSelectionView.buildPlaybackEngineTypeSelections())
playbackEngineOptions.addView(rb)
selectedPlaybackEngineTypeAccess.promiseSelectedPlaybackEngineType()
.eventually(LoopedInPromise.response({ t ->
playbackEngineOptions.check(t.ordinal)
for (i in 0 until playbackEngineOptions.childCount)
playbackEngineOptions.getChildAt(i).isEnabled = true
}, this))
playbackEngineOptions
.setOnCheckedChangeListener { _, checkedId -> selection.selectPlaybackEngine(PlaybackEngineType.values()[checkedId]) }
killPlaybackEngineButton.findView().setOnClickListener { PlaybackService.killService(this) }
addServerButton.findView().setOnClickListener(EditServerClickListener(this, -1))
updateServerList()
notificationSettingsContainer.findView().visibility = View.GONE
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
notificationSettingsContainer.findView().visibility = View.VISIBLE
tutorialManager
.promiseWasTutorialShown(TutorialManager.KnownTutorials.adjustNotificationInApplicationSettingsTutorial)
.eventually(LoopedInPromise.response({ wasTutorialShown ->
if (wasTutorialShown) {
modifyNotificationSettingsButton.findView().setOnClickListener { launchNotificationSettings() }
} else {
val displayColor = getColor(R.color.clearstream_blue)
val tourGuide = TourGuide.init(this).with(TourGuide.Technique.CLICK)
.setPointer(Pointer().setColor(displayColor))
.setToolTip(ToolTip()
.setTitle(getString(R.string.notification_settings_tutorial_title))
.setDescription(getString(R.string.notification_settings_tutorial).format(
getString(R.string.modify_notification_settings),
getString(R.string.app_name)))
.setBackgroundColor(displayColor))
.setOverlay(Overlay())
.playOn(modifyNotificationSettingsButton.findView())
modifyNotificationSettingsButton.findView().setOnClickListener {
tourGuide.cleanUp()
launchNotificationSettings()
}
tutorialManager.promiseTutorialMarked(TutorialManager.KnownTutorials.adjustNotificationInApplicationSettingsTutorial)
}
}, this))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean = settingsMenu.buildSettingsMenu(menu)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
updateServerList()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = settingsMenu.handleSettingsMenuClicks(item)
@RequiresApi(api = Build.VERSION_CODES.O)
private fun launchNotificationSettings() {
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelConfiguration.channelId)
startActivity(intent)
}
private fun updateServerList() {
serverListView.findView().visibility = View.INVISIBLE
progressBar.findView().visibility = View.VISIBLE
val libraryProvider = LibraryRepository(this)
val promisedLibraries = libraryProvider.allLibraries
val promisedSelectedLibrary = SelectedBrowserLibraryIdentifierProvider(applicationSettingsRepository).selectedLibraryId
val adapter = ServerListAdapter(
this,
BrowserLibrarySelection(applicationSettingsRepository, messageBus, libraryProvider))
val serverListView = serverListView.findView()
serverListView.adapter = adapter
serverListView.layoutManager = LinearLayoutManager(this)
promisedLibraries
.eventually { libraries ->
promisedSelectedLibrary
.eventually(LoopedInPromise.response({ chosenLibraryId ->
val selectedBrowserLibrary = libraries.firstOrNull { l -> l.libraryId == chosenLibraryId }
adapter.updateLibraries(libraries, selectedBrowserLibrary)
progressBar.findView().visibility = View.INVISIBLE
serverListView.visibility = View.VISIBLE
}, this))
}
}
companion object {
fun launch(context: Context) =
context.startActivity(Intent(context, ApplicationSettingsActivity::class.java))
}
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/settings/ApplicationSettingsActivity.kt | 1019949743 |
package io.kotest.runner.console
import com.github.ajalt.mordant.TermColors
import io.kotest.core.StringTag
import io.kotest.core.Tag
import net.sourceforge.argparse4j.ArgumentParsers
import kotlin.system.exitProcess
// this main method will launch the KotestConsoleRunner
fun main(args: Array<String>) {
val parser = ArgumentParsers.newFor("kotest").build().defaultHelp(true).description("Kotest console runner")
parser.addArgument("--test").help("Specify the test name to execute (can be a leaf test or a container test)")
parser.addArgument("--spec").help("Specify the fully qualified name of the spec class which contains the test to execute")
parser.addArgument("--writer").help("Specify the name of console writer implementation. Defaults TeamCity")
parser.addArgument("--source").help("Optional string describing how the launcher was invoked")
parser.addArgument("--slow-duration").help("Optional time in millis controlling when a test is marked as slow")
parser.addArgument("--very-slow-duration").help("Optional time in millis controlling when a test is marked as very slow")
// parser.addArgument("--max-test-duration").help("Optional time in millis controlling when the duration of a test should be marked as an error")
parser.addArgument("--include-tags").help("Optional string setting which tags to be included")
parser.addArgument("--exclude-tags").help("Optional string setting which tags to be excluded")
val ns = parser.parseArgs(args)
val writerClass: String? = ns.getString("writer")
val spec: String? = ns.getString("spec")
val test: String? = ns.getString("test")
val source: String? = ns.getString("source")
val includeTags: Set<Tag> = ns.getString("include-tags")?.split(',')?.map {
StringTag(
it
)
}?.toSet() ?: emptySet()
val excludeTags: Set<Tag> = ns.getString("exclude-tags")?.split(',')?.map {
StringTag(
it
)
}?.toSet() ?: emptySet()
val slowDuration: Int = ns.getString("slow-duration")?.toInt() ?: 1000
val verySlowDuration: Int = ns.getString("very-slow-duration")?.toInt() ?: 3000
// val maxTestDuration: Int = ns.getString("max-test-duration")?.toInt() ?: 0
val term = if (source == "kotest-gradle-plugin") TermColors(TermColors.Level.ANSI256) else TermColors()
val writer = when (writerClass) {
"mocha" -> MochaConsoleWriter(term, slowDuration, verySlowDuration)
"basic" -> BasicConsoleWriter()
else -> TeamCityConsoleWriter()
}
val runner = KotestConsoleRunner(writer)
runner.execute(spec, test, includeTags, excludeTags)
// there could be threads in the background that will stop the launcher shutting down
// for example if a test keeps a thread running
// so we must force the exit
if (writer.hasErrors()) exitProcess(-1) else exitProcess(0)
}
// returns a console writer appropriate for the environment when none was specified
// attempts to find the idea_rt.jar and if it exists, we assume we are running from intellij, and thus
// change our output to be an IDEA compatible team city writer
// otherwise we use the default colour writer
fun defaultWriter(): ConsoleWriter = try {
Class.forName("com.intellij.rt.execution.CommandLineWrapper")
TeamCityConsoleWriter()
} catch (_: ClassNotFoundException) {
BasicConsoleWriter()
}
| kotest-runner/kotest-runner-console/src/jvmMain/kotlin/io/kotest/runner/console/launcher.kt | 326769559 |
/*
* Copyright (C) 2016 Mihály Szabó
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.component.replicator
import dagger.Component
import org.libreplicator.component.LibReplicatorTestComponent
import org.libreplicator.module.replicator.ReplicatorModule
@ReplicatorScope
@Component(dependencies = [ LibReplicatorTestComponent::class ], modules = [ ReplicatorModule::class ])
interface ReplicatorTestComponent : ReplicatorComponent
| libreplicator/src/test/kotlin/org/libreplicator/component/replicator/ReplicatorTestComponent.kt | 3216684494 |
package com.newsblur.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.newsblur.databinding.StateToggleBinding
import com.newsblur.util.StateFilter
import com.newsblur.util.UIUtils
import com.newsblur.util.setViewGone
import com.newsblur.util.setViewVisible
class StateToggleButton(context: Context, art: AttributeSet?) : LinearLayout(context, art) {
private var state = StateFilter.SOME
private var stateChangedListener: StateChangedListener? = null
private val binding: StateToggleBinding
init {
binding = StateToggleBinding.inflate(LayoutInflater.from(context), this, true)
setState(state)
binding.toggleAll.setOnClickListener { setState(StateFilter.ALL) }
binding.toggleSome.setOnClickListener { setState(StateFilter.SOME) }
binding.toggleFocus.setOnClickListener { setState(StateFilter.BEST) }
binding.toggleSaved.setOnClickListener { setState(StateFilter.SAVED) }
}
fun setStateListener(stateChangedListener: StateChangedListener?) {
this.stateChangedListener = stateChangedListener
}
fun setState(state: StateFilter) {
this.state = state
updateButtonStates()
stateChangedListener?.changedState(this.state)
}
private fun updateButtonStates() {
binding.toggleAll.isEnabled = state != StateFilter.ALL
binding.toggleSome.isEnabled = state != StateFilter.SOME
binding.toggleSomeIcon.alpha = if (state == StateFilter.SOME) 1.0f else 0.6f
binding.toggleFocus.isEnabled = state != StateFilter.BEST
binding.toggleFocusIcon.alpha = if (state == StateFilter.BEST) 1.0f else 0.6f
binding.toggleSaved.isEnabled = state != StateFilter.SAVED
binding.toggleSavedIcon.alpha = if (state == StateFilter.SAVED) 1.0f else 0.6f
val widthDp = UIUtils.px2dp(context, context.resources.displayMetrics.widthPixels)
if (widthDp > 450) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewVisible()
binding.toggleSavedText.setViewVisible()
} else if (widthDp > 400) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewVisible()
binding.toggleSavedText.setViewGone()
} else if (widthDp > 350) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewGone()
binding.toggleSavedText.setViewGone()
} else {
binding.toggleSomeText.setViewGone()
binding.toggleFocusText.setViewGone()
binding.toggleSavedText.setViewGone()
}
}
interface StateChangedListener {
fun changedState(state: StateFilter?)
}
} | clients/android/NewsBlur/src/com/newsblur/view/StateToggleButton.kt | 34739845 |
package com.jetbrains.rider.plugins.unity.ui
import com.intellij.ide.plugins.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.jetbrains.rider.plugins.unity.isUnityProject
class UssDisabledEditorNotification: EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY = Key.create<EditorNotificationPanel>("unity.uss.css.plugin.disabled.notification.panel")
private const val DO_NOT_SHOW_AGAIN_KEY = "unity.uss.css.plugin.disabled.do.not.show"
private const val CSS_PLUGIN_ID = "com.intellij.css"
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (project.isUnityProject() && isUssFileSafe(file) && PluginManagerCore.isDisabled(PluginId.getId(CSS_PLUGIN_ID))) {
if (PropertiesComponent.getInstance(project).getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
return null
}
val panel = EditorNotificationPanel()
panel.text(UnityUIBundle.message("uss.disabled.editor.notification.panel.text"))
panel.createActionLabel(UnityUIBundle.message("uss.disabled.editor.notification.enable.css.plugin")) {
// TODO: Maybe in 2020.2 we can do this dynamically without restart?
// That would require enabling the CSS plugin dynamically, and then enabling our PluginCssPart.xml part
// dynamically, too
PluginManagerCore.enablePlugin(PluginId.getId(CSS_PLUGIN_ID))
PluginManagerMain.notifyPluginsUpdated(project)
EditorNotifications.getInstance(project).updateAllNotifications()
}
panel.createActionLabel(UnityUIBundle.message("don.t.show.again")) {
// Project level - do not show again for this project
PropertiesComponent.getInstance(project).setValue(DO_NOT_SHOW_AGAIN_KEY, true)
EditorNotifications.getInstance(project).updateAllNotifications()
}
return panel
}
return null
}
private fun isUssFileSafe(file: VirtualFile): Boolean {
// We can't check for UssFileType because it won't be loaded. The file type is part of the USS language, which
// derives from CSSLanguage, which will be unavailable.
return file.extension.equals("uss", true)
}
} | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ui/UssDisabledEditorNotification.kt | 4152209630 |
package github.nisrulz.example.splitsigninconfig
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import github.nisrulz.example.splitsigninconfig.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
with(binding) {
setContentView(root)
}
}
}
| SplitSigninConfig/app/src/main/java/github/nisrulz/example/splitsigninconfig/MainActivity.kt | 2577879524 |
package net.println.kt13.module
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import retrofit2.Converter
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
/**
* Created by benny on 12/11/16.
*/
@Module(includes = arrayOf(GsonModule::class))
class GsonConverterModule {
@Singleton @Provides fun converter(gson: Gson): Converter.Factory = GsonConverterFactory.create(gson)
} | app/src/main/java/com/dgrlucky/extend/kotlin/_restful/module/GsonConverterModule.kt | 4078859745 |
/*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* 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,
* THE SOFTWARE.
*/
package tests.api.get
import nl.komponents.kovenant.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
import kotlin.test.assertEquals
import kotlin.test.fail
class GetTest {
@Before fun setup() {
Kovenant.testMode {
fail(it.message)
}
}
@Test fun successResult() {
val promise = Promise.of(13)
assertEquals(13, promise.get(), "should return the proper value")
}
@Test fun errorResult() {
val promise = Promise.ofFail<Int, Int>(13)
assertEquals(13, promise.getError(), "should return the proper value")
}
@Test fun nullSuccessResult() {
val promise = Promise.of(null)
assertEquals(null, promise.get(), "should return null")
}
@Test fun nullErrorResult() {
val promise = Promise.ofFail<Int, Int?>(null)
assertEquals(null, promise.getError(), "should return null")
}
@Test fun failResultException() {
val promise = Promise.ofFail<Int, Exception>(Exception("bummer"))
var thrown : Boolean
try {
promise.get()
fail("Should not be reachable")
} catch(e: FailedException) {
fail("Exception should not be wrapped")
} catch(e: Exception) {
thrown = true
}
assert(thrown) { "should throw an exception" }
}
@Test fun failResultValue() {
val promise = Promise.ofFail<Int, String>("bummer")
var thrown : Boolean
try {
promise.get()
fail("Should not be reachable")
} catch(e: FailedException) {
thrown = true
} catch(e: Exception) {
fail("Should be of type FailedException")
}
assert(thrown) { "should throw a FailedException" }
}
}
class GetAsyncTest {
@Before fun setup() {
Kovenant.context {
val dispatcher = buildDispatcher { concurrentTasks = 1 }
callbackContext.dispatcher = dispatcher
workerContext.dispatcher = dispatcher
}
}
@After fun shutdown() {
Kovenant.stop()
}
@Test(timeout = 10000) fun blockingGet() {
val deferred = deferred<Int, Exception>()
verifyBlocking({ deferred.resolve(42) }) {
try {
val i = deferred.promise.get()
assertEquals(42, i, "Should succeed")
} catch(e: Exception) {
fail("Should not fail")
}
}
}
private fun verifyBlocking(trigger: () -> Unit, blockingAction: () -> Unit) {
val startLatch = CountDownLatch(1)
val stopLatch = CountDownLatch(1)
val ref = AtomicReference<Throwable>()
val thread = Thread {
startLatch.countDown()
try {
blockingAction()
} catch (err: Throwable) {
ref.set(err)
} finally {
stopLatch.countDown()
}
}
thread.start()
startLatch.await()
loop@while (true) when (thread.state) {
Thread.State.BLOCKED, Thread.State.WAITING, Thread.State.TIMED_WAITING -> break@loop
Thread.State.TERMINATED -> break@loop
else -> Thread.`yield`()
}
trigger()
stopLatch.await()
val throwable = ref.get()
if (throwable != null) {
throw throwable
}
}
}
| projects/core/src/test/kotlin/tests/api/get.kt | 3980419673 |
package configurations
import common.BuildCache
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildType
import model.CIBuildModel
import model.Stage
open class BaseGradleBuildType(model: CIBuildModel, val stage: Stage? = null, usesParentBuildCache: Boolean = false, init: BaseGradleBuildType.() -> Unit = {}) : BuildType() {
val buildCache: BuildCache = if (usesParentBuildCache) model.parentBuildCache else model.childBuildCache
init {
this.init()
}
}
| .teamcity/Gradle_Check/configurations/BaseGradleBuildType.kt | 1755458415 |
package io.particle.mesh.bluetooth.scanning
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import io.particle.mesh.common.Predicate
import io.particle.mesh.common.Procedure
import mu.KotlinLogging
import java.util.*
class SimpleScanCallback(
private val isResultValid: Predicate<ScanResult?>,
private val scanResultAction: Procedure<List<ScanResult>>
) : ScanCallback() {
private val log = KotlinLogging.logger {}
override fun onScanResult(callbackType: Int, result: ScanResult) {
onBatchScanResults(Collections.singletonList(result))
}
override fun onBatchScanResults(results: List<ScanResult?>) {
scanResultAction(results.filterNotNull().filter(isResultValid))
}
override fun onScanFailed(errorCode: Int) {
when (errorCode) {
ScanCallback.SCAN_FAILED_ALREADY_STARTED,
ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED,
ScanCallback.SCAN_FAILED_INTERNAL_ERROR,
ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED -> {
log.warn { "onScanFailed(), error code=$errorCode" }
}
else -> return
}
}
}
| mesh/src/main/java/io/particle/mesh/bluetooth/scanning/SimpleScanCallback.kt | 3185124071 |
package com.amar.library.ui
import android.os.Build
import android.view.View
import androidx.core.view.ViewCompat
internal object PropertySetter {
fun setTranslationZ(view: View?, translationZ: Float) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.let {
ViewCompat.setTranslationZ(it, translationZ)
}
} else if (translationZ != 0f) {
view?.bringToFront()
if (view?.parent != null) {
(view.parent as View).invalidate()
}
}
}
} | library/src/main/java/com/amar/library/ui/PropertySetter.kt | 934658595 |
package cn.thens.kdroid.upay
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.Serializable
@Suppress("SpellCheckingInspection", "unused")
object WeChatPay : Payment, IWXAPIEventHandler {
private var wxApi: IWXAPI? = null
private var observer: ObservableEmitter<PayResult>? = null
private const val CODE_SUCCESS = 0
private const val CODE_CANCEL = -2
private const val CODE_FAIL = -1
private val gson by lazy { Gson() }
fun initialize(context: Context, appId: String) {
if (wxApi == null) {
val api = WXAPIFactory.createWXAPI(context, appId)
api.registerApp(appId)
wxApi = api
}
}
fun handleIntent(intent: Intent) {
wxApi?.handleIntent(intent, this)
}
override fun pay(activity: Activity, orderInfo: String): Observable<PayResult> {
val api = wxApi
val observable = if (api == null || api.isWXAppInstalled || api.wxAppSupportAPI < Build.PAY_SUPPORTED_SDK_INT) {
Observable.just(PayResult(PayResult.FAIL, "IWXAPI 未初始化"))
} else {
Observable.create<PayResult> {
val order = gson.fromJson(orderInfo, OrderInfo::class.java)
api.sendReq(order.toPayRequest())
observer = it
}
}
return observable
.onErrorReturn { PayResult(PayResult.FAIL, "支付失败: ${it.message}") }
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
}
override fun onResp(resp: BaseResp) {
if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
val status = resp.errCode
val description = resp.errStr
observer?.onNext(when (status) {
CODE_SUCCESS -> PayResult(PayResult.SUCCESS, "支付成功: $status")
CODE_CANCEL -> PayResult(PayResult.CANCEL, "支付已取消: $status")
CODE_FAIL -> PayResult(PayResult.FAIL, "支付失败: $status,$description")
else -> PayResult(PayResult.FAIL, "支付失败: $status,$description")
})
}
}
override fun onReq(req: BaseReq) {
}
data class OrderInfo(
@SerializedName("appid") val appId: String,
@SerializedName("partnerid") val partnerId: String,
@SerializedName("prepayid") val prepayId: String,
@SerializedName("package") val packageValue: String,
@SerializedName("noncestr") val nonceStr: String,
@SerializedName("timestamp") val timestamp: String,
@SerializedName("sign") val sign: String
) : Serializable {
fun toPayRequest(): PayReq {
return PayReq().also {
it.appId = appId
it.partnerId = partnerId
it.prepayId = prepayId
it.packageValue = packageValue
it.nonceStr = nonceStr
it.timeStamp = timestamp
it.sign = sign
}
}
}
class CallbackActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
}
} | upay/src/main/java/cn/thens/kdroid/upay/WeChatPay.kt | 3931883722 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import org.rust.ide.inspections.RsExperimentalChecksInspection
import org.rust.ide.inspections.RsInspectionsTestBase
// Typecheck errors are currently shown via disabled by default inspection,
// but should be shown via error annotator when will be complete
class RsTypeCheckTest : RsInspectionsTestBase(RsExperimentalChecksInspection()) {
fun `test type mismatch E0308 primitive`() = checkByText("""
fn main () {
let _: u8 = <error>1u16</error>;
}
""")
fun `test typecheck in constant`() = checkByText("""
const A: u8 = <error>1u16</error>;
""")
fun `test typecheck in array size`() = checkByText("""
const A: [u8; <error>1u8</error>] = [0];
""")
fun `test typecheck in enum variant discriminant`() = checkByText("""
enum Foo { BAR = <error>1u8</error> }
""")
fun `test type mismatch E0308 coerce ptr mutability`() = checkByText("""
fn fn_const(p: *const u8) { }
fn fn_mut(p: *mut u8) { }
fn main () {
let mut ptr_const: *const u8;
let mut ptr_mut: *mut u8;
fn_const(ptr_const);
fn_const(ptr_mut);
fn_mut(<error>ptr_const</error>);
fn_mut(ptr_mut);
ptr_const = ptr_mut;
ptr_mut = <error>ptr_const</error>;
}
""")
fun `test type mismatch E0308 coerce reference to ptr`() = checkByText("""
fn fn_const(p: *const u8) { }
fn fn_mut(p: *mut u8) { }
fn main () {
let const_u8 = &1u8;
let mut_u8 = &mut 1u8;
fn_const(const_u8);
fn_const(mut_u8);
fn_mut(<error>const_u8</error>);
fn_mut(mut_u8);
}
""")
fun `test type mismatch E0308 struct`() = checkByText("""
struct X; struct Y;
fn main () {
let _: X = <error>Y</error>;
}
""")
fun `test type mismatch E0308 tuple`() = checkByText("""
fn main () {
let _: (u8, ) = (<error>1u16</error>, );
}
""")
// TODO error should be more local
fun `test type mismatch E0308 array`() = checkByText("""
fn main () {
let _: [u8; 1] = <error>[1u16]</error>;
}
""")
fun `test type mismatch E0308 array size`() = checkByText("""
fn main () {
let _: [u8; 1] = <error>[1, 2]</error>;
}
""")
fun `test type mismatch E0308 struct field`() = checkByText("""
struct S { f: u8 }
fn main () {
S { f: <error>1u16</error> };
}
""")
fun `test type mismatch E0308 function parameter`() = checkByText("""
fn foo(_: u8) {}
fn main () {
foo(<error>1u16</error>)
}
""")
fun `test type mismatch E0308 unconstrained integer`() = checkByText("""
struct S;
fn main () {
let mut a = 0;
a = <error>S</error>;
}
""")
// issue #1753
fun `test no type mismatch E0308 for multiple impls of the same trait`() = checkByText("""
pub trait From<T> { fn from(_: T) -> Self; }
struct A; struct B; struct C;
impl From<B> for A { fn from(_: B) -> A { unimplemented!() } }
impl From<C> for A { fn from(_: C) -> A { unimplemented!() } }
fn main() {
A::from(C);
}
""")
// issue #1790
fun `test not type mismatch E0308 with unknown size array`() = checkByText("""
struct Foo {
v: [usize; COUNT]
}
fn main() {
let x = Foo { v: [10, 20] };
}
""")
// issue 1753
fun `test no type mismatch E0308 on struct argument reference coercion`() = checkByText("""
#[lang = "deref"]
trait Deref { type Target; }
struct Wrapper<T>(T);
struct RefWrapper<'a, T : 'a>(&'a T);
impl<T> Deref for Wrapper<T> { type Target = T; }
fn foo(w: &Wrapper<u32>) {
let _: RefWrapper<u32> = RefWrapper(w);
}
""")
}
| src/test/kotlin/org/rust/ide/annotator/RsTypeCheckTest.kt | 3577291565 |
package siosio.doma.refactoring
import siosio.doma.*
class DaoMethodRenameProcessorTest : DaoTestCase() {
override fun getTestDataPath(): String = "testData/siosio/doma/refactoring/rename/"
fun test_daoメソッド名変更() {
createSqlFile("User/insert.sql")
myFixture.configureByFiles("DaoMethodRename.java")
myFixture.renameElementAtCaret("insertUser")
myFixture.checkResultByFile("DaoMethodRenameAfter.java", false)
assert(findSqlFile("User/insertUser.sql") != null) { "リネーム後のSQLファイルが存在すること" }
assert(findSqlFile("User/insert.sql") == null) { "リネーム前のSQLファイルは存在しないこと" }
}
fun test_SQLファイルなし_メソッド名のリネームは成功すること() {
myFixture.configureByFiles("RenameWithoutSqlFile.java")
myFixture.renameElementAtCaret("insert2")
myFixture.checkResultByFile("RenameWithoutSqlFileAfter.java", false)
}
}
| src/test/java/siosio/doma/refactoring/DaoMethodRenameProcessorTest.kt | 3219012581 |
package me.colombiano.timesheet.dbmigration
trait DatabaseMigration {
fun migrate()
} | src/main/kotlin/me/colombiano/timesheet/dbmigration/DatabaseMigration.kt | 1685538739 |
package me.mattak.moment
operator fun Moment.minus(rhs: Moment): Duration {
return this.intervalSince(rhs)
}
operator fun Moment.plus(rhs: Duration): Moment {
return this.add(rhs)
}
operator fun Moment.minus(rhs: Duration): Moment {
return this.subtract(rhs)
}
operator fun Duration.plus(rhs: Moment): Moment {
return rhs.add(this)
}
operator fun Duration.minus(rhs: Moment): Moment {
return rhs.subtract(this)
}
operator fun Duration.plus(rhs: Duration): Duration {
return this.add(rhs)
}
operator fun Duration.minus(rhs: Duration): Duration {
return this.subtract(rhs)
} | src/main/kotlin/me/mattak/moment/Operators.kt | 295931992 |
package xyz.javecs.tools.expr.test.kotlin
import kotlin.test.assertEquals
import org.junit.Test
import xyz.javecs.tools.expr.Calculator
class CalculatorClearTest {
@Test fun clearTest() {
val calc = Calculator().eval("x = 3")
assertEquals(3, calc.value)
assertEquals(3, calc.eval("x").value)
calc.clear()
assertEquals(Double.NaN, calc.value)
assertEquals(Double.NaN, calc.eval("x").value)
}
}
| src/test/kotlin/xyz/javecs/tools/expr/test/kotlin/CalculatorClearTest.kt | 992065334 |
package com.github.siosio.upsource.internal
import com.github.siosio.upsource.*
import com.github.siosio.upsource.bean.*
import org.apache.http.*
import org.apache.http.client.methods.*
import org.apache.http.message.*
import org.hamcrest.*
import org.junit.*
import org.junit.Assert.*
import org.mockito.*
internal class GetProjectInfoCommandTest : UpsourceApiTestSupport() {
@Test
fun testGetProjectInfo() {
// -------------------------------------------------- setup
Mockito.`when`(mockResponse.entity).thenReturn(
TestData("testdata/upsourceapi/getProjectInfo_result.json").getStringEntity()
)
// -------------------------------------------------- execute
val sut = UpsourceApi("http://testserver", UpsourceAccount("user", "password"), mockHttpClient)
val project = sut.send(GetProjectInfoCommand("sample-project"))
// -------------------------------------------------- assert
assertThat(httpPost.value.uri.toASCIIString(), CoreMatchers.`is`("http://testserver/~rpc/getProjectInfo"))
assertThat(project, CoreMatchers.`is`(
ProjectInfo(
projectId = "sample-project",
projectName = "サンプルプロジェクト",
headHash = "abc123",
codeReviewIdPattern = "sample-{}",
externalLinks = listOf(
ExternalLink("http://hoge.com", "issue-"),
ExternalLink("http://hoge.com", "hotfix-")
),
issueTrackerConnections = listOf(
ExternalLink("http://hogehoge.com", "hogehoge:")
),
projectModelType = "Gradle",
defaultEffectiveCharset = "utf-8",
defaultBranch = "develop",
isConnectedToGithub = false
)
))
}
}
| src/test/java/com/github/siosio/upsource/internal/GetProjectInfoCommandTest.kt | 148629552 |
package com.github.siosio.upsource.internal
import com.github.siosio.upsource.*
import com.github.siosio.upsource.bean.*
import com.jayway.jsonpath.matchers.JsonPathMatchers.*
import org.hamcrest.*
import org.hamcrest.CoreMatchers.*
import org.junit.*
import org.junit.Assert.*
import org.mockito.*
internal class CreateProjectCommandTest : UpsourceApiTestSupport() {
@Test
fun createProject() {
// -------------------------------------------------- setup
Mockito.`when`(mockResponse.entity).thenReturn(
TestData("testdata/upsourceapi/voidMessageResult.json").getStringEntity()
)
// -------------------------------------------------- execute
val voidMessage = sut.send(CreateProjectCommand(
CreateProjectRequest("kotlin-sql", ProjectSettings(
"kotlin-sql-project",
Vcs.git.value,
600L,
ProjectModel(
ProjectType.Gradle.value
),
"kot-{}"
))
))
// -------------------------------------------------- assert
assertThat(httpPost.value.uri.toASCIIString(), CoreMatchers.`is`("http://testserver/~rpc/createProject"))
assertThat(voidMessage, CoreMatchers.`is`(VoidMessage()))
assertThat(httpPost.value.entity.content.readText(),
allOf(
hasJsonPath("newProjectId", equalTo("kotlin-sql")),
hasJsonPath("settings.projectName", equalTo("kotlin-sql-project")),
hasJsonPath("settings.vcsSettings", equalTo("git")),
hasJsonPath("settings.checkIntervalSeconds", equalTo(600)),
hasJsonPath("settings.projectModel.type", equalTo("gradle")),
hasJsonPath("settings.codeReviewIdPattern", equalTo("kot-{}")),
hasNoJsonPath("settings.issueTrackerConnections")
)
)
}
}
| src/test/java/com/github/siosio/upsource/internal/CreateProjectCommandTest.kt | 2930537558 |
package com.tngtech.demo.weather.repositories
import com.tngtech.demo.weather.domain.measurement.AtmosphericData
import com.tngtech.demo.weather.domain.measurement.DataPoint
import com.tngtech.demo.weather.domain.measurement.DataPointType
import com.tngtech.demo.weather.lib.TimestampFactory
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
open class StationDataRepository(
private val timestampFactory: TimestampFactory
) {
private val dataPointByType = ConcurrentHashMap<DataPointType, DataPoint>()
private var lastUpdateTime = 0L
open fun update(data: DataPoint) {
val shouldAddData = acceptanceRuleByType
.get(data.type)
?.let { rulePredicate: (DataPoint) -> Boolean -> rulePredicate.invoke(data) }
?: true
if (shouldAddData) {
dataPointByType.put(data.type, data)
lastUpdateTime = timestampFactory.currentTimestamp
}
}
open fun toData(): AtmosphericData {
var data = AtmosphericData(lastUpdateTime = lastUpdateTime)
typesWithBuilderMethods.forEach { dataTypeAndBuilderMethod ->
val dataType = dataTypeAndBuilderMethod.first
val updateAdapter = dataTypeAndBuilderMethod.second
val dataPoint: DataPoint? = dataPointByType[dataType]
if (dataPoint != null) {
data = dataPoint.let { updateAdapter.invoke(data, it) }
}
}
return data
}
companion object {
private val acceptanceRuleByType: Map<DataPointType, (DataPoint) -> Boolean> = mapOf(
Pair(DataPointType.WIND, { dataPoint -> dataPoint.mean >= 0.0 }),
Pair(DataPointType.TEMPERATURE, { dataPoint -> dataPoint.mean >= -50.0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.HUMIDITY, { dataPoint -> dataPoint.mean >= 0.0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.PRESSURE, { dataPoint -> dataPoint.mean >= 650.0 && dataPoint.mean < 800.0 }),
Pair(DataPointType.CLOUDCOVER, { dataPoint -> dataPoint.mean >= 0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.PRECIPITATION, { dataPoint -> dataPoint.mean >= 0 && dataPoint.mean < 100.0 })
)
private val typesWithBuilderMethods = listOf(
Pair(DataPointType.WIND, { data: AtmosphericData, point: DataPoint -> data.copy(wind = point) }),
Pair(DataPointType.TEMPERATURE, { data: AtmosphericData, point: DataPoint -> data.copy(temperature = point) }),
Pair(DataPointType.HUMIDITY, { data: AtmosphericData, point: DataPoint -> data.copy(humidity = point) }),
Pair(DataPointType.PRESSURE, { data: AtmosphericData, point: DataPoint -> data.copy(pressure = point) }),
Pair(DataPointType.CLOUDCOVER, { data: AtmosphericData, point: DataPoint -> data.copy(cloudCover = point) }),
Pair(DataPointType.PRECIPITATION, { data: AtmosphericData, point: DataPoint -> data.copy(precipitation = point) })
)
}
}
| src/main/java/com/tngtech/demo/weather/repositories/StationDataRepository.kt | 1779770619 |
package com.ilaps.androidtest.main
import android.Manifest
import android.app.Activity
import android.app.Fragment
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.google.firebase.auth.FirebaseAuth
import com.ilaps.androidtest.R
import com.ilaps.androidtest.common.BaseActivity
import com.ilaps.androidtest.main.models.BluetoothDeviceModel
import com.ilaps.androidtest.navigation.navigateToFragment
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.view_progress.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.onClick
class BluetoothDeviceListActivity : BaseActivity() {
val btAdapter:BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
lateinit var presenter:BluetoothDeviceListPresenter
val REQUEST_BLUETOOTH = 1234
val REQUEST_BLUETOOTH_PERMISSIONS = 43221
val SAVED_STATE_KEY = "saved state"
val SAVED_FRAGMENT = "saved fragment"
val SAVED_STATE_VALUE = 12345
var savedFragment:BluetoothDeviceListFragment? = null
lateinit var fragment: BluetoothDeviceListFragment
private val bReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (BluetoothDevice.ACTION_FOUND == intent?.action) {
val deviceReceived = intent
.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val device = BluetoothDeviceModel(deviceReceived.name ?: "NO NAMED", deviceReceived.address)
presenter.sendDevice(device)
progressLayout.visibility = View.GONE
}
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED == intent?.action){
progressLayout.visibility = View.VISIBLE
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED == intent?.action){
progressLayout.visibility = View.GONE
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
if(savedInstanceState != null){
savedFragment = fragmentManager
.getFragment(savedInstanceState,SAVED_FRAGMENT) as BluetoothDeviceListFragment?
}
if(SAVED_STATE_VALUE != savedInstanceState?.getInt(SAVED_STATE_KEY)){
checkIfBluetoothPermissionIsNeeded()
checkBluetoothAdapterAvailability()
}
initFragment()
initListener()
}
private fun initListener() {
toolbar.btnScanDevices.onClick {
reloadScan()
startBluetoothScan()
}
}
fun reloadScan(){
presenter.view.clearAllDevices()
}
private fun getFragmentInstance():BluetoothDeviceListFragment{
return savedFragment ?: BluetoothDeviceListFragment.newInstance()
}
private fun initFragment() {
fragment = getFragmentInstance()
presenter = BluetoothDeviceListPresenter(fragment)
navigateToFragment(fragment, R.id.mainContainer, false)
}
private fun checkBluetoothAdapterAvailability() {
if (btAdapter == null) alert {
title(R.string.not_compatible_error)
message(R.string.not_support_bluetooth_error_message)
}else {
enableBluetooth(btAdapter)
}
}
private fun enableBluetooth(btAdapter:BluetoothAdapter){
if(!btAdapter.isEnabled) {
startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_BLUETOOTH)
}else startBluetoothScan()
}
private fun initBluetoothBroadcastReceiver() {
registerReceiver(bReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
registerReceiver(bReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
registerReceiver(bReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
}
fun startBluetoothScan(){
initBluetoothBroadcastReceiver()
val started = btAdapter?.startDiscovery()
Log.d("BLUETOOTH", "DISCOVERY is $started")
}
private fun checkIfBluetoothPermissionIsNeeded() {
var rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
rc += ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN)
rc += ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (rc != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_COARSE_LOCATION),
REQUEST_BLUETOOTH_PERMISSIONS)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(REQUEST_BLUETOOTH == requestCode && Activity.RESULT_OK == resultCode)
startBluetoothScan()
if(REQUEST_BLUETOOTH_PERMISSIONS == requestCode && Activity.RESULT_OK == resultCode)
startBluetoothScan()
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putInt(SAVED_STATE_KEY,SAVED_STATE_VALUE)
fragmentManager.putFragment(outState,SAVED_FRAGMENT,fragment)
}
override fun onDestroy() {
super.onDestroy()
try {
unregisterReceiver(bReceiver)
}catch (e: IllegalArgumentException) {
}
}
}
| app/src/main/java/com/ilaps/androidtest/main/BluetoothDeviceListActivity.kt | 460533137 |
/*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.list.view
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.format.DateFormat
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import coil.compose.AsyncImage
import jp.toastkid.article_viewer.R
import jp.toastkid.article_viewer.article.data.AppDatabase
import jp.toastkid.article_viewer.article.list.ArticleListFragmentViewModel
import jp.toastkid.article_viewer.article.list.ArticleListFragmentViewModelFactory
import jp.toastkid.article_viewer.article.list.SearchResult
import jp.toastkid.article_viewer.article.list.date.DateFilterDialogUi
import jp.toastkid.article_viewer.article.list.menu.ArticleListMenuPopupActionUseCase
import jp.toastkid.article_viewer.article.list.menu.MenuPopupActionUseCase
import jp.toastkid.article_viewer.article.list.sort.SortSettingDialogUi
import jp.toastkid.article_viewer.article.list.usecase.UpdateUseCase
import jp.toastkid.article_viewer.calendar.DateSelectedActionUseCase
import jp.toastkid.article_viewer.zip.ZipFileChooserIntentFactory
import jp.toastkid.article_viewer.zip.ZipLoadProgressBroadcastIntentFactory
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.view.scroll.usecase.ScrollerUseCase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
@Composable
fun ArticleListUi() {
val context = LocalContext.current as? ComponentActivity ?: return
val dataBase = AppDatabase.find(context)
val articleRepository = dataBase.articleRepository()
val preferenceApplier = PreferenceApplier(context)
val bookmarkRepository = AppDatabase.find(context).bookmarkRepository()
val contentViewModel = ViewModelProvider(context).get(ContentViewModel::class.java)
val viewModel = remember {
ArticleListFragmentViewModelFactory(
articleRepository,
bookmarkRepository,
preferenceApplier
)
.create(ArticleListFragmentViewModel::class.java)
}
val progressBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
viewModel.hideProgress()
showFeedback()
}
private fun showFeedback() {
contentViewModel.snackShort(R.string.message_done_import)
}
}
context.registerReceiver(
progressBroadcastReceiver,
ZipLoadProgressBroadcastIntentFactory.makeProgressBroadcastIntentFilter()
)
contentViewModel.replaceAppBarContent {
AppBarContent(viewModel)
val openSortDialog = remember { mutableStateOf(false) }
if (openSortDialog.value) {
SortSettingDialogUi(preferenceApplier, openSortDialog, onSelect = {
viewModel.sort(it)
})
}
val openDateDialog = remember { mutableStateOf(false) }
if (openDateDialog.value) {
DateFilterDialogUi(
preferenceApplier.colorPair(),
openDateDialog,
DateSelectedActionUseCase(articleRepository, contentViewModel)
)
}
}
val itemFlowState = remember { mutableStateOf<Flow<PagingData<SearchResult>>?>(null) }
viewModel.dataSource.observe(context) {
itemFlowState.value = it.flow
}
val menuPopupUseCase = ArticleListMenuPopupActionUseCase(
articleRepository,
bookmarkRepository,
{
contentViewModel.snackWithAction(
"Deleted: \"${it.title}\".",
"UNDO"
) { CoroutineScope(Dispatchers.IO).launch { articleRepository.insert(it) } }
}
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
ArticleListUi(
itemFlowState.value,
rememberLazyListState(),
contentViewModel,
menuPopupUseCase
)
if (viewModel.progressVisibility.value) {
CircularProgressIndicator(color = MaterialTheme.colors.primary)
}
}
LaunchedEffect(key1 = "first_launch", block = {
viewModel.search("")
})
DisposableEffect(key1 = "unregisterReceiver", effect = {
onDispose {
context.unregisterReceiver(progressBroadcastReceiver)
}
})
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AppBarContent(viewModel: ArticleListFragmentViewModel) {
val activityContext = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(activityContext)
Row {
Column(Modifier.weight(1f)) {
TextField(
value = viewModel.searchInput.value,
onValueChange = {
viewModel.searchInput.value = it
CoroutineScope(Dispatchers.Default).launch {
//inputChannel.send(it)
}
},
label = {
Text(
stringResource(id = R.string.hint_search_articles),
color = MaterialTheme.colors.onPrimary
)
},
singleLine = true,
keyboardActions = KeyboardActions{
viewModel.search(viewModel.searchInput.value)
},
keyboardOptions = KeyboardOptions(
autoCorrect = true,
imeAction = ImeAction.Search
),
colors = TextFieldDefaults.textFieldColors(
textColor = Color(preferenceApplier.fontColor),
cursorColor = MaterialTheme.colors.onPrimary
),
trailingIcon = {
Icon(
Icons.Filled.Clear,
tint = Color(preferenceApplier.fontColor),
contentDescription = "clear text",
modifier = Modifier
.offset(x = 8.dp)
.clickable {
viewModel.searchInput.value = ""
}
)
},
modifier = Modifier.weight(0.7f)
)
Text(
text = viewModel.searchResult.value,
color = MaterialTheme.colors.onPrimary,
fontSize = 12.sp,
modifier = Modifier
.weight(0.3f)
.padding(start = 16.dp)
)
}
val tabListViewModel = ViewModelProvider(activityContext).get<TabListViewModel>()
Box(
Modifier
.width(40.dp)
.fillMaxHeight()
.combinedClickable(
true,
onClick = {
ViewModelProvider(activityContext)
.get(ContentViewModel::class.java)
.switchTabList()
},
onLongClick = {
tabListViewModel.openNewTabForLongTap()
}
)
) {
Image(
painter = painterResource(id = R.drawable.ic_tab),
contentDescription = stringResource(id = R.string.tab),
colorFilter = ColorFilter.tint(
MaterialTheme.colors.onPrimary,
BlendMode.SrcIn
),
modifier = Modifier.align(Alignment.Center)
)
Text(
text = tabListViewModel.tabCount.value.toString(),
fontSize = 9.sp,
color = MaterialTheme.colors.onPrimary,
modifier = Modifier
.align(Alignment.Center)
.padding(start = 2.dp, bottom = 2.dp)
)
}
}
viewModel.progress.observe(activityContext) {
it?.getContentIfNotHandled()?.let { message ->
viewModel.searchResult.value = message
}
}
viewModel.messageId.observe(activityContext) {
it?.getContentIfNotHandled()?.let { messageId ->
viewModel.searchResult.value = activityContext.getString(messageId)
}
}
val setTargetLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
UpdateUseCase(viewModel) { activityContext }.invokeIfNeed(it.data?.data)
}
val useTitleFilter = remember { mutableStateOf(preferenceApplier.useTitleFilter()) }
val openSortDialog = remember { mutableStateOf(false) }
val openDateDialog = remember { mutableStateOf(false) }
val contentViewModel = ViewModelProvider(activityContext).get(ContentViewModel::class.java)
LaunchedEffect(key1 = "add_option_menu", block = {
contentViewModel.optionMenus(
OptionMenu(
titleId = R.string.action_all_article,
action = {
viewModel.search("")
}
),
OptionMenu(
titleId = R.string.action_set_target,
action = {
setTargetLauncher.launch(ZipFileChooserIntentFactory()())
}
),
OptionMenu(
titleId = R.string.action_sort,
action = {
openSortDialog.value = true
}
),
OptionMenu(
titleId = R.string.action_date_filter,
action = {
openDateDialog.value = true
}
),
OptionMenu(
titleId = R.string.action_switch_title_filter,
action = {
val newState = !useTitleFilter.value
preferenceApplier.switchUseTitleFilter(newState)
useTitleFilter.value = newState
},
checkState = useTitleFilter
)
)
})
if (openSortDialog.value) {
SortSettingDialogUi(preferenceApplier, openSortDialog, onSelect = {
viewModel.sort(it)
})
}
if (openDateDialog.value) {
DateFilterDialogUi(
preferenceApplier.colorPair(),
openDateDialog,
DateSelectedActionUseCase(AppDatabase.find(activityContext).articleRepository(), contentViewModel)
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ArticleListUi(
flow: Flow<PagingData<SearchResult>>?,
listState: LazyListState,
contentViewModel: ContentViewModel?,
menuPopupUseCase: MenuPopupActionUseCase
) {
val articles = flow?.collectAsLazyPagingItems() ?: return
LazyColumn(state = listState) {
items(articles, { it.id }) {
it ?: return@items
ListItem(it, contentViewModel, menuPopupUseCase,
Modifier.animateItemPlacement()
)
}
}
val lifecycleOwner = LocalLifecycleOwner.current
ScrollerUseCase(contentViewModel, listState).invoke(lifecycleOwner)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ListItem(
article: SearchResult,
contentViewModel: ContentViewModel?,
menuPopupUseCase: MenuPopupActionUseCase,
modifier: Modifier
) {
var expanded by remember { mutableStateOf(false) }
val items = listOf(
stringResource(id = R.string.action_add_to_bookmark),
stringResource(id = R.string.delete)
)
Surface(
elevation = 4.dp,
modifier = modifier
.padding(start = 8.dp, end = 8.dp, top = 2.dp, bottom = 2.dp)
.combinedClickable(
onClick = { contentViewModel?.newArticle(article.title) },
onLongClick = { contentViewModel?.newArticleOnBackground(article.title) }
)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(4.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = article.title,
fontSize = 16.sp,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Text(
text = "Last updated: ${
DateFormat.format(
"yyyy/MM/dd(E) HH:mm:ss",
article.lastModified
)
}" +
" / ${article.length}",
maxLines = 1,
fontSize = 14.sp,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 4.dp)
)
}
Box(
Modifier
.width(32.dp)
.fillMaxHeight()
) {
AsyncImage(
R.drawable.ic_more,
stringResource(id = R.string.menu),
colorFilter = ColorFilter.tint(
MaterialTheme.colors.secondary,
BlendMode.SrcIn
),
modifier = Modifier
.fillMaxSize()
.clickable {
expanded = true
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
items.forEachIndexed { index, s ->
DropdownMenuItem(onClick = {
when (index) {
0 -> menuPopupUseCase.addToBookmark(article.id)
1 -> menuPopupUseCase.delete(article.id)
}
expanded = false
}) { Text(text = s) }
}
}
}
}
}
} | article/src/main/java/jp/toastkid/article_viewer/article/list/view/ArticleListUi.kt | 144118611 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.account
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Divider
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import app.tivi.common.compose.theme.foregroundColor
import app.tivi.common.compose.ui.AsyncImage
import app.tivi.data.entities.TraktUser
import app.tivi.trakt.TraktAuthState
import com.google.accompanist.flowlayout.FlowMainAxisAlignment
import com.google.accompanist.flowlayout.FlowRow
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.ZoneOffset
import app.tivi.common.ui.resources.R as UiR
@Composable
fun AccountUi(
openSettings: () -> Unit
) {
AccountUi(
viewModel = hiltViewModel(),
openSettings = openSettings
)
}
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun AccountUi(
viewModel: AccountUiViewModel,
openSettings: () -> Unit
) {
val viewState by viewModel.state.collectAsState()
val loginLauncher = rememberLauncherForActivityResult(
viewModel.buildLoginActivityResult()
) { result ->
if (result != null) {
viewModel.onLoginResult(result)
}
}
AccountUi(
viewState = viewState,
openSettings = openSettings,
login = { loginLauncher.launch(Unit) },
logout = { viewModel.logout() }
)
}
@Composable
internal fun AccountUi(
viewState: AccountUiViewState,
openSettings: () -> Unit,
login: () -> Unit,
logout: () -> Unit
) {
Surface(
shape = MaterialTheme.shapes.medium,
elevation = 2.dp,
// FIXME: Force the dialog to wrap the content. Need to work out why
// this doesn't work automatically
modifier = Modifier.heightIn(min = 200.dp)
) {
Column {
Spacer(modifier = Modifier.height(16.dp))
if (viewState.user != null) {
UserRow(
user = viewState.user,
modifier = Modifier.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
FlowRow(
mainAxisAlignment = FlowMainAxisAlignment.End,
mainAxisSpacing = 8.dp,
crossAxisSpacing = 4.dp,
modifier = Modifier
.padding(horizontal = 16.dp)
.wrapContentSize(Alignment.CenterEnd)
.align(Alignment.End)
) {
if (viewState.authState == TraktAuthState.LOGGED_OUT) {
OutlinedButton(onClick = login) {
Text(text = stringResource(UiR.string.login))
}
} else {
TextButton(onClick = login) {
Text(text = stringResource(UiR.string.refresh_credentials))
}
}
OutlinedButton(onClick = logout) {
Text(text = stringResource(UiR.string.logout))
}
}
Spacer(
modifier = Modifier
.height(16.dp)
.fillMaxWidth()
)
Divider()
AppAction(
label = stringResource(UiR.string.settings_title),
icon = Icons.Default.Settings,
contentDescription = stringResource(UiR.string.settings_title),
onClick = openSettings
)
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
}
}
}
@Composable
private fun UserRow(
user: TraktUser,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
) {
val avatarUrl = user.avatarUrl
if (avatarUrl != null) {
AsyncImage(
model = avatarUrl,
requestBuilder = { crossfade(true) },
contentDescription = stringResource(UiR.string.cd_profile_pic, user.name ?: user.username),
modifier = Modifier
.size(40.dp)
.clip(RoundedCornerShape(50))
)
}
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = user.name ?: stringResource(UiR.string.account_name_unknown),
style = MaterialTheme.typography.subtitle2
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = user.username,
style = MaterialTheme.typography.caption
)
}
}
}
}
@Composable
private fun AppAction(
label: String,
icon: ImageVector,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.sizeIn(minHeight = 48.dp)
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Spacer(modifier = Modifier.width(8.dp))
Image(
imageVector = icon,
contentDescription = contentDescription,
colorFilter = ColorFilter.tint(foregroundColor())
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = label,
style = MaterialTheme.typography.body2
)
}
}
@Preview
@Composable
fun PreviewUserRow() {
UserRow(
TraktUser(
id = 0,
username = "sammendes",
name = "Sam Mendes",
location = "London, UK",
joined = OffsetDateTime.of(2019, 5, 4, 11, 12, 33, 0, ZoneOffset.UTC)
)
)
}
| ui/account/src/main/java/app/tivi/account/AccountUi.kt | 2465302776 |
package siilinkari.types
import siilinkari.ast.Expression
import siilinkari.env.Binding
import siilinkari.env.StaticEnvironment
import siilinkari.env.VariableAlreadyBoundException
import siilinkari.lexer.SourceLocation
import siilinkari.objects.Value
/**
* Type-checker for expressions.
*
* Type-checker walks through the syntax tree, maintaining a [StaticEnvironment] mapping
* identifiers to their types and validates that all types agree. If type-checking
* succeeds, the checker will return a simplified and type checked tree where each
* expression is annotated with [Type]. If the checking fails, it will throw a
* [TypeCheckException].
*/
fun Expression.typeCheck(env: StaticEnvironment): TypedExpression = when (this) {
is Expression.Lit -> TypedExpression.Lit(value, value.type)
is Expression.Ref -> TypedExpression.Ref(env.lookupBinding(name, location))
is Expression.Not -> TypedExpression.Not(exp.typeCheckExpected(Type.Boolean, env))
is Expression.Binary -> typeCheck(env)
is Expression.Call -> typeCheck(env)
is Expression.Assign -> {
val binding = env.lookupBinding(variable, location)
if (!binding.mutable)
throw TypeCheckException("can't assign to immutable variable ${binding.name}", location)
val typedLhs = expression.typeCheckExpected(binding.type, env)
TypedExpression.Assign(binding, typedLhs)
}
is Expression.Var -> {
val typed = expression.typeCheck(env)
val binding = env.bindType(variable, typed.type, location, mutable)
TypedExpression.Var(binding, typed)
}
is Expression.If -> {
val typedCondition = condition.typeCheckExpected(Type.Boolean, env)
val typedConsequent = consequent.typeCheck(env)
val typedAlternative = alternative?.typeCheck(env)
val type = if (typedAlternative != null && typedConsequent.type == typedAlternative.type)
typedConsequent.type
else
Type.Unit
TypedExpression.If(typedCondition, typedConsequent, typedAlternative, type)
}
is Expression.While -> {
val typedCondition = condition.typeCheckExpected(Type.Boolean, env)
val typedBody = body.typeCheck(env)
TypedExpression.While(typedCondition, typedBody)
}
is Expression.ExpressionList -> {
val childEnv = env.newScope()
val expressions = expressions.map { it.typeCheck(childEnv) }
val lastType = expressions.lastOrNull()?.type ?: Type.Unit
TypedExpression.ExpressionList(expressions, lastType)
}
}
private fun Expression.Call.typeCheck(env: StaticEnvironment): TypedExpression {
val typedFunc = func.typeCheck(env)
if (typedFunc.type !is Type.Function)
throw TypeCheckException("expected function type for call, but got ${typedFunc.type}", location)
val expectedArgTypes = typedFunc.type.argumentTypes
if (args.size != expectedArgTypes.size)
throw TypeCheckException("expected ${expectedArgTypes.size} arguments, but got ${args.size}", location)
val typedArgs = args.mapIndexed { i, arg -> arg.typeCheckExpected(expectedArgTypes[i], env) }
return TypedExpression.Call(typedFunc, typedArgs, typedFunc.type.returnType)
}
private fun Expression.Binary.typeCheck(env: StaticEnvironment): TypedExpression = when (this) {
is Expression.Binary.Plus ->
typeCheck(env)
is Expression.Binary.Minus -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Minus(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.Multiply -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Multiply(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.Divide -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Divide(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.And -> {
val typedLhs = lhs.typeCheckExpected(Type.Boolean, env)
val typedRhs = rhs.typeCheckExpected(Type.Boolean, env)
TypedExpression.If(typedLhs, typedRhs, TypedExpression.Lit(Value.Bool.False), Type.Boolean)
}
is Expression.Binary.Or -> {
val typedLhs = lhs.typeCheckExpected(Type.Boolean, env)
val typedRhs = rhs.typeCheckExpected(Type.Boolean, env)
TypedExpression.If(typedLhs, TypedExpression.Lit(Value.Bool.True), typedRhs, Type.Boolean)
}
is Expression.Binary.Relational -> {
val (l, r) = typeCheckMatching(env)
if (!l.type.supports(op))
throw TypeCheckException("operator $op is not supported for type ${l.type}", location)
TypedExpression.Binary.Relational(op, l, r)
}
}
private fun Expression.Binary.Plus.typeCheck(env: StaticEnvironment): TypedExpression {
val typedLhs = lhs.typeCheck(env)
return if (typedLhs.type == Type.String) {
val typedRhs = rhs.typeCheck(env)
TypedExpression.Binary.ConcatString(typedLhs, typedRhs)
} else {
val typedLhs2 = typedLhs.expectAssignableTo(Type.Int, lhs.location)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Plus(typedLhs2, typedRhs, Type.Int)
}
}
private fun Expression.Binary.typeCheckMatching(env: StaticEnvironment): Pair<TypedExpression, TypedExpression> {
val typedLhs = lhs.typeCheck(env)
val typedRhs = rhs.typeCheck(env)
if (typedLhs.type != typedRhs.type)
throw TypeCheckException("lhs type ${typedLhs.type} did not match rhs type ${typedRhs.type}", location)
return Pair(typedLhs, typedRhs)
}
fun TypedExpression.expectAssignableTo(expectedType: Type, location: SourceLocation): TypedExpression =
if (type == expectedType)
this
else
throw TypeCheckException("expected type $expectedType, but was $type", location)
fun Expression.typeCheckExpected(expectedType: Type, env: StaticEnvironment): TypedExpression =
typeCheck(env).expectAssignableTo(expectedType, location)
private fun StaticEnvironment.lookupBinding(name: String, location: SourceLocation): Binding =
this[name] ?: throw TypeCheckException("unbound variable '$name'", location)
private fun StaticEnvironment.bindType(name: String, type: Type, location: SourceLocation, mutable: Boolean): Binding {
try {
return this.bind(name, type, mutable)
} catch (e: VariableAlreadyBoundException) {
throw TypeCheckException("variable already bound '$name'", location)
}
}
| src/main/kotlin/siilinkari/types/TypeChecker.kt | 1738911282 |
/*
* Copyright 2020 Thomas Nappo (Jire)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jire.strukt.benchmarks.fixed
import org.jire.strukt.benchmarks.Read
import org.openjdk.jmh.annotations.TearDown
open class FixedRead : Read<FixedPoint>(FixedPoints, FixedPoints.x) {
@TearDown
fun tearDown() {
FixedPoints.free()
}
} | src/jmh/kotlin/org/jire/strukt/benchmarks/fixed/FixedRead.kt | 1974609607 |
package com.radiostream.player
import android.content.Context
import com.radiostream.Settings
import com.radiostream.networking.metadata.MetadataBackendGetter
import com.radiostream.networking.models.SongResult
import com.radiostream.wrapper.UriInterface
import com.radiostream.wrapper.UriWrapper
import javax.inject.Inject
class SongFactory @Inject
constructor(private val mMediaPlayerFactory: MediaPlayerFactory, private val mContext: Context, private val mSettings: Settings,
private val mMetadataBackendGetter: MetadataBackendGetter, private val mUriWrapper: UriWrapper) {
fun build(songResult: SongResult): Song {
return Song(songResult, MediaPlayerWrapper(mMediaPlayerFactory.build()), mContext, mSettings,
mMetadataBackendGetter, mUriWrapper)
}
fun build(otherSong: Song): Song {
return Song(otherSong, MediaPlayerWrapper(mMediaPlayerFactory.build()), mContext, mSettings,
mMetadataBackendGetter, mUriWrapper)
}
}
| app/android/app/src/main/java/com/radiostream/player/SongFactory.kt | 434066452 |
/*
* Copyright (C) 2020. OpenLattice, 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.users
import com.auth0.client.mgmt.ManagementAPI
import com.auth0.json.mgmt.users.User
import com.dataloom.mappers.ObjectMappers
import com.openlattice.users.export.Auth0ApiExtension
import com.openlattice.users.export.JobStatus
import com.openlattice.users.export.UserExportJobRequest
import com.openlattice.users.export.UserExportJobResult
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.InputStreamReader
import java.time.Instant
import java.util.stream.Collectors
import java.util.zip.GZIPInputStream
private const val DEFAULT_PAGE_SIZE = 100
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class Auth0UserListingService(
private val managementApi: ManagementAPI, private val auth0ApiExtension: Auth0ApiExtension
) : UserListingService {
companion object {
private val logger = LoggerFactory.getLogger(Auth0UserListingService::class.java)
}
/**
* Retrieves all users from auth0 as a result of an export job.
*/
override fun getAllUsers(): Sequence<User> {
return getUsers(auth0ApiExtension).asSequence()
}
/**
* Calls an export job to download all users from auth0 to a json and parses it to a sequence of users.
*
* Note: This export is used, because the user API has a 1000 user limitation.
* @see <a href="https://auth0.com/docs/users/search/v3/get-users-endpoint#limitations"> Auth0 user endpoint
* limitations </a>
*/
private fun getUsers(auth0ApiExtension: Auth0ApiExtension): List<User> {
val exportEntity = auth0ApiExtension.userExport()
val job = exportEntity.submitExportJob(UserExportJobRequest(AUTH0_USER_FIELDS))
// will fail if export job hangs too long with too many requests error (429 status code)
// https://auth0.com/docs/policies/rate-limits
var exportJobResult = exportEntity.getJob(job.id)
while (exportJobResult.status == JobStatus.PENDING || exportJobResult.status == JobStatus.PROCESSING) {
Thread.sleep(200) // wait before calling again for job status
exportJobResult = exportEntity.getJob(job.id)
}
Thread.sleep(1000) // TODO actually fix
return readUsersFromLocation(exportJobResult)
}
private fun readUsersFromLocation(exportJobResult: UserExportJobResult): List<User> {
val downloadUrl = exportJobResult.location.get()
try {
val mapper = ObjectMappers.getMapper(ObjectMappers.Mapper.valueOf(exportJobResult.format.name.toUpperCase()))
val connection = downloadUrl.openConnection()
connection.setRequestProperty("Accept-Encoding", "gzip")
val input = GZIPInputStream(connection.getInputStream())
val buffered = BufferedReader(InputStreamReader(input, "UTF-8"))
// export json format has a line by line user object format
// if at any point we have too many users, we might have to download the file
return buffered.lines().map { line -> mapper.readValue(line, User::class.java) }.collect(Collectors.toList())
} catch (e: Exception) {
logger.error("Couldn't read list of users from download url $downloadUrl.",e)
throw e
}
}
/**
* Retrieves users from auth0 where the updated_at property is larger than [from] (exclusive) and smaller than
* [to] (inclusive) as a sequence.
*/
override fun getUpdatedUsers(from: Instant, to: Instant): Sequence<User> {
return Auth0UserListingResult(managementApi, from, to).asSequence()
}
}
class Auth0UserListingResult(
private val managementApi: ManagementAPI, private val from: Instant, private val to: Instant
) : Iterable<User> {
override fun iterator(): Iterator<User> {
return Auth0UserListingIterator(managementApi, from, to)
}
}
class Auth0UserListingIterator(
private val managementApi: ManagementAPI, private val from: Instant, private val to: Instant
) : Iterator<User> {
companion object {
private val logger = LoggerFactory.getLogger(Auth0UserListingIterator::class.java)
}
var page = 0
private var pageOfUsers = getNextPage()
private var pageIterator = pageOfUsers.iterator()
override fun hasNext(): Boolean {
if (!pageIterator.hasNext()) {
if (pageOfUsers.size == DEFAULT_PAGE_SIZE) {
pageOfUsers = getNextPage()
pageIterator = pageOfUsers.iterator()
} else {
return false
}
}
return pageIterator.hasNext()
}
override fun next(): User {
return pageIterator.next()
}
private fun getNextPage(): List<User> {
return try {
val nextPage = getUpdatedUsersPage(managementApi, from, to, page++, DEFAULT_PAGE_SIZE).items
?: listOf()
logger.info("Loaded page {} of {} auth0 users", page - 1, nextPage.size)
nextPage
} catch (ex: Exception) {
logger.error("Retrofit called failed during auth0 sync task.", ex)
listOf()
}
}
}
| src/main/kotlin/com/openlattice/users/Auth0UserListingService.kt | 2227143002 |
package com.openlattice.graph.processing.processors
import org.springframework.stereotype.Component
import java.time.temporal.ChronoUnit
private const val entity_type = "justice.booking"
private const val start = "date.booking"
private const val end = "publicsafety.ReleaseDate"
private const val duration = "criminaljustice.timeserveddays"
@Component
class JusticeBookingDurationProcessor: DurationProcessor() {
override fun getSql(): String {
return numberOfDays()
}
override fun getHandledEntityType(): String {
return entity_type
}
override fun getPropertyTypeForStart(): String {
return start
}
override fun getPropertyTypeForEnd(): String {
return end
}
override fun getPropertyTypeForDuration(): String {
return duration
}
override fun getCalculationTimeUnit(): ChronoUnit {
return ChronoUnit.DAYS
}
override fun getDisplayTimeUnit(): ChronoUnit {
return ChronoUnit.DAYS
}
}
| src/main/kotlin/com/openlattice/graph/processing/processors/JusticeBookingProcessor.kt | 3469630328 |
/*
* Copyright (C) 2018. OpenLattice, 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.edm
import com.openlattice.datastore.services.EdmManager
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class EdmDiffService(private val edm: EdmManager) {
fun diff(otherDataModel: EntityDataModel): EdmDiff {
val currentDataModel = edm.entityDataModel!!
return matchingVersionDiff(currentDataModel, otherDataModel)
}
private fun differentVersionDiff(currentDataModel: EntityDataModel, otherDataModel: EntityDataModel): EdmDiff {
//Since the versions are different we will do our best using FQNs.
val currentPropertyTypes = currentDataModel.propertyTypes.asSequence().map { it.type to it }.toMap()
val currentEntityTypes = currentDataModel.entityTypes.asSequence().map { it.type to it }.toMap()
val currentAssociationTypes = currentDataModel.associationTypes.asSequence().map { it.associationEntityType.type to it }.toMap()
val currentSchemas = currentDataModel.schemas.map { it.fqn to it }.toMap()
val currentNamespaces = currentDataModel.namespaces.toSet()
val presentPropertyTypes = otherDataModel.propertyTypes.filter { currentPropertyTypes.keys.contains(it.type) }
val presentEntityTypes = otherDataModel.entityTypes.filter { currentEntityTypes.keys.contains(it.type) }
val presentAssociationTypes = otherDataModel.associationTypes.filter {
currentAssociationTypes.keys.contains(
it.associationEntityType.type
)
}
val presentSchemas = otherDataModel.schemas.asIterable().filter { currentSchemas.contains(it.fqn) }
val presentNamespaces = otherDataModel.namespaces.minus(currentNamespaces)
val missingPropertyTypes = currentDataModel.propertyTypes.filter { !currentPropertyTypes.contains(it.type) }
val missingEntityTypes = currentDataModel.entityTypes.filter { !currentEntityTypes.contains(it.type) }
val missingAssociationTypes = currentDataModel.associationTypes.filter {
!currentAssociationTypes.contains(
it.associationEntityType.type
)
}
val missingSchemas = currentDataModel.schemas.filter { !currentSchemas.contains(it.fqn) }
val missingNamespaces = currentDataModel.namespaces.minus(currentNamespaces)
val conflictingPropertyTypes = otherDataModel.propertyTypes
.asSequence()
.map { it to currentPropertyTypes[it.type] }
.filter { it.first == it.second }
.map { it.first }
.toSet()
val conflictingEntityTypes = otherDataModel.entityTypes
.asSequence()
.mapNotNull {
it to currentEntityTypes[it.type]
}
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingAssociationTypes = otherDataModel.associationTypes
.asSequence()
.map { it to currentAssociationTypes[it.associationEntityType.type] }
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingSchemas = otherDataModel.schemas.filter {
currentSchemas.containsKey(it.fqn)
&& it.propertyTypes == currentSchemas[it.fqn]?.propertyTypes
&& it.entityTypes == currentSchemas[it.fqn]?.entityTypes
}
//Namespaces cannot conflict.
return EdmDiff(
EntityDataModel(
presentNamespaces,
presentSchemas,
presentEntityTypes,
presentAssociationTypes,
presentPropertyTypes
),
EntityDataModel(
missingNamespaces,
missingSchemas,
missingEntityTypes,
missingAssociationTypes,
missingPropertyTypes
),
EntityDataModel(
listOf(),
conflictingSchemas,
conflictingEntityTypes,
conflictingAssociationTypes,
conflictingPropertyTypes
)
)
}
private fun matchingVersionDiff(currentDataModel: EntityDataModel, otherDataModel: EntityDataModel): EdmDiff {
//Since the versions are same we use ids
val currentPropertyTypes = currentDataModel.propertyTypes.asSequence().map { it.id to it }.toMap()
val currentEntityTypes = currentDataModel.entityTypes.asSequence().map { it.id to it }.toMap()
val currentAssociationTypes = currentDataModel.associationTypes.asSequence().map { it.associationEntityType.id to it }.toMap()
val currentSchemas = currentDataModel.schemas.map { it.fqn to it }.toMap()
val currentNamespaces = currentDataModel.namespaces.toSet()
val presentPropertyTypes = otherDataModel.propertyTypes.filter { currentPropertyTypes.keys.contains(it.id) }
val presentEntityTypes = otherDataModel.entityTypes.filter { currentEntityTypes.keys.contains(it.id) }
val presentAssociationTypes = otherDataModel.associationTypes.filter {
currentAssociationTypes.keys.contains(
it.associationEntityType.id
)
}
val presentSchemas = otherDataModel.schemas.asIterable().filter { currentSchemas.contains(it.fqn) }
val presentNamespaces = otherDataModel.namespaces.minus(currentNamespaces)
val missingPropertyTypes = currentDataModel.propertyTypes.filter { !currentPropertyTypes.contains(it.id) }
val missingEntityTypes = currentDataModel.entityTypes.filter { !currentEntityTypes.contains(it.id) }
val missingAssociationTypes = currentDataModel.associationTypes.filter {
!currentAssociationTypes.contains(
it.associationEntityType.id
)
}
val missingSchemas = currentDataModel.schemas.filter { !currentSchemas.contains(it.fqn) }
val missingNamespaces = currentDataModel.namespaces.minus(currentNamespaces)
val conflictingPropertyTypes = otherDataModel.propertyTypes
.asSequence()
.map { it to currentPropertyTypes[it.id] }
.filter { it.first == it.second }
.map { it.first }
.toSet()
val conflictingEntityTypes = otherDataModel.entityTypes
.asSequence()
.mapNotNull {
it to currentEntityTypes[it.id]
}
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingAssociationTypes = otherDataModel.associationTypes
.asSequence()
.map { it to currentAssociationTypes[it.associationEntityType.id] }
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingSchemas = otherDataModel.schemas.filter {
currentSchemas.containsKey(it.fqn)
&& it.propertyTypes == currentSchemas[it.fqn]?.propertyTypes
&& it.entityTypes == currentSchemas[it.fqn]?.entityTypes
}
//Namespaces cannot conflict.
return EdmDiff(
EntityDataModel(
presentNamespaces,
presentSchemas,
presentEntityTypes,
presentAssociationTypes,
presentPropertyTypes
),
EntityDataModel(
missingNamespaces,
missingSchemas,
missingEntityTypes,
missingAssociationTypes,
missingPropertyTypes
),
EntityDataModel(
listOf(),
conflictingSchemas,
conflictingEntityTypes,
conflictingAssociationTypes,
conflictingPropertyTypes
)
)
}
} | src/main/java/com/openlattice/edm/EdmDiffService.kt | 2907075207 |
package fr.letroll.kotlinandroidlib
import android.widget.TextView
fun TextView.string() : String {
return getText()?.toString() ?: ""
} | kotlinandroidlib/src/main/kotlin/fr/letroll/kotlinandroidlib/KotlinTextView.kt | 4023155983 |
package org.http4k.template.dust
import jdk.nashorn.api.scripting.JSObject
import org.apache.commons.pool2.BasePooledObjectFactory
import org.apache.commons.pool2.impl.DefaultPooledObject
import org.apache.commons.pool2.impl.GenericObjectPool
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import java.io.StringWriter
import java.net.URL
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings
typealias TemplateLoader = (templateName: String) -> String?
interface TemplateExpansion {
fun expandTemplate(
templateName: String,
params: Any,
onMissingTemplate: (templateName: String) -> Nothing = ::missingTemplateIllegalArgument
): String
}
interface TemplateExpansionService : AutoCloseable, TemplateExpansion
private object TEMPLATE_NOT_FOUND
private fun missingTemplateIllegalArgument(templateName: String): Nothing = throw IllegalArgumentException("template $templateName not found")
private fun ScriptEngine.eval(srcUrl: URL) {
eval(srcUrl.readText())
}
// Must only be used on one thread.
private class SingleThreadedDust(
private val js: ScriptEngine,
private val cacheTemplates: Boolean = true,
private val dustPluginScripts: List<URL>,
private val notifyOnClosed: (SingleThreadedDust) -> Unit
) : TemplateExpansionService {
private val dust: JSObject = run {
js.eval(javaClass.getResource("dust-full-2.7.5.js"))
dustPluginScripts.forEach(js::eval)
js.eval(
//language=JavaScript
"""
// This lets Dust iterate over Java collections.
dust.isArray = function(o) {
return Array.isArray(o) || o instanceof java.util.List;
};
dust.config.cache = $cacheTemplates;
dust.onLoad = function(templateName, callback) {
var template = loader.invoke(templateName);
if (template === null) {
callback(TEMPLATE_NOT_FOUND, null)
} else {
callback(null, template);
}
}
""")
js["dust"] as? JSObject ?: throw IllegalStateException("could not initialise Dust")
}
override fun close() {
notifyOnClosed(this)
}
override fun expandTemplate(
templateName: String,
params: Any,
onMissingTemplate: (templateName: String) -> Nothing
): String {
val writer = StringWriter()
var error: Any? = null
val bindings = SimpleBindings(mapOf(
"dust" to dust,
"templateName" to templateName,
"templateParams" to params,
"writer" to writer,
"reportError" to { e: Any -> error = e }
))
js.eval(
//language=JavaScript
"""
dust.render(templateName, templateParams, function(err, result) {
if (err) {
reportError.invoke(err);
} else {
writer.write(result, 0, result.length);
}
});
""", bindings)
return when (error) {
null -> writer.toString()
TEMPLATE_NOT_FOUND -> onMissingTemplate(templateName)
else -> throw IllegalStateException(error.toString())
}
}
}
class Dust(
private val cacheTemplates: Boolean,
private val precachePoolSize: Int,
private val dustPluginScripts: List<URL>,
loader: TemplateLoader
) {
private val scriptEngineManager = ScriptEngineManager().apply {
bindings = SimpleBindings(mapOf(
"loader" to loader,
"TEMPLATE_NOT_FOUND" to TEMPLATE_NOT_FOUND))
}
private val pool = GenericObjectPool(
object : BasePooledObjectFactory<SingleThreadedDust>() {
override fun create(): SingleThreadedDust = SingleThreadedDust(
js = scriptEngineManager.getEngineByName("nashorn"),
cacheTemplates = cacheTemplates,
dustPluginScripts = dustPluginScripts,
notifyOnClosed = { returnDustEngine(it) })
override fun wrap(obj: SingleThreadedDust) = DefaultPooledObject(obj)
},
GenericObjectPoolConfig<SingleThreadedDust>().apply {
minIdle = precachePoolSize
})
private fun returnDustEngine(dustEngine: SingleThreadedDust) {
pool.returnObject(dustEngine)
}
fun openTemplates(): TemplateExpansionService = pool.borrowObject()
inline fun <T> withTemplates(block: (TemplateExpansion) -> T): T = openTemplates().use(block)
}
| http4k-template/dust/src/main/kotlin/org/http4k/template/dust/Dust.kt | 982517017 |
package org.http4k.security.oauth.server
import org.http4k.core.Request
import org.http4k.core.Response
/**
* Provides a mechanism to track OAuth authorization parameters to be used later
* (i.e. can be used later to generate code and/or tokens)
*/
interface AuthRequestTracking {
/**
* Assign a reference of AuthRequest to the response
*/
fun trackAuthRequest(request: Request, authRequest: AuthRequest, response: Response): Response
/**
* Resolves a particular AuthRequest related to the particular request
*/
fun resolveAuthRequest(request: Request): AuthRequest?
}
| http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/server/AuthRequestTracking.kt | 4198646525 |
/*
* Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
* Copyright (C) 2017-2020 Pacien TRAN-GIRARD
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.pacien.tincapp.commands
import org.pacien.tincapp.R
import org.pacien.tincapp.commands.Executor.runAsyncTask
import org.pacien.tincapp.context.App
import org.pacien.tincapp.context.AppPaths
import org.pacien.tincapp.data.TincConfiguration
import org.pacien.tincapp.data.VpnInterfaceConfiguration
import org.pacien.tincapp.utils.PemUtils
import java.io.FileNotFoundException
/**
* @author pacien
*/
object TincApp {
private val SCRIPT_SUFFIXES = listOf("-up", "-down", "-created", "-accepted")
private val STATIC_SCRIPTS = listOf("tinc", "host", "subnet", "invitation").flatMap { s -> SCRIPT_SUFFIXES.map { s + it } }
private fun listScripts(netName: String) =
AppPaths.confDir(netName).listFiles { f -> f.name in STATIC_SCRIPTS }!! +
AppPaths.hostsDir(netName).listFiles { f -> SCRIPT_SUFFIXES.any { f.name.endsWith(it) } }!!
fun listPrivateKeys(netName: String) = try {
TincConfiguration.fromTincConfiguration(AppPaths.existing(AppPaths.tincConfFile(netName))).let {
listOf(
it.privateKeyFile ?: AppPaths.defaultRsaPrivateKeyFile(netName),
it.ed25519PrivateKeyFile ?: AppPaths.defaultEd25519PrivateKeyFile(netName))
}
} catch (e: FileNotFoundException) {
throw FileNotFoundException(App.getResources().getString(R.string.notification_error_message_network_config_not_found_format, e.message!!))
}
fun removeScripts(netName: String) = runAsyncTask {
listScripts(netName).forEach { it.delete() }
}
fun generateIfaceCfg(netName: String) = runAsyncTask {
VpnInterfaceConfiguration
.fromInvitation(AppPaths.invitationFile(netName))
.write(AppPaths.netConfFile(netName))
}
fun generateIfaceCfgTemplate(netName: String) = runAsyncTask {
App.getResources().openRawResource(R.raw.network).use { inputStream ->
AppPaths.netConfFile(netName).outputStream().use { inputStream.copyTo(it) }
}
}
fun setPassphrase(netName: String, currentPassphrase: String? = null, newPassphrase: String?) = runAsyncTask {
listPrivateKeys(netName)
.filter { it.exists() }
.map { Pair(PemUtils.read(it), it) }
.map { Pair(PemUtils.decrypt(it.first, currentPassphrase), it.second) }
.map { Pair(if (newPassphrase?.isNotEmpty() == true) PemUtils.encrypt(it.first, newPassphrase) else it.first, it.second) }
.forEach { PemUtils.write(it.first, it.second.writer()) }
}
}
| app/src/main/java/org/pacien/tincapp/commands/TincApp.kt | 1339781565 |
package de.westnordost.streetcomplete.quests.oneway
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.ALL_ROADS
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.Way
import de.westnordost.streetcomplete.quests.cycleway.createCyclewaySides
import de.westnordost.streetcomplete.quests.cycleway.estimatedWidth
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR
import de.westnordost.streetcomplete.quests.oneway.OnewayAnswer.*
import de.westnordost.streetcomplete.quests.parking_lanes.*
class AddOneway : OsmElementQuestType<OnewayAnswer> {
/** find all roads */
private val allRoadsFilter by lazy { """
ways with highway ~ ${ALL_ROADS.joinToString("|")} and area != yes
""".toElementFilterExpression() }
/** find only those roads eligible for asking for oneway */
private val elementFilter by lazy { """
ways with highway ~ living_street|residential|service|tertiary|unclassified
and !oneway and area != yes and junction != roundabout
and (access !~ private|no or (foot and foot !~ private|no))
and lanes <= 1 and width
""".toElementFilterExpression() }
override val commitMessage = "Add whether this road is a one-way road because it is quite slim"
override val wikiLink = "Key:oneway"
override val icon = R.drawable.ic_quest_oneway
override val hasMarkersAtEnds = true
override val isSplitWayEnabled = true
override val questTypeAchievements = listOf(CAR)
override fun getTitle(tags: Map<String, String>) = R.string.quest_oneway2_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val allRoads = mapData.ways.filter { allRoadsFilter.matches(it) && it.nodeIds.size >= 2 }
val connectionCountByNodeIds = mutableMapOf<Long, Int>()
val onewayCandidates = mutableListOf<Way>()
for (road in allRoads) {
for (nodeId in road.nodeIds) {
val prevCount = connectionCountByNodeIds[nodeId] ?: 0
connectionCountByNodeIds[nodeId] = prevCount + 1
}
if (isOnewayRoadCandidate(road)) {
onewayCandidates.add(road)
}
}
return onewayCandidates.filter {
/* ways that are simply at the border of the download bounding box are treated as if
they are dead ends. This is fine though, because it only leads to this quest not
showing up for those streets (which is better than the other way round)
*/
// check if the way has connections to other roads at both ends
(connectionCountByNodeIds[it.nodeIds.first()] ?: 0) > 1 &&
(connectionCountByNodeIds[it.nodeIds.last()] ?: 0) > 1
}
}
override fun isApplicableTo(element: Element): Boolean? {
if (!isOnewayRoadCandidate(element)) return false
/* return null because oneway candidate roads must also be connected on both ends with other
roads for which we'd need to look at surrounding geometry */
return null
}
private fun isOnewayRoadCandidate(road: Element): Boolean {
if (!elementFilter.matches(road)) return false
// check if the width of the road minus the space consumed by other stuff is quite narrow
val width = road.tags["width"]?.toFloatOrNull()
val isNarrow = width != null && width <= estimatedWidthConsumedByOtherThings(road.tags) + 4f
return isNarrow
}
private fun estimatedWidthConsumedByOtherThings(tags: Map<String, String>): Float {
return estimateWidthConsumedByParkingLanes(tags) +
estimateWidthConsumedByCycleLanes(tags)
}
private fun estimateWidthConsumedByParkingLanes(tags: Map<String, String>): Float {
val sides = createParkingLaneSides(tags) ?: return 0f
return (sides.left?.estimatedWidthOnRoad ?: 0f) + (sides.right?.estimatedWidthOnRoad ?: 0f)
}
private fun estimateWidthConsumedByCycleLanes(tags: Map<String, String>): Float {
/* left or right hand traffic is irrelevant here because we don't make a difference between
left and right side */
val sides = createCyclewaySides(tags, false) ?: return 0f
return (sides.left?.estimatedWidth ?: 0f) + (sides.right?.estimatedWidth ?: 0f)
}
override fun createForm() = AddOnewayForm()
override fun applyAnswerTo(answer: OnewayAnswer, changes: StringMapChangesBuilder) {
changes.add("oneway", when(answer) {
FORWARD -> "yes"
BACKWARD -> "-1"
NO_ONEWAY -> "no"
})
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOneway.kt | 1698891646 |
/*
* Copyright 2020 Alex Almeida Tavella
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.core.android
import android.util.Log
import br.com.moov.core.android.BuildConfig
const val LOG_TAG = "MooV"
inline fun logd(block: () -> String) {
if (BuildConfig.DEBUG) {
Log.d(LOG_TAG, block())
}
}
inline fun logw(block: () -> String) {
if (BuildConfig.DEBUG) {
Log.w(LOG_TAG, block())
}
}
| core-android/src/main/java/br/com/core/android/Logger.kt | 1527929091 |
package test
class UnknownSystem(val worker: UnknownWorker) {
fun add(arg1: Int, arg2: Int): Int {
return arg1 + arg2
}
fun command(arg: Int) {
worker.work(arg)
}
}
class UnknownWorker {
fun work(arg: Int): Int {
return arg * arg + arg
}
} | Advanced_kb/src/test/UnknownSystem.kt | 1875283719 |
package org.basinmc.faucet.internal.warn
/**
* Marks the annotated element as a stable API (e.g. safe to use and covered by the project's
* deprecation policy).
*
* @author [Johannes Donath](mailto:[email protected])
*/
@MustBeDocumented
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.CONSTRUCTOR)
annotation class Stable
| faucet/src/main/kotlin/org/basinmc/faucet/internal/warn/Stable.kt | 1026204697 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientClickWindowButtonPacket
object ClientClickWindowButtonDecoder : PacketDecoder<ClientClickWindowButtonPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientClickWindowButtonPacket {
val windowId = buf.readByte().toInt()
val button = buf.readByte().toInt()
return ClientClickWindowButtonPacket(windowId, button)
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientClickWindowButtonDecoder.kt | 4101408640 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientUseItemPacket
import org.spongepowered.api.data.type.HandTypes
object ClientUseItemDecoder : PacketDecoder<ClientUseItemPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientUseItemPacket =
ClientUseItemPacket(if (buf.readVarInt() == 0) HandTypes.MAIN_HAND.get() else HandTypes.OFF_HAND.get())
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientUseItemDecoder.kt | 4226839477 |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlin.test.*
/**
* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER]
*/
internal const val MAX_SAFE_INTEGER: Double = 9007199254740991.toDouble() // 2^53 - 1
class DynamicToLongTest {
@Serializable
data class HasLong(val l: Long)
private fun test(dynamic: dynamic, expectedResult: Result<Long>) {
val parsed = kotlin.runCatching { Json.decodeFromDynamic(HasLong.serializer(), dynamic).l }
assertEquals(expectedResult.isSuccess, parsed.isSuccess, "Results are different")
parsed.onSuccess { assertEquals(expectedResult.getOrThrow(), it) }
// to compare without message
parsed.onFailure { assertSame(expectedResult.exceptionOrNull()!!::class, it::class) }
}
private fun shouldFail(dynamic: dynamic) = test(dynamic, Result.failure(SerializationException("")))
@Test
fun canParseNotSoBigLongs() {
test(js("{l:1}"), Result.success(1))
test(js("{l:0}"), Result.success(0))
test(js("{l:-1}"), Result.success(-1))
}
@Test
fun ignoresIncorrectValues() {
shouldFail(js("{l:0.5}"))
shouldFail(js("{l: Math.PI}"))
shouldFail(js("{l: NaN}"))
shouldFail(js("""{l: "a string"}"""))
shouldFail(js("{l:Infinity}"))
shouldFail(js("{l:+Infinity}"))
shouldFail(js("{l:-Infinity}"))
}
@Test
fun handlesEdgyValues() {
test(js("{l:Number.MAX_SAFE_INTEGER}"), Result.success(MAX_SAFE_INTEGER.toLong()))
test(js("{l:Number.MAX_SAFE_INTEGER - 1}"), Result.success(MAX_SAFE_INTEGER.toLong() - 1))
test(js("{l:-Number.MAX_SAFE_INTEGER}"), Result.success(-MAX_SAFE_INTEGER.toLong()))
shouldFail(js("{l: Number.MAX_SAFE_INTEGER + 1}"))
shouldFail(js("{l: Number.MAX_SAFE_INTEGER + 2}"))
shouldFail(js("{l: -Number.MAX_SAFE_INTEGER - 1}"))
shouldFail(js("{l: 2e100}"))
shouldFail(js("{l: 2e100 + 1}"))
test(js("{l: Math.pow(2, 53) - 1}"), Result.success(MAX_SAFE_INTEGER.toLong()))
}
}
| formats/json-tests/jsTest/src/kotlinx/serialization/json/DynamicToLongTest.kt | 2929021427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.