content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.elpassion.android.commons.espresso.matchers
import android.view.View
import androidx.annotation.StringRes
import com.google.android.material.textfield.TextInputLayout
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
class EditTextErrorMatcher(
@StringRes private val textId: Int
) : TypeSafeMatcher<View>(View::class.java) {
override fun matchesSafely(view: View): Boolean {
val expectedErrorText = view.context.getString(textId)
return matchErrorText(view, expectedErrorText)
}
private fun matchErrorText(view: View, expectedErrorText: String): Boolean {
val parent = view.parent
return when (parent) {
is TextInputLayout -> parent.error == expectedErrorText
is View -> matchErrorText(parent, expectedErrorText)
else -> false
}
}
override fun describeTo(description: Description) {
description.appendText("has error text from string resource on TextInputLayout: $textId")
}
} | espresso/src/main/java/com/elpassion/android/commons/espresso/matchers/EditTextErrorMatcher.kt | 2521550884 |
package com.denysnovoa.nzbmanager.radarr.movie.release.repository.api
import com.denysnovoa.nzbmanager.radarr.movie.release.repository.model.MovieReleaseModel
import io.reactivex.Flowable
import io.reactivex.Single
interface MovieReleaseApiClient {
fun getReleases(id: Int): Flowable<List<MovieReleaseModel>>
fun download(movieReleaseModel: MovieReleaseModel): Single<MovieReleaseModel>
} | app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/repository/api/MovieReleaseApiClient.kt | 1521878553 |
package net.yslibrary.monotweety.base
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.google.android.material.snackbar.Snackbar
import net.yslibrary.monotweety.base.di.Names
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
import kotlin.properties.Delegates
abstract class BaseActivity : AppCompatActivity() {
@set:Inject
@setparam:Named(Names.FOR_ACTIVITY)
var activityBus by Delegates.notNull<EventBus>()
protected abstract val layoutResId: Int
protected lateinit var router: Router
private set
protected abstract val container: ChangeHandlerFrameLayout
protected abstract val rootController: Controller
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.i("onCreate - BaseActivity")
setContentView(layoutResId)
router = Conductor.attachRouter(this, container, savedInstanceState)
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(rootController))
}
}
override fun onBackPressed() {
if (!router.handleBack()) {
super.onBackPressed()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Timber.i("onActivityResult - BaseActivity")
router.onActivityResult(requestCode, resultCode, data)
}
fun showSnackBar(message: String) =
Snackbar.make(container.parent as ViewGroup, message, Snackbar.LENGTH_SHORT).show()
}
| app/src/main/java/net/yslibrary/monotweety/base/BaseActivity.kt | 164326921 |
package com.eden.orchid.changelog
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.publication.OrchidPublisher
import com.eden.orchid.api.registration.OrchidModule
import com.eden.orchid.api.theme.components.OrchidComponent
import com.eden.orchid.changelog.components.ChangelogComponent
import com.eden.orchid.changelog.components.ChangelogVersionPicker
import com.eden.orchid.changelog.publication.GithubReleasesPublisher
import com.eden.orchid.changelog.publication.RequiredChangelogVersionPublisher
import com.eden.orchid.utilities.addToSet
class ChangelogModule : OrchidModule() {
override fun configure() {
withResources(20)
addToSet<OrchidGenerator, ChangelogGenerator>()
addToSet<OrchidPublisher>(
RequiredChangelogVersionPublisher::class,
GithubReleasesPublisher::class)
addToSet<OrchidComponent>(
ChangelogComponent::class,
ChangelogVersionPicker::class)
}
}
| plugins/OrchidChangelog/src/main/kotlin/com/eden/orchid/changelog/ChangelogModule.kt | 3658479696 |
package us.mikeandwan.photos.ui.controls.categorylist
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import us.mikeandwan.photos.domain.models.PhotoCategory
import us.mikeandwan.photos.ui.toCategoryWithYearVisibility
class CategoryListViewModel: ViewModel() {
private val _categories = MutableStateFlow(emptyList<CategoryWithYearVisibility>())
val categories = _categories.asStateFlow()
private val _showYear = MutableStateFlow(false)
fun setCategories(items: List<PhotoCategory>) {
_categories.value = items.map { it.toCategoryWithYearVisibility(_showYear.value) }
}
fun setShowYear(doShow: Boolean) {
_showYear.value = doShow
}
} | MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/categorylist/CategoryListViewModel.kt | 48862512 |
package us.mikeandwan.photos.ui.screens.photo
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import us.mikeandwan.photos.domain.models.Photo
class PhotoFragmentStateAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {
private var _photos = emptyList<Photo>()
override fun getItemCount(): Int {
return _photos.size
}
override fun createFragment(position: Int): Fragment {
val fragment = PhotoViewHolderFragment()
fragment.arguments = Bundle().apply {
val photo = _photos[position]
putString(PhotoViewHolderFragment.PHOTO_URL, photo.mdUrl)
}
return fragment
}
fun updatePhotoList(photos: List<Photo>) {
_photos = photos
notifyDataSetChanged()
}
} | MaWPhotos/src/main/java/us/mikeandwan/photos/ui/screens/photo/PhotoFragmentStateAdapter.kt | 3037239154 |
package com.exsilicium.scripture.shared.model
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class ChapterRangesTest {
@Test fun `Require non-empty ranges`() {
assertThrows(IllegalArgumentException::class.java) { ChapterRanges() }
}
@Test fun `Require ranges start at one or greater`() {
assertThrows(IllegalArgumentException::class.java) { ChapterRanges(0..3) }
}
@Test fun `Secondary constructor sorts input`() {
assertEquals(ChapterRanges(1..2, 4..5), ChapterRanges(4..5, 1..2))
}
@Test fun `ChapterRanges with earlier start is less than later chapter`() {
val threeThroughFive = ChapterRanges(3..5)
val four = ChapterRanges(ChapterRange(4))
assertTrue(threeThroughFive < four)
}
@Test fun `ChapterRanges with earlier start is less than ChapterRanges with later start`() {
val threeThroughFive = ChapterRanges(3..5)
val fourAndFive = ChapterRanges(4..5)
assertTrue(threeThroughFive < fourAndFive)
}
@Test fun `ChapterRanges with same start chapter as VerseRanges is equal if VerseRanges starts at verse 1`() {
val threeThroughFive = ChapterRanges(3..5)
val threeOneThroughSeventeen = VerseRanges(VerseRange(Verse(3, 1), Verse(3, 17)))
assertTrue(threeThroughFive.compareTo(threeOneThroughSeventeen) == 0)
}
@Test
fun `ChapterRanges with same start chapter as VerseRanges is less if VerseRanges doesn't start at verse 1`() {
val threeThroughFive = ChapterRanges(3..5)
val threeSixteen = VerseRanges(VerseRange(Verse(3, 16)))
assertTrue(threeThroughFive < threeSixteen)
}
@Test
fun `ChapterRanges with longer ranges is greater than ChapterRanges with shorter ranges`() {
val twoRanges = ChapterRanges(1..5, 9..10)
val oneRange = ChapterRanges(1..20)
assertTrue(oneRange > twoRanges)
}
@Test
fun `ChapterRanges with more ranges is not necessarily greater than ChapterRanges with fewer ranges`() {
val twoRanges = ChapterRanges(1..5, 9..10)
val oneRange = ChapterRanges(1..9)
assertTrue(oneRange > twoRanges)
}
@Test
fun `ChapterRanges with shorter ranges is less than ChapterRanges with longer ranges`() {
val twoRanges = ChapterRanges(1..5, 9..20)
val oneRange = ChapterRanges(1..9)
assertTrue(twoRanges > oneRange)
}
@Test
fun `ChapterRanges with fewer ranges is not necessarily less than ChapterRanges with more ranges`() {
val twoRanges = ChapterRanges(1..5, 9..10)
val oneRange = ChapterRanges(1..9)
assertTrue(twoRanges < oneRange)
}
@Test fun `All chapter ranges must be valid for a given Book`() {
assertFalse(ChapterRanges(1..2).isValid(Book.JUDE))
}
}
| src/test/kotlin/com/exsilicium/scripture/shared/model/ChapterRangesTest.kt | 2044062206 |
package org.ozinger.ika.annotation.processor
import com.google.auto.service.AutoService
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
@AutoService(SymbolProcessorProvider::class)
class ServiceCommandProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment) = ServiceCommandProcessor(
environment.codeGenerator,
environment.logger,
environment.options,
)
}
| annotation-processor/src/main/kotlin/org/ozinger/ika/annotation/processor/ServiceCommandProcessorProvider.kt | 4231717223 |
package com.sbg.vindinium.kindinium.bot.state
import com.sbg.vindinium.kindinium.bot.Bot
import com.sbg.vindinium.kindinium.bot.Action
import com.sbg.vindinium.kindinium.model.board.MetaBoard
import com.sbg.vindinium.kindinium.model.Response
import com.sbg.vindinium.kindinium.bot.state
class Waiting(val bot: Bot): BotState {
override fun chooseAction(response: Response, metaboard: MetaBoard): Action {
if (response.hero.life <= 20) {
bot.switchToState(GoingToTavern(bot))
return Action.Stay
} else if (metaboard.neutralMines().isNotEmpty()) {
bot.switchToState(CapturingNearestNeutralMine(bot))
return Action.Stay
} else {
return Action.Stay
}
}
} | src/main/kotlin/com/sbg/vindinium/kindinium/bot/state/Waiting.kt | 4262064416 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.hrs.view
import android.content.Context
import android.graphics.Color
import android.graphics.DashPathEffect
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import no.nordicsemi.android.hrs.data.HRSData
private const val X_AXIS_ELEMENTS_COUNT = 40f
private const val AXIS_MIN = 0
private const val AXIS_MAX = 300
@Composable
internal fun LineChartView(state: HRSData, zoomIn: Boolean,) {
val items = state.heartRates.takeLast(X_AXIS_ELEMENTS_COUNT.toInt()).reversed()
val isSystemInDarkTheme = isSystemInDarkTheme()
AndroidView(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
factory = { createLineChartView(isSystemInDarkTheme, it, items, zoomIn) },
update = { updateData(items, it, zoomIn) }
)
}
internal fun createLineChartView(
isDarkTheme: Boolean,
context: Context,
points: List<Int>,
zoomIn: Boolean
): LineChart {
return LineChart(context).apply {
description.isEnabled = false
legend.isEnabled = false
setTouchEnabled(false)
setDrawGridBackground(false)
isDragEnabled = true
setScaleEnabled(false)
setPinchZoom(false)
if (isDarkTheme) {
setBackgroundColor(Color.TRANSPARENT)
xAxis.gridColor = Color.WHITE
xAxis.textColor = Color.WHITE
axisLeft.gridColor = Color.WHITE
axisLeft.textColor = Color.WHITE
} else {
setBackgroundColor(Color.WHITE)
xAxis.gridColor = Color.BLACK
xAxis.textColor = Color.BLACK
axisLeft.gridColor = Color.BLACK
axisLeft.textColor = Color.BLACK
}
xAxis.apply {
xAxis.enableGridDashedLine(10f, 10f, 0f)
axisMinimum = -X_AXIS_ELEMENTS_COUNT
axisMaximum = 0f
setAvoidFirstLastClipping(true)
position = XAxis.XAxisPosition.BOTTOM
}
axisLeft.apply {
enableGridDashedLine(10f, 10f, 0f)
axisMaximum = points.getMax(zoomIn)
axisMinimum = points.getMin(zoomIn)
}
axisRight.isEnabled = false
val entries = points.mapIndexed { i, v ->
Entry(-i.toFloat(), v.toFloat())
}.reversed()
// create a dataset and give it a type
if (data != null && data.dataSetCount > 0) {
val set1 = data!!.getDataSetByIndex(0) as LineDataSet
set1.values = entries
set1.notifyDataSetChanged()
data!!.notifyDataChanged()
notifyDataSetChanged()
} else {
val set1 = LineDataSet(entries, "DataSet 1")
set1.setDrawIcons(false)
set1.setDrawValues(false)
// draw dashed line
// draw dashed line
set1.enableDashedLine(10f, 5f, 0f)
// black lines and points
// black lines and points
if (isDarkTheme) {
set1.color = Color.WHITE
set1.setCircleColor(Color.WHITE)
} else {
set1.color = Color.BLACK
set1.setCircleColor(Color.BLACK)
}
// line thickness and point size
// line thickness and point size
set1.lineWidth = 1f
set1.circleRadius = 3f
// draw points as solid circles
// draw points as solid circles
set1.setDrawCircleHole(false)
// customize legend entry
// customize legend entry
set1.formLineWidth = 1f
set1.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
set1.formSize = 15f
// text size of values
// text size of values
set1.valueTextSize = 9f
// draw selection line as dashed
// draw selection line as dashed
set1.enableDashedHighlightLine(10f, 5f, 0f)
val dataSets = ArrayList<ILineDataSet>()
dataSets.add(set1) // add the data sets
// create a data object with the data sets
val data = LineData(dataSets)
// set data
// set data
setData(data)
}
}
}
private fun updateData(points: List<Int>, chart: LineChart, zoomIn: Boolean) {
val entries = points.mapIndexed { i, v ->
Entry(-i.toFloat(), v.toFloat())
}.reversed()
with(chart) {
axisLeft.apply {
axisMaximum = points.getMax(zoomIn)
axisMinimum = points.getMin(zoomIn)
}
if (data != null && data.dataSetCount > 0) {
val set1 = data!!.getDataSetByIndex(0) as LineDataSet
set1.values = entries
set1.notifyDataSetChanged()
data!!.notifyDataChanged()
notifyDataSetChanged()
invalidate()
}
}
}
private fun List<Int>.getMin(zoomIn: Boolean): Float {
return if (zoomIn) {
minOrNull() ?: AXIS_MIN
} else {
AXIS_MIN
}.toFloat()
}
private fun List<Int>.getMax(zoomIn: Boolean): Float {
return if (zoomIn) {
maxOrNull() ?: AXIS_MAX
} else {
AXIS_MAX
}.toFloat()
}
| profile_hrs/src/main/java/no/nordicsemi/android/hrs/view/LineChartView.kt | 1993566011 |
package wu.seal.jsontokotlin.interceptor.annotations.gson
import wu.seal.jsontokotlin.model.classscodestruct.DataClass
import wu.seal.jsontokotlin.model.codeannotations.GsonPropertyAnnotationTemplate
import wu.seal.jsontokotlin.model.codeelements.KPropertyName
import wu.seal.jsontokotlin.interceptor.IKotlinClassInterceptor
import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass
class AddGsonAnnotationInterceptor : IKotlinClassInterceptor<KotlinClass> {
override fun intercept(kotlinClass: KotlinClass): KotlinClass {
return if (kotlinClass is DataClass) {
val addGsonAnnotationProperties = kotlinClass.properties.map {
val camelCaseName = KPropertyName.makeLowerCamelCaseLegalName(it.originName)
it.copy(annotations = GsonPropertyAnnotationTemplate(it.originName).getAnnotations(), name = camelCaseName)
}
kotlinClass.copy(properties = addGsonAnnotationProperties)
} else {
kotlinClass
}
}
}
| src/main/kotlin/wu/seal/jsontokotlin/interceptor/annotations/gson/AddGsonAnnotationInterceptor.kt | 3659130660 |
package com.sefford.kor.repositories.utils
import com.sefford.kor.repositories.components.CacheFolder
import java.io.File
/**
* Default implementation of a cache folder.
*
*
* Provides a basic implementation on how a folder should provide files to the
* [DataSource][com.sefford.kor.repositories.DiskJsonDataSource] or the [FileTimeExpirationPolicy]
*
* @author Saul Diaz Gonzalez <[email protected]>
*/
abstract class CacheFolderImpl<K>
/**
* Creates a new instance of CacheFolder.
*
*
* The creation of the directory will be attempted.
*
* @param root File pointing to the folder.
*/
(
/**
* File which honors the folder the instance is representing
*/
protected val root: File) : CacheFolder<K> {
/**
* Creates a new instance of CacheFolder.
*
*
* The creation of the directory will be attempted.
*
* @param root Path of the folder, it will be wrapped
*/
constructor(root: String) : this(File(root))
init {
if (!this.root.exists()) {
this.root.mkdirs()
}
}
/**
* {@inheritDoc}
*/
override fun files(): Array<File> {
val files = root.listFiles()
return if (files != null) files else emptyArray()
}
/**
* {@inheritDoc}
*/
override fun exists(): Boolean {
return root.exists()
}
}
| modules/kor-repositories-extensions/src/main/kotlin/com/sefford/kor/repositories/utils/CacheFolderImpl.kt | 1277550448 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsNamedElement
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.psi.ext.typeElement
import org.rust.lang.core.types.declaration
class AddMutableFix(val binding: RsNamedElement) : LocalQuickFixAndIntentionActionOnPsiElement(binding) {
override fun getFamilyName(): String = "Make mutable"
override fun getText(): String = "Make `${binding.name}` mutable"
val mutable = true
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
updateMutable(project, binding, mutable)
}
companion object {
fun createIfCompatible(expr: RsExpr): AddMutableFix? {
val declaration = expr.declaration
return if (declaration is RsSelfParameter || declaration is RsPatBinding) {
AddMutableFix(declaration as RsNamedElement)
} else {
null
}
}
}
}
fun updateMutable(project: Project, binding: RsNamedElement, mutable: Boolean = true) {
when (binding) {
is RsPatBinding -> {
val tuple = binding.parentOfType<RsPatTup>()
val parameter = binding.parentOfType<RsValueParameter>()
if (tuple != null && parameter != null) {
return
}
val type = parameter?.typeReference?.typeElement
if (type is RsRefLikeType) {
val newParameterExpr = RsPsiFactory(project)
.createValueParameter(parameter.pat?.text!!, type.typeReference, mutable)
parameter.replace(newParameterExpr)
return
}
val newPatBinding = RsPsiFactory(project).createPatBinding(binding.identifier.text, mutable)
binding.replace(newPatBinding)
}
is RsSelfParameter -> {
val newSelf = RsPsiFactory(project).createSelf(true)
binding.replace(newSelf)
}
}
}
| src/main/kotlin/org/rust/ide/annotator/fixes/AddMutableFix.kt | 3970986658 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.rust.utils.GeneralCommandLine
import org.rust.utils.fullyRefreshDirectory
import org.rust.utils.seconds
import org.rust.utils.withWorkDirectory
import java.nio.file.Path
private val LOG = Logger.getInstance(Rustup::class.java)
class Rustup(
private val rustup: Path,
private val rustc: Path,
private val projectDirectory: Path
) {
sealed class DownloadResult {
class Ok(val library: VirtualFile) : DownloadResult()
class Err(val error: String) : DownloadResult()
}
fun downloadStdlib(): DownloadResult {
val downloadProcessOutput = GeneralCommandLine(rustup)
.withWorkDirectory(projectDirectory)
.withParameters("component", "add", "rust-src")
.exec()
return if (downloadProcessOutput.exitCode != 0) {
DownloadResult.Err("rustup failed: `${downloadProcessOutput.stderr}`")
} else {
val sources = getStdlibFromSysroot() ?: return DownloadResult.Err("Failed to find stdlib in sysroot")
fullyRefreshDirectory(sources)
DownloadResult.Ok(sources)
}
}
fun getStdlibFromSysroot(): VirtualFile? {
val sysroot = GeneralCommandLine(rustc)
.withCharset(Charsets.UTF_8)
.withWorkDirectory(projectDirectory)
.withParameters("--print", "sysroot")
.exec(5.seconds)
.stdout.trim()
val fs = LocalFileSystem.getInstance()
return fs.refreshAndFindFileByPath(FileUtil.join(sysroot, "lib/rustlib/src/rust/src"))
}
fun createRunCommandLine(channel: RustChannel, varargs: String): GeneralCommandLine =
if (channel.rustupArgument != null) {
GeneralCommandLine(rustup, "run", channel.rustupArgument, varargs)
} else {
GeneralCommandLine(rustup, "run", varargs)
}
private fun GeneralCommandLine.exec(timeoutInMilliseconds: Int? = null): ProcessOutput {
val handler = CapturingProcessHandler(this)
LOG.info("Executing `$commandLineString`")
val output = if (timeoutInMilliseconds != null)
handler.runProcess(timeoutInMilliseconds)
else
handler.runProcess()
if (output.exitCode != 0) {
LOG.warn("Failed to execute `$commandLineString`" +
"\ncode : ${output.exitCode}" +
"\nstdout:\n${output.stdout}" +
"\nstderr:\n${output.stderr}")
}
return output
}
}
| src/main/kotlin/org/rust/cargo/toolchain/Rustup.kt | 1961296635 |
package edu.cs4730.supportdesigndemo2_kt
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
/**
* this is class to hold data so even when the destroy view is called for the fragment
* the data can survive. The left and right fragment are creating their own instance of this object.
*/
class DataViewModel(application: Application) : AndroidViewModel(application) {
private val left: MutableLiveData<String>
private val right: MutableLiveData<String>
val dataLeft: LiveData<String>
get() = left
val dataRight: LiveData<String>
get() = right
val strLeft: String?
get() = left.value
val strRight: String?
get() = right.value
fun setStrLeft(item: String) {
left.value = item
}
fun setStrRight(item: String) {
right.value = item
}
fun appendStrRight(item: String) {
val prev = right.value
right.value = prev + "\n" + item
}
fun appendStrLeft(item: String) {
val prev = left.value
left.value = prev + "\n" + item
}
init {
left = MutableLiveData("left")
right = MutableLiveData("right")
}
} | Material Design/SupportDesignDemo2_kt/app/src/main/java/edu/cs4730/supportdesigndemo2_kt/DataViewModel.kt | 1387645611 |
package com.radiostream.wrapper
import android.net.Uri
import javax.inject.Inject
/**
* Created by vitaly on 06/10/2017.
*/
class UriWrapper @Inject constructor() : UriInterface {
override fun parse(url: String): Uri {
return Uri.parse(url)
}
} | app/android/app/src/main/java/com/radiostream/wrapper/UriWrapper.kt | 3898198696 |
/*
* Copyright (C) 2019. 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.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.processors.RefreshMaterializedEntitySetProcessor
import com.openlattice.hazelcast.StreamSerializerTypeIds
import org.springframework.stereotype.Component
@Component
class RefreshMaterializedEntitySetProcessorStreamSerializer
: SelfRegisteringStreamSerializer<RefreshMaterializedEntitySetProcessor>,
AssemblerConnectionManagerDependent<Void?> {
private lateinit var acm: AssemblerConnectionManager
override fun getTypeId(): Int {
return StreamSerializerTypeIds.REFRESH_MATERIALIZED_ENTITY_SET_PROCESSOR.ordinal
}
override fun getClazz(): Class<out RefreshMaterializedEntitySetProcessor> {
return RefreshMaterializedEntitySetProcessor::class.java
}
override fun write(out: ObjectDataOutput, obj: RefreshMaterializedEntitySetProcessor) {
EntitySetStreamSerializer.serialize(out, obj.entitySet)
}
override fun read(input: ObjectDataInput): RefreshMaterializedEntitySetProcessor {
val entitySet = EntitySetStreamSerializer.deserialize(input)
return RefreshMaterializedEntitySetProcessor(entitySet).init(acm)
}
override fun init(acm: AssemblerConnectionManager): Void? {
this.acm = acm
return null
}
} | src/main/kotlin/com/openlattice/hazelcast/serializers/RefreshMaterializedEntitySetProcessorStreamSerializer.kt | 770828088 |
/*
* Copyright (C) 2019. 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.assembler.processors
import com.hazelcast.core.Offloadable
import com.hazelcast.spi.impl.executionservice.ExecutionService
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.EntitySetAssemblyKey
import com.openlattice.assembler.MaterializedEntitySet
@Deprecated("Use Transporter instead")
class DropMaterializedEntitySetProcessor
: AbstractRhizomeEntryProcessor<EntitySetAssemblyKey, MaterializedEntitySet, Void?>(),
AssemblerConnectionManagerDependent<DropMaterializedEntitySetProcessor>,
Offloadable {
@Transient
private var acm: AssemblerConnectionManager? = null
override fun process(entry: MutableMap.MutableEntry<EntitySetAssemblyKey, MaterializedEntitySet?>): Void? {
val entitySetAssemblyKey = entry.key
val materializedEntitySet = entry.value
if (materializedEntitySet == null) {
throw IllegalStateException("Encountered null materialized entity set while trying to drop materialized " +
"entity set for entity set ${entitySetAssemblyKey.entitySetId} in organization " +
"${entitySetAssemblyKey.organizationId}.")
} else {
acm?.dematerializeEntitySets(entitySetAssemblyKey.organizationId, setOf(entitySetAssemblyKey.entitySetId))
?: throw IllegalStateException(AssemblerConnectionManagerDependent.NOT_INITIALIZED)
entry.setValue(null)
}
return null
}
override fun getExecutorName(): String {
return ExecutionService.OFFLOADABLE_EXECUTOR
}
override fun init(acm: AssemblerConnectionManager): DropMaterializedEntitySetProcessor {
this.acm = acm
return this
}
override fun equals(other: Any?): Boolean {
return (other != null && other is DropMaterializedEntitySetProcessor)
}
override fun hashCode(): Int {
return super.hashCode()
}
} | src/main/kotlin/com/openlattice/assembler/processors/DropMaterializedEntitySetProcessor.kt | 2650224132 |
package com.lewisjmorgan.harvesterdroid.api.service
import com.lewisjmorgan.harvesterdroid.api.DataFactory
import com.lewisjmorgan.harvesterdroid.api.Galaxy
import com.lewisjmorgan.harvesterdroid.api.MappingType
import com.lewisjmorgan.harvesterdroid.api.Tracker
import com.lewisjmorgan.harvesterdroid.api.repository.GalaxyListRepository
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
import java.io.InputStream
import java.io.OutputStream
class GalaxyListService(private val repository: GalaxyListRepository, private val tracker: Tracker) {
private var updated = false
fun getGalaxies(): Flowable<Galaxy> {
return repository.getAll()
}
fun downloadGalaxies(): Flowable<Galaxy> {
return tracker.downloadGalaxies()
.doOnNext { resource -> repository.add(resource) }
.doOnComplete { updated = true }
}
fun save(outputStream: OutputStream, dataFactory: DataFactory, mappingType: MappingType): Single<OutputStream> {
return getGalaxies().toList().map { dataFactory.serialize(outputStream, it, mappingType) }
}
fun load(inputStream: InputStream, dataFactory: DataFactory, mappingType: MappingType): Flowable<Galaxy> {
return Observable.create<Galaxy> { emitter ->
val galaxies = dataFactory.deserialize<List<Galaxy>>(inputStream, mappingType)
galaxies.forEach { emitter.onNext(it) }
emitter.onComplete()
}.doOnNext { repository.add(it) }.toFlowable(BackpressureStrategy.BUFFER)
}
fun hasUpdatedGalaxies() = updated
}
| api/src/main/kotlin/com/lewisjmorgan/harvesterdroid/api/service/GalaxyListService.kt | 403898606 |
package guide.howto.create_a_custom_json_marshaller
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.KotlinModule
// this import is important so you don't pick up the standard auto method!
import guide.howto.create_a_custom_json_marshaller.MyJackson.auto
import org.http4k.core.Body
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.with
import org.http4k.format.ConfigurableJackson
import org.http4k.format.asConfigurable
import org.http4k.format.text
import org.http4k.format.withStandardMappings
object MyJackson : ConfigurableJackson(
KotlinModule.Builder().build()
.asConfigurable()
.withStandardMappings()
// declare custom mapping for our own types - this one represents our type as a
// simple String
.text(::PublicType, PublicType::value)
// ... and this one shows a masked value and cannot be deserialised
// (as the mapping is only one way)
.text(SecretType::toString)
.done()
.deactivateDefaultTyping()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
)
data class PublicType(val value: String)
data class SecretType(val value: String) {
override fun toString(): String {
return "****"
}
}
data class MyType(val public: PublicType, val hidden: SecretType)
fun main() {
println(
Response(OK).with(
Body.auto<MyType>().toLens() of MyType(
PublicType("hello"),
SecretType("secret")
)
)
)
/** Prints:
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
{"public":"hello","hidden":"****"}
*/
}
| src/docs/guide/howto/create_a_custom_json_marshaller/example.kt | 1954502772 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.digitalwellbeingexperiments.toolkit.notificationlistener
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.gson.Gson
class NotificationListener : NotificationListenerService() {
companion object {
const val ACTION_REFRESH_UI = "REFRESH"
const val ACTION_CLEAR_DATA = "CLEAR"
const val KEY_NOTIFICATIONS = "key_notifications"
}
//Handles messages from UI (Activity) to background service
private val receiver: BroadcastReceiver = object: BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Log.w(TAG(), "onReceive() ${intent?.action}")
dataMap.clear()
sendUpdate()
}
}
private val dataMap = HashMap<String, NotificationItem>()
//when user switches ON in Settings
override fun onListenerConnected() {
Log.w(TAG(), "onListenerConnected()")
val currentNotifications = activeNotifications
.filter { sbn -> sbn.packageName != this.packageName }
.map {
createNotificationItem(it)
}.toTypedArray()
currentNotifications.forEach {
dataMap[it.sbnKey] = it
}
sendUpdate()
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
IntentFilter(ACTION_CLEAR_DATA)
)
}
//when user switches OFF in Settings
override fun onListenerDisconnected() {
Log.w(TAG(), "onListenerDisconnected()")
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
if (this.packageName != sbn.packageName) {
Log.w(TAG(), "onNotificationPosted() ${sbn.key}")
val notificationItem = createNotificationItem(sbn)
dataMap[sbn.key] = notificationItem
sendUpdate()
}
}
private fun sendUpdate() {
val intent = Intent(ACTION_REFRESH_UI)
val dataList = dataMap.values.toList()
intent.putExtra(KEY_NOTIFICATIONS, Gson().toJson(dataList))
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
private fun createNotificationItem(sbn: StatusBarNotification): NotificationItem {
return NotificationItem(
sbn.key,
sbn.packageName,
title = "${sbn.getTitleBig()}\n${sbn.getTitle()}".trim(),
text = "${sbn.getText()}\n${sbn.getSubText()}".trim(),
postTime = sbn.postTime
)
}
}
| notifications/notifications-listener/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationlistener/NotificationListener.kt | 1915149553 |
package ii_conventions
import util.TODO
fun iterateOverCollection(collection: Collection<Int>) {
for (element in collection) {}
}
fun iterateOverString() {
//You can iterate over anything that has a method 'iterator', member or extension.
for (c in "abcd") {}
"abcd".iterator() //library extension method
}
fun todoTask12() = TODO(
"""
Task 12.
Uncomment the commented code and make it compile.
Add all changes to the file MyDate.kt.
Make class DateRange implement Iterable<MyDate>.
Use object expression to implement Iterator<MyDate>.
Use an utility function 'MyDate.nextDay()'.
""",
references = { date: MyDate -> DateRange(date, date.nextDay()) })
fun iterateOverDateRange(firstDate: MyDate, secondDate: MyDate, handler: (MyDate) -> Unit) {
for (date in DateRange(firstDate, secondDate)) {
handler(date)
}
} | src/ii_conventions/_12_ForLoop.kt | 22370640 |
/* Copyright 2018 Conny Duck
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky.fragment.preference
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.preference.SwitchPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import android.util.Log
import android.view.View
import com.keylesspalace.tusky.*
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.appstore.PreferenceChangedEvent
import com.keylesspalace.tusky.db.AccountManager
import com.keylesspalace.tusky.di.Injectable
import com.keylesspalace.tusky.entity.Account
import com.keylesspalace.tusky.entity.Status
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.util.ThemeUtils
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class AccountPreferencesFragment : PreferenceFragmentCompat(),
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
Injectable {
@Inject
lateinit var accountManager: AccountManager
@Inject
lateinit var mastodonApi: MastodonApi
@Inject
lateinit var eventHub: EventHub
private lateinit var notificationPreference: Preference
private lateinit var tabPreference: Preference
private lateinit var mutedUsersPreference: Preference
private lateinit var blockedUsersPreference: Preference
private lateinit var defaultPostPrivacyPreference: ListPreference
private lateinit var defaultMediaSensitivityPreference: SwitchPreference
private lateinit var alwaysShowSensitiveMediaPreference: SwitchPreference
private lateinit var mediaPreviewEnabledPreference: SwitchPreference
private val iconSize by lazy {resources.getDimensionPixelSize(R.dimen.preference_icon_size)}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.account_preferences)
notificationPreference = findPreference("notificationPreference")
tabPreference = findPreference("tabPreference")
mutedUsersPreference = findPreference("mutedUsersPreference")
blockedUsersPreference = findPreference("blockedUsersPreference")
defaultPostPrivacyPreference = findPreference("defaultPostPrivacy") as ListPreference
defaultMediaSensitivityPreference = findPreference("defaultMediaSensitivity") as SwitchPreference
mediaPreviewEnabledPreference = findPreference("mediaPreviewEnabled") as SwitchPreference
alwaysShowSensitiveMediaPreference = findPreference("alwaysShowSensitiveMedia") as SwitchPreference
notificationPreference.icon = IconicsDrawable(notificationPreference.context, GoogleMaterial.Icon.gmd_notifications).sizePx(iconSize).color(ThemeUtils.getColor(notificationPreference.context, R.attr.toolbar_icon_tint))
mutedUsersPreference.icon = getTintedIcon(R.drawable.ic_mute_24dp)
blockedUsersPreference.icon = IconicsDrawable(blockedUsersPreference.context, GoogleMaterial.Icon.gmd_block).sizePx(iconSize).color(ThemeUtils.getColor(blockedUsersPreference.context, R.attr.toolbar_icon_tint))
notificationPreference.onPreferenceClickListener = this
tabPreference.onPreferenceClickListener = this
mutedUsersPreference.onPreferenceClickListener = this
blockedUsersPreference.onPreferenceClickListener = this
defaultPostPrivacyPreference.onPreferenceChangeListener = this
defaultMediaSensitivityPreference.onPreferenceChangeListener = this
mediaPreviewEnabledPreference.onPreferenceChangeListener = this
alwaysShowSensitiveMediaPreference.onPreferenceChangeListener = this
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
accountManager.activeAccount?.let {
defaultPostPrivacyPreference.value = it.defaultPostPrivacy.serverString()
defaultPostPrivacyPreference.icon = getIconForVisibility(it.defaultPostPrivacy)
defaultMediaSensitivityPreference.isChecked = it.defaultMediaSensitivity
defaultMediaSensitivityPreference.icon = getIconForSensitivity(it.defaultMediaSensitivity)
mediaPreviewEnabledPreference.isChecked = it.mediaPreviewEnabled
alwaysShowSensitiveMediaPreference.isChecked = it.alwaysShowSensitiveMedia
}
}
override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
when(preference) {
defaultPostPrivacyPreference -> {
preference.icon = getIconForVisibility(Status.Visibility.byString(newValue as String))
syncWithServer(visibility = newValue)
}
defaultMediaSensitivityPreference -> {
preference.icon = getIconForSensitivity(newValue as Boolean)
syncWithServer(sensitive = newValue)
}
mediaPreviewEnabledPreference -> {
accountManager.activeAccount?.let {
it.mediaPreviewEnabled = newValue as Boolean
accountManager.saveAccount(it)
}
}
alwaysShowSensitiveMediaPreference -> {
accountManager.activeAccount?.let {
it.alwaysShowSensitiveMedia = newValue as Boolean
accountManager.saveAccount(it)
}
}
}
eventHub.dispatch(PreferenceChangedEvent(preference.key))
return true
}
override fun onPreferenceClick(preference: Preference): Boolean {
when(preference) {
notificationPreference -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val intent = Intent()
intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
intent.putExtra("android.provider.extra.APP_PACKAGE", BuildConfig.APPLICATION_ID)
startActivity(intent)
} else {
activity?.let {
val intent = PreferencesActivity.newIntent(it, PreferencesActivity.NOTIFICATION_PREFERENCES)
it.startActivity(intent)
it.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
}
}
return true
}
tabPreference -> {
val intent = Intent(context, TabPreferenceActivity::class.java)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
mutedUsersPreference -> {
val intent = Intent(context, AccountListActivity::class.java)
intent.putExtra("type", AccountListActivity.Type.MUTES)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
blockedUsersPreference -> {
val intent = Intent(context, AccountListActivity::class.java)
intent.putExtra("type", AccountListActivity.Type.BLOCKS)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
else -> return false
}
}
private fun syncWithServer(visibility: String? = null, sensitive: Boolean? = null) {
mastodonApi.accountUpdateSource(visibility, sensitive)
.enqueue(object: Callback<Account>{
override fun onResponse(call: Call<Account>, response: Response<Account>) {
val account = response.body()
if(response.isSuccessful && account != null) {
accountManager.activeAccount?.let {
it.defaultPostPrivacy = account.source?.privacy ?: Status.Visibility.PUBLIC
it.defaultMediaSensitivity = account.source?.sensitive ?: false
accountManager.saveAccount(it)
}
} else {
Log.e("AccountPreferences", "failed updating settings on server")
showErrorSnackbar(visibility, sensitive)
}
}
override fun onFailure(call: Call<Account>, t: Throwable) {
Log.e("AccountPreferences", "failed updating settings on server", t)
showErrorSnackbar(visibility, sensitive)
}
})
}
private fun showErrorSnackbar(visibility: String?, sensitive: Boolean?) {
view?.let {view ->
Snackbar.make(view, R.string.pref_failed_to_sync, Snackbar.LENGTH_LONG)
.setAction(R.string.action_retry) { syncWithServer( visibility, sensitive)}
.show()
}
}
private fun getIconForVisibility(visibility: Status.Visibility): Drawable? {
val drawableId = when (visibility) {
Status.Visibility.PRIVATE -> R.drawable.ic_lock_outline_24dp
Status.Visibility.UNLISTED -> R.drawable.ic_lock_open_24dp
else -> R.drawable.ic_public_24dp
}
return getTintedIcon(drawableId)
}
private fun getIconForSensitivity(sensitive: Boolean): Drawable? {
val drawableId = if (sensitive) {
R.drawable.ic_hide_media_24dp
} else {
R.drawable.ic_eye_24dp
}
return getTintedIcon(drawableId)
}
private fun getTintedIcon(iconId: Int): Drawable? {
val drawable = context?.getDrawable(iconId)
ThemeUtils.setDrawableTint(context, drawable, R.attr.toolbar_icon_tint)
return drawable
}
companion object {
fun newInstance(): AccountPreferencesFragment {
return AccountPreferencesFragment()
}
}
}
| app/src/main/java/com/keylesspalace/tusky/fragment/preference/AccountPreferencesFragment.kt | 3184332207 |
package io.gitlab.arturbosch.detekt.formatting.wrappers
import com.pinterest.ktlint.ruleset.experimental.PackageNameRule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.formatting.FormattingRule
/**
* See <a href="https://ktlint.github.io">ktlint-website</a> for documentation.
*
* @active since v1.0.0
* @autoCorrect since v1.0.0
*/
class PackageName(config: Config) : FormattingRule(config) {
override val wrapping = PackageNameRule()
override val issue = issueFor("Checks package name is formatted correctly")
}
| detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/PackageName.kt | 864043374 |
package de.christinecoenen.code.zapp.app.app.livestream.ui.detail
import android.app.Activity
import android.content.pm.ActivityInfo
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import de.christinecoenen.code.zapp.app.livestream.ui.detail.ChannelPlayerActivity
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ChannelDetailActivityTest {
@Test
fun testRecreation() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val intent = ChannelPlayerActivity.getStartIntent(context, "das_erste")
val scenario = ActivityScenario.launch<Activity>(intent)
scenario.recreate()
scenario.onActivity { it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE }
scenario.recreate()
}
}
| app/src/androidTest/java/de/christinecoenen/code/zapp/app/app/livestream/ui/detail/ChannelDetailActivityTest.kt | 2275080860 |
package com.infinum.dbinspector.ui.edit.history
import com.infinum.dbinspector.domain.history.models.History as HistoryModel
internal sealed class HistoryState {
data class History(
val history: HistoryModel
) : HistoryState()
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/edit/history/HistoryState.kt | 4256207199 |
package io.javalin.plugin.openapi
import io.javalin.http.Context
import io.swagger.v3.oas.models.OpenAPI
@FunctionalInterface
interface OpenApiModelModifier {
fun apply(ctx : Context, model : OpenAPI) : OpenAPI
}
class NoOpOpenApiModelModifier : OpenApiModelModifier {
override fun apply(ctx: Context, model: OpenAPI) = model
}
| javalin-openapi/src/main/java/io/javalin/plugin/openapi/OpenApiModelModifier.kt | 2329168783 |
/*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import sir.wellington.alchemy.collections.maps.Maps
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.StringGenerators
import java.net.URL
import java.util.Objects
/**
*
* @author SirWellington
*/
@Internal
internal data class TestRequest(override var queryParams: Map<String, String> = CollectionGenerators.mapOf(StringGenerators.alphabeticStrings(), StringGenerators.alphabeticStrings(), 6),
override var url: URL? = one(Generators.validUrls()),
override var body: JsonElement? = one(Generators.jsonElements()),
override var method: RequestMethod = Constants.DEFAULT_REQUEST_METHOD) : HttpRequest
{
override var requestHeaders: Map<String, String>? = CollectionGenerators.mapOf(StringGenerators.alphabeticStrings(),
StringGenerators.alphabeticStrings(),
20).toMap()
override fun hasBody(): Boolean
{
return body?.let { it != JsonNull.INSTANCE } ?: false
}
override fun hasQueryParams(): Boolean
{
return Maps.isEmpty(queryParams)
}
override fun equals(other: HttpRequest?): Boolean
{
return this == other as Any?
}
override fun hasMethod(): Boolean
{
return Objects.nonNull(method)
}
override fun equals(other: Any?): Boolean
{
val other = other as? HttpRequest ?: return false
return super.equals(other)
}
}
| src/test/java/tech/sirwellington/alchemy/http/TestRequest.kt | 2859478822 |
package de.westnordost.streetcomplete.quests.traffic_signals_button
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddTrafficSignalsButton : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes with
crossing = traffic_signals
and highway ~ crossing|traffic_signals
and foot != no
and !button_operated
"""
override val commitMessage = "Add whether traffic signals have a button for pedestrians"
override val wikiLink = "Tag:highway=traffic_signals"
override val icon = R.drawable.ic_quest_traffic_lights
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_traffic_signals_button_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("button_operated", answer.toYesNo())
}
override val defaultDisabledMessage = R.string.default_disabled_msg_boring
}
| app/src/main/java/de/westnordost/streetcomplete/quests/traffic_signals_button/AddTrafficSignalsButton.kt | 30375287 |
/*
* 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.bookmark.movie.data.local
import br.com.bookmark.movie.data.BookmarkDataSource
import br.com.bookmark.movie.data.DatabaseError
import br.com.bookmark.movie.data.local.dao.MovieBookmarksDao
import br.com.bookmark.movie.data.local.entity.MovieBookmark
import br.com.moov.core.di.AppScope
import br.com.moov.core.result.Result
import com.squareup.anvil.annotations.ContributesBinding
import java.io.IOException
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class LocalBookmarkDataSource @Inject constructor(
private val movieBookmarksDao: MovieBookmarksDao
) : BookmarkDataSource {
override suspend fun bookmarkMovie(movieId: Int): Result<Unit, DatabaseError> {
return try {
movieBookmarksDao.insert(MovieBookmark(movieId))
Result.Ok(Unit)
} catch (exception: IOException) {
Result.Err(DatabaseError(exception.message ?: "Unknown error"))
}
}
override suspend fun unBookmarkMovie(movieId: Int): Result<Unit, DatabaseError> {
return try {
movieBookmarksDao.delete(movieId)
Result.Ok(Unit)
} catch (exception: IOException) {
Result.Err(DatabaseError(exception.message ?: "Unknown error"))
}
}
}
| feature/bookmark-movie/impl/src/main/java/br/com/bookmark/movie/data/local/LocalBookmarkDataSource.kt | 3737570997 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import java.time.LocalDate
/** key <= date */
class HasDateTagLessOrEqualThan(key: String, dateFilter: DateFilter): CompareDateTagValue(key, dateFilter) {
override val operator = "<="
override fun compareTo(tagValue: LocalDate) = tagValue <= date
}
| app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasDateTagLessOrEqualThan.kt | 866764974 |
package com.mapalarm.usecases
import com.mapalarm.datatypes.Position
interface MovePresenter {
fun showUserAt(position: Position)
open fun showPositionUnknown()
}
| alarm-lib/src/main/java/com/mapalarm/usecases/MovePresenter.kt | 2370223034 |
package org.mifos.mobile.models.accounts.loan.calendardata
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Created by Rajan Maurya on 04/03/17.
*/
@Parcelize
data class Type(
@SerializedName("id")
var id: Int? = null,
@SerializedName("code")
var code: String,
@SerializedName("value")
var value: String
) : Parcelable | app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Type.kt | 1101586590 |
package by.heap.apiary.api.lib
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.apache.http.HttpEntity
import org.apache.http.util.EntityUtils
data class ApiaryResponse (val error: Boolean?, val message: String?, val code: String?)
val mapper = jacksonObjectMapper()
fun HttpEntity.toResponse(): ApiaryResponse = mapper.readValue(EntityUtils.toString(this))
| apiary-api-lib/src/main/kotlin/by/heap/apiary/api/lib/ApiaryResponse.kt | 870263613 |
package fr.insapp.insapp.activities
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.util.Linkify
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.google.firebase.analytics.FirebaseAnalytics
import com.varunest.sparkbutton.SparkEventListener
import fr.insapp.insapp.R
import fr.insapp.insapp.adapters.CommentRecyclerViewAdapter
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.*
import fr.insapp.insapp.utility.Utils
import kotlinx.android.synthetic.main.activity_post.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by thomas on 12/11/2016.
*/
class PostActivity : AppCompatActivity() {
private lateinit var commentAdapter: CommentRecyclerViewAdapter
private lateinit var post: Post
private var association: Association? = null
private lateinit var requestManager: RequestManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestManager = Glide.with(this)
val user = Utils.user
// post
if (intent.getParcelableExtra<Post>("post") != null) {
// coming from navigation
this.post = intent.getParcelableExtra("post")
generateActivity()
// mark notification as seen
if (intent.getParcelableExtra<Notification>("notification") != null) {
val notification = intent.getParcelableExtra<Notification>("notification")
if (user != null) {
val call = ServiceGenerator.client.markNotificationAsSeen(user.id, notification.id)
call.enqueue(object : Callback<Notifications> {
override fun onResponse(call: Call<Notifications>, response: Response<Notifications>) {
if (!response.isSuccessful) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Notifications>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "")
}
}
} else {
// coming from notification
setContentView(R.layout.loading)
ServiceGenerator.client.getPostFromId(intent.getStringExtra("ID"))
.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
val result = response.body()
if (response.isSuccessful && result != null) {
post = result
generateActivity()
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Toast.makeText(this@PostActivity, R.string.check_internet_connection, Toast.LENGTH_LONG).show()
// Open the application
startActivity(Intent(this@PostActivity, MainActivity::class.java))
finish()
}
})
}
}
private fun generateActivity() {
setContentView(R.layout.activity_post)
// toolbar
setSupportActionBar(post_toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val user = Utils.user
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, post.id)
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, post.title)
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Post")
bundle.putInt("favorites_count", post.likes.size)
bundle.putInt("comments_count", post.comments.size)
FirebaseAnalytics.getInstance(this).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
// hide image if necessary
if (post.image.isEmpty()) {
post_placeholder?.visibility = View.GONE
post_image?.visibility = View.GONE
}
// like button
user?.let {
post_like_button?.setChecked(post.isPostLikedBy(user.id))
}
post_like_counter?.text = post.likes.size.toString()
post_like_button?.setEventListener(object : SparkEventListener {
override fun onEvent(icon: ImageView, buttonState: Boolean) {
if (buttonState) {
post_like_counter?.text = (Integer.valueOf(post_like_counter?.text as String) + 1).toString()
if (user != null) {
val call = ServiceGenerator.client.likePost(post.id, user.id)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
val results = response.body()
if (response.isSuccessful && results != null) {
post = results.post
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "Couldn't update the like status: user is null")
}
} else {
post_like_counter?.text = (Integer.valueOf(post_like_counter?.text as String) - 1).toString()
if (Integer.valueOf(post_like_counter?.text as String) < 0) {
post_like_counter?.text = "0"
}
if (user != null) {
val call = ServiceGenerator.client.dislikePost(post.id, user.id)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
val result = response.body()
if (response.isSuccessful && result != null) {
post = result.post
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "Couldn't update the like status: user is null")
}
}
}
override fun onEventAnimationEnd(button: ImageView?, buttonState: Boolean) {}
override fun onEventAnimationStart(button: ImageView?, buttonState: Boolean) {}
})
val call = ServiceGenerator.client.getAssociationFromId(post.association)
call.enqueue(object : Callback<Association> {
override fun onResponse(call: Call<Association>, response: Response<Association>) {
if (response.isSuccessful) {
association = response.body()
requestManager
.load(ServiceGenerator.CDN_URL + association!!.profilePicture)
.apply(RequestOptions.circleCropTransform())
.transition(withCrossFade())
.into(post_association_avatar)
// listener
post_association_avatar?.setOnClickListener { startActivity(Intent(this@PostActivity, AssociationActivity::class.java).putExtra("association", association)) }
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Association>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
post_title?.text = post.title
post_text?.text = post.description
post_date?.text = Utils.displayedDate(post.date)
// view links contained in description
Linkify.addLinks(post_text, Linkify.ALL)
Utils.convertToLinkSpan(this@PostActivity, post_text)
// edit comment adapter
commentAdapter = CommentRecyclerViewAdapter(post.comments, requestManager)
commentAdapter.setOnCommentItemLongClickListener(PostCommentLongClickListener(this@PostActivity, post, commentAdapter))
comment_post_input.setupComponent()
comment_post_input.setOnEditorActionListener(TextView.OnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// hide keyboard
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(textView.windowToken, 0)
val content = comment_post_input.text.toString()
comment_post_input.text.clear()
if (content.isNotBlank()) {
user?.let {
val comment = Comment(null, user.id, content, null, comment_post_input.tags)
Log.d(TAG, comment.toString())
ServiceGenerator.client.commentPost(post.id, comment)
.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
if (response.isSuccessful) {
commentAdapter.addComment(comment)
comment_post_input.tags.clear()
Toast.makeText(this@PostActivity, resources.getText(R.string.write_comment_success), Toast.LENGTH_LONG).show()
} else {
Log.e(TAG, "Couldn't post comment: ${response.code()}")
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Log.e(TAG, "Couldn't post comment: ${t.message}")
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
}
}
return@OnEditorActionListener true
}
false
})
// recycler view
recyclerview_comments_post.setHasFixedSize(true)
recyclerview_comments_post.isNestedScrollingEnabled = false
val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerview_comments_post.layoutManager = layoutManager
recyclerview_comments_post.adapter = commentAdapter
// retrieve the avatar of the user
val id = resources.getIdentifier(Utils.drawableProfileName(user?.promotion, user?.gender), "drawable", packageName)
requestManager
.load(id)
.transition(withCrossFade())
.apply(RequestOptions.circleCropTransform())
.into(comment_post_username_avatar)
// image
if (post.image.isNotEmpty()) {
post_placeholder?.setImageSize(post.imageSize)
requestManager
.load(ServiceGenerator.CDN_URL + post.image)
.transition(withCrossFade())
.into(post_image)
}
}
override fun finish() {
if (::post.isInitialized) {
val sendIntent = Intent()
sendIntent.putExtra("post", post)
setResult(Activity.RESULT_OK, sendIntent)
} else {
setResult(Activity.RESULT_CANCELED)
}
super.finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
if (isTaskRoot) {
startActivity(Intent(this@PostActivity, MainActivity::class.java))
} else {
finish()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
companion object {
const val TAG = "PostActivity"
}
class PostCommentLongClickListener(
private val context: Context,
private val post: Post,
private val adapter: CommentRecyclerViewAdapter
): CommentRecyclerViewAdapter.OnCommentItemLongClickListener {
override fun onCommentItemLongClick(comment: Comment) {
val alertDialogBuilder = AlertDialog.Builder(context)
val user = Utils.user
// delete comment
if (user != null) {
if (user.id == comment.user) {
alertDialogBuilder
.setTitle(context.resources.getString(R.string.delete_comment_action))
.setMessage(R.string.delete_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.uncommentPost(post.id, comment.id!!)
call.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
val post = response.body()
if (response.isSuccessful && post != null) {
adapter.setComments(post.comments)
} else {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show()
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
// report comment
else {
alertDialogBuilder
.setTitle(context.getString(R.string.report_comment_action))
.setMessage(R.string.report_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.reportComment(post.id, comment.id!!)
call.enqueue(object : Callback <Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
Toast.makeText(context, context.getString(R.string.report_comment_success), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show();
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show();
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
}
}
}
}
fun Post.isPostLikedBy(userID: String): Boolean {
for (idUser in likes)
if (idUser == userID) return true
return false
} | app/src/main/java/fr/insapp/insapp/activities/PostActivity.kt | 463918978 |
package msg_queue.demo
import msg_queue.*
import kotlin.concurrent.thread
fun main1(args: Array<String>) {
val handler = object : Handler() {
override fun handleMessage(msg: Message) {
println("szw handler handleMesage(${msg.what})")
}
}
val msg = Message()
msg.what = 11
msg.obj = "test" //要是obj是Object类型, 这就会报错. 正确得是Any类型
handler.sendMessage(msg)
handler.sendMessageDelay(Message(), 1000)
handler.sendMessageDelay(Message(), 2000)
handler.sendMessageDelay(Message(), 4000)
// 省略了Looper.prepare()
println("01")
Looper.loop()
println("02") //=> 这一句永远就不执行了
}
fun main(args: Array<String>) {
// 不加isDaemon=true, 就报错 "Exception in thread "main" java.lang.IllegalThreadStateException"
thread(start = true, isDaemon = true) {
val handler = object : Handler() {
override fun handleMessage(msg: Message) {
println("szw handler handleMesage(${msg.what})")
}
}
val msg = Message()
msg.what = 11
msg.obj = "test" //要是obj是Object类型, 这就会报错. 正确得是Any类型
handler.sendMessage(msg)
println("011")
Looper.loop()
println("022") // 不会执行到这一句
}.join() //加了join, 就一直在等此线程完结. 但此线程因为loop()死循环, 一直不结束, 所以main()方法也一直不结束
} | AdvancedJ/src/main/kotlin/msg_queue/demo/HandlerDemo.kt | 452275253 |
/*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.forecast.ui.cities
import android.app.Activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import io.michaelrocks.forecast.R
import io.michaelrocks.forecast.databinding.CitiesActivityBinding
import io.michaelrocks.forecast.ui.base.BaseActivity
import io.michaelrocks.forecast.ui.common.EXTRA_CITY_ID
import io.michaelrocks.forecast.ui.common.EXTRA_CITY_NAME
import io.michaelrocks.forecast.ui.common.EXTRA_COUNTRY
import io.michaelrocks.forecast.ui.common.vertical
import io.michaelrocks.lightsaber.inject
import javax.inject.Inject
class CitiesActivity : BaseActivity() {
@Inject private val viewModel: CitiesActivityViewModel = inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<CitiesActivityBinding>(this, R.layout.cities_activity)
binding.model = viewModel.apply {
onChooseCity = { city ->
city?.apply {
val intent = Intent()
intent.putExtra(EXTRA_CITY_ID, id)
intent.putExtra(EXTRA_CITY_NAME, name)
intent.putExtra(EXTRA_COUNTRY, country)
setResult(Activity.RESULT_OK, intent)
}
finish()
}
}
@Suppress("DEPRECATION")
val dividerDrawable = resources.getDrawable(R.drawable.list_divider)
val dividerPadding = resources.getDimensionPixelSize(R.dimen.divider_size)
binding.recycler.addItemDecoration(vertical(dividerDrawable, dividerPadding))
}
override fun onDestroy() {
super.onDestroy()
viewModel.close()
}
}
| app/src/main/kotlin/io/michaelrocks/forecast/ui/cities/CitiesActivity.kt | 2826986845 |
package tech.devezin.allstorj
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/tech/devezin/allstorj/ExampleUnitTest.kt | 4026687379 |
package org.wordpress.android.fluxc.network.rest.wpcom.stats.time
import org.wordpress.android.fluxc.model.stats.insights.PostingActivityModel.Day
import org.wordpress.android.fluxc.network.utils.CurrentDateUtils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import javax.inject.Inject
const val DATE_FORMAT_DAY = "yyyy-MM-dd"
class StatsUtils
@Inject constructor(private val currentDateUtils: CurrentDateUtils) {
fun getFormattedDate(date: Date? = null, timeZone: TimeZone? = null): String {
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
timeZone?.let {
dateFormat.timeZone = timeZone
}
return dateFormat.format(date ?: currentDateUtils.getCurrentDate())
}
fun getFormattedDate(day: Day): String {
val calendar = Calendar.getInstance()
calendar.set(day.year, day.month, day.day)
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
return dateFormat.format(calendar.time)
}
fun fromFormattedDate(date: String): Date? {
if (date.isEmpty()) {
return null
}
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
return dateFormat.parse(date)
}
}
| fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/stats/time/StatsUtils.kt | 1746514738 |
/*
* 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.statistic
import org.lanternpowered.api.catalog.CatalogType
import org.spongepowered.api.NamedCatalogType
import org.spongepowered.api.statistic.Statistic
interface XStatistic : Statistic, NamedCatalogType {
interface TypeInstance<T : CatalogType> : XStatistic, Statistic.TypeInstance<T>
}
| src/main/kotlin/org/lanternpowered/server/statistic/XStatistic.kt | 3689896898 |
package com.mooveit.library.providers.definition
interface Provider {
} | library/src/main/java/com/mooveit/library/providers/definition/Provider.kt | 3177448887 |
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileContentForTest
import io.gitlab.arturbosch.detekt.test.lint
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
/**
* @author Artur Bosch
*/
internal class MatchingDeclarationNameSpec : Spek({
given("compliant test cases") {
it("should pass for object declaration") {
val ktFile = compileContentForTest("object O")
ktFile.name = "O.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for class declaration") {
val ktFile = compileContentForTest("class C")
ktFile.name = "C.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for interface declaration") {
val ktFile = compileContentForTest("interface I")
ktFile.name = "I.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for enum declaration") {
val ktFile = compileContentForTest("""
enum class E {
ONE, TWO, THREE
}
""")
ktFile.name = "E.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for multiple declaration") {
val ktFile = compileContentForTest("""
class C
object O
fun a() = 5
""")
ktFile.name = "MultiDeclarations.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for class declaration with utility functions") {
val ktFile = compileContentForTest("""
class C
fun a() = 5
fun C.b() = 5
""")
ktFile.name = "C.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for private class declaration") {
val ktFile = compileContentForTest("""
private class C
fun a() = 5
""")
ktFile.name = "b.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for a class with a typealias") {
val code = """
typealias Foo = FooImpl
class FooImpl {}"""
val ktFile = compileContentForTest(code)
ktFile.name = "Foo.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
}
given("non-compliant test cases") {
it("should not pass for object declaration") {
val ktFile = compileContentForTest("object O")
ktFile.name = "Objects.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'object O' at (1,1) in /Objects.kt")
}
it("should not pass for class declaration") {
val ktFile = compileContentForTest("class C")
ktFile.name = "Classes.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'class C' at (1,1) in /Classes.kt")
}
it("should not pass for class declaration with utility functions") {
val ktFile = compileContentForTest("""
class C
fun a() = 5
fun C.b() = 5
""")
ktFile.name = "ClassUtils.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("""'
class C
fun a() = 5
fun C.b() = 5
' at (1,1) in /ClassUtils.kt""", trimIndent = true)
}
it("should not pass for interface declaration") {
val ktFile = compileContentForTest("interface I")
ktFile.name = "Not_I.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'interface I' at (1,1) in /Not_I.kt")
}
it("should not pass for enum declaration") {
val ktFile = compileContentForTest("""
enum class NOT_E {
ONE, TWO, THREE
}
""")
ktFile.name = "E.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("""'
enum class NOT_E {
ONE, TWO, THREE
}
' at (1,1) in /E.kt""", trimIndent = true)
}
it("should not pass for a typealias with a different name") {
val code = """
typealias Bar = FooImpl
class FooImpl {}"""
val ktFile = compileContentForTest(code)
ktFile.name = "Foo.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasSize(1)
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/MatchingDeclarationNameSpec.kt | 1155203833 |
package io.gitlab.arturbosch.detekt.core.processors
import io.gitlab.arturbosch.detekt.core.path
import io.gitlab.arturbosch.detekt.test.compileForTest
import org.assertj.core.api.Assertions
import org.jetbrains.kotlin.psi.KtFile
import org.junit.jupiter.api.Test
class KtFileCountVisitorTest {
@Test
fun twoFiles() {
val files = arrayOf(
compileForTest(path.resolve("Default.kt")),
compileForTest(path.resolve("Test.kt"))
)
val count = files
.map { getData(it) }
.sum()
Assertions.assertThat(count).isEqualTo(2)
}
private fun getData(file: KtFile): Int {
return with(file) {
accept(KtFileCountVisitor())
getUserData(numberOfFilesKey)!!
}
}
}
| detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/processors/KtFileCountVisitorTest.kt | 3160232454 |
package io.clappr.player.base
import org.junit.Test
import kotlin.test.assertEquals
class EventTest {
@Test
fun shouldHaveUniqueValue() {
Event.values().forEach {
assertEquals(1, Event.values().filter { event -> event.value == it.value }.size, "More than 1 event with \"${it.value}\" value")
}
}
} | clappr/src/test/kotlin/io/clappr/player/base/EventTest.kt | 953131603 |
/*
* Copyright 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.mlkit.showcase.translate.analyzer
import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.widget.Toast
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.tasks.Task
import com.google.mlkit.common.MlKitException
import com.google.mlkit.showcase.translate.util.ImageUtils
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import java.util.concurrent.Executor
/**
* Analyzes the frames passed in from the camera and returns any detected text within the requested
* crop region.
*/
class TextAnalyzer(
private val context: Context,
lifecycle: Lifecycle,
executor: Executor,
private val result: MutableLiveData<String>,
private val imageCropPercentages: MutableLiveData<Pair<Int, Int>>
) : ImageAnalysis.Analyzer {
private val detector =
TextRecognition.getClient(TextRecognizerOptions.Builder().setExecutor(executor).build())
init {
lifecycle.addObserver(detector)
}
@androidx.camera.core.ExperimentalGetImage
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotationDegrees = imageProxy.imageInfo.rotationDegrees
// We requested a setTargetAspectRatio, but it's not guaranteed that's what the camera
// stack is able to support, so we calculate the actual ratio from the first frame to
// know how to appropriately crop the image we want to analyze.
val imageHeight = mediaImage.height
val imageWidth = mediaImage.width
val actualAspectRatio = imageWidth / imageHeight
val convertImageToBitmap = ImageUtils.convertYuv420888ImageToBitmap(mediaImage)
val cropRect = Rect(0, 0, imageWidth, imageHeight)
// If the image has a way wider aspect ratio than expected, crop less of the height so we
// don't end up cropping too much of the image. If the image has a way taller aspect ratio
// than expected, we don't have to make any changes to our cropping so we don't handle it
// here.
val currentCropPercentages = imageCropPercentages.value ?: return
if (actualAspectRatio > 3) {
val originalHeightCropPercentage = currentCropPercentages.first
val originalWidthCropPercentage = currentCropPercentages.second
imageCropPercentages.value =
Pair(originalHeightCropPercentage / 2, originalWidthCropPercentage)
}
// If the image is rotated by 90 (or 270) degrees, swap height and width when calculating
// the crop.
val cropPercentages = imageCropPercentages.value ?: return
val heightCropPercent = cropPercentages.first
val widthCropPercent = cropPercentages.second
val (widthCrop, heightCrop) = when (rotationDegrees) {
90, 270 -> Pair(heightCropPercent / 100f, widthCropPercent / 100f)
else -> Pair(widthCropPercent / 100f, heightCropPercent / 100f)
}
cropRect.inset(
(imageWidth * widthCrop / 2).toInt(),
(imageHeight * heightCrop / 2).toInt()
)
val croppedBitmap = ImageUtils.rotateAndCrop(convertImageToBitmap, rotationDegrees, cropRect)
recognizeTextOnDevice(InputImage.fromBitmap(croppedBitmap, 0)).addOnCompleteListener {
imageProxy.close()
}
}
private fun recognizeTextOnDevice(
image: InputImage
): Task<Text> {
// Pass image to an ML Kit Vision API
return detector.process(image)
.addOnSuccessListener { visionText ->
// Task completed successfully
result.value = visionText.text
}
.addOnFailureListener { exception ->
// Task failed with an exception
Log.e(TAG, "Text recognition error", exception)
val message = getErrorMessage(exception)
message?.let {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
}
private fun getErrorMessage(exception: Exception): String? {
val mlKitException = exception as? MlKitException ?: return exception.message
return if (mlKitException.errorCode == MlKitException.UNAVAILABLE) {
"Waiting for text recognition model to be downloaded"
} else exception.message
}
companion object {
private const val TAG = "TextAnalyzer"
}
} | android/translate-showcase/app/src/main/java/com/google/mlkit/showcase/translate/analyzer/TextAnalyzer.kt | 2049343196 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.cherrypick
import git4idea.test.branch
import git4idea.test.checkout
import git4idea.test.checkoutNew
import git4idea.test.file
class GitCherryPickAutoCommitTest : GitCherryPickTest() {
override fun setUp() {
super.setUp()
myGitSettings.isAutoCommitOnCherryPick = true
}
fun `test simple cherry-pick`() {
branch("feature")
val commit = file("c.txt").create().addCommit("fix #1").hash()
checkout("feature")
cherryPick(commit)
assertSuccessfulNotification("Cherry-pick successful", "${shortHash(commit)} fix #1")
assertLastMessage("fix #1\n\n(cherry picked from commit ${commit})")
assertOnlyDefaultChangelist()
}
fun `test dirty tree conflicting with commit`() {
`check dirty tree conflicting with commit`()
}
fun `test untracked file conflicting with commit`() {
`check untracked file conflicting with commit`()
}
fun `test conflict with cherry-picked commit should show merge dialog`() {
`check conflict with cherry-picked commit should show merge dialog`()
}
fun `test unresolved conflict with cherry-picked commit should produce a changelist`() {
val commit = prepareConflict()
`do nothing on merge`()
cherryPick(commit)
`assert merge dialog was shown`()
assertChangelistCreated("on_master (cherry picked from commit ${shortHash(commit)})")
assertWarningNotification("Cherry-picked with conflicts", """
${shortHash(commit)} on_master
Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>
""")
}
fun `test resolve conflicts and commit`() {
`check resolve conflicts and commit`()
}
fun `test resolve conflicts but cancel commit`() {
val commit = prepareConflict()
`mark as resolved on merge`()
vcsHelper.onCommit { msg -> false }
cherryPick(commit)
`assert merge dialog was shown`()
assertChangelistCreated("on_master (cherry picked from commit ${shortHash(commit)})")
assertNoNotification()
}
fun `test cherry-pick 2 commit`() {
branch("feature")
val commit1 = file("one.txt").create().addCommit("fix #1").hash()
val commit2 = file("two.txt").create().addCommit("fix #2").hash()
checkout("feature")
cherryPick(commit1, commit2)
assertLogMessages("""
fix #2
(cherry picked from commit $commit2)""", """
fix #1
(cherry picked from commit $commit1)""")
assertSuccessfulNotification("Cherry-pick successful","""
${shortHash(commit1)} fix #1
${shortHash(commit2)} fix #2
""")
}
fun `test cherry-picked 3 commits where 2nd conflicts with local changes`() {
val common = file("common.txt")
common.create("initial content\n").addCommit("common")
branch("feature")
val commit1 = file("one.txt").create().addCommit("fix #1").hash()
val commit2 = common.append("on master\n").addCommit("appended common").hash()
val commit3 = file("two.txt").create().addCommit("fix #2").hash()
checkout("feature")
common.append("on feature\n")
cherryPick(commit1, commit2, commit3)
assertErrorNotification("Cherry-pick Failed", """
${shortHash(commit2)} appended common
Your local changes would be overwritten by cherry-pick.
Commit your changes or stash them to proceed.
However cherry-pick succeeded for the following commit:
${shortHash(commit1)} fix #1""")
}
fun `test cherry-pick 3 commits, where second conflicts with master`() {
val common = file("common.txt")
common.create("initial content\n").addCommit("common")
branch("feature")
val commit1 = file("one.txt").create().addCommit("fix #1").hash()
val commit2 = common.append("on master\n").addCommit("appended common").hash()
val commit3 = file("two.txt").create().addCommit("fix #2").hash()
checkout("feature")
common.append("on feature\n").addCommit("appended on feature").hash()
`do nothing on merge`()
cherryPick(commit1, commit2, commit3)
`assert merge dialog was shown`()
assertLastMessage("fix #1\n\n(cherry picked from commit $commit1)")
}
// IDEA-73548
fun `test nothing to commit`() {
val commit = file("c.txt").create().addCommit("fix #1").hash()
checkoutNew("feature")
cherryPick(commit)
assertWarningNotification("Nothing to cherry-pick",
"All changes from ${shortHash(commit)} have already been applied")
}
// IDEA-73548
fun `test several commits one of which have already been applied`() {
file("common.txt").create("common content\n").addCommit("common file")
checkoutNew("feature")
val commit1 = file("a.txt").create("initial\n").addCommit("fix #1").hash()
val emptyCommit = file("common.txt").append("more to common\n").addCommit("to common").hash()
val commit3 = file("a.txt").append("more\n").addCommit("fix #2").hash()
checkout("master")
file("common.txt").append("more to common\n").addCommit("to common from master")
cherryPick(commit1, emptyCommit, commit3)
assertLogMessages(
"""
fix #2
(cherry picked from commit $commit3)""",
"""
fix #1
(cherry picked from commit $commit1)""")
assertSuccessfulNotification("Cherry-picked 2 commits from 3","""
${shortHash(commit1)} fix #1
${shortHash(commit3)} fix #2
${shortHash(emptyCommit)} was skipped, because all changes have already been applied.""")
}
} | plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickAutoCommitTest.kt | 3199013444 |
package com.github.ptrteixeira.cookbook.data
import com.github.ptrteixeira.cookbook.core.RecipeEgg
import com.github.ptrteixeira.cookbook.core.User
import cookbook.server.src.test.kotlin.data.jdbi
import cookbook.server.src.test.kotlin.data.migrate
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
class RecipeDataTest {
private val ID = 0
private val USER = User("test-user")
@Test
fun itReturnsMissingRecipesAsAbsent() {
val result = recipeDao.getRecipe(USER, ID)
assertThat(result)
.isEmpty()
}
@Test
fun whenNoRecipesItReturnsEmptyList() {
val result = recipeDao.getRecipes(USER)
assertThat(result)
.isEmpty()
}
@Test
fun itAllowsRecipesToBeCreated() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val recipe = recipeDao.getRecipe(USER, id)
.get()
assertThat(recipe)
.isEqualTo(sampleRecipeEgg.toRecipe(id, USER))
}
@Test
fun whenRecipesAddedReturnedListContainsRecipes() {
recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val allRecipes = recipeDao.getRecipes(USER)
assertThat(allRecipes)
.hasSize(1)
.extracting<String> { it.name }
.containsExactly(sampleRecipeEgg.name)
}
@Test
fun itAllowsRecipesToBeDeleted() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
recipeDao.deleteRecipe(USER, id)
val getResult = recipeDao.getRecipe(USER, id)
assertThat(getResult)
.isEmpty()
}
@Test
fun itAllowsRecipesToBeUpdated() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val newIngredients = listOf(
"Eggs", "White Sugar", "Brown Sugar",
"Butter", "Flour", "Chocolate Chips"
)
val updated = sampleRecipeEgg.copy(ingredients = newIngredients)
recipeDao.patchRecipeKeys(USER, id, updated)
val getResult = recipeDao.getRecipe(USER, id)
assertThat(getResult)
.contains(updated.toRecipe(id, USER))
assertThat(getResult.get().ingredients)
.containsExactlyInAnyOrder(*newIngredients.toTypedArray())
}
@Test
fun itOnlyListsRecipesForTheGivenUser() {
recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
assertThat(recipeDao.getRecipes(User("user-2")))
.isEmpty()
assertThat(recipeDao.getRecipes(User("user-1")))
.isNotEmpty()
}
@Test
fun itForbidsAccessToAnotherUsersRecipes() {
val id = recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
assertThat(recipeDao.getRecipe(User("user-2"), id))
.isEmpty()
assertThat(recipeDao.getRecipe(User("user-1"), id))
.isNotEmpty()
}
@Test
fun itForbidsUpdatesToAnotherUsersRecipes() {
val id = recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
recipeDao.deleteRecipe(User("user-2"), id)
assertThat(recipeDao.getRecipe(User("user-1"), id))
.isNotEmpty()
}
@BeforeEach
fun truncateTable() {
dbi.withHandle<Unit, Nothing> {
it.createUpdate("DELETE FROM RECIPES")
.execute()
}
}
companion object {
private val logger = LoggerFactory.getLogger(RecipeDataTest::class.java)
private val dbi = jdbi()
private val recipeDao = dbi.onDemand<RecipeData>(RecipeData::class.java)
private val sampleRecipeEgg = RecipeEgg(
name = "Chocolate Chip Cookies",
ingredients = listOf("Chocolate", "Chips", "Cookies"),
instructions = "Mix",
summary = "They were invented right here in Massachusetts, you know",
description = "They're chocolate chip cookies. Waddya want?"
)
@BeforeAll
@JvmStatic
fun migrate() {
logger.info("Running migrations before DaoTest")
migrate(dbi)
}
}
}
| cookbook/server/src/test/kotlin/data/RecipeDataTest.kt | 3249405625 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.observers
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import com.facebook.flipper.plugins.uidebugger.LogTag
import com.facebook.flipper.plugins.uidebugger.common.BitmapPool
import com.facebook.flipper.plugins.uidebugger.core.Context
import com.facebook.flipper.plugins.uidebugger.scheduler.throttleLatest
import java.lang.ref.WeakReference
import kotlinx.coroutines.*
typealias DecorView = View
/** Responsible for subscribing to updates to the content view of an activity */
class DecorViewObserver(val context: Context) : TreeObserver<DecorView>() {
private val throttleTimeMs = 500L
private var nodeRef: WeakReference<View>? = null
private var listener: ViewTreeObserver.OnPreDrawListener? = null
override val type = "DecorView"
private val waitScope = CoroutineScope(Dispatchers.IO)
private val mainScope = CoroutineScope(Dispatchers.Main)
override fun subscribe(node: Any) {
node as View
nodeRef = WeakReference(node)
Log.i(LogTag, "Subscribing to decor view changes")
val throttledUpdate =
throttleLatest<WeakReference<View>?>(throttleTimeMs, waitScope, mainScope) { weakView ->
weakView?.get()?.let { view ->
var snapshotBitmap: BitmapPool.ReusableBitmap? = null
if (view.width > 0 && view.height > 0) {
snapshotBitmap = context.bitmapPool.getBitmap(node.width, node.height)
}
processUpdate(context, view, snapshotBitmap)
}
}
listener =
ViewTreeObserver.OnPreDrawListener {
throttledUpdate(nodeRef)
true
}
node.viewTreeObserver.addOnPreDrawListener(listener)
// It can be the case that the DecorView the current observer owns has already
// drawn. In this case, manually trigger an update.
throttledUpdate(nodeRef)
}
override fun unsubscribe() {
Log.i(LogTag, "Unsubscribing from decor view changes")
listener.let {
nodeRef?.get()?.viewTreeObserver?.removeOnPreDrawListener(it)
listener = null
}
nodeRef = null
}
}
object DecorViewTreeObserverBuilder : TreeObserverBuilder<DecorView> {
override fun canBuildFor(node: Any): Boolean {
return node.javaClass.simpleName.contains("DecorView")
}
override fun build(context: Context): TreeObserver<DecorView> {
Log.i(LogTag, "Building DecorView observer")
return DecorViewObserver(context)
}
}
| android/src/main/java/com/facebook/flipper/plugins/uidebugger/observers/DecorViewTreeObserver.kt | 3694768562 |
package com.didichuxing.doraemonkit.kit.toolpanel
import android.view.View
import android.widget.TextView
import com.didichuxing.doraemonkit.R
import com.didichuxing.doraemonkit.widget.dialog.DialogListener
import com.didichuxing.doraemonkit.widget.dialog.DialogProvider
/**
* Created by jint on 2019/4/12
* 确认弹框
*
* @author jintai
*/
class ConfirmDialogProvider(data: Any?, listener: DialogListener?) : DialogProvider<Any?>(data, listener) {
private lateinit var mTvContent: TextView
private lateinit var mTvPositive: TextView
private lateinit var mTvNegative: TextView
override fun getLayoutId(): Int {
return R.layout.dk_dialog_confirm
}
override fun findViews(view: View) {
mTvContent = view.findViewById(R.id.tv_content)
mTvPositive = view.findViewById(R.id.positive)
mTvNegative = view.findViewById(R.id.negative)
}
override fun bindData(data: Any?) {
if (data is String) {
mTvContent.text = data
}
}
override fun getPositiveView(): View? {
return mTvPositive
}
override fun getNegativeView(): View? {
return mTvNegative
}
override fun isCancellable(): Boolean {
return false
}
} | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/toolpanel/ConfirmDialogProvider.kt | 3935778446 |
package org.luftbild4p3d.app
import tornadofx.App
class Luftbild4P3DApp : App(MainView::class) {
} | src/main/kotlin/org/luftbild4p3d/app/Luftbild4P3DApp.kt | 1600990994 |
@file:Suppress("unused")
package azadev.backt.sql
import azadev.backt.sql.utils.escapeSqlIdentifier
import azadev.backt.sql.utils.escapeSqlLiteral
import java.sql.ResultSet
import java.util.*
class QueryBuilder(
val quoteIdentifiers: Boolean = true
) {
val sb = StringBuilder(15) // SELECT * FROM t
var params: ArrayList<Any?>? = null
val paramArray: Array<Any?> get() = params?.toArray() ?: emptyArray()
var hasSet = false
var hasWhere = false
var hasOnDupUpd = false
var hasOrder = false
fun executeQuery(db: Database): ResultSet {
if (params == null)
return db.executeQuery(toString())
return db.executeQuery(toString(), *paramArray)
}
fun executeUpdate(db: Database): Int {
if (params == null)
return db.executeUpdate(toString())
return db.executeUpdate(toString(), *paramArray)
}
fun executeUpdateWithAutoKeys(db: Database): ResultSet? {
if (params == null)
return db.executeUpdateWithAutoKeys(toString())
return db.executeUpdateWithAutoKeys(toString(), *paramArray)
}
override fun toString() = sb.toString()
fun p(param: Any?): QueryBuilder {
params = (params ?: ArrayList<Any?>(1)).apply { add(param) }
return this
}
fun select(col: String = "*"): QueryBuilder {
if (col == "*")
sb.append("SELECT *")
else
sb.append("SELECT ").appendIdentifier(col)
return this
}
fun select(vararg cols: String): QueryBuilder {
sb.append("SELECT ")
cols.forEachIndexed { i,col ->
if (i > 0) sb.append(',')
sb.appendIdentifier(col)
}
return this
}
fun insert(table: String): QueryBuilder {
sb.append("INSERT INTO ").appendIdentifier(table)
return this
}
fun update(table: String): QueryBuilder {
sb.append("UPDATE ").appendIdentifier(table)
return this
}
fun delete(): QueryBuilder {
sb.append("DELETE")
return this
}
fun from(table: String): QueryBuilder {
sb.append(" FROM ").appendIdentifier(table)
return this
}
fun where(col: String, value: Any) = where0(col, '=', value)
fun wherep(col: String, param: Any) = where0(col, "=?").p(param)
fun whereNot(col: String, value: Any) = where0(col, "<>", value)
fun wherepNot(col: String, param: Any) = where0(col, "<>?").p(param)
fun whereNull(col: String): QueryBuilder {
where0(col)
sb.append(" IS NULL")
return this
}
fun whereNotNull(col: String): QueryBuilder {
where0(col)
sb.append(" IS NOT NULL")
return this
}
fun whereGt(col: String, value: Any) = where0(col, '>', value)
fun wherepGt(col: String, param: Any) = where0(col, ">?").p(param)
fun whereLt(col: String, value: Any) = where0(col, '<', value)
fun wherepLt(col: String, param: Any) = where0(col, "<?").p(param)
fun whereBetween(col: String, min: Any, max: Any): QueryBuilder {
where0(col)
sb.append(" BETWEEN ").appendLiteral(min).append(" AND ").appendLiteral(max)
return this
}
fun wherepBetween(col: String, min: Any, max: Any): QueryBuilder {
return where0(col, " BETWEEN ? AND ?").p(min).p(max)
}
fun whereNotBetween(col: String, min: Any, max: Any): QueryBuilder {
where0(col)
sb.append(" NOT BETWEEN ").appendLiteral(min).append(" AND ").appendLiteral(max)
return this
}
fun wherepNotBetween(col: String, min: Any, max: Any): QueryBuilder {
return where0(col, " NOT BETWEEN ? AND ?").p(min).p(max)
}
fun whereIn(col: String, values: Any): QueryBuilder {
where0(col)
sb.append(" IN (").appendJoined(values).append(')')
return this
}
fun whereNotIn(col: String, values: Any): QueryBuilder {
where0(col)
sb.append(" NOT IN (").appendJoined(values).append(')')
return this
}
private fun where0(col: String, eq: Any? = null, value: Any? = null): QueryBuilder {
if (!hasWhere) {
sb.append(" WHERE ")
hasWhere = true
}
else sb.append(" AND ")
sb.appendIdentifier(col)
when (eq) {
is Char -> sb.append(eq)
is String -> sb.append(eq)
}
if (value != null)
sb.appendLiteral(value)
return this
}
fun orderBy(col: String, desc: Boolean = false): QueryBuilder {
if (!hasOrder) {
sb.append(" ORDER BY ")
hasOrder = true
}
else sb.append(',')
sb.appendIdentifier(col)
if (desc)
sb.append(" DESC")
return this
}
fun limit(num: Int): QueryBuilder {
sb.append(" LIMIT ").append(num)
return this
}
fun set(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> set0(col, "=NULL")
else -> set0(col, '=', value)
}
}
fun setp(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> set(col, null)
else -> set0(col, "=?").p(value)
}
}
private fun set0(col: String, eq: Any, value: Any? = null): QueryBuilder {
appendColValPair(col, eq, value, if (hasSet) ", " else " SET ")
hasSet = true
return this
}
fun onDupUpdate(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> onDupUpdate0(col, "=NULL")
else -> onDupUpdate0(col, '=', value)
}
}
fun onDupUpdatep(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> onDupUpdate(col, value)
else -> onDupUpdate0(col, "=?").p(value)
}
}
private fun onDupUpdate0(col: String, eq: Any, value: Any? = null): QueryBuilder {
appendColValPair(col, eq, value, if (hasOnDupUpd) ", " else " ON DUPLICATE KEY UPDATE ")
hasOnDupUpd = true
return this
}
private fun appendColValPair(col: String, eq: Any, value: Any? = null, prefix: Any): QueryBuilder {
when (prefix) {
is Char -> sb.append(prefix)
is String -> sb.append(prefix)
}
sb.appendIdentifier(col)
when (eq) {
is Char -> sb.append(eq)
is String -> sb.append(eq)
}
if (value != null)
sb.appendLiteral(value)
return this
}
private fun StringBuilder.appendIdentifier(name: String): StringBuilder {
if (quoteIdentifiers) append('`')
append(name.escapeSqlIdentifier())
if (quoteIdentifiers) append('`')
return this
}
private fun StringBuilder.appendLiteral(value: Any): StringBuilder {
// Common types (to avoid "toString" inside StringBuilder)
return when (value) {
is Boolean -> append(if (value) 1 else 0)
is Long -> append(value)
is Int -> append(value)
is Short -> append(value)
is Byte -> append(value)
is Double -> append(value)
is Float -> append(value)
is String -> append('\'').append(value.escapeSqlLiteral()).append('\'')
is Char -> append('\'').apply {
val esc = value.escapeSqlLiteral()
if (esc != null) append(esc)
else append(value)
}.append('\'')
else -> appendLiteral(value.toString())
}
}
private fun StringBuilder.appendJoined(values: Any): StringBuilder {
var i = -1
when (values) {
is Array<*> -> values.forEach {
if (it != null) {
if (++i > 0) sb.append(',')
appendLiteral(it)
}
}
is Iterable<*> -> values.forEach {
if (it != null) {
if (++i > 0) sb.append(',')
appendLiteral(it)
}
}
else -> appendLiteral(values)
}
return this
}
}
| src/main/kotlin/azadev/backt/sql/QueryBuilder.kt | 756028700 |
package com.gm.soundzones.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.gm.soundzones.Utils
import com.gm.soundzones.log
/**
* Created by Pavel Aizendorf on 19/10/2017.
*/
abstract class BaseActivity : AppCompatActivity(){
override fun onBackPressed() {
// super.onBackPressed()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
log(Utils.getAppVersion(this))
}
} | app/src/main/java/com/gm/soundzones/activity/BaseActivity.kt | 3185499038 |
/*
* Copyright (C) 2014 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.chrisprime.primestationonecontrol.utilities
import android.content.Context
import android.support.test.espresso.EspressoException
import android.support.test.espresso.FailureHandler
import android.support.test.espresso.PerformException
import android.support.test.espresso.core.deps.guava.base.Preconditions
import android.support.test.espresso.core.deps.guava.base.Throwables
import android.view.View
import junit.framework.AssertionFailedError
import org.hamcrest.Matcher
/**
* Recreating Espresso's [android.support.test.espresso.base.DefaultFailureHandler]
* since the source class is final
*/
class CustomFailureHandler(
appContext: Context) : FailureHandler {
init {
Preconditions.checkNotNull(appContext)
}
override fun handle(error: Throwable, viewMatcher: Matcher<View>) {
if (error is EspressoException || error is AssertionFailedError
|| error is AssertionError || error is RuntimeException) {
throw Throwables.propagate(getUserFriendlyError(error, viewMatcher))
} else {
throw Throwables.propagate(error)
}
}
/**
* When the error is coming from espresso, it is more user friendly to:
* 1. propagate assertions as assertions
* 2. swap the stack trace of the error to that of current thread (which will show
* directly where the actual problem is)
*/
private fun getUserFriendlyError(error: Throwable, viewMatcher: Matcher<View>): Throwable {
var error = error
if (error is PerformException) {
// Re-throw the exception with the viewMatcher (used to locate the view) as the view
// description (makes the error more readable). The reason we do this here: not all creators
// of PerformException have access to the viewMatcher.
throw PerformException.Builder()
.from(error)
.withViewDescription(viewMatcher.toString())
.build()
}
if (error is AssertionError) {
// reports Failure instead of Error.
// assertThat(...) throws an AssertionFailedError.
error = AssertionFailedWithCauseError(error.message!!, error)
}
// if (error !is RuntimeException) { //Only set stack traces if not extending runtimeexception to keep our logs clean
// error.setStackTrace(Thread.currentThread().stackTrace)
// }
return error
}
//Below needs to be public if we are going to catch this particular assertion and use it for retry logic...
class AssertionFailedWithCauseError/* junit hides the cause constructor. */
(message: String, cause: Throwable) : AssertionFailedError(message) {
// init {
// initCause(cause)
// }
}
}
| app/src/androidTest/java/com/chrisprime/primestationonecontrol/utilities/CustomFailureHandler.kt | 2106001908 |
package com.jereksel.libresubstratumlib.compilercommon
class AndroidManifestGenerator(val testing: Boolean = false) {
val metadataOverlayTarget = "Substratum_Target"
val metadataOverlayParent = "Substratum_Parent"
val metadataOverlayType1a = "Substratum_Type1a"
val metadataOverlayType1b = "Substratum_Type1b"
val metadataOverlayType1c = "Substratum_Type1c"
val metadataOverlayType2 = "Substratum_Type2"
val metadataOverlayType3 = "Substratum_Type3"
fun generateManifest(theme: ThemeToCompile): String {
val appId = theme.targetOverlayId
val target = theme.fixedTargetApp
val themeId = theme.targetThemeId
val type1a = theme.getType("a").replace("&", "&")
val type1b = theme.getType("b").replace("&", "&")
val type1c = theme.getType("c").replace("&", "&")
val type2 = theme.getType2().replace("&", "&")
val type3 = theme.getType3().replace("&", "&")
val xmlnsAndroid = if (testing) {
"http://schemas.android.com/apk/lib/$appId"
} else {
"http://schemas.android.com/apk/res/android"
}
//TODO: DSL
return """<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="$xmlnsAndroid" package="$appId"
android:versionCode="${theme.versionCode}" android:versionName="${theme.versionName}">
<overlay android:priority="1" android:targetPackage="$target" />
<application android:label="$appId" allowBackup="false" android:hasCode="false">
<meta-data android:name="$metadataOverlayTarget" android:value="$target" />
<meta-data android:name="$metadataOverlayParent" android:value="$themeId" />
<meta-data android:name="$metadataOverlayType1a" android:value="$type1a" />
<meta-data android:name="$metadataOverlayType1b" android:value="$type1b" />
<meta-data android:name="$metadataOverlayType1c" android:value="$type1c" />
<meta-data android:name="$metadataOverlayType2" android:value="$type2" />
<meta-data android:name="$metadataOverlayType3" android:value="$type3" />
</application>
</manifest>
"""
}
private fun ThemeToCompile.getType(type: String): String {
val t = this.type1.find { it.suffix == type }?.extension ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
private fun ThemeToCompile.getType2(): String {
val t = this.type2 ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
private fun ThemeToCompile.getType3(): String {
val t = this.type3 ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
}
| sublib/compilercommon/src/main/java/com/jereksel/libresubstratumlib/compilercommon/AndroidManifestGenerator.kt | 3637057144 |
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters.fields
import javafx.event.EventHandler
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.Tooltip
import javafx.scene.layout.HBox
import uk.co.nickthecoder.paratask.gui.ApplicationActions
import uk.co.nickthecoder.paratask.gui.ShortcutHelper
import uk.co.nickthecoder.paratask.parameters.MultipleParameter
import uk.co.nickthecoder.paratask.parameters.Parameter
import uk.co.nickthecoder.paratask.parameters.ParameterEvent
import uk.co.nickthecoder.paratask.parameters.ParameterEventType
import uk.co.nickthecoder.paratask.util.focusNext
class MultipleField<T>(val multipleParameter: MultipleParameter<T, *>)
: ParameterField(multipleParameter), FieldParent {
val addButton = Button("+")
val parametersForm = ParametersForm(multipleParameter, this)
val shortcuts = ShortcutHelper("MultipleField", parametersForm, false)
init {
shortcuts.add(ApplicationActions.ITEM_ADD) { extraValue() }
}
override fun updateError(field: ParameterField) {
parametersForm.updateField(field)
}
override fun updateField(field: ParameterField) {
parametersForm.updateField(field)
}
override fun iterator(): Iterator<ParameterField> = parametersForm.iterator()
override fun createControl(): Node {
addButton.onAction = EventHandler {
extraValue()
}
addButton.tooltip = Tooltip("Add")
parametersForm.styleClass.add("multiple")
// Add 'blank' items, so that the required minimum number of items can be entered.
// The most common scenarios, is adding a single 'blank' item when minItems == 1
while (multipleParameter.minItems > multipleParameter.value.size) {
multipleParameter.newValue()
}
buildContent()
if (isBoxed) {
val box = HBox()
box.styleClass.add("padded-box")
box.children.add(parametersForm)
control = box
} else {
control = parametersForm
}
return control!!
}
fun buildContent() {
parametersForm.clear()
for ((index, innerParameter) in multipleParameter.innerParameters.withIndex()) {
addParameter(innerParameter, index)
}
if (multipleParameter.innerParameters.isEmpty()) {
parametersForm.add(addButton)
}
}
fun addParameter(parameter: Parameter, index: Int): ParameterField {
val result = parametersForm.addParameter(parameter)
val buttons = HBox()
buttons.styleClass.add("multiple-line-buttons")
val addButton = Button("+")
addButton.onAction = EventHandler {
newValue(index + 1)
}
addButton.tooltip = Tooltip("Insert Before")
buttons.children.add(addButton)
val removeButton = Button("-")
removeButton.onAction = EventHandler {
removeAt(index)
}
removeButton.tooltip = Tooltip("Remove")
buttons.children.add(removeButton)
result.plusMinusButtons(buttons)
return result
}
private fun newValue(index: Int) {
val valueParameter = multipleParameter.newValue(index)
parametersForm.findField(valueParameter)?.control?.focusNext()
}
private fun extraValue() {
newValue(multipleParameter.children.size)
}
fun removeAt(index: Int) {
multipleParameter.removeAt(index)
}
override fun parameterChanged(event: ParameterEvent) {
super.parameterChanged(event)
if (event.type == ParameterEventType.STRUCTURAL) {
buildContent()
}
}
}
| paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/MultipleField.kt | 836794080 |
package com.flexpoker.table.command.handlers
import com.flexpoker.framework.command.CommandHandler
import com.flexpoker.framework.event.EventPublisher
import com.flexpoker.table.command.aggregate.applyEvents
import com.flexpoker.table.command.aggregate.eventproducers.fold
import com.flexpoker.table.command.commands.FoldCommand
import com.flexpoker.table.command.events.TableEvent
import com.flexpoker.table.command.repository.TableEventRepository
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class FoldCommandHandler @Inject constructor(
private val eventPublisher: EventPublisher<TableEvent>,
private val tableEventRepository: TableEventRepository
) : CommandHandler<FoldCommand> {
@Async
override fun handle(command: FoldCommand) {
val existingEvents = tableEventRepository.fetchAll(command.tableId)
val state = applyEvents(existingEvents)
val newEvents = fold(state, command.playerId)
val newlySavedEventsWithVersions = tableEventRepository.setEventVersionsAndSave(existingEvents.size, newEvents)
newlySavedEventsWithVersions.forEach { eventPublisher.publish(it) }
}
} | src/main/kotlin/com/flexpoker/table/command/handlers/FoldCommandHandler.kt | 3063384772 |
package net.nemerosa.ontrack.extension.indicators.ui
import net.nemerosa.ontrack.extension.indicators.acl.IndicatorPortfolioManagement
import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorPortfolio
import net.nemerosa.ontrack.ui.resource.AbstractResourceDecoratorTestSupport
import net.nemerosa.ontrack.ui.resource.Link
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
class IndicatorPortfolioResourceDecoratorIT : AbstractResourceDecoratorTestSupport() {
@Autowired
private lateinit var decorator: IndicatorPortfolioResourceDecorator
@Test
fun `No link when not authorized`() {
val portfolio = IndicatorPortfolio("test", "Test", null, emptyList())
asUser().call {
portfolio.decorate(decorator) {
assertLinkNotPresent(Link.UPDATE)
assertLinkNotPresent(Link.DELETE)
}
}
}
@Test
fun `Links when authorized`() {
val portfolio = IndicatorPortfolio("test", "Test", null, emptyList())
asUserWith<IndicatorPortfolioManagement> {
portfolio.decorate(decorator) {
assertLinkPresent(Link.UPDATE)
assertLinkPresent(Link.DELETE)
}
}
}
} | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/IndicatorPortfolioResourceDecoratorIT.kt | 1660476551 |
package net.nemerosa.ontrack.graphql
import com.fasterxml.jackson.databind.JsonNode
import graphql.GraphQL
import net.nemerosa.ontrack.graphql.schema.GraphqlSchemaService
import net.nemerosa.ontrack.graphql.schema.UserError
import net.nemerosa.ontrack.graphql.support.exception
import net.nemerosa.ontrack.it.links.AbstractBranchLinksTestJUnit4Support
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.json.isNullOrNullNode
import net.nemerosa.ontrack.json.parse
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.fail
@Deprecated(message = "JUnit is deprecated", replaceWith = ReplaceWith("AbstractQLKTITSupport"))
abstract class AbstractQLKTITJUnit4Support : AbstractBranchLinksTestJUnit4Support() {
@Autowired
private lateinit var schemaService: GraphqlSchemaService
fun run(query: String, variables: Map<String, *> = emptyMap<String, Any>()): JsonNode {
// Task to run
val code = { internalRun(query, variables) }
// Making sure we're at least authenticated
return if (securityService.isLogged) {
code()
} else {
asUser().call(code)
}
}
fun run(query: String, variables: Map<String, *> = emptyMap<String, Any>(), code: (data: JsonNode) -> Unit) {
run(query, variables).let { data ->
code(data)
}
}
private fun internalRun(query: String, variables: Map<String, *> = emptyMap<String, Any>()): JsonNode {
val result = GraphQL
.newGraphQL(schemaService.schema)
.build()
.execute {
it.query(query).variables(variables)
}
val error = result.exception
if (error != null) {
throw error
} else if (result.errors != null && !result.errors.isEmpty()) {
fail(result.errors.joinToString("\n") { it.message })
} else {
val data: Any? = result.getData()
if (data != null) {
return JsonUtils.format(data)
} else {
fail("No data was returned and no error was thrown.")
}
}
}
protected fun assertNoUserError(data: JsonNode, userNodeName: String): JsonNode {
val userNode = data.path(userNodeName)
val errors = userNode.path("errors")
if (!errors.isNullOrNullNode() && errors.isArray && errors.size() > 0) {
errors.forEach { error: JsonNode ->
error.path("exception")
.takeIf { !it.isNullOrNullNode() }
?.let { println("Error exception: ${it.asText()}") }
error.path("location")
.takeIf { !it.isNullOrNullNode() }
?.let { println("Error location: ${it.asText()}") }
fail(error.path("message").asText())
}
}
return userNode
}
protected fun assertUserError(
data: JsonNode,
userNodeName: String,
message: String? = null,
exception: String? = null
) {
val errors = data.path(userNodeName).path("errors")
if (errors.isNullOrNullNode()) {
fail("Excepted the `errors` user node.")
} else if (!errors.isArray) {
fail("Excepted the `errors` user node to be an array.")
} else if (errors.isEmpty) {
fail("Excepted the `errors` user node to be a non-empty array.")
} else {
val error = errors.first()
if (message != null) {
assertEquals(message, error.path("message").asText())
}
if (exception != null) {
assertEquals(exception, error.path("exception").asText())
}
}
}
protected fun checkGraphQLUserErrors(data: JsonNode, field: String): JsonNode {
val payload = data.path(field)
val node = payload.path("errors")
if (node != null && node.isArray && node.size() > 0) {
val error = node.first().parse<UserError>()
throw IllegalStateException(error.toString())
}
return payload
}
protected fun checkGraphQLUserErrors(data: JsonNode, field: String, code: (payload: JsonNode) -> Unit) {
val payload = checkGraphQLUserErrors(data, field)
code(payload)
}
}
| ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/AbstractQLKTITJUnit4Support.kt | 1419608105 |
package ch.bailu.aat_gtk.util.sql
import ch.bailu.aat_lib.util.sql.DbResultSet
import java.sql.ResultSet
/**
* https://www.baeldung.com/jdbc-resultset
* https://stackoverflow.com/questions/192078/how-do-i-get-the-size-of-a-java-sql-resultset
*/
class ScrollInsensitiveResultSet(private val resultSet: ResultSet) : DbResultSet {
private val size = if (resultSet.last()) {
resultSet.row
} else {
0
}
override fun moveToFirst(): Boolean {
return resultSet.first()
}
override fun moveToNext(): Boolean {
return resultSet.next()
}
override fun close() {
resultSet.close()
}
override fun moveToPrevious(): Boolean {
return resultSet.previous()
}
override fun moveToPosition(pos: Int): Boolean {
return resultSet.absolute(pos + 1)
}
override fun getCount(): Int {
return size
}
override fun getString(column: String): String {
return resultSet.getString(column)
}
override fun getLong(column: String): Long {
return resultSet.getLong(column)
}
override fun getFloat(column: String): Float {
return resultSet.getFloat(column)
}
override fun getPosition(): Int {
return resultSet.row - 1
}
override fun isClosed(): Boolean {
return resultSet.isClosed
}
}
| aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/util/sql/ScrollInsensitiveResultSet.kt | 2809478939 |
package com.fireflysource.net.http.server.impl.matcher
import com.fireflysource.net.http.server.Matcher
import com.fireflysource.net.http.server.Router
import java.util.*
import java.util.regex.Pattern
abstract class AbstractRegexMatcher :AbstractMatcher<AbstractRegexMatcher.RegexRule>(), Matcher {
companion object {
const val paramName = "group"
}
class RegexRule(val rule: String) {
val pattern: Pattern = Pattern.compile(rule)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as RegexRule
return rule == other.rule
}
override fun hashCode(): Int {
return rule.hashCode()
}
}
override fun add(rule: String, router: Router) {
routersMap.computeIfAbsent(RegexRule(rule)) { TreeSet() }.add(router)
}
override fun match(value: String): Matcher.MatchResult? {
if (routersMap.isEmpty()) return null
val routers = TreeSet<Router>()
val parameters = HashMap<Router, Map<String, String>>()
routersMap.forEach { (rule, routerSet) ->
var matcher = rule.pattern.matcher(value)
if (matcher.matches()) {
routers.addAll(routerSet)
matcher = rule.pattern.matcher(value)
val param: MutableMap<String, String> = HashMap()
while (matcher.find()) {
for (i in 1..matcher.groupCount()) {
param["$paramName$i"] = matcher.group(i)
}
}
if (param.isNotEmpty()) {
routerSet.forEach { router -> parameters[router] = param }
}
}
}
return if (routers.isEmpty()) null else Matcher.MatchResult(routers, parameters, matchType)
}
} | firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/matcher/AbstractRegexMatcher.kt | 3918971290 |
package net.nemerosa.ontrack.job
data class JobType(
val category: JobCategory,
val key: String,
val name: String
) {
fun withName(name: String) = JobType(category, key, name)
fun getKey(id: String): JobKey {
return JobKey.of(this, id)
}
override fun toString(): String {
return String.format(
"%s[%s]",
category,
key
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is JobType) return false
if (category != other.category) return false
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
var result = category.hashCode()
result = 31 * result + key.hashCode()
return result
}
companion object {
@JvmStatic
fun of(category: JobCategory, key: String): JobType {
return JobType(category, key, key)
}
}
}
| ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobType.kt | 2143721857 |
package com.fireflysource.net.http.client.impl.content.provider
import com.fireflysource.common.io.BufferUtils
import com.fireflysource.net.http.client.HttpClientContentProviderFactory.stringBody
import com.fireflysource.net.http.common.model.HttpFields
import kotlinx.coroutines.future.await
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import java.nio.charset.StandardCharsets
class TestMultiPartContentProvider {
@Test
@DisplayName("should generate multi-part format successfully")
fun testRead() = runBlocking {
val provider = MultiPartContentProvider()
val str = "Hello string body"
val strProvider = stringBody(str, StandardCharsets.UTF_8)
provider.addPart("hello string", strProvider, null)
val str2 = "string body 2"
val strProvider2 = stringBody(str2, StandardCharsets.UTF_8)
val httpFields = HttpFields()
httpFields.put("x1", "y1")
provider.addPart("string 2", strProvider2, httpFields)
val buffer = BufferUtils.allocate(provider.length().toInt())
val pos = BufferUtils.flipToFill(buffer)
while (buffer.hasRemaining()) {
val len = provider.read(buffer).await()
if (len < 0) {
break
}
}
BufferUtils.flipToFlush(buffer, pos)
println()
println("Content-Type: ${provider.contentType}")
println()
provider.closeAsync().await()
val content = BufferUtils.toUTF8String(buffer)
println(content)
assertTrue(content.contains("Hello string body"))
assertTrue(content.contains("string body 2"))
assertTrue(content.contains("x1: y1"))
}
} | firefly-net/src/test/kotlin/com/fireflysource/net/http/client/impl/content/provider/TestMultiPartContentProvider.kt | 3613364070 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.thomas.needham.neurophidea.core
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.ui.Messages
import com.thomas.needham.neurophidea.Constants.COMMA_DELIMITED
import com.thomas.needham.neurophidea.Constants.NETWORK_TO_TRAIN_LOCATION_KEY
import com.thomas.needham.neurophidea.actions.OpenExistingNetworkConfigurationAction
import com.thomas.needham.neurophidea.actions.ShowTrainNetworkFormAction
import com.thomas.needham.neurophidea.datastructures.LearningRules
import com.thomas.needham.neurophidea.datastructures.NetworkConfiguration
import com.thomas.needham.neurophidea.datastructures.NetworkTypes
import com.thomas.needham.neurophidea.datastructures.TransferFunctions
import com.thomas.needham.neurophidea.exceptions.UnknownLearningRuleException
import com.thomas.needham.neurophidea.exceptions.UnknownNetworkTypeException
import com.thomas.needham.neurophidea.exceptions.UnknownTransferFunctionException
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.*
import org.neuroph.nnet.learning.*
import org.neuroph.util.TransferFunctionType
import java.io.*
import java.util.*
/**
* Created by Thomas Needham on 30/05/2016.
*/
class NetworkTrainer {
var network: NeuralNetwork? = null
var trainingSet: TrainingSet<SupervisedTrainingElement?>? = null
var trainingData: DoubleArray? = null
var properties = PropertiesComponent.getInstance()
var inputSize: Int = 0
var outputSize: Int = 0
companion object Data {
var networkPath = ""
var trainingSetPath = ""
var networkConfiguration: NetworkConfiguration? = null
var outputPath = ""
}
constructor(path: String, trainingSet: String) {
networkPath = path
trainingSetPath = trainingSet
networkConfiguration = LoadNetworkConfiguration()
this.trainingSet = LoadTrainingSet()
}
constructor(path: String, trainingData: DoubleArray) {
networkPath = path
this.trainingData = trainingData
networkConfiguration = LoadNetworkConfiguration()
this.trainingSet = CreateTrainingSet()
}
private fun LoadNetworkConfiguration(): NetworkConfiguration? {
val network: NetworkConfiguration?
try {
val file = File(networkPath)
val fis = FileInputStream(file)
val ois = ObjectInputStream(fis)
network = ois.readObject() as NetworkConfiguration?
inputSize = network?.networkLayers?.first()!!
outputSize = network?.networkLayers?.last()!!
return network
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
Messages.showErrorDialog(OpenExistingNetworkConfigurationAction.project, "Error Reading Network From file", "Error")
return null
} catch (fnfe: FileNotFoundException) {
fnfe.printStackTrace(System.err)
Messages.showErrorDialog(OpenExistingNetworkConfigurationAction.project, "No Network Configuration Found at: ${ShowTrainNetworkFormAction.properties.getValue(NETWORK_TO_TRAIN_LOCATION_KEY, "")}", "Error")
return null
}
}
private fun CreateTrainingSet(): TrainingSet<SupervisedTrainingElement?>? {
if (trainingData == null)
return null
try {
var set = TrainingSet<SupervisedTrainingElement?>(networkConfiguration?.networkLayers?.first()!!, networkConfiguration?.networkLayers?.last()!!)
for (i in 0..trainingData?.size!! step inputSize + outputSize) {
val inputSize = networkConfiguration?.networkLayers?.first()!!
val outputSize = networkConfiguration?.networkLayers?.last()!!
set.addElement(SupervisedTrainingElement(trainingData!!.copyOfRange(i, (i + inputSize)),
trainingData!!.copyOfRange((i + inputSize), (i + inputSize + outputSize))))
}
return set
} catch (ioobe: IndexOutOfBoundsException) {
ioobe.printStackTrace(System.err)
Messages.showErrorDialog(ShowTrainNetworkFormAction.project, "Training data does not contain the correct amount of inputs or outputs", "Error")
return null
}
}
private fun LoadTrainingSet(): TrainingSet<SupervisedTrainingElement?>? {
return TrainingSet.createFromFile(trainingSetPath, inputSize, outputSize, COMMA_DELIMITED) as TrainingSet<SupervisedTrainingElement?>?
}
fun TrainNetwork(): NeuralNetwork? {
var function: TransferFunctionType? = null
when (networkConfiguration?.networkTransferFunction) {
TransferFunctions.Functions.GAUSSIAN -> function = TransferFunctionType.GAUSSIAN
TransferFunctions.Functions.LINEAR -> function = TransferFunctionType.LINEAR
TransferFunctions.Functions.LOG -> function = TransferFunctionType.LOG
TransferFunctions.Functions.RAMP -> function = TransferFunctionType.RAMP
TransferFunctions.Functions.SGN -> function = TransferFunctionType.SGN
TransferFunctions.Functions.SIGMOID -> function = TransferFunctionType.SIGMOID
TransferFunctions.Functions.STEP -> function = TransferFunctionType.STEP
TransferFunctions.Functions.TANH -> function = TransferFunctionType.TANH
TransferFunctions.Functions.TRAPEZOID -> function = TransferFunctionType.TRAPEZOID
else -> UnknownTransferFunctionException("Unknown Transfer Function: ${TransferFunctions.GetClassName(networkConfiguration?.networkTransferFunction!!)}")
}
when (networkConfiguration?.networkType) {
NetworkTypes.Types.ADALINE -> network = Adaline(inputSize)
NetworkTypes.Types.BAM -> BAM(inputSize, outputSize)
NetworkTypes.Types.COMPETITIVE_NETWORK -> network = CompetitiveNetwork(inputSize, outputSize)
NetworkTypes.Types.HOPFIELD -> network = Hopfield(inputSize + outputSize)
NetworkTypes.Types.INSTAR -> network = Instar(inputSize)
NetworkTypes.Types.KOHONEN -> network = Kohonen(inputSize, outputSize)
NetworkTypes.Types.MAX_NET -> network = MaxNet(inputSize + outputSize)
NetworkTypes.Types.MULTI_LAYER_PERCEPTRON -> network = MultiLayerPerceptron(networkConfiguration?.networkLayers?.toList(), function)
NetworkTypes.Types.NEURO_FUZZY_PERCEPTRON -> network = NeuroFuzzyPerceptron(inputSize, Vector<Int>(inputSize), outputSize)
NetworkTypes.Types.NEUROPH -> network = Perceptron(inputSize, outputSize, function)
NetworkTypes.Types.OUTSTAR -> network = Outstar(outputSize)
NetworkTypes.Types.PERCEPTRON -> network = Perceptron(inputSize, outputSize, function)
NetworkTypes.Types.RBF_NETWORK -> network = RbfNetwork(inputSize, inputSize, outputSize)
NetworkTypes.Types.SUPERVISED_HEBBIAN_NETWORK -> network = SupervisedHebbianNetwork(inputSize, outputSize, function)
NetworkTypes.Types.UNSUPERVISED_HEBBIAN_NETWORK -> network = UnsupervisedHebbianNetwork(inputSize, outputSize, function)
else -> UnknownNetworkTypeException("Unknown Network Type: ${NetworkTypes.GetClassName(networkConfiguration?.networkType!!)}")
//TODO add more network types
}
when (networkConfiguration?.networkLearningRule) {
LearningRules.Rules.ANTI_HEBBAN_LEARNING -> network?.learningRule = AntiHebbianLearning()
LearningRules.Rules.BACK_PROPAGATION -> network?.learningRule = BackPropagation()
LearningRules.Rules.BINARY_DELTA_RULE -> network?.learningRule = BinaryDeltaRule()
LearningRules.Rules.BINARY_HEBBIAN_LEARNING -> network?.learningRule = BinaryHebbianLearning()
LearningRules.Rules.COMPETITIVE_LEARNING -> network?.learningRule = CompetitiveLearning()
LearningRules.Rules.DYNAMIC_BACK_PROPAGATION -> network?.learningRule = DynamicBackPropagation()
LearningRules.Rules.GENERALIZED_HEBBIAN_LEARNING -> network?.learningRule = GeneralizedHebbianLearning()
LearningRules.Rules.HOPFIELD_LEARNING -> network?.learningRule = HopfieldLearning()
LearningRules.Rules.INSTAR_LEARNING -> network?.learningRule = InstarLearning()
LearningRules.Rules.KOHONEN_LEARNING -> network?.learningRule = KohonenLearning()
LearningRules.Rules.LMS -> network?.learningRule = LMS()
LearningRules.Rules.MOMENTUM_BACK_PROPAGATION -> network?.learningRule = MomentumBackpropagation()
LearningRules.Rules.OJA_LEARNING -> network?.learningRule = OjaLearning()
LearningRules.Rules.OUTSTAR_LEARNING -> network?.learningRule = OutstarLearning()
LearningRules.Rules.PERCEPTRON_LEARNING -> network?.learningRule = PerceptronLearning()
LearningRules.Rules.RESILIENT_PROPAGATION -> network?.learningRule = ResilientPropagation()
LearningRules.Rules.SIGMOID_DELTA_RULE -> network?.learningRule = SigmoidDeltaRule()
LearningRules.Rules.SIMULATED_ANNEALING_LEARNING -> network?.learningRule = SimulatedAnnealingLearning(network)
LearningRules.Rules.SUPERVISED_HEBBIAN_LEARNING -> network?.learningRule = SupervisedHebbianLearning()
LearningRules.Rules.UNSUPERVISED_HEBBIAN_LEARNING -> network?.learningRule = UnsupervisedHebbianLearning()
else -> UnknownLearningRuleException("Unknown Learning Rule: ${LearningRules.GetClassName(networkConfiguration?.networkLearningRule!!)}")
}
if (trainingSet == null) {
Messages.showErrorDialog("Invalid Training Set", "Error")
return null
}
val outfile = File(networkPath + ".nnet")
properties.setValue(NETWORK_TO_TRAIN_LOCATION_KEY, networkPath)
if (!outfile.exists()) {
outfile.createNewFile()
}
network?.learn(trainingSet)
network?.calculate()
network?.save(networkPath + ".nnet")
return network
}
} | neuroph-plugin/src/com/thomas/needham/neurophidea/core/NetworkTrainer.kt | 2847797070 |
package no.tornadofx.fxsamples.withfxproperties
import javafx.application.Application
import no.tornadofx.fxsamples.withfxproperties.views.ItemViewModelWithFxMainView
import tornadofx.App
class WithFXPropertiesApp : App(ItemViewModelWithFxMainView::class)
fun main(args: Array<String>) {
Application.launch(WithFXPropertiesApp::class.java, *args)
} | itemviewmodel/withFXproperties/src/main/kotlin/no/tornadofx/fxsamples/withfxproperties/withfxpropertiesApp.kt | 225587044 |
/*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.base
import android.support.v4.app.Fragment
import org.jetbrains.anko.AnkoLogger
open class BaseFragment: Fragment(), AnkoLogger {
val TAG = "Gachi__${javaClass.simpleName}"
} | Gachi/app/src/main/kotlin/com/pickth/gachi/base/BaseFragment.kt | 1142250214 |
// 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 com.intellij.configurationStore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.roots.ProjectModelElement
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.PathUtilRt
import com.intellij.util.ReflectionUtil
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.systemIndependentPath
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.regex.Pattern
import kotlin.concurrent.read
import kotlin.concurrent.write
private val MACRO_PATTERN = Pattern.compile("(\\$[^$]*\\$)")
/**
* If componentManager not specified, storage will not add file tracker
*/
open class StateStorageManagerImpl(private val rootTagName: String,
override final val macroSubstitutor: TrackingPathMacroSubstitutor? = null,
override val componentManager: ComponentManager? = null,
private val virtualFileTracker: StorageVirtualFileTracker? = StateStorageManagerImpl.createDefaultVirtualTracker(componentManager)) : StateStorageManager {
private val macros: MutableList<Macro> = ContainerUtil.createLockFreeCopyOnWriteList()
private val storageLock = ReentrantReadWriteLock()
private val storages = THashMap<String, StateStorage>()
val compoundStreamProvider: CompoundStreamProvider = CompoundStreamProvider()
val isStreamProviderPreventExportAction: Boolean
get() = compoundStreamProvider.providers.any { it.isDisableExportAction }
override fun addStreamProvider(provider: StreamProvider, first: Boolean) {
if (first) {
compoundStreamProvider.providers.add(0, provider)
}
else {
compoundStreamProvider.providers.add(provider)
}
}
override fun removeStreamProvider(clazz: Class<out StreamProvider>) {
compoundStreamProvider.providers.removeAll { clazz.isInstance(it) }
}
// access under storageLock
@Suppress("LeakingThis")
private var isUseVfsListener = if (componentManager == null || !isUseVfsForWrite) ThreeState.NO else ThreeState.UNSURE // unsure because depends on stream provider state
protected open val isUseXmlProlog: Boolean
get() = true
protected open val isUseVfsForWrite: Boolean
get() = true
companion object {
private fun createDefaultVirtualTracker(componentManager: ComponentManager?): StorageVirtualFileTracker? {
return when (componentManager) {
null -> {
null
}
is Application -> {
StorageVirtualFileTracker(componentManager.messageBus)
}
else -> {
val tracker = (ApplicationManager.getApplication().stateStore.storageManager as? StateStorageManagerImpl)?.virtualFileTracker ?: return null
Disposer.register(componentManager, Disposable {
tracker.remove { it.storageManager.componentManager == componentManager }
})
tracker
}
}
}
}
private data class Macro(val key: String, var value: String)
@TestOnly
fun getVirtualFileTracker(): StorageVirtualFileTracker? = virtualFileTracker
/**
* @param expansion System-independent
*/
fun addMacro(key: String, expansion: String): Boolean {
LOG.assertTrue(!key.isEmpty())
val value: String
if (expansion.contains('\\')) {
LOG.error("Macro $key set to system-dependent expansion $expansion")
value = FileUtilRt.toSystemIndependentName(expansion)
}
else {
value = expansion
}
// e.g ModuleImpl.setModuleFilePath update macro value
for (macro in macros) {
if (key == macro.key) {
macro.value = value
return false
}
}
macros.add(Macro(key, value))
return true
}
// system-independent paths
open fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) {
for (macro in macros) {
if (oldPath == macro.value) {
macro.value = newPath
}
}
}
@Suppress("CAST_NEVER_SUCCEEDS")
override final fun getStateStorage(storageSpec: Storage): StateStorage = getOrCreateStorage(
storageSpec.path,
storageSpec.roamingType,
storageSpec.storageClass.java,
storageSpec.stateSplitter.java,
storageSpec.exclusive,
storageCreator = storageSpec as? StorageCreator
)
protected open fun normalizeFileSpec(fileSpec: String): String {
val path = FileUtilRt.toSystemIndependentName(fileSpec)
// fileSpec for directory based storage could be erroneously specified as "name/"
return if (path.endsWith('/')) path.substring(0, path.length - 1) else path
}
// storageCustomizer - to ensure that other threads will use fully constructed and configured storage (invoked under the same lock as created)
fun getOrCreateStorage(collapsedPath: String,
roamingType: RoamingType = RoamingType.DEFAULT,
storageClass: Class<out StateStorage> = StateStorage::class.java,
@Suppress("DEPRECATION") stateSplitter: Class<out StateSplitter> = StateSplitterEx::class.java,
exclusive: Boolean = false,
storageCustomizer: (StateStorage.() -> Unit)? = null,
storageCreator: StorageCreator? = null): StateStorage {
val normalizedCollapsedPath = normalizeFileSpec(collapsedPath)
val key: String
if (storageClass == StateStorage::class.java) {
if (normalizedCollapsedPath.isEmpty()) {
throw Exception("Normalized path is empty, raw path '$collapsedPath'")
}
key = storageCreator?.key ?: normalizedCollapsedPath
}
else {
key = storageClass.name!!
}
val storage = storageLock.read { storages.get(key) } ?: return storageLock.write {
storages.getOrPut(key) {
@Suppress("IfThenToElvis")
val storage = if (storageCreator == null) createStateStorage(storageClass, normalizedCollapsedPath, roamingType, stateSplitter, exclusive) else storageCreator.create(this)
storageCustomizer?.let { storage.it() }
storage
}
}
storageCustomizer?.let { storage.it() }
return storage
}
fun getCachedFileStorages(): Set<StateStorage> = storageLock.read { storages.values.toSet() }
fun findCachedFileStorage(name: String): StateStorage? = storageLock.read { storages.get(name) }
fun getCachedFileStorages(changed: Collection<String>,
deleted: Collection<String>,
pathNormalizer: ((String) -> String)? = null): Pair<Collection<FileBasedStorage>, Collection<FileBasedStorage>> = storageLock.read {
Pair(getCachedFileStorages(changed, pathNormalizer), getCachedFileStorages(deleted, pathNormalizer))
}
fun updatePath(spec: String, newPath: String) {
val storage = getCachedFileStorages(listOf(spec)).firstOrNull() ?: return
if (storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.let { tracker ->
tracker.remove(storage.file.systemIndependentPath)
tracker.put(newPath, storage)
}
}
storage.setFile(null, Paths.get(newPath))
}
fun getCachedFileStorages(fileSpecs: Collection<String>, pathNormalizer: ((String) -> String)? = null): Collection<FileBasedStorage> {
if (fileSpecs.isEmpty()) {
return emptyList()
}
storageLock.read {
var result: MutableList<FileBasedStorage>? = null
for (fileSpec in fileSpecs) {
val path = normalizeFileSpec(pathNormalizer?.invoke(fileSpec) ?: fileSpec)
val storage = storages.get(path)
if (storage is FileBasedStorage) {
if (result == null) {
result = SmartList<FileBasedStorage>()
}
result.add(storage)
}
}
return result ?: emptyList()
}
}
// overridden in upsource
protected open fun createStateStorage(storageClass: Class<out StateStorage>,
collapsedPath: String,
roamingType: RoamingType,
@Suppress("DEPRECATION") stateSplitter: Class<out StateSplitter>,
exclusive: Boolean = false): StateStorage {
if (storageClass != StateStorage::class.java) {
val constructor = storageClass.constructors.first { it.parameterCount <= 3 }
constructor.isAccessible = true
if (constructor.parameterCount == 2) {
return constructor.newInstance(componentManager!!, this) as StateStorage
}
else {
return constructor.newInstance(collapsedPath, componentManager!!, this) as StateStorage
}
}
val effectiveRoamingType = getEffectiveRoamingType(roamingType, collapsedPath)
if (isUseVfsListener == ThreeState.UNSURE) {
isUseVfsListener = ThreeState.fromBoolean(!compoundStreamProvider.isApplicable(collapsedPath, effectiveRoamingType))
}
val filePath = expandMacros(collapsedPath)
@Suppress("DEPRECATION")
if (stateSplitter != StateSplitter::class.java && stateSplitter != StateSplitterEx::class.java) {
val storage = createDirectoryBasedStorage(filePath, collapsedPath, ReflectionUtil.newInstance(stateSplitter))
if (storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.put(filePath, storage)
}
return storage
}
if (!ApplicationManager.getApplication().isHeadlessEnvironment && PathUtilRt.getFileName(filePath).lastIndexOf('.') < 0) {
throw IllegalArgumentException("Extension is missing for storage file: $filePath")
}
val storage = createFileBasedStorage(filePath, collapsedPath, effectiveRoamingType, if (exclusive) null else rootTagName)
if (isUseVfsListener == ThreeState.YES && storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.put(filePath, storage)
}
return storage
}
// open for upsource
protected open fun createFileBasedStorage(path: String, collapsedPath: String, roamingType: RoamingType, rootTagName: String?): StateStorage {
val provider = if (roamingType == RoamingType.DISABLED) {
// remove to ensure that repository doesn't store non-roamable files
compoundStreamProvider.delete(collapsedPath, roamingType)
null
}
else {
compoundStreamProvider
}
return MyFileStorage(this, Paths.get(path), collapsedPath, rootTagName, roamingType, getMacroSubstitutor(collapsedPath), provider)
}
// open for upsource
protected open fun createDirectoryBasedStorage(path: String, collapsedPath: String, @Suppress("DEPRECATION") splitter: StateSplitter): StateStorage = MyDirectoryStorage(this,
Paths.get(
path),
splitter)
private class MyDirectoryStorage(override val storageManager: StateStorageManagerImpl, file: Path, @Suppress("DEPRECATION") splitter: StateSplitter) :
DirectoryBasedStorage(file, splitter, storageManager.macroSubstitutor), StorageVirtualFileTracker.TrackedStorage
protected open class MyFileStorage(override val storageManager: StateStorageManagerImpl,
file: Path,
fileSpec: String,
rootElementName: String?,
roamingType: RoamingType,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
provider: StreamProvider? = null) : FileBasedStorage(file, fileSpec, rootElementName, pathMacroManager, roamingType,
provider), StorageVirtualFileTracker.TrackedStorage {
override val isUseXmlProlog: Boolean
get() = rootElementName != null && storageManager.isUseXmlProlog
override val isUseVfsForWrite: Boolean
get() = storageManager.isUseVfsForWrite
override fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
if (rootElementName != null) {
storageManager.beforeElementSaved(elements, rootAttributes)
}
super.beforeElementSaved(elements, rootAttributes)
}
override fun beforeElementLoaded(element: Element) {
storageManager.beforeElementLoaded(element)
super.beforeElementLoaded(element)
}
override fun providerDataStateChanged(writer: DataWriter?, type: DataStateChanged) {
storageManager.providerDataStateChanged(this, writer, type)
super.providerDataStateChanged(writer, type)
}
override fun getResolution(component: PersistentStateComponent<*>, operation: StateStorageOperation): Resolution {
if (operation == StateStorageOperation.WRITE && component is ProjectModelElement && storageManager.isExternalSystemStorageEnabled && component.externalSource != null) {
return Resolution.CLEAR
}
return Resolution.DO
}
}
open val isExternalSystemStorageEnabled: Boolean
get() = false
protected open fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
}
protected open fun providerDataStateChanged(storage: FileBasedStorage, writer: DataWriter?, type: DataStateChanged) {
}
protected open fun beforeElementLoaded(element: Element) {
}
override final fun rename(path: String, newName: String) {
storageLock.write {
val storage = getOrCreateStorage(collapseMacros(path), RoamingType.DEFAULT) as FileBasedStorage
val file = storage.virtualFile
try {
if (file != null) {
file.rename(storage, newName)
}
else if (storage.file.fileName.toString() != newName) {
// old file didn't exist or renaming failed
val expandedPath = expandMacros(path)
val parentPath = PathUtilRt.getParentPath(expandedPath)
storage.setFile(null, Paths.get(parentPath, newName))
pathRenamed(expandedPath, "$parentPath/$newName", null)
}
}
catch (e: IOException) {
LOG.debug(e)
}
}
}
fun clearStorages() {
storageLock.write {
try {
virtualFileTracker?.let {
storages.forEachEntry { collapsedPath, _ ->
it.remove(expandMacros(collapsedPath))
true
}
}
}
finally {
storages.clear()
}
}
}
protected open fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? = macroSubstitutor
override fun expandMacros(path: String): String {
// replacement can contains $ (php tests), so, this check must be performed before expand
val matcher = MACRO_PATTERN.matcher(path)
matcherLoop@
while (matcher.find()) {
val m = matcher.group(1)
for ((key) in macros) {
if (key == m) {
continue@matcherLoop
}
}
throw IllegalArgumentException("Unknown macro: $m in storage file spec: $path")
}
var expanded = path
for ((key, value) in macros) {
expanded = StringUtil.replace(expanded, key, value)
}
return expanded
}
fun expandMacro(macro: String): String {
for ((key, value) in macros) {
if (key == macro) {
return value
}
}
throw IllegalArgumentException("Unknown macro $macro")
}
fun collapseMacros(path: String): String {
var result = path
for ((key, value) in macros) {
result = result.replace(value, key)
}
return normalizeFileSpec(result)
}
override final fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation): StateStorage? {
val oldStorageSpec = getOldStorageSpec(component, componentName, operation) ?: return null
return getOrCreateStorage(oldStorageSpec, RoamingType.DEFAULT)
}
protected open fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? = null
}
private fun String.startsWithMacro(macro: String): Boolean {
val i = macro.length
return getOrNull(i) == '/' && startsWith(macro)
}
fun removeMacroIfStartsWith(path: String, macro: String): String = if (path.startsWithMacro(macro)) path.substring(macro.length + 1) else path
@Suppress("DEPRECATION")
internal val Storage.path: String
get() = if (value.isEmpty()) file else value
internal fun getEffectiveRoamingType(roamingType: RoamingType, collapsedPath: String): RoamingType {
if (roamingType != RoamingType.DISABLED && (collapsedPath == StoragePathMacros.WORKSPACE_FILE || collapsedPath == "other.xml" || collapsedPath == StoragePathMacros.CACHE_FILE)) {
return RoamingType.DISABLED
}
else {
return roamingType
}
} | platform/configuration-store-impl/src/StateStorageManagerImpl.kt | 2324734975 |
package io.mockk.it
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
@Suppress("UNUSED_PARAMETER")
class RelaxedSuspendingMockingTest {
@Suppress("RedundantSuspendModifier")
class MockCls {
suspend fun op(a: Int, b: Int) = a + b
suspend fun opUnit(a: Int, b: Int) {}
suspend fun complexOp(a: Int, b: Int): List<Int> = listOf(a, b)
}
@Test
fun rurfRegularOperationOk() {
val mock = mockk<MockCls>(relaxUnitFun = true) {
coEvery { op(1, 2) } returns 4
coEvery { opUnit(1, 2) } returns Unit
coEvery { complexOp(1, 2) } returns listOf(4, 5)
}
assertEquals(4, runBlocking { mock.op(1, 2) })
assertEquals(Unit, runBlocking { mock.opUnit(1, 2) })
assertEquals(listOf(4, 5), runBlocking { mock.complexOp(1, 2) })
}
@Test
fun rurfFullyRelaxedRegularOperationOk() {
val mock = mockk<MockCls>(relaxed = true)
assertEquals(0, runBlocking { mock.op(1, 2) })
assertEquals(emptyList(), runBlocking { mock.complexOp(1, 2) })
}
@Test
fun rurfFullyRelaxedRegularUnitOperationOk() {
val mock = mockk<MockCls>(relaxed = true)
assertEquals(Unit, runBlocking { mock.opUnit(1, 2) })
}
}
| modules/mockk/src/jvmTest/kotlin/io/mockk/it/RelaxedSuspendingMockingTest.kt | 3719133652 |
package io.mockk.impl.stub
import io.mockk.*
import io.mockk.impl.InternalPlatform
class AnswerAnsweringOpportunity<T>(
private val matcherStr: () -> String
) : MockKGateway.AnswerOpportunity<T>, Answer<T> {
private var storedAnswer: Answer<T>? = null
private val firstAnswerHandlers = mutableListOf<(Answer<T>) -> Unit>()
private fun getAnswer() = storedAnswer ?: throw MockKException("no answer provided for ${matcherStr()}")
override fun answer(call: Call) = getAnswer().answer(call)
override suspend fun coAnswer(call: Call) = getAnswer().answer(call)
override fun provideAnswer(answer: Answer<T>) {
InternalPlatform.synchronized(this) {
val currentAnswer = this.storedAnswer
this.storedAnswer = if (currentAnswer == null) {
notifyFirstAnswerHandlers(answer)
answer
} else {
ManyAnswersAnswer(listOf(currentAnswer, answer))
}
}
}
private fun notifyFirstAnswerHandlers(answer: Answer<T>) {
firstAnswerHandlers.forEach { it(answer) }
}
fun onFirstAnswer(handler: (Answer<T>) -> Unit) {
InternalPlatform.synchronized(this) {
firstAnswerHandlers.add(handler)
}
}
}
| modules/mockk/src/commonMain/kotlin/io/mockk/impl/stub/AnswerAnsweringOpportunity.kt | 2667331779 |
package com.soywiz.korge.view
import com.soywiz.korge.render.*
inline fun Container.scaleView(
width: Int, height: Int, scale: Double = 2.0, filtering: Boolean = false,
callback: @ViewDslMarker Container.() -> Unit = {}
) = ScaleView(width, height, scale, filtering).addTo(this, callback)
class ScaleView(width: Int, height: Int, scale: Double = 2.0, var filtering: Boolean = false) :
FixedSizeContainer(), View.Reference {
init {
this.width = width.toDouble()
this.height = height.toDouble()
this.scale = scale
}
//val once = Once()
override fun renderInternal(ctx: RenderContext) {
val iwidth = width.toInt()
val iheight = height.toInt()
ctx.renderToTexture(iwidth, iheight, render = {
super.renderInternal(ctx)
}, use = { renderTexture ->
ctx.useBatcher { batch ->
batch.drawQuad(
tex = renderTexture,
x = 0f, y = 0f,
width = iwidth.toFloat(),
height = iheight.toFloat(),
m = globalMatrix,
colorMul = renderColorMul,
colorAdd = renderColorAdd,
filtering = filtering,
blendFactors = renderBlendMode.factors
)
}
})
}
}
| korge/src/commonMain/kotlin/com/soywiz/korge/view/ScaleView.kt | 2423169975 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.nav
import com.google.android.material.shape.EdgeTreatment
import com.google.android.material.shape.ShapePath
import kotlin.math.atan
import kotlin.math.sqrt
private const val ARC_QUARTER = 90
private const val ARC_HALF = 180
private const val ANGLE_UP = 270
private const val ANGLE_LEFT = 180
/**
* An edge treatment which draws a semicircle cutout at any point along the edge.
*
* @param cutoutMargin Additional width to be added to the [cutoutDiameter], resulting in a
* larger total cutout size.
* @param cutoutRoundedCornerRadius The radius of the each of the corners where the semicircle
* meets the straight edge.
* @param cutoutVerticalOffset The amount the cutout should be lifted up in relation to the circle's
* middle.
* @param cutoutDiameter The diameter of the semicircle to be cutout.
* @param cutoutHorizontalOffset The horizontal offset, from the middle of the edge, where the
* cutout should be drawn.
*/
class SemiCircleEdgeCutoutTreatment(
private var cutoutMargin: Float = 0F,
private var cutoutRoundedCornerRadius: Float = 0F,
private var cutoutVerticalOffset: Float = 0F,
private var cutoutDiameter: Float = 0F,
private var cutoutHorizontalOffset: Float = 0F
) : EdgeTreatment() {
private var cradleDiameter = 0F
private var cradleRadius = 0F
private var roundedCornerOffset = 0F
private var middle = 0F
private var verticalOffset = 0F
private var verticalOffsetRatio = 0F
private var distanceBetweenCenters = 0F
private var distanceBetweenCentersSquared = 0F
private var distanceY = 0F
private var distanceX = 0F
private var leftRoundedCornerCircleX = 0F
private var rightRoundedCornerCircleX = 0F
private var cornerRadiusArcLength = 0F
private var cutoutArcOffset = 0F
init {
require(cutoutVerticalOffset >= 0) {
"cutoutVerticalOffset must be positive but was $cutoutVerticalOffset"
}
}
override fun getEdgePath(
length: Float,
center: Float,
interpolation: Float,
shapePath: ShapePath
) {
if (cutoutDiameter == 0f) {
// There is no cutout to draw.
shapePath.lineTo(length, 0f)
return
}
cradleDiameter = cutoutMargin * 2 + cutoutDiameter
cradleRadius = cradleDiameter / 2f
roundedCornerOffset = interpolation * cutoutRoundedCornerRadius
middle = length / 2f + cutoutHorizontalOffset
verticalOffset = interpolation * cutoutVerticalOffset +
(1 - interpolation) * cradleRadius
verticalOffsetRatio = verticalOffset / cradleRadius
if (verticalOffsetRatio >= 1.0f) {
// Vertical offset is so high that there's no curve to draw in the edge. The circle is
// actually above the edge, so just draw a straight line.
shapePath.lineTo(length, 0f)
return
}
// Calculate the path of the cutout by calculating the location of two adjacent circles. One
// circle is for the rounded corner. If the rounded corner circle radius is 0 the corner
// will not be rounded. The other circle is the cutout.
// Calculate the X distance between the center of the two adjacent circles using pythagorean
// theorem.
distanceBetweenCenters = cradleRadius + roundedCornerOffset
distanceBetweenCentersSquared = distanceBetweenCenters * distanceBetweenCenters
distanceY = verticalOffset + roundedCornerOffset
distanceX = sqrt(
(distanceBetweenCentersSquared - distanceY * distanceY).toDouble()
).toFloat()
// Calculate the x position of the rounded corner circles.
leftRoundedCornerCircleX = middle - distanceX
rightRoundedCornerCircleX = middle + distanceX
// Calculate the arc between the center of the two circles.
cornerRadiusArcLength = Math.toDegrees(
atan((distanceX / distanceY).toDouble())
).toFloat()
cutoutArcOffset = ARC_QUARTER - cornerRadiusArcLength
// Draw the starting line up to the left rounded corner.
shapePath.lineTo(leftRoundedCornerCircleX - roundedCornerOffset, 0f)
// Draw the arc for the left rounded corner circle. The bounding box is the area around the
// circle's center which is at (leftRoundedCornerCircleX, roundedCornerOffset).
shapePath.addArc(
leftRoundedCornerCircleX - roundedCornerOffset,
0f,
leftRoundedCornerCircleX + roundedCornerOffset,
roundedCornerOffset * 2,
ANGLE_UP.toFloat(),
cornerRadiusArcLength)
// Draw the cutout circle.
shapePath.addArc(
middle - cradleRadius,
-cradleRadius - verticalOffset,
middle + cradleRadius,
cradleRadius - verticalOffset,
ANGLE_LEFT - cutoutArcOffset,
cutoutArcOffset * 2 - ARC_HALF)
// Draw an arc for the right rounded corner circle. The bounding box is the area around the
// circle's center which is at (rightRoundedCornerCircleX, roundedCornerOffset).
shapePath.addArc(
rightRoundedCornerCircleX - roundedCornerOffset,
0f,
rightRoundedCornerCircleX + roundedCornerOffset,
roundedCornerOffset * 2,
ANGLE_UP - cornerRadiusArcLength,
cornerRadiusArcLength)
// Draw the ending line after the right rounded corner.
shapePath.lineTo(length, 0f)
}
}
| app/src/main/java/com/materialstudies/reply/ui/nav/SemiCircleEdgeCutoutTreatment.kt | 2210727594 |
package de.grannath.pardona
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
import sx.blah.discord.api.ClientBuilder
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.api.events.Event
import sx.blah.discord.api.events.IListener
import sx.blah.discord.handle.impl.events.ReadyEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MentionEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import java.util.regex.Pattern
@Configuration
@EnableConfigurationProperties
class BotConfiguration {
private val LOGGER by logger()
@Bean(destroyMethod = "logout")
fun discordClient(properties: DiscordProperties): IDiscordClient {
with(properties.token) {
LOGGER.info("Logging in at discord with token {}.",
replaceRange(5, length, "*".repeat(length - 5)))
}
val readyListener = IListener<ReadyEvent> {
LOGGER.info("I'm ready!")
}
val debugListener = IListener<Event> {
LOGGER.debug("Received event of type {}.", it.javaClass.name)
}
return ClientBuilder().withToken(properties.token)
.registerListeners(debugListener, readyListener)
.login()!!
}
@Bean
fun pingPongListener(client: IDiscordClient): IListener<MessageReceivedEvent> {
val listener = IListener<MessageReceivedEvent> {
if (it.message.content == "ping") {
it.message.reply("pong")
}
}
client.dispatcher.registerListener(listener)
return listener
}
}
@Component
class CommandListener(client: IDiscordClient,
val commands: List<Command>) {
init {
client.dispatcher.registerListener(getMentionListener())
client.dispatcher.registerListener(getPrivateListener())
}
private val LOGGER by logger()
private val splitPattern = Pattern.compile("\\p{Blank}+")
private fun getMentionListener() = IListener<MentionEvent> {
if (!it.channel.isPrivate) {
handleIfCommand(it)
}
}
private fun getPrivateListener() = IListener<MessageReceivedEvent> {
if (it.channel.isPrivate) {
handleIfCommand(it)
}
}
private fun handleIfCommand(event: MessageEvent) {
LOGGER.debug("I'm mentioned in {}.", event.message.content)
val split = event.message.content.split(splitPattern).filterIndexed { index, string ->
index != 0 || !string.startsWith("<@")
}
commands.find { it.canHandle(split[0]) }.apply {
if (this == null)
return
LOGGER.debug("Found keyword {}.", split[0])
if (event.channel.isPrivate) {
event.channel.sendMessage(buildReply(split.subList(1, split.size)))
} else {
event.message.reply(buildReply(split.subList(1, split.size)))
}
}
}
}
interface Command {
fun canHandle(keyword: String): Boolean
fun buildReply(args: List<String>): String
}
@ConfigurationProperties("discord")
@Component
class DiscordProperties(var token: String = "",
var clientId: String = "",
var permissions: Int = 0) | src/main/kotlin/de/grannath/pardona/BotConfiguration.kt | 782080802 |
package com.emogoth.android.phone.mimi.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.disposables.Disposable
class GalleryScrollReceiver(val boardName: String, val threadId: Long, val positionChangedListener: ((Long) -> (Unit))) : BroadcastReceiver() {
var scrollPositionEmitter: FlowableEmitter<Long>? = null
var scrollPositionObserver: Disposable? = null
val intentFilter: String
get() = createIntentFilter(boardName, threadId)
var id: Long = 0
init {
val flowable: Flowable<Long> = Flowable.create({
scrollPositionEmitter = it
}, BackpressureStrategy.DROP)
scrollPositionObserver = flowable.subscribe({
positionChangedListener.invoke(it)
}, {
Log.e("GalleryScrollReceiver", "Error running GalleryScrollReceiver", it)
})
}
public fun destroy() {
RxUtil.safeUnsubscribe(scrollPositionObserver)
}
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.extras?.containsKey(SCROLL_ID_FLAG) == true) {
id = intent.extras?.getLong(SCROLL_ID_FLAG) ?: -1
scrollPositionEmitter?.onNext(id)
}
}
companion object {
const val SCROLL_ID_FLAG = "gallery_scroll_position"
private const val SCROLL_INTENT_FILTER = "gallery_scrolled_event"
fun createIntentFilter(boardName: String, threadId: Long): String {
return "${boardName}_${threadId}_${SCROLL_INTENT_FILTER}"
}
}
} | mimi-app/src/main/java/com/emogoth/android/phone/mimi/util/GalleryScrollReceiver.kt | 1383110580 |
package com.soywiz.korge.debug
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.color.*
import com.soywiz.korma.geom.*
import com.soywiz.korma.geom.vector.*
import com.soywiz.korui.*
import com.soywiz.korui.layout.*
import com.soywiz.korui.layout.Size
import com.soywiz.korui.native.*
object KoruiSample2 {
@JvmStatic
fun main(args: Array<String>) {
val window = DEFAULT_UI_FACTORY.createWindow()
val scrollPanel = DEFAULT_UI_FACTORY.createScrollPanel()
val button = DEFAULT_UI_FACTORY.createButton()
button.bounds = RectangleInt(0, 0, 400, 250)
scrollPanel.insertChildAt(-1, button)
scrollPanel.bounds = RectangleInt(0, 0, 300, 300)
window.insertChildAt(-1, scrollPanel)
//window.insertChildAt(-1, button)
window.bounds = RectangleInt(0, 0, 600, 600)
window.visible = true
}
}
/*
object KoruiSample1 {
@JvmStatic
fun main(args: Array<String>) {
/*
val window = defaultKoruiFactory.createWindow()
val button = defaultKoruiFactory.createButton()
defaultKoruiFactory.setBounds(window, 16, 16, 600, 600)
defaultKoruiFactory.setBounds(button, 16, 16, 320, 100)
defaultKoruiFactory.setText(button, "hello")
defaultKoruiFactory.setParent(button, window)
defaultKoruiFactory.setVisible(window, true)
*/
UiApplication(DEFAULT_UI_FACTORY).window(600, 600) {
val crossIcon = NativeImage(16, 16).context2d {
stroke(Colors.RED, lineWidth = 3.0) {
line(0, 0, 16 - 1.5, 16 - 1.5)
line(16 - 1.5, 0, 0, 16 - 1.5)
}
}
menu = UiMenu(listOf(UiMenuItem("hello", listOf(UiMenuItem("world", icon = crossIcon))), UiMenuItem("world")))
layout = UiFillLayout
scrollPanel(xbar = false, ybar = true) {
//run {
layout = VerticalUiLayout
focusable = true
layoutChildrenPadding = 8
//var checked by state { false }
var checked = true
//val checked by ObservableProperty(false)
//var checked: Boolean by ObservableProperty(false)
//var checked2: Boolean by ObservableProperty(false)
println("checked: $checked")
onClick {
focus()
}
//vertical {
run {
//toolbar {
// button("1") { }
// button("2") { }
// button("3") { }
//}
canvas(NativeImage(128, 128).context2d {
stroke(Colors.WHITE, lineWidth = 3.0) {
line(0, 0, 128 - 1.5, 128 - 1.5)
line(128 - 1.5, 0, 0, 128 - 1.5)
}
}) {
}
checkBox("hello", checked = checked) {
//enabled = false
bounds = RectangleInt(16, 16, 320, 32)
onClick {
checked = !checked
//checked = false
//checked = true
}
}
button("save", {
bounds = RectangleInt(16, 64, 320, 32)
}) {
this.showPopupMenu(listOf(UiMenuItem("HELLO", icon = crossIcon)))
}
lateinit var props: UiContainer
button("Properties") {
props.visible = !props.visible
}
props = vertical {
addChild(UiRowEditableValue(app, "position", UiTwoItemEditableValue(app, UiNumberEditableValue(app, 0.0, -1000.0, +1000.0, decimalPlaces = 0), UiNumberEditableValue(app, 0.0, -1000.0, +1000.0))))
addChild(UiRowEditableValue(app, "ratio", UiNumberEditableValue(app, 0.0, min = 0.0, max = 1.0, clampMin = true, clampMax = true)))
addChild(UiRowEditableValue(app, "y", UiListEditableValue(app, listOf("hello", "world"), "world")))
}
tree {
minimumSize = Size(32.pt, 128.pt)
nodeRoot = SimpleUiTreeNode("hello",
(0 until 40).map { SimpleUiTreeNode("world$it") }
)
}
lateinit var vert: UiContainer
label("DEMO") {
icon = crossIcon
onClick {
vert.visible = !vert.visible
icon = if (vert.visible) crossIcon else null
}
}
vert = vertical {
label("HELLO") {}
label("WORLD") {}
button("test")
label("LOL") {}
}
button("TEST") {
}
}
}
}
}
}
*/
| korge/src/jvmTest/kotlin/com/soywiz/korge/debug/KoruiSample1.kt | 2176903682 |
package com.telenav.osv.data.collector.phonedata.collector
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.BatteryObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
/**
* BatteryCollector collects the information about battery status
* It registers a broadcastReceiver in order to monitoring the battery state
*/
class BatteryCollector(private val context: Context, phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) {
/**
* BroadcastReceiver used for detecting any changes on battery
*/
private var batteryBroadcastReceiver: BroadcastReceiver? = null
/**
* Field used to verify if the battery receiver was registerd or not
*/
private var isBatteryReceiverRegisterd = false
/**
* Register a [BroadcastReceiver] for monitoring the battery state.
* Every change of battery state will notify the receiver
*/
fun startCollectingBatteryData() {
if (!isBatteryReceiverRegisterd) {
batteryBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val batteryObject = BatteryObject(getBatteryLevel(intent), getBatteryState(intent), LibraryUtil.PHONE_SENSOR_READ_SUCCESS)
onNewSensorEvent(batteryObject)
}
}
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
context.registerReceiver(batteryBroadcastReceiver, intentFilter, null, notifyHandler)
isBatteryReceiverRegisterd = true
}
}
/**
* Retrieve the batery level of the device
*
* @param intent Intent used for extracting battery information
* @return The batery level
*/
fun getBatteryLevel(intent: Intent): Float {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
return level / scale.toFloat() * 100
}
/**
* Retrieve the batery state (charging or not) of the device
*
* @param intent Intent used for extracting battery information
* @return The battery state
*/
fun getBatteryState(intent: Intent): String {
val state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
val isCharging = state == BatteryManager.BATTERY_STATUS_CHARGING || state == BatteryManager.BATTERY_STATUS_FULL
val charger = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
val usbCharger = charger == BatteryManager.BATTERY_PLUGGED_USB
val accCharger = charger == BatteryManager.BATTERY_PLUGGED_AC
val response = StringBuilder()
if (isCharging) {
response.append(CHARGING_MODE_ON)
if (usbCharger) {
response.append(USB_CHARGING)
} else if (accCharger) {
response.append(ACC_CHARGING)
}
} else {
response.append(CHARGING_MODE_OFF)
}
return response.toString()
}
fun unregisterReceiver() {
if (batteryBroadcastReceiver != null && isBatteryReceiverRegisterd) {
context.unregisterReceiver(batteryBroadcastReceiver)
isBatteryReceiverRegisterd = false
}
}
companion object {
/**
* BleConstants used for determine the battery state
*/
const val CHARGING_MODE_ON = "Battery is charging via "
const val CHARGING_MODE_OFF = "Battery is not charging"
const val USB_CHARGING = "USB"
const val ACC_CHARGING = "ACC"
}
} | app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/BatteryCollector.kt | 3452351589 |
/*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ffc.app.person
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import ffc.android.getString
import ffc.android.layoutInflater
import ffc.android.load
import ffc.app.R
import ffc.app.health.analyze.toIconTitlePair
import ffc.app.util.AdapterClickListener
import ffc.entity.Person
import kotlinx.android.synthetic.main.person_list_item.view.personAgeView
import kotlinx.android.synthetic.main.person_list_item.view.personDeadLabel
import kotlinx.android.synthetic.main.person_list_item.view.personImageView
import kotlinx.android.synthetic.main.person_list_item.view.personNameView
import kotlinx.android.synthetic.main.person_list_item.view.personStatus
import org.jetbrains.anko.dip
import timber.log.Timber
class PersonAdapter(
var persons: List<Person>,
var limit: Int = Int.MAX_VALUE,
onClickDsl: AdapterClickListener<Person>.() -> Unit
) : RecyclerView.Adapter<PersonAdapter.PersonHolder>() {
val listener = AdapterClickListener<Person>().apply(onClickDsl)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonHolder {
val view = parent.layoutInflater.inflate(R.layout.person_list_item, parent, false)
return PersonHolder(view)
}
override fun getItemCount(): Int {
Timber.d("person size ${persons.size}")
return persons.size.takeIf { it < limit } ?: limit
}
override fun onBindViewHolder(holder: PersonHolder, position: Int) {
holder.bind(persons[position], listener)
}
fun update(update: List<Person>) {
this.persons = update
notifyDataSetChanged()
}
class PersonHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(person: Person, listener: AdapterClickListener<Person>) {
with(person) {
itemView.personNameView.text = name
itemView.personAgeView.text = "$age ปี"
itemView.personDeadLabel.visibility = if (isDead) View.VISIBLE else View.GONE
itemView.personImageView.setImageResource(R.drawable.ic_account_circle_black_24dp)
itemView.personStatus.removeAllViews()
person.healthAnalyze?.result?.filterValues { it.haveIssue }?.forEach {
val layoutParam = LinearLayout.LayoutParams(itemView.dip(16), itemView.dip(16)).apply {
marginStart = itemView.dip(4)
marginEnd = itemView.dip(4)
}
val pair = it.value.issue.toIconTitlePair() ?: return@forEach
itemView.personStatus.addView(ImageView(itemView.context).apply {
setImageResource(pair.first)
contentDescription = getString(pair.second)
}, layoutParam)
}
avatarUrl?.let { itemView.personImageView.load(Uri.parse(it)) }
listener.bindOnItemClick(itemView, person)
}
}
}
}
| ffc/src/main/kotlin/ffc/app/person/PersonAdapter.kt | 2763829906 |
package com.telenav.osv.tasks.utils
interface CurrencyUtil {
fun getCurrencySymbol(currencyCode: String): String
fun getAmountWithCurrencySymbol(currencyCode: String, amount: Double): String
} | app/src/main/java/com/telenav/osv/tasks/utils/CurrencyUtil.kt | 4019562851 |
package de.saschahlusiak.freebloks.utils
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
val Context.prefs: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(this)
fun Float.toPixel(context: Context) = this * context.resources.displayMetrics.density | app/src/main/java/de/saschahlusiak/freebloks/utils/Context.kt | 1783024684 |
/*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import javax.persistence.CascadeType
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.OneToMany
import javax.persistence.Table
import javax.validation.constraints.NotNull
/**
* @author nmaerchy
* @since 2.0.0
*/
@Entity
@Table(name = "COMPETITOR")
data class CompetitorEntity(
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
var startnumber: Int? = null,
@NotNull
@ManyToOne
@JoinColumn(name = "fk_PARTICIPANT_id", referencedColumnName = "id")
var participant: ParticipantEntity = ParticipantEntity(),
@OneToMany(cascade = [CascadeType.ALL], mappedBy = "competitor")
var results: Set<ResultEntity> = setOf()
)
| app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/CompetitorEntity.kt | 838718486 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.media
import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder
import org.mariotaku.ktextension.nextPowerOf2
import org.mariotaku.mediaviewer.library.CacheDownloadLoader
import org.mariotaku.mediaviewer.library.subsampleimageview.SubsampleImageViewerFragment
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.activity.MediaViewerActivity
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.util.UriUtils
import de.vanita5.twittnuker.util.media.MediaExtra
import java.io.IOException
import java.lang.ref.WeakReference
class ImagePageFragment : SubsampleImageViewerFragment() {
private val media: ParcelableMedia?
get() = arguments.getParcelable<ParcelableMedia?>(EXTRA_MEDIA)
private val accountKey: UserKey?
get() = arguments.getParcelable<UserKey?>(EXTRA_ACCOUNT_KEY)
private val sizedResultCreator: CacheDownloadLoader.ResultCreator by lazy {
return@lazy SizedResultCreator(context)
}
private var mediaLoadState: Int = 0
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
activity?.invalidateOptionsMenu()
}
}
override fun getDownloadUri(): Uri? {
return media?.media_url?.let(Uri::parse)
}
override fun getDownloadExtra(): Any? {
val mediaExtra = MediaExtra()
mediaExtra.accountKey = accountKey
mediaExtra.fallbackUrl = media?.preview_url
mediaExtra.isSkipUrlReplacing = mediaExtra.fallbackUrl != downloadUri?.toString()
return mediaExtra
}
override fun hasDownloadedData(): Boolean {
return super.hasDownloadedData() && mediaLoadState != State.ERROR
}
override fun onMediaLoadStateChange(@State state: Int) {
mediaLoadState = state
if (userVisibleHint) {
activity?.invalidateOptionsMenu()
}
}
override fun setupImageView(imageView: SubsamplingScaleImageView) {
imageView.maxScale = resources.displayMetrics.density
imageView.setBitmapDecoderClass(PreviewBitmapDecoder::class.java)
imageView.setParallelLoadingEnabled(true)
imageView.setOnClickListener {
val activity = activity as? MediaViewerActivity ?: return@setOnClickListener
activity.toggleBar()
}
}
override fun getImageSource(data: CacheDownloadLoader.Result): ImageSource {
assert(data.cacheUri != null)
if (data !is SizedResult) {
return super.getImageSource(data)
}
val imageSource = ImageSource.uri(data.cacheUri!!)
imageSource.tilingEnabled()
imageSource.dimensions(data.width, data.height)
return imageSource
}
override fun getPreviewImageSource(data: CacheDownloadLoader.Result): ImageSource? {
if (data !is SizedResult) return null
assert(data.cacheUri != null)
return ImageSource.uri(UriUtils.appendQueryParameters(data.cacheUri, QUERY_PARAM_PREVIEW, true))
}
override fun getResultCreator(): CacheDownloadLoader.ResultCreator? {
return sizedResultCreator
}
internal class SizedResult(cacheUri: Uri, val width: Int, val height: Int) : CacheDownloadLoader.Result(cacheUri, null)
internal class SizedResultCreator(context: Context) : CacheDownloadLoader.ResultCreator {
private val weakContext = WeakReference(context)
override fun create(uri: Uri): CacheDownloadLoader.Result {
val context = weakContext.get() ?: return CacheDownloadLoader.Result.getInstance(InterruptedException())
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
try {
decodeBitmap(context.contentResolver, uri, o)
} catch (e: IOException) {
return CacheDownloadLoader.Result.getInstance(uri)
}
if (o.outWidth > 0 && o.outHeight > 0) {
return SizedResult(uri, o.outWidth, o.outHeight)
}
return CacheDownloadLoader.Result.getInstance(uri)
}
}
class PreviewBitmapDecoder : SkiaImageDecoder() {
@Throws(Exception::class)
override fun decode(context: Context, uri: Uri): Bitmap {
if (AUTHORITY_TWITTNUKER_CACHE == uri.authority && uri.getBooleanQueryParameter(QUERY_PARAM_PREVIEW, false)) {
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
o.inPreferredConfig = Bitmap.Config.RGB_565
val cr = context.contentResolver
decodeBitmap(cr, uri, o)
val dm = context.resources.displayMetrics
val targetSize = Math.min(1024, Math.max(dm.widthPixels, dm.heightPixels))
val sizeRatio = Math.ceil(Math.max(o.outHeight, o.outWidth) / targetSize.toDouble())
o.inSampleSize = Math.max(1.0, sizeRatio).toInt().nextPowerOf2
o.inJustDecodeBounds = false
return decodeBitmap(cr, uri, o) ?: throw IOException()
}
return super.decode(context, uri)
}
}
companion object {
@Throws(IOException::class)
internal fun decodeBitmap(cr: ContentResolver, uri: Uri, o: BitmapFactory.Options): Bitmap? {
cr.openInputStream(uri).use {
return BitmapFactory.decodeStream(it, null, o)
}
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/media/ImagePageFragment.kt | 2736811399 |
package io.github.ajoz.workshop.intro
sealed class Option<out T> {
fun <R> map(f: (T) -> R): Option<R> = when (this) {
is None -> None
is Some -> Some(f(value))
}
abstract fun isEmpty(): Boolean
abstract fun isDefined(): Boolean
}
data class Some<out T>(val value: T) : Option<T>() {
override fun isDefined() = true
override fun isEmpty() = false
}
object None : Option<Nothing>() {
override fun isDefined() = false
override fun isEmpty() = true
} | intro/src/main/kotlin/io/github/ajoz/workshop/intro/Sealeds.kt | 798894885 |
package com.stripe.android.link.ui.wallet
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.stripe.android.model.CardBrand
import com.stripe.android.model.ConsumerPaymentDetails
import com.stripe.android.model.CvcCheck
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private val MOCK_CARD = ConsumerPaymentDetails.Card(
id = "id1",
isDefault = true,
expiryYear = 2032,
expiryMonth = 12,
brand = CardBrand.Visa,
last4 = "4242",
cvcCheck = CvcCheck.Pass
)
private val MOCK_BANK_ACCOUNT = ConsumerPaymentDetails.BankAccount(
id = "id2",
isDefault = false,
bankIconCode = "icon",
bankName = "Stripe Bank",
last4 = "6789"
)
@RunWith(AndroidJUnit4::class)
class WalletPaymentMethodMenuTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun testCardMenuIsDisplayedCorrectlyForNonDefaultCard() {
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD.copy(isDefault = false),
onEditClick = {},
onSetDefaultClick = {},
onRemoveClick = {},
onCancelClick = {}
)
}
composeTestRule.onNodeWithText("Update card").assertExists()
composeTestRule.onNodeWithText("Set as default").assertExists()
composeTestRule.onNodeWithText("Remove card").assertExists()
composeTestRule.onNodeWithText("Cancel").assertExists()
}
@Test
fun testCardMenuIsDisplayedCorrectlyForDefaultCard() {
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD.copy(isDefault = true),
onEditClick = {},
onSetDefaultClick = {},
onRemoveClick = {},
onCancelClick = {}
)
}
composeTestRule.onNodeWithText("Update card").assertExists()
composeTestRule.onNodeWithText("Set as default").assertDoesNotExist()
composeTestRule.onNodeWithText("Remove card").assertExists()
composeTestRule.onNodeWithText("Cancel").assertExists()
}
@Test
fun testBankAccountMenuIsDisplayedCorrectlyForNonDefaultAccount() {
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_BANK_ACCOUNT.copy(isDefault = false),
onEditClick = {},
onSetDefaultClick = {},
onRemoveClick = {},
onCancelClick = {}
)
}
composeTestRule.onNodeWithText("Update card").assertDoesNotExist()
composeTestRule.onNodeWithText("Set as default").assertExists()
composeTestRule.onNodeWithText("Remove linked account").assertExists()
composeTestRule.onNodeWithText("Cancel").assertExists()
}
@Test
fun testBankAccountMenuIsDisplayedCorrectlyForDefaultAccount() {
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_BANK_ACCOUNT.copy(isDefault = true),
onEditClick = {},
onSetDefaultClick = {},
onRemoveClick = {},
onCancelClick = {}
)
}
composeTestRule.onNodeWithText("Update card").assertDoesNotExist()
composeTestRule.onNodeWithText("Set as default").assertDoesNotExist()
composeTestRule.onNodeWithText("Remove linked account").assertExists()
composeTestRule.onNodeWithText("Cancel").assertExists()
}
@Test
fun testUpdateCardWorksCorrectly() {
val clickRecorder = MockClickRecorder()
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD,
onEditClick = clickRecorder::onEditClick,
onSetDefaultClick = clickRecorder::onSetAsDefaultClick,
onRemoveClick = clickRecorder::onRemoveClick,
onCancelClick = clickRecorder::onCancelClick
)
}
composeTestRule.onNodeWithText("Update card").performClick()
assertThat(clickRecorder).isEqualTo(
MockClickRecorder(editClicked = true)
)
}
@Test
fun testSetAsDefaultWorksCorrectly() {
val clickRecorder = MockClickRecorder()
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD.copy(isDefault = false),
onEditClick = clickRecorder::onEditClick,
onSetDefaultClick = clickRecorder::onSetAsDefaultClick,
onRemoveClick = clickRecorder::onRemoveClick,
onCancelClick = clickRecorder::onCancelClick
)
}
composeTestRule.onNodeWithText("Set as default").performClick()
assertThat(clickRecorder).isEqualTo(
MockClickRecorder(setAsDefaultClicked = true)
)
}
@Test
fun testRemoveWorksCorrectly() {
val clickRecorder = MockClickRecorder()
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD,
onEditClick = clickRecorder::onEditClick,
onSetDefaultClick = clickRecorder::onSetAsDefaultClick,
onRemoveClick = clickRecorder::onRemoveClick,
onCancelClick = clickRecorder::onCancelClick
)
}
composeTestRule.onNodeWithText("Remove card").performClick()
assertThat(clickRecorder).isEqualTo(
MockClickRecorder(removeClicked = true)
)
}
@Test
fun testCancelWorksCorrectly() {
val clickRecorder = MockClickRecorder()
composeTestRule.setContent {
WalletPaymentMethodMenu(
paymentDetails = MOCK_CARD,
onEditClick = clickRecorder::onEditClick,
onSetDefaultClick = clickRecorder::onSetAsDefaultClick,
onRemoveClick = clickRecorder::onRemoveClick,
onCancelClick = clickRecorder::onCancelClick
)
}
composeTestRule.onNodeWithText("Cancel").performClick()
assertThat(clickRecorder).isEqualTo(
MockClickRecorder(cancelClicked = true)
)
}
private data class MockClickRecorder(
var editClicked: Boolean = false,
var setAsDefaultClicked: Boolean = false,
var removeClicked: Boolean = false,
var cancelClicked: Boolean = false
) {
fun onEditClick() { editClicked = true }
fun onSetAsDefaultClick() { setAsDefaultClicked = true }
fun onRemoveClick() { removeClicked = true }
fun onCancelClick() { cancelClicked = true }
}
}
| link/src/androidTest/java/com/stripe/android/link/ui/wallet/WalletPaymentMethodMenuTest.kt | 2366993363 |
package com.intellij.idekonsole.results
import com.intellij.ide.IdeBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.unscramble.AnalyzeStacktraceDialog
import com.intellij.unscramble.AnalyzeStacktraceUtil
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
/**
* @author simon
*/
class KAnalyzeStacktraceDialog : DialogWrapper {
val project: Project
val text : String
lateinit var myEditorPanel: AnalyzeStacktraceUtil.StacktraceEditorPanel
constructor(project: Project, text:String) : super(project, true) {
this.project = project
this.text = text
this.title = IdeBundle.message("unscramble.dialog.title", *arrayOfNulls<Any>(0))
this.init()
}
override fun createCenterPanel(): JComponent? {
val var1 = JPanel(BorderLayout())
var1.add(JLabel("Stacktrace:"), "North")
this.myEditorPanel = AnalyzeStacktraceUtil.createEditorPanel(this.project, this.myDisposable)
this.myEditorPanel.text = text
var1.add(this.myEditorPanel, "Center")
return var1
}
override fun doOKAction() {
AnalyzeStacktraceUtil.addConsole(this.project, null, "<Stacktrace>", this.myEditorPanel.text)
super.doOKAction()
}
override fun getPreferredFocusedComponent(): JComponent? {
return this.myEditorPanel.editorComponent
}
} | Konsole/src/com/intellij/idekonsole/results/KAnalyzeStacktraceDialog.kt | 1167711962 |
package abi43_0_0.expo.modules.haptics.arguments
val HapticsSelectionType = HapticsVibrationType(
timings = longArrayOf(0, 100),
amplitudes = intArrayOf(0, 100),
oldSDKPattern = longArrayOf(0, 70)
)
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/haptics/arguments/HapticsSelectionType.kt | 834627249 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation
import androidx.annotation.IdRes
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.navigation.testing.TestNavigatorState
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.setMain
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NavGraphNavigatorTest {
companion object {
@IdRes
private const val FIRST_DESTINATION_ID = 1
@IdRes
private const val SECOND_DESTINATION_ID = 2
}
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var provider: NavigatorProvider
private lateinit var noOpState: TestNavigatorState
private lateinit var noOpNavigator: NoOpNavigator
private lateinit var navGraphState: TestNavigatorState
private lateinit var navGraphNavigator: NavGraphNavigator
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() {
Dispatchers.setMain(UnconfinedTestDispatcher())
provider = NavigatorProvider().apply {
addNavigator(NoOpNavigator().also { noOpNavigator = it })
addNavigator(
NavGraphNavigator(this).also {
navGraphNavigator = it
}
)
}
noOpState = TestNavigatorState()
noOpNavigator.onAttach(noOpState)
navGraphState = TestNavigatorState()
navGraphNavigator.onAttach(navGraphState)
}
private fun createFirstDestination() = noOpNavigator.createDestination().apply {
id = FIRST_DESTINATION_ID
}
private fun createSecondDestination() = noOpNavigator.createDestination().apply {
id = SECOND_DESTINATION_ID
}
private fun createGraphWithDestination(
destination: NavDestination,
startId: Int = destination.id
) = navGraphNavigator.createDestination().apply {
addDestination(destination)
setStartDestination(startId)
}
@Test(expected = IllegalStateException::class)
fun navigateWithoutStartDestination() {
val destination = createFirstDestination()
val graph = navGraphNavigator.createDestination().apply {
addDestination(destination)
id = 2 // can't match id of first destination or the start destination
setStartDestination(0)
}
val entry = navGraphState.createBackStackEntry(graph, null)
navGraphNavigator.navigate(listOf(entry), null, null)
}
@Test
fun navigate() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
val entry = navGraphState.createBackStackEntry(graph, null)
navGraphNavigator.navigate(listOf(entry), null, null)
assertThat(noOpState.backStack.value.map { it.destination })
.containsExactly(destination)
}
}
| navigation/navigation-common/src/test/java/androidx/navigation/NavGraphNavigatorTest.kt | 3928298437 |
package com.twitter.meil_mitu.twitter4hk.converter
import com.squareup.okhttp.Response
import com.twitter.meil_mitu.twitter4hk.ResponseData
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
interface IPlaceConverter<TPlace> : IJsonConverter {
@Throws(Twitter4HKException::class)
fun toPlaceResponseData(res: Response): ResponseData<TPlace>
} | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/IPlaceConverter.kt | 123760290 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.openapi.util.text.StringUtil
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.*
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.addToHolder
/**
* Inspection that detects the E0049 error.
*/
class RsWrongGenericParametersNumberInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() {
override fun visitFunction(function: RsFunction) {
checkParameters(holder, function, "type") { typeParameters }
checkParameters(holder, function, "const") { constParameters }
}
override fun visitTypeAlias(alias: RsTypeAlias) {
checkParameters(holder, alias, "type") { typeParameters }
checkParameters(holder, alias, "const") { constParameters }
}
}
private fun <T> checkParameters(
holder: RsProblemsHolder,
item: T,
paramType: String,
getParameters: RsGenericDeclaration.() -> List<RsGenericParameter>
) where T : RsAbstractable, T : RsGenericDeclaration {
val itemName = item.name ?: return
val itemType = when (item) {
is RsFunction -> "Method"
is RsTypeAlias -> "Type"
else -> return
}
val superItem = item.superItem as? RsGenericDeclaration ?: return
val toHighlight = item.typeParameterList ?: item.nameIdentifier ?: return
val typeParameters = item.getParameters()
val superTypeParameters = superItem.getParameters()
if (typeParameters.size == superTypeParameters.size) return
val paramName = "$paramType ${StringUtil.pluralize("parameter", typeParameters.size)}"
val superParamName = "$paramType ${StringUtil.pluralize("parameter", superTypeParameters.size)}"
val problemText = "$itemType `$itemName` has ${typeParameters.size} $paramName " +
"but its trait declaration has ${superTypeParameters.size} $superParamName"
RsDiagnostic.WrongNumberOfGenericParameters(toHighlight, problemText).addToHolder(holder)
}
}
| src/main/kotlin/org/rust/ide/inspections/RsWrongGenericParametersNumberInspection.kt | 1211760980 |
package solutions.day03
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
data class Cursor(var x: Int, var y:Int)
fun Cursor.manhattanDistance() : Int = Math.abs(x) + Math.abs(y)
data class CircleInfo(val circle: Int, val numbers: Int)
class Day3: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val target = input.first().toInt()
if(target == 1) {
return 0.toString()
}
if(partTwo) {
return doPartTwo(target)
}
val circleInfo = determineCircle(target)
val number = circleInfo.numbers + (circleInfo.circle-2)
val cursor = Cursor(circleInfo.circle - 1, 0)
val valueAtTopRightCorner = number + (circleInfo.circle - 1)
if(target <= valueAtTopRightCorner) {
val steps = (target-number) - 1
cursor.y = cursor.y + steps
return cursor.manhattanDistance().toString()
}
cursor.y = circleInfo.circle - 1
val stepsToTraverseSide = (circleInfo.circle - 1) * 2
val valueAtTopLeftCorner = valueAtTopRightCorner + stepsToTraverseSide
if(target <= valueAtTopLeftCorner) {
val steps = target - valueAtTopRightCorner - 1
cursor.x = cursor.x - steps
return cursor.manhattanDistance().toString()
}
cursor.x = cursor.x - stepsToTraverseSide
val valueAtBottomLeftCorner = valueAtTopLeftCorner + stepsToTraverseSide
if(target <= valueAtBottomLeftCorner) {
val steps = target - valueAtTopLeftCorner - 1
cursor.y = cursor.y - steps
return cursor.manhattanDistance().toString()
}
cursor.y = cursor.y - stepsToTraverseSide
val valueAtBottomRightCorner = valueAtBottomLeftCorner + stepsToTraverseSide
if(target <= valueAtBottomRightCorner) {
val steps = target - valueAtBottomLeftCorner - 1
cursor.x = cursor.x + steps
return cursor.manhattanDistance().toString()
}
cursor.x = cursor.x + stepsToTraverseSide
val valueBeforeBackAtStart = valueAtBottomRightCorner + (stepsToTraverseSide / 2 - 1)
if(target <= valueBeforeBackAtStart) {
val steps = target - valueAtBottomRightCorner - 1
cursor.y = cursor.y + steps
return cursor.manhattanDistance().toString()
}
throw RuntimeException("Not found")
}
private fun doPartTwo(target: Int): String {
val memory: MutableMap<Coordinate, Int> = mutableMapOf<Coordinate, Int>().withDefault { 0 }
val start = Coordinate(0, 0)
memory.put(start, 1)
return traverse(target, start, memory, Direction.RIGHT, 1)
}
private fun traverse(target: Int, curr: Coordinate, memory: MutableMap<Coordinate, Int>, direction: Direction, steps: Int): String {
if(steps == 0) {
val circleInfo = determineCircle(memory.size)
val stepsNext = (circleInfo.circle - 1) * 2
return when(direction) {
Direction.UP -> traverse(target, curr, memory, Direction.LEFT, stepsNext)
Direction.LEFT -> traverse(target, curr, memory, Direction.DOWN, stepsNext)
Direction.DOWN -> traverse(target, curr, memory, Direction.RIGHT, stepsNext+1)
Direction.RIGHT -> traverse(target, curr, memory, Direction.UP, stepsNext-1)
}
}
val next = curr.step(direction)
val sum = getSum(next, memory)
if(sum > target) {
return sum.toString()
}
memory.put(next, sum)
return traverse(target, next, memory, direction, steps-1)
}
private fun getSum(coordinate: Coordinate, memory: MutableMap<Coordinate, Int>): Int {
return memory.getValue(coordinate.step(Direction.UP)) +
memory.getValue(coordinate.step(Direction.LEFT)) +
memory.getValue(coordinate.step(Direction.RIGHT)) +
memory.getValue(coordinate.step(Direction.DOWN)) +
memory.getValue(Coordinate(coordinate.x+1, coordinate.y+1)) +
memory.getValue(Coordinate(coordinate.x-1, coordinate.y+1)) +
memory.getValue(Coordinate(coordinate.x+1, coordinate.y-1)) +
memory.getValue(Coordinate(coordinate.x-1, coordinate.y-1))
}
private fun determineCircle(target: Int): CircleInfo {
var steps = 0
if(target > 1) {
steps += 1
}
var circle = 2
while(true) {
val nextSteps = steps + (circle-1) * 8
if(nextSteps > target) {
return CircleInfo(circle, steps)
}
circle++
steps = nextSteps
}
}
} | src/main/kotlin/solutions/day03/Day3.kt | 1441567562 |
package com.habitrpg.android.habitica.ui.viewHolders
import android.content.res.Resources
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toBitmap
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.MountOverviewItemBinding
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.inventory.Mount
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.menu.BottomSheetMenu
import com.habitrpg.android.habitica.ui.menu.BottomSheetMenuItem
import io.reactivex.rxjava3.subjects.PublishSubject
class MountViewHolder(parent: ViewGroup, private val equipEvents: PublishSubject<String>) : androidx.recyclerview.widget.RecyclerView.ViewHolder(parent.inflate(R.layout.mount_overview_item)), View.OnClickListener {
private var binding: MountOverviewItemBinding = MountOverviewItemBinding.bind(itemView)
private var owned: Boolean = false
var animal: Mount? = null
private var currentMount: String? = null
var resources: Resources = itemView.resources
init {
itemView.setOnClickListener(this)
}
fun bind(item: Mount, owned: Boolean, currentMount: String?) {
animal = item
this.owned = owned
this.currentMount = currentMount
binding.titleTextView.visibility = View.GONE
binding.ownedTextView.visibility = View.GONE
val imageName = "stable_Mount_Icon_" + item.animal + "-" + item.color
binding.imageView.alpha = 1.0f
if (!owned) {
binding.imageView.alpha = 0.2f
}
binding.imageView.background = null
binding.activeIndicator.visibility = if (currentMount.equals(animal?.key)) View.VISIBLE else View.GONE
DataBindingUtils.loadImage(itemView.context, imageName) {
val drawable = if (owned) it else BitmapDrawable(itemView.context.resources, it.toBitmap().extractAlpha())
binding.imageView.background = drawable
}
}
override fun onClick(v: View) {
if (!owned) {
return
}
val menu = BottomSheetMenu(itemView.context)
menu.setTitle(animal?.text)
val hasCurrentMount = currentMount.equals(animal?.key)
val labelId = if (hasCurrentMount) R.string.unequip else R.string.equip
menu.addMenuItem(BottomSheetMenuItem(resources.getString(labelId)))
menu.setSelectionRunnable {
animal?.let { equipEvents.onNext(it.key ?: "") }
}
menu.show()
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/MountViewHolder.kt | 2412885545 |
package org.jetbrains.dokka.gradle
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Test
import kotlin.test.assertEquals
class BasicTest : AbstractDokkaGradleTest() {
fun prepareTestData(testDataRootPath: String) {
val testDataRoot = testDataFolder.resolve(testDataRootPath)
val tmpRoot = testProjectDir.root.toPath()
testDataRoot.resolve("src").copy(tmpRoot.resolve("src"))
testDataRoot.resolve("classDir").copy(tmpRoot.resolve("classDir"))
testDataRoot.resolve("build.gradle").copy(tmpRoot.resolve("build.gradle"))
testDataRoot.resolve("settings.gradle").copy(tmpRoot.resolve("settings.gradle"))
}
private fun doTest(gradleVersion: String, kotlinVersion: String) {
prepareTestData("basic")
val result = configure(gradleVersion, kotlinVersion, arguments = arrayOf("dokka", "--stacktrace")).build()
println(result.output)
assertEquals(TaskOutcome.SUCCESS, result.task(":dokka")?.outcome)
val docsOutput = "build/dokka"
checkOutputStructure("basic/fileTree.txt", docsOutput)
checkNoErrorClasses(docsOutput)
checkNoUnresolvedLinks(docsOutput)
checkExternalLink(docsOutput, "<span class=\"identifier\">String</span>",
"""<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html"><span class="identifier">String</span></a>""")
}
@Test fun `test kotlin 1_1_2 and gradle 3_5`() {
doTest("3.5", "1.1.2")
}
@Test fun `test kotlin 1_0_7 and gradle 2_14_1`() {
doTest("2.14.1", "1.0.7")
}
@Test fun `test kotlin 1_1_2 and gradle 4_0`() {
doTest("4.0", "1.1.2")
}
@Test fun `test kotlin 1_2_20 and gradle 4_5`() {
doTest("4.5", "1.2.20")
}
} | runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt | 1016881114 |
package nl.brouwerijdemolen.borefts2013.gui.screens
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.SparseArray
import androidx.annotation.ColorInt
import coil.Coil
import coil.api.get
import com.google.android.gms.maps.GoogleMapOptions
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.model.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import nl.brouwerijdemolen.borefts2013.R
import nl.brouwerijdemolen.borefts2013.api.Area
import nl.brouwerijdemolen.borefts2013.api.Brewer
import nl.brouwerijdemolen.borefts2013.api.Poi
import nl.brouwerijdemolen.borefts2013.gui.CoroutineScope
import nl.brouwerijdemolen.borefts2013.gui.components.ResourceProvider
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.io.IOException
import java.util.*
@SuppressLint("ViewConstructor") // Only to be created programmatically
class BoreftsMapView(
context: Context,
mapOptions: GoogleMapOptions) : MapView(context, mapOptions), KoinComponent {
private val res: ResourceProvider by inject()
private var poiMarkers: MutableMap<Marker, Poi> = mutableMapOf()
private var poiIds: MutableMap<String, Marker> = mutableMapOf()
private var brewerMarkers: MutableMap<Marker, Brewer> = mutableMapOf()
private var brewerIds: SparseArray<Marker> = SparseArray()
fun showBrewers(brewers: List<Brewer>, focusBrewerId: Int? = null) {
getMapAsync { map ->
GlobalScope.launch(CoroutineScope.ui) {
brewerMarkers = mutableMapOf()
brewerIds = SparseArray()
for (brewer in brewers) {
if (brewer.latitude != null && brewer.longitude != null) {
val brewerPin = withContext(CoroutineScope.io) {
drawBrewerMarker(brewer)
}
val bitmapToUse: BitmapDescriptor = if (brewerPin == null)
BitmapDescriptorFactory.fromResource(R.drawable.ic_marker_mask)
else
BitmapDescriptorFactory.fromBitmap(brewerPin)
val marker = map.addMarker(
MarkerOptions()
.position(LatLng(brewer.latitude, brewer.longitude))
.title(brewer.shortName)
.icon(bitmapToUse))
brewerMarkers[marker] = brewer
brewerIds.put(brewer.id, marker)
}
}
// Set focus on a specific marker
if (focusBrewerId != null) {
brewerIds.get(focusBrewerId)?.showInfoWindow()
}
}
// DEBUG
// map.setOnMapClickListener { Log.v("MAP", "Lat ${it.latitude} Long ${it.longitude}") }
}
}
fun showAreas(areas: List<Area>) {
getMapAsync { map ->
for (area in areas) {
map.addPolygon(
PolygonOptions()
.addAll(area.pointLatLngs)
.strokeColor(getColor(area.color))
.strokeWidth(5f)
.fillColor(getFillColor(area.color)))
}
}
}
fun showPois(pois: List<Poi>, focusPoiId: String? = null) {
getMapAsync { map ->
poiMarkers = HashMap()
poiIds = HashMap()
for (poi in pois) {
val marker = map.addMarker(
MarkerOptions()
.position(poi.pointLatLng)
.title(getPoiName(poi))
.icon(BitmapDescriptorFactory.fromResource(getDrawable(poi.marker))))
poiMarkers[marker] = poi
poiIds[poi.id] = marker
}
// Set focus on a specific marker
if (focusPoiId != null) {
poiIds.get<String?, Marker>(focusPoiId)?.showInfoWindow()
}
}
}
fun handleInfoWindowClicks(onBrewerClicked: (Brewer) -> Unit) {
getMapAsync { map ->
map.setOnInfoWindowClickListener { marker ->
brewerMarkers[marker]?.let(onBrewerClicked)
}
}
}
private suspend fun drawBrewerMarker(brewer: Brewer): Bitmap? {
try {
val mask = BitmapFactory.decodeResource(resources, R.drawable.ic_marker_mask)
val outline = BitmapFactory.decodeResource(resources, R.drawable.ic_marker_outline)
val logoDrawable = Coil.get(brewer.logoUrl) {
allowHardware(false)
}
val logo = (logoDrawable as? BitmapDrawable)?.bitmap
?: throw IllegalStateException("Coil decoder didn't provide a BitmapDrawable")
val bmp = Bitmap.createBitmap(mask.width, mask.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bmp)
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
canvas.drawBitmap(mask, 0f, 0f, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(logo, null, Rect(0, 0, mask.width, mask.height), paint)
paint.xfermode = null
canvas.drawBitmap(outline, 0f, 0f, paint)
return bmp
} catch (e: IOException) {
return null // Should never happen, as the brewer logo always exists
}
}
private fun getPoiName(poi: Poi): String {
return if (Locale.getDefault().language == "nl") {
poi.name_nl
} else poi.name_en
}
private fun getDrawable(resName: String): Int {
return resources.getIdentifier(resName, "drawable", context.packageName)
}
@ColorInt
private fun getColor(resName: String): Int {
return res.getColor(resources.getIdentifier(resName, "color", context.packageName))
}
@ColorInt
private fun getFillColor(resName: String): Int {
return getColor(resName + "_half")
}
}
| android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/BoreftsMapView.kt | 4153635432 |
package li.ruoshi.rekotlin.reducer
import li.ruoshi.rekotlin.action.IAction
import li.ruoshi.rekotlin.state.State
/**
* Created by ruoshili on 3/16/16.
*/
interface Reducer<T : State> {
fun handleAction(action: IAction, state: T?): T
} | rekotlin/src/main/kotlin/li/ruoshi/rekotlin/reducer/Reducer.kt | 3212651993 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.experimental
class TimeProviderKt {
@ExperimentalDateTimeKt
fun getTime(): Int {
return -1
}
@ExperimentalDateTime
fun getTimeJava(): Int {
return -1
}
internal companion object {
@JvmStatic
@ExperimentalDateTimeKt
fun getTimeStatically(): Int {
return -1
}
}
}
| annotation/annotation-experimental-lint/integration-tests/src/main/java/sample/experimental/TimeProviderKt.kt | 3730717936 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.inspection.inspector
import com.google.common.truth.Truth.assertThat
import org.junit.Test
private val topLambda1 = {}
private val topLambda2 = withArgument {}
private val topLambda3 = withArguments({}, {})
private fun withArgument(a: (Int) -> Unit = {}): (Int) -> Unit = a
private fun withArguments(a1: () -> Unit = {}, a2: () -> Unit = {}): List<() -> Unit> =
listOf(a1, a2)
/**
* Test the compiler generated lambda names.
*
* There is code in Studio that relies on this format.
* If this test should start to fail, please check the LambdaResolver in the Layout Inspector.
*/
@Suppress("JoinDeclarationAndAssignment")
class SynthesizedLambdaNameTest {
private val cls = SynthesizedLambdaNameTest::class.java.name
private val memberLambda1 = {}
private val memberLambda2 = withArgument {}
private val memberLambda3 = withArguments({}, {})
private val initLambda1: (Int) -> Unit
private val initLambda2: (Int) -> Unit
private val defaultLambda1 = withArgument()
private val defaultLambda2 = withArguments()
init {
initLambda1 = withArgument {}
initLambda2 = withArgument {}
}
@Test
fun testSynthesizedNames() {
assertThat(name(topLambda1)).isEqualTo("${cls}Kt\$topLambda1$1")
assertThat(name(topLambda2)).isEqualTo("${cls}Kt\$topLambda2$1")
assertThat(name(topLambda3[0])).isEqualTo("${cls}Kt\$topLambda3$1")
assertThat(name(topLambda3[1])).isEqualTo("${cls}Kt\$topLambda3$2")
assertThat(name(memberLambda1)).isEqualTo("$cls\$memberLambda1$1")
assertThat(name(memberLambda2)).isEqualTo("$cls\$memberLambda2$1")
assertThat(name(memberLambda3[0])).isEqualTo("$cls\$memberLambda3$1")
assertThat(name(memberLambda3[1])).isEqualTo("$cls\$memberLambda3$2")
assertThat(name(initLambda1)).isEqualTo("$cls$1")
assertThat(name(initLambda2)).isEqualTo("$cls$2")
assertThat(name(defaultLambda1)).isEqualTo("${cls}Kt\$withArgument$1")
assertThat(name(defaultLambda2[0])).isEqualTo("${cls}Kt\$withArguments$1")
assertThat(name(defaultLambda2[1])).isEqualTo("${cls}Kt\$withArguments$2")
}
private fun name(lambda: Any) = lambda.javaClass.name
} | compose/ui/ui-inspection/src/androidTest/java/androidx/compose/ui/inspection/inspector/SynthesizedLambdaNameTest.kt | 2950119043 |
package com.github.jacobswanson.budgety
import com.github.jacobswanson.budgety.authentication.LoginRequest
import com.github.jacobswanson.budgety.authentication.UserController
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class AuthenticationTest {
@Autowired
lateinit var userController: UserController
}
| budgety/src/test/kotlin/com/github/jacobswanson/budgety/AuthenticationTest.kt | 3269026390 |
package com.lv.service
import com.lv.model.Message
/**
* Date: 2017-03-23
* Time: 15:12
* Description:
*/
interface MessageService {
fun findAll(command:String?, description:String?,pageNo:Int=1):List<Message>
fun deleteOne( id: Any?):Int
fun deleteBatch(ids:List<Int>):Int
} | BootMybatis/src/main/kotlin/com/lv/service/MessageService.kt | 2250193034 |
package com.percolate.sdk.api.request.users
import com.percolate.sdk.api.BaseApiTest
import org.junit.Assert
import org.junit.Test
class UsersRequestTest : BaseApiTest() {
@Test
fun testGet() {
val users = percolateApi
.users()
.get(UsersParams())
.execute()
.body();
val data = users?.data
Assert.assertNotNull(data)
Assert.assertEquals(2, data!!.size.toLong())
}
}
| api/src/test/java/com/percolate/sdk/api/request/users/UsersRequestTest.kt | 2615850458 |
package com.baeldung.springreactivekotlin
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyInserters.fromObject
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import reactor.core.publisher.Mono
@Component
class HomeSensorsHandler {
var data = mapOf("lamp" to arrayOf(0.7, 0.65, 0.67), "fridge" to arrayOf(12.0, 11.9, 12.5))
fun setLight(request: ServerRequest): Mono<ServerResponse> = ServerResponse.ok().build()
fun getLightReading(request: ServerRequest): Mono<ServerResponse> =
ServerResponse.ok().body(fromObject(data["lamp"]!!))
fun getDeviceReadings(request: ServerRequest): Mono<ServerResponse> {
val id = request.pathVariable("id")
return ServerResponse.ok().body(fromObject(Device(id, 1.0)))
}
fun getAllDevices(request: ServerRequest): Mono<ServerResponse> =
ServerResponse.ok().body(fromObject(arrayOf("lamp", "tv")))
fun getAllDeviceApi(request: ServerRequest): Mono<ServerResponse> =
ServerResponse.ok().body(fromObject(arrayListOf("kettle", "fridge")))
fun setDeviceReadingApi(request: ServerRequest): Mono<ServerResponse> {
return request.bodyToMono(Device::class.java).flatMap { it ->
ServerResponse.ok().body(fromObject(Device(it.name.toUpperCase(), it.reading)))
}
}
} | projects/tutorials-master/tutorials-master/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt | 3885984923 |
package io.mockk
import kotlin.coroutines.experimental.Continuation
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
actual object InternalPlatformDsl {
actual fun identityHashCode(obj: Any): Int = Kotlin.identityHashCode(obj)
actual fun <T> runCoroutine(block: suspend () -> T): T =
throw UnsupportedOperationException(
"Coroutines are not supported for JS MockK version"
)
actual fun Any?.toStr(): String =
try {
when (this) {
null -> "null"
is BooleanArray -> this.contentToString()
is ByteArray -> this.contentToString()
is CharArray -> this.contentToString()
is ShortArray -> this.contentToString()
is IntArray -> this.contentToString()
is LongArray -> this.contentToString()
is FloatArray -> this.contentToString()
is DoubleArray -> this.contentToString()
is Array<*> -> this.contentDeepToString()
is KClass<*> -> this.simpleName ?: "<null name class>"
is Function<*> -> "lambda {}"
else -> toString()
}
} catch (thr: Throwable) {
"<error \"$thr\">"
}
actual fun deepEquals(obj1: Any?, obj2: Any?): Boolean {
return if (obj1 === obj2) {
true
} else if (obj1 == null || obj2 == null) {
obj1 === obj2
} else {
arrayDeepEquals(obj1, obj2)
}
}
private fun arrayDeepEquals(obj1: Any, obj2: Any): Boolean {
return when (obj1) {
is BooleanArray -> obj1 contentEquals obj2 as BooleanArray
is ByteArray -> obj1 contentEquals obj2 as ByteArray
is CharArray -> obj1 contentEquals obj2 as CharArray
is ShortArray -> obj1 contentEquals obj2 as ShortArray
is IntArray -> obj1 contentEquals obj2 as IntArray
is LongArray -> obj1 contentEquals obj2 as LongArray
is FloatArray -> obj1 contentEquals obj2 as FloatArray
is DoubleArray -> obj1 contentEquals obj2 as DoubleArray
is Array<*> -> return obj1 contentDeepEquals obj2 as Array<*>
else -> obj1 == obj2
}
}
actual fun unboxChar(value: Any): Any =
if (value is Char) {
value.toInt()
} else {
value
}
actual fun Any.toArray(): Array<*> =
when (this) {
is BooleanArray -> this.toTypedArray()
is ByteArray -> this.toTypedArray()
is CharArray -> this.toTypedArray()
is ShortArray -> this.toTypedArray()
is IntArray -> this.toTypedArray()
is LongArray -> this.toTypedArray()
is FloatArray -> this.toTypedArray()
is DoubleArray -> this.toTypedArray()
else -> this as Array<*>
}
actual fun classForName(name: String): Any = throw MockKException("classForName is not support on JS platform")
actual fun dynamicCall(
self: Any,
methodName: String,
args: Array<out Any?>,
anyContinuationGen: () -> Continuation<*>
): Any? = throw MockKException("dynamic call is not supported on JS platform")
actual fun dynamicGet(self: Any, name: String): Any? =
throw MockKException("dynamic get is not supported on JS platform")
actual fun dynamicSet(self: Any, name: String, value: Any?) {
throw MockKException("dynamic set is not supported on JS platform")
}
actual fun dynamicSetField(self: Any, name: String, value: Any?) {
throw MockKException("dynamic set is not supported on JS platform")
}
actual fun <T> threadLocal(initializer: () -> T): InternalRef<T> {
return object : InternalRef<T> {
override val value = initializer()
}
}
actual fun counter() = object : InternalCounter {
override var value = 0L
override fun increment() = value++
}
actual fun <T> coroutineCall(lambda: suspend () -> T): CoroutineCall<T> {
throw MockKException("coroutineCall is not supported")
}
}
internal external object Kotlin {
fun identityHashCode(obj: Any): Int
}
| dsl/js/src/main/kotlin/io/mockk/InternalPlatformDsl.kt | 1455358577 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.main
import android.support.annotation.CheckResult
import com.pyamsoft.powermanager.base.preference.ServicePreferences
import io.reactivex.Single
import javax.inject.Inject
import javax.inject.Singleton
@Singleton internal class MainInteractor @Inject constructor(
private val servicePreferences: ServicePreferences) {
/**
* public
*/
@CheckResult internal fun isStartWhenOpen(): Single<Boolean> {
return Single.fromCallable { servicePreferences.startWhenOpen }
}
}
| powermanager-main/src/main/java/com/pyamsoft/powermanager/main/MainInteractor.kt | 737842440 |
package at.ac.tuwien.caa.docscan.export
import android.content.Context
import android.net.Uri
import at.ac.tuwien.caa.docscan.db.model.error.IOErrorCode
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation
import at.ac.tuwien.caa.docscan.extensions.await
import at.ac.tuwien.caa.docscan.logic.Resource
import at.ac.tuwien.caa.docscan.logic.Success
import at.ac.tuwien.caa.docscan.logic.asFailure
import at.ac.tuwien.caa.docscan.logic.calculateImageResolution
import at.ac.tuwien.caa.docscan.ui.crop.ImageMeta
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.Text.TextBlock
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.TextRecognizer
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import com.itextpdf.text.*
import com.itextpdf.text.pdf.BaseFont
import com.itextpdf.text.pdf.ColumnText
import com.itextpdf.text.pdf.PdfWriter
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import java.io.File
object PdfCreator {
suspend fun analyzeFileWithOCR(
context: Context,
uri: Uri,
textRecognizer: TextRecognizer = TextRecognition.getClient(
TextRecognizerOptions.DEFAULT_OPTIONS
)
): Resource<Text> {
@Suppress("BlockingMethodInNonBlockingContext")
val image = InputImage.fromFilePath(context, uri)
val task = textRecognizer.process(image)
return task.await()
}
// suppressed, since this is expected and mitigated by making this function cooperative
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun savePDF(
context: Context,
outputUri: Uri,
files: List<FileWrapper>,
ocrResults: List<Text>? = null
): Resource<Unit> {
context.contentResolver.openOutputStream(outputUri, "rw").use { outputStream ->
return withContext(Dispatchers.IO) {
try {
val first = files[0]
var resolution = calculateImageResolution(first.file, first.rotation)
val landscapeFirst = isLandscape(resolution)
val firstPageSize = getPageSize(resolution, landscapeFirst)
val document = Document(firstPageSize, 0F, 0F, 0F, 0F)
val writer = PdfWriter.getInstance(document, outputStream)
document.open()
for (i in files.indices) {
// check if the coroutine is still active, if not, close the document and throw a CancellationException
if (!isActive) {
document.close()
throw CancellationException()
}
var file = files[i]
val rotationInDegrees = file.rotation.angle
//add the original image to the pdf and set the DPI of it to 600
val image = Image.getInstance(file.file.absolutePath)
image.setRotationDegrees(-rotationInDegrees.toFloat())
if (rotationInDegrees == 0 || rotationInDegrees == 180) image.scaleAbsolute(
document.pageSize.width,
document.pageSize.height
) else image.scaleAbsolute(
document.pageSize.height,
document.pageSize.width
)
image.setDpi(600, 600)
document.add(image)
if (ocrResults != null) {
// the direct content where we write on
// directContentUnder instead of directContent, because then the text is in the background)
//PdfContentByte cb = writer.getDirectContentUnder();
val cb = writer.directContentUnder
val bf = BaseFont.createFont()
//sort the result based on the y-Axis so that the markup order is correct
val sortedBlocks = sortBlocks(ocrResults[i])
resolution = calculateImageResolution(file.file, file.rotation)
//int j = 0;
for (column in sortedBlocks) {
for (line in sortLinesInColumn(column)) {
// one FirebaseVisionText.Line corresponds to one line
// the rectangle we want to draw this line corresponds to the lines boundingBox
val boundingBox = line.boundingBox ?: continue
val left =
boundingBox.left.toFloat() / resolution.width.toFloat() * document.pageSize.width
val right =
boundingBox.right.toFloat() / resolution.width.toFloat() * document.pageSize.width
val top =
boundingBox.top.toFloat() / resolution.height.toFloat() * document.pageSize.height
val bottom =
boundingBox.bottom.toFloat() / resolution.height.toFloat() * document.pageSize.height
val rect = Rectangle(
left,
document.pageSize.height - bottom,
right,
document.pageSize.height - top
)
val drawText = line.text
// try to get max font size that fit in rectangle
val textHeightInGlyphSpace =
bf.getAscent(drawText) - bf.getDescent(drawText)
var fontSize = 1000f * rect.height / textHeightInGlyphSpace
while (bf.getWidthPoint(drawText, fontSize) < rect.width) {
fontSize++
}
while (bf.getWidthPoint(drawText, fontSize) > rect.width) {
fontSize -= 0.1f
}
val phrase = Phrase(drawText, Font(bf, fontSize))
// write the text on the pdf
ColumnText.showTextAligned(
cb, Element.ALIGN_CENTER, phrase, // center horizontally
(rect.left + rect.right) / 2, // shift baseline based on descent
rect.bottom - bf.getDescentPoint(drawText, fontSize), 0f
)
}
}
}
if (i < files.size - 1) {
file = files[i + 1]
val pageSize = getPageSize(
calculateImageResolution(file.file, file.rotation),
landscapeFirst
)
document.pageSize = pageSize
document.newPage()
}
}
document.close()
return@withContext Success(Unit)
} catch (e: Exception) {
// if this has happened because of a cancellation, then this needs to be re-thrown
if (e is CancellationException) {
throw e
} else {
return@withContext IOErrorCode.EXPORT_CREATE_PDF_FAILED.asFailure(e)
}
}
}
}
}
private fun isLandscape(size: ImageMeta): Boolean {
return size.width > size.height
}
private fun getPageSize(size: ImageMeta, landscape: Boolean): Rectangle {
val pageSize: Rectangle = if (landscape) {
val height = PageSize.A4.height / size.width * size.height
Rectangle(PageSize.A4.height, height)
} else {
val height = PageSize.A4.width / size.width * size.height
Rectangle(PageSize.A4.width, height)
}
return pageSize
}
private fun sortBlocks(ocrResult: Text?): List<MutableList<TextBlock>> {
val sortedBlocks: MutableList<MutableList<TextBlock>> = ArrayList()
val biggestBlocks: MutableList<TextBlock> = ArrayList()
val blocksSortedByWidth = sortByWidth(ocrResult!!.textBlocks)
for (block in blocksSortedByWidth) {
if (block.boundingBox == null) continue
if (sortedBlocks.isEmpty()) {
val blocks: MutableList<TextBlock> = ArrayList()
blocks.add(block)
biggestBlocks.add(block)
sortedBlocks.add(blocks)
} else {
var added = false
for (checkBlock in biggestBlocks) {
if (checkBlock.boundingBox == null) continue
if (block.boundingBox!!.centerX() > checkBlock.boundingBox!!.left &&
block.boundingBox!!.centerX() < checkBlock.boundingBox!!.right
) {
sortedBlocks[biggestBlocks.indexOf(checkBlock)].add(block)
if (block.boundingBox!!.width() > checkBlock.boundingBox!!.width()) {
biggestBlocks[biggestBlocks.indexOf(checkBlock)] = block
}
added = true
break
}
}
if (!added) {
val blocks: MutableList<TextBlock> = ArrayList()
blocks.add(block)
var i = 0
while (i < biggestBlocks.size) {
if (biggestBlocks[i].boundingBox == null ||
block.boundingBox!!.centerX() > biggestBlocks[i].boundingBox!!.centerX()
) {
i++
} else {
break
}
}
biggestBlocks.add(i, block)
sortedBlocks.add(i, blocks)
}
}
}
for (textBlocks in sortedBlocks) {
sortedBlocks[sortedBlocks.indexOf(textBlocks)] = textBlocks
}
return sortedBlocks
}
private fun sortByWidth(result: List<TextBlock>): List<TextBlock> {
val sortedBlocks: MutableList<TextBlock> = ArrayList()
for (textBlock in result) {
if (textBlock.boundingBox == null) continue
if (sortedBlocks.isEmpty()) {
sortedBlocks.add(textBlock)
} else {
var i = 0
while (i < sortedBlocks.size) {
if (sortedBlocks[i].boundingBox == null ||
textBlock.boundingBox!!.width() < sortedBlocks[i].boundingBox!!.width()
) {
i++
} else {
break
}
}
sortedBlocks.add(i, textBlock)
}
}
return sortedBlocks
}
private fun sortLinesInColumn(result: List<TextBlock>): List<Text.Line> {
val sortedLines: MutableList<Text.Line> = ArrayList()
for (textBlock in result) {
for (line in textBlock.lines) // if (line.getCornerPoints() == null || line.getCornerPoints().length == 0)
// continue;
if (sortedLines.isEmpty()) {
sortedLines.add(line)
} else {
var i = 0
while (i < sortedLines.size) {
if (line.cornerPoints!![0].y > sortedLines[i].cornerPoints!![0].y) {
i++
} else {
break
}
}
sortedLines.add(i, line)
}
}
return sortedLines
}
data class FileWrapper(val file: File, val rotation: Rotation)
} | app/src/main/java/at/ac/tuwien/caa/docscan/export/PdfCreator.kt | 2782406739 |
Subsets and Splits