repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
afollestad/material-dialogs | core/src/main/java/com/afollestad/materialdialogs/internal/list/AdapterPayload.kt | 2 | 1104 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogs.internal.list
/**
* Used by the single and multi-choice list adapters to selectively bind list items. This
* payload indicates that the notified list item should check its toggleable view.
*/
internal object CheckPayload
/**
* Used by the single and multi-choice list adapters to selectively bind list items. This
* payload indicates that the notified list item should uncheck its toggleable view.
*/
internal object UncheckPayload
| apache-2.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/rendering/PieChart.kt | 1 | 6361 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.wildplot.android.rendering
import com.wildplot.android.rendering.graphics.wrapper.ColorWrap
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import com.wildplot.android.rendering.interfaces.Drawable
import com.wildplot.android.rendering.interfaces.Legendable
class PieChart(plotSheet: PlotSheet, values: DoubleArray, colors: Array<ColorWrap>) : Drawable, Legendable {
private val mPlotSheet: PlotSheet
private val mValues: DoubleArray
private val mColors: Array<ColorWrap>
override var name: String = ""
set(value) {
field = value
mNameIsSet = true
}
private var mNameIsSet = false
private val mPercent: DoubleArray
private var mSum = 0.0
private fun checkArguments(values: DoubleArray, colors: Array<ColorWrap>) {
require(values.size == colors.size) { "The number of colors must match the number of values" }
}
override fun isOnFrame(): Boolean {
return false
}
override fun paint(g: GraphicsWrap) {
// Do not show chart if segments are all zero
if (mSum == 0.0) {
return
}
val maxSideBorders = Math.max(
mPlotSheet.frameThickness[PlotSheet.LEFT_FRAME_THICKNESS_INDEX],
mPlotSheet.frameThickness[PlotSheet.RIGHT_FRAME_THICKNESS_INDEX]
)
val maxUpperBottomBorders = Math.max(
mPlotSheet.frameThickness[PlotSheet.UPPER_FRAME_THICKNESS_INDEX],
mPlotSheet.frameThickness[PlotSheet.BOTTOM_FRAME_THICKNESS_INDEX]
)
val realBorder = Math.max(maxSideBorders, maxUpperBottomBorders) + 3
val field = g.clipBounds
val diameter = Math.min(field.width, field.height) - 2 * realBorder
val xCenter = field.width / 2.0f
val yCenter = field.height / 2.0f
val oldColor = g.color
drawSectors(g, diameter, xCenter, yCenter)
drawSectorLabels(g, diameter, xCenter, yCenter)
g.color = oldColor
}
private fun drawSectors(g: GraphicsWrap, diameter: Float, xCenter: Float, yCenter: Float) {
val left = xCenter - diameter / 2f
val top = yCenter - diameter / 2f
var currentAngle = FIRST_SECTOR_OFFSET
for (i in 0 until mPercent.size - 1) {
g.color = mColors[i]
val arcLength = (360 * mValues[i] / mSum).toFloat()
g.fillArc(left, top, diameter, diameter, currentAngle, arcLength)
currentAngle += arcLength
}
// last one does need some corrections to fill a full circle:
g.color = lastSectorColor
g.fillArc(
left, top, diameter, diameter, currentAngle,
360f + FIRST_SECTOR_OFFSET - currentAngle
)
g.color = ColorWrap.black
g.drawArc(left, top, diameter, diameter, 0f, 360f)
}
private val lastSectorColor: ColorWrap
get() = mColors[mColors.size - 1]
private fun drawSectorLabels(g: GraphicsWrap, diameter: Float, xCenter: Float, yCenter: Float) {
val labelBackground = ColorWrap(0.0f, 0.0f, 0.0f, 0.5f)
for (j in mPercent.indices) {
if (mValues[j] == 0.0) {
continue
}
var oldPercent = 0.0
if (j != 0) {
oldPercent = mPercent[j - 1]
}
val text = "" + Math.round((mPercent[j] - oldPercent) * 100 * 100) / 100.0 + "%"
val x = (xCenter + Math.cos(-1 * ((oldPercent + (mPercent[j] - oldPercent) * 0.5) * 360 + FIRST_SECTOR_OFFSET) * Math.PI / 180.0) * 0.375 * diameter).toFloat() - 20
val y = (yCenter - Math.sin(-1 * ((oldPercent + (mPercent[j] - oldPercent) * 0.5) * 360 + FIRST_SECTOR_OFFSET) * Math.PI / 180.0) * 0.375 * diameter).toFloat()
val fm = g.fontMetrics
val width = fm.stringWidth(text)
val height = fm.height
g.color = labelBackground
g.fillRect(x - 1, y - height + 3, width + 2, height)
g.color = ColorWrap.white
g.drawString(text, x, y)
}
}
override fun isClusterable(): Boolean {
return true
}
override fun isCritical(): Boolean {
return false
}
override val color: ColorWrap
get() = if (mColors.size > 0) mColors[0] else ColorWrap.WHITE
override fun nameIsSet(): Boolean {
return mNameIsSet
}
companion object {
// First sector starts at 12 o'clock.
private const val FIRST_SECTOR_OFFSET = -90f
}
init {
checkArguments(values, colors)
mPlotSheet = plotSheet
mValues = values
mColors = colors
mPercent = DoubleArray(mValues.size)
for (v in mValues) {
mSum += v
}
val denominator: Double = if (mSum == 0.0) 1.0 else mSum
mPercent[0] = mValues[0] / denominator
for (i in 1 until mValues.size) {
mPercent[i] = mPercent[i - 1] + mValues[i] / denominator
}
}
}
| gpl-3.0 |
mixitconf/mixit | src/main/kotlin/mixit/security/model/AuthenticationService.kt | 1 | 6999 | package mixit.security.model
import mixit.MixitProperties
import mixit.security.MixitWebFilter.Companion.AUTHENT_COOKIE
import mixit.ticket.repository.LotteryRepository
import mixit.user.model.Role
import mixit.user.model.User
import mixit.user.model.UserService
import mixit.user.model.generateNewToken
import mixit.user.model.hasValidToken
import mixit.user.model.hasValidTokens
import mixit.user.model.jsonToken
import mixit.user.repository.UserRepository
import mixit.util.camelCase
import mixit.util.email.EmailService
import mixit.util.errors.CredentialValidatorException
import mixit.util.errors.DuplicateException
import mixit.util.errors.EmailSenderException
import mixit.util.errors.NotFoundException
import mixit.util.errors.TokenException
import mixit.util.toSlug
import mixit.util.validator.EmailValidator
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseCookie
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.util.Locale
@Service
class AuthenticationService(
private val userRepository: UserRepository,
private val userService: UserService,
private val lotteryRepository: LotteryRepository,
private val emailService: EmailService,
private val emailValidator: EmailValidator,
private val cryptographer: Cryptographer,
private val properties: MixitProperties
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
/**
* Create user from HTTP form or from a ticket
*/
fun createUser(nonEncryptedMail: String?, firstname: String?, lastname: String?): Pair<String, User> =
emailValidator.check(nonEncryptedMail).let { email ->
if (firstname == null || lastname == null) {
throw CredentialValidatorException()
}
Pair(
email,
User(
login = email.split("@")[0].toSlug(),
firstname = firstname.camelCase(),
lastname = lastname.camelCase(),
email = cryptographer.encrypt(email),
role = Role.USER
)
)
}
/**
* Create user if he does not exist
*/
fun createUserIfEmailDoesNotExist(nonEncryptedMail: String, user: User): Mono<User> =
userRepository.findOne(user.login)
.flatMap { Mono.error<User> { DuplicateException("Login already exist") } }
.switchIfEmpty(
Mono.defer {
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
// Email is unique and if an email is found we return an error
.flatMap { Mono.error<User> { DuplicateException("Email already exist") } }
.switchIfEmpty(Mono.defer { userRepository.save(user) })
}
)
/**
* This function try to find a user in the user table and if not try to read his information in
* ticketing table to create a new one.
*/
fun searchUserByEmailOrCreateHimFromTicket(nonEncryptedMail: String): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.switchIfEmpty(
Mono.defer {
lotteryRepository.findByEncryptedEmail(cryptographer.encrypt(nonEncryptedMail)!!)
.flatMap {
createUserIfEmailDoesNotExist(
nonEncryptedMail,
createUser(nonEncryptedMail, it.firstname, it.lastname).second
)
}
.switchIfEmpty(Mono.empty())
}
)
fun createCookie(user: User) = ResponseCookie
.from(AUTHENT_COOKIE, user.jsonToken(cryptographer))
.secure(properties.baseUri.startsWith("https"))
.httpOnly(true)
.maxAge(user.tokenLifeTime)
.build()
/**
* Function used on login to check if user email and token are valids
*/
fun checkUserEmailAndToken(nonEncryptedMail: String, token: String): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap {
if (it.hasValidToken(token.trim())) {
return@flatMap Mono.just(it)
}
return@flatMap Mono.error<User> { TokenException("Token is invalid or is expired") }
}
.switchIfEmpty(Mono.defer { throw NotFoundException() })
/**
* Function used on login to check if user email and token are valids
*/
fun checkUserEmailAndTokenOrAppToken(nonEncryptedMail: String, token: String?, appToken: String?): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap {
if (it.hasValidTokens(token, appToken)) {
return@flatMap Mono.just(it)
}
return@flatMap Mono.error<User> { TokenException("Token is invalid or is expired") }
}
.switchIfEmpty(Mono.defer { throw NotFoundException() })
/**
* Sends an email with a token to the user. We don't need validation of the email adress. If he receives
* the email it's OK. If he retries a login a new token is sent. Be careful email service can throw
* an EmailSenderException
*/
fun generateAndSendToken(
user: User,
locale: Locale,
nonEncryptedMail: String,
tokenForNewsletter: Boolean,
generateExternalToken: Boolean = false
): Mono<User> =
user.generateNewToken(generateExternalToken).let { newUser ->
try {
if (!properties.feature.email) {
logger.info("A token ${newUser.token} was sent by email")
}
emailService.send(if (tokenForNewsletter) "email-newsletter-subscribe" else "email-token", newUser, locale)
userRepository.save(newUser)
} catch (e: EmailSenderException) {
Mono.error<User> { e }
}
}
/**
* Sends an email with a token to the user. We don't need validation of the email adress.
*/
fun clearToken(nonEncryptedMail: String): Mono<User> =
userRepository
.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap { user -> user.generateNewToken().let { userRepository.save(it) } }
fun updateNewsletterSubscription(user: User, tokenForNewsletter: Boolean): Mono<User> =
if (tokenForNewsletter) {
userRepository.save(user.copy(newsletterSubscriber = true))
} else if (user.email == null) {
// Sometimes we can have a email hash in the DB but not the email (for legacy users). So in this case
// we store the email
userService.updateReference(user).flatMap { userRepository.save(it) }
} else {
Mono.just(user)
}
}
| apache-2.0 |
tipsy/javalin | javalin/src/test/kotlin/io/javalin/examples/HelloWorldCors.kt | 1 | 842 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.examples
import io.javalin.Javalin
import io.javalin.apibuilder.ApiBuilder.get
import io.javalin.apibuilder.ApiBuilder.patch
import io.javalin.apibuilder.ApiBuilder.post
fun main() {
val corsApp = Javalin.create { it.enableCorsForOrigin("http://localhost:7001/", "http://localhost:7002") }.start(7070)
corsApp.routes {
get { it.json("Hello Get") }
post { it.json("Hello Post") }
patch { it.json("Hello Patch") }
}
Javalin.create().start(7001).get("/") { it.html("Try some CORS") }
Javalin.create().start(7002).get("/") { it.html("Try some CORS") }
Javalin.create().start(7003).get("/") { it.html("No CORS here") }
}
| apache-2.0 |
EvidentSolutions/apina | apina-core/src/main/kotlin/fi/evident/apina/spring/SpringUriTemplateParser.kt | 1 | 1778 | package fi.evident.apina.spring
import fi.evident.apina.model.URITemplate
/**
* Converts URI-template in Spring format to plain URI-template, removing
* the specified regex constraints from variables.
*/
fun parseSpringUriTemplate(template: String): URITemplate {
val parser = SpringUriTemplateParser(template)
parser.parse()
return URITemplate(parser.result.toString())
}
private class SpringUriTemplateParser(private val template: String) {
private var pos = 0
val result = StringBuilder()
fun parse() {
while (hasMore()) {
readPlainText()
if (hasMore())
readVariable()
}
}
private fun readChar(): Char {
check(hasMore()) { "unexpected end of input" }
return template[pos++]
}
private fun readVariable() {
check(readChar() == '{') { "expected '{'" }
var braceLevel = 0
val start = pos
while (hasMore()) {
when (template[pos++]) {
'\\' -> readChar() // skip next
'{' -> braceLevel++
'}' -> if (braceLevel == 0) {
val variable = template.substring(start, pos - 1)
val colonIndex = variable.indexOf(':')
result.append('{').append(if (colonIndex == -1) variable else variable.substring(0, colonIndex)).append('}')
return
} else {
braceLevel--
}
}
}
error("unexpected end of input for template '$template'")
}
private fun readPlainText() {
while (hasMore() && template[pos] != '{')
result.append(template[pos++])
}
private fun hasMore() = pos < template.length
}
| mit |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/database/usecases/CopyDatabaseUseCaseTest.kt | 1 | 1021 | package com.infinum.dbinspector.domain.database.usecases
import com.infinum.dbinspector.domain.Repositories
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("CopyDatabaseUseCase tests")
internal class CopyDatabaseUseCaseTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Repositories.Database>() }
}
)
@Test
fun `Invoking use case clears history per database`() {
val repository: Repositories.Database = get()
val useCase = CopyDatabaseUseCase(repository)
coEvery { repository.copy(any()) } returns mockk()
test {
useCase.invoke(any())
}
coVerify(exactly = 1) { repository.copy(any()) }
}
}
| apache-2.0 |
nosix/vue-kotlin | single-file/greeting/main/greeting.kt | 1 | 484 | import org.musyozoku.vuekt.*
@JsModule("greeting-component.vue")
external val GreetingComponent: Component = definedExternally
@JsModule("vue")
@JsName("Vue")
external class AppVue(options: ComponentOptions<AppVue>) : Vue {
var message: String
}
val vm = AppVue(ComponentOptions {
el = ElementConfig("#app")
data = Data(json<AppVue> {
message = "Vue & Kotlin"
})
components = json {
this["greeting"] = ComponentConfig(GreetingComponent)
}
}) | apache-2.0 |
igorka48/CleanSocialAppTemplate | domain/src/main/java/com/social/com/domain/interactor/UseCase.kt | 1 | 2798 | /**
* Copyright (C) 2015 Fernando Cejas 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.social.com.domain.interactor
import com.social.com.domain.executor.PostExecutionThread
import com.social.com.domain.executor.ThreadExecutor
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
/**
* Abstract class for a Use Case (Interactor in terms of Clean Architecture).
* This interface represents a execution unit for different use cases (this means any use case
* in the application should implement this contract).
* By convention each UseCase implementation will return the result using a [DisposableObserver]
* that will execute its job in a background thread and will post the result in the UI thread.
*/
abstract class UseCase<T, Params> internal constructor(val threadExecutor: ThreadExecutor, val postExecutionThread: PostExecutionThread) {
private val disposables: CompositeDisposable
init {
this.disposables = CompositeDisposable()
}
/**
* Builds an [Observable] which will be used when executing the current [UseCase].
*/
internal abstract fun buildUseCaseObservable(params: Params?): Observable<T>
/**
* Executes the current use case.
* @param observer [DisposableObserver] which will be listening to the observable build
* * by [.buildUseCaseObservable] ()} method.
* *
* @param params Parameters (Optional) used to build/execute this use case.
*/
fun execute(observer: DisposableObserver<T>, params: Params?) {
val observable = this.buildUseCaseObservable(params)
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.scheduler)
addDisposable(observable.subscribeWith(observer))
}
/**
* Dispose from current [CompositeDisposable].
*/
fun dispose() {
if (!disposables.isDisposed) {
disposables.dispose()
}
}
/**
* Dispose from current [CompositeDisposable].
*/
private fun addDisposable(disposable: Disposable) {
disposables.add(disposable)
}
}
| apache-2.0 |
apoi/quickbeer-android | app/src/main/java/quickbeer/android/domain/beerlist/network/BeersInCountryFetcher.kt | 2 | 413 | package quickbeer.android.domain.beerlist.network
import quickbeer.android.data.fetcher.Fetcher
import quickbeer.android.domain.beer.Beer
import quickbeer.android.domain.beer.network.BeerJson
import quickbeer.android.network.RateBeerApi
class BeersInCountryFetcher(
api: RateBeerApi
) : Fetcher<String, List<Beer>, List<BeerJson>>(
BeerListJsonMapper(), { countryId -> api.beersInCountry(countryId) }
)
| gpl-3.0 |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/engine/ProcessData.kt | 1 | 5055 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import net.devrieze.util.Named
import nl.adaptivity.process.ProcessConsts
import nl.adaptivity.serialutil.decodeElements
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.serialization.ICompactFragmentSerializer
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlSerialName
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
/** Class to represent data attached to process instances. */
@Serializable(with = ProcessData.Companion::class)
@XmlSerialName(ProcessData.ELEMENTLOCALNAME, ProcessConsts.Engine.NAMESPACE, ProcessConsts.Engine.NSPREFIX)
class ProcessData
constructor(
override val name: String?,
val content: ICompactFragment
) : Named {
val contentStream: XmlReader get() = content.getXmlReader()
override fun copy(name: String?): ProcessData = copy(name, content)
fun copy(name: String?, value: ICompactFragment): ProcessData = ProcessData(name, value)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ProcessData
if (name != other.name) return false
if (content != other.content) return false
return true
}
override fun hashCode(): Int {
var result = name?.hashCode() ?: 0
result = 31 * result + content.hashCode()
return result
}
override fun toString(): String {
return "ProcessData($name=$content)"
}
@Serializable
@XmlSerialName(ELEMENTLOCALNAME, ProcessConsts.Engine.NAMESPACE, ProcessConsts.Engine.NSPREFIX)
private class SerialAnnotationHelper
companion object: KSerializer<ProcessData> {
const val ELEMENTLOCALNAME = "value"
val ELEMENTNAME = QName(ProcessConsts.Engine.NAMESPACE, ELEMENTLOCALNAME, ProcessConsts.Engine.NSPREFIX)
fun missingData(name: String): ProcessData {
return ProcessData(name, CompactFragment(""))
}
@OptIn(XmlUtilInternal::class, ExperimentalSerializationApi::class)
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ProcessData") {
annotations = SerialAnnotationHelper.serializer().descriptor.annotations
element<String>("name")
element<ICompactFragment>("content")
}
override fun deserialize(decoder: Decoder): ProcessData {
var name: String? = null
lateinit var content: ICompactFragment
decoder.decodeStructure(descriptor) {
decodeElements(this) { i ->
when (i) {
0 -> name = decodeSerializableElement(descriptor, 0, String.serializer().nullable)
1 -> content = when (this) {
is XML.XmlInput -> this.input.siblingsToFragment()
else -> decodeSerializableElement(descriptor, 1, ICompactFragmentSerializer)
}
}
}
}
return ProcessData(name, content)
}
@OptIn(ExperimentalSerializationApi::class)
override fun serialize(encoder: Encoder, value: ProcessData) {
val newOutput = encoder.beginStructure(descriptor)
newOutput.encodeNullableSerializableElement(descriptor, 0, String.serializer(), value.name)
if (newOutput is XML.XmlOutput) {
value.content.serialize(newOutput.target)
} else {
newOutput.encodeSerializableElement(descriptor, 1, ICompactFragmentSerializer, value.content)
}
newOutput.endStructure(descriptor)
}
}
}
| lgpl-3.0 |
magnusja/libaums | app/src/main/java/me/jahnen/libaums/core/usbfileman/MainActivity.kt | 2 | 37623 | /*
* (C) Copyright 2014-2016 mjahnen <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.core.usbfileman
import android.Manifest
import android.app.*
import android.content.*
import android.content.pm.PackageManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.net.Uri
import android.os.*
import android.provider.OpenableColumns
import android.util.Log
import android.view.ContextMenu
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import androidx.drawerlayout.widget.DrawerLayout
import me.jahnen.libaums.javafs.JavaFsFileSystemCreator
import me.jahnen.libaums.core.UsbMassStorageDevice
import me.jahnen.libaums.core.UsbMassStorageDevice.Companion.getMassStorageDevices
import me.jahnen.libaums.core.fs.FileSystem
import me.jahnen.libaums.core.fs.FileSystemFactory.registerFileSystem
import me.jahnen.libaums.core.fs.UsbFile
import me.jahnen.libaums.core.fs.UsbFileInputStream
import me.jahnen.libaums.core.fs.UsbFileStreamFactory.createBufferedOutputStream
import me.jahnen.libaums.server.http.UsbFileHttpServerService
import me.jahnen.libaums.server.http.UsbFileHttpServerService.ServiceBinder
import me.jahnen.libaums.server.http.server.AsyncHttpServer
import me.jahnen.libaums.core.usb.UsbCommunicationFactory
import me.jahnen.libaums.core.usb.UsbCommunicationFactory.registerCommunication
import me.jahnen.libaums.core.usb.UsbCommunicationFactory.underlyingUsbCommunication
import me.jahnen.libaums.libusbcommunication.LibusbCommunicationCreator
import java.io.*
import java.nio.ByteBuffer
import java.util.*
/**
* MainActivity of the demo application which shows the contents of the first
* partition.
*
* @author mjahnen
*/
class MainActivity : AppCompatActivity(), AdapterView.OnItemClickListener {
companion object {
/**
* Action string to request the permission to communicate with an UsbDevice.
*/
private const val ACTION_USB_PERMISSION = "me.jahnen.libaums.USB_PERMISSION"
private val TAG = MainActivity::class.java.simpleName
private const val COPY_STORAGE_PROVIDER_RESULT = 0
private const val OPEN_STORAGE_PROVIDER_RESULT = 1
private const val OPEN_DOCUMENT_TREE_RESULT = 2
private const val REQUEST_EXT_STORAGE_WRITE_PERM = 0
init {
registerFileSystem(JavaFsFileSystemCreator())
registerCommunication(LibusbCommunicationCreator())
underlyingUsbCommunication = UsbCommunicationFactory.UnderlyingUsbCommunication.OTHER
}
}
private val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (ACTION_USB_PERMISSION == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
setupDevice()
}
}
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
Log.d(TAG, "USB device attached")
// determine if connected device is a mass storage devuce
if (device != null) {
discoverDevice()
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
Log.d(TAG, "USB device detached")
// determine if connected device is a mass storage devuce
if (device != null) {
if (currentDevice != -1) {
massStorageDevices[currentDevice].close()
}
// check if there are other devices or set action bar title
// to no device if not
discoverDevice()
}
}
}
}
/**
* Dialog to create new directories.
*
* @author mjahnen
*/
class NewDirDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity as MainActivity
return AlertDialog.Builder(activity).apply {
setTitle("New Directory")
setMessage("Please enter a name for the new directory")
val input = EditText(activity)
setView(input)
setPositiveButton("Ok") { _, _ ->
val dir = activity.adapter.currentDir
try {
dir.createDirectory(input.text.toString())
activity.adapter.refresh()
} catch (e: Exception) {
Log.e(TAG, "error creating dir!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
}.create()
}
}
/**
* Dialog to create new files.
*
* @author mjahnen
*/
class NewFileDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity as MainActivity
return AlertDialog.Builder(activity).apply {
setTitle("New File")
setMessage("Please enter a name for the new file and some input")
val input = EditText(activity)
val content = EditText(activity)
setView(
LinearLayout(activity).apply {
orientation = LinearLayout.VERTICAL
addView(TextView(activity).apply { setText(R.string.name) })
addView(input)
addView(TextView(activity).apply { setText(R.string.content) })
addView(content)
}
)
setPositiveButton("Ok") { _, _ ->
val dir = activity.adapter.currentDir
try {
val file = dir.createFile(input.text.toString())
file.write(0, ByteBuffer.wrap(content.text.toString().toByteArray()))
file.close()
activity.adapter.refresh()
} catch (e: Exception) {
Log.e(TAG, "error creating file!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
}.create()
}
}
/**
* Class to hold the files for a copy task. Holds the source and the
* destination file.
*
* @author mjahnen
*/
private class CopyTaskParam {
/* package */
var from: UsbFile? = null
/* package */
var to: File? = null
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyTask : AsyncTask<CopyTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying file")
setMessage("Copying a file to the internal storage, this can take some time!")
isIndeterminate = false
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyTaskParam? = null
override fun onPreExecute() {
dialog.show()
}
protected override fun doInBackground(vararg params: CopyTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
try {
val out: OutputStream = BufferedOutputStream(FileOutputStream(param!!.to))
val inputStream: InputStream = UsbFileInputStream(param!!.from!!)
val bytes = ByteArray(currentFs.chunkSize)
var count: Int
var total: Long = 0
Log.d(TAG, "Copy file with length: " + param!!.from!!.length)
while (inputStream.read(bytes).also { count = it } != -1) {
out.write(bytes, 0, count)
total += count.toLong()
var progress = total.toInt()
if (param!!.from!!.length > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
out.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
val myIntent = Intent(Intent.ACTION_VIEW)
val file = File(param!!.to!!.absolutePath)
val extension = MimeTypeMap.getFileExtensionFromUrl(Uri
.fromFile(file).toString())
val mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
extension)
val uri: Uri
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
myIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
uri = FileProvider.getUriForFile(this@MainActivity,
[email protected] + ".provider",
file)
} else {
uri = Uri.fromFile(file)
}
myIntent.setDataAndType(uri, mimetype)
try {
startActivity(myIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@MainActivity, "Could no find an app for that file!",
Toast.LENGTH_LONG).show()
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
var max = param!!.from!!.length.toInt()
if (param!!.from!!.length > Int.MAX_VALUE) {
max = (param!!.from!!.length / 1024).toInt()
}
dialog.max = max
dialog.progress = values[0]!!
}
}
/**
* Class to hold the files for a copy task. Holds the source and the
* destination file.
*
* @author mjahnen
*/
private class CopyToUsbTaskParam {
/* package */
var from: Uri? = null
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyToUsbTask : AsyncTask<CopyToUsbTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying file")
setMessage("Copying a file to the USB drive, this can take some time!")
isIndeterminate = true
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyToUsbTaskParam? = null
private var name: String? = null
private var size: Long = -1
private fun queryUriMetaData(uri: Uri?) {
contentResolver
.query(uri!!, null, null, null, null, null)
?.apply {
if (moveToFirst()) {
// TODO: query created and modified times to write it USB
name = getString(
getColumnIndex(OpenableColumns.DISPLAY_NAME))
Log.i(TAG, "Display Name: $name")
val sizeIndex = getColumnIndex(OpenableColumns.SIZE)
if (!isNull(sizeIndex)) {
size = getLong(sizeIndex)
}
Log.i(TAG, "Size: $size")
}
}
?.close()
}
override fun onPreExecute() = dialog.show()
protected override fun doInBackground(vararg params: CopyToUsbTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
queryUriMetaData(param!!.from)
if (name == null) {
val segments = param!!.from!!.path!!.split("/".toRegex()).toTypedArray()
name = segments[segments.size - 1]
}
try {
val file = adapter.currentDir.createFile(name!!)
if (size > 0) {
file.length = size
}
val inputStream = contentResolver.openInputStream(param!!.from!!)
val outputStream: OutputStream = createBufferedOutputStream(file, currentFs)
val bytes = ByteArray(1337)
var count: Int
var total: Long = 0
while (inputStream!!.read(bytes).also { count = it } != -1) {
outputStream.write(bytes, 0, count)
if (size > 0) {
total += count.toLong()
var progress = total.toInt()
if (size > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
try {
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "Error refreshing adapter", e)
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
dialog.isIndeterminate = false
var max = size.toInt()
if (size > Int.MAX_VALUE) {
max = (size / 1024).toInt()
}
dialog.max = max
dialog.progress = values[0]!!
}
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyFolderToUsbTask : AsyncTask<CopyToUsbTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying a folder")
setMessage("Copying a folder to the USB drive, this can take some time!")
isIndeterminate = true
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyToUsbTaskParam? = null
private var size: Long = -1
private var pickedDir: DocumentFile? = null
override fun onPreExecute() {
dialog.show()
}
@Throws(IOException::class)
private fun copyDir(dir: DocumentFile?, currentUsbDir: UsbFile) {
for (file in dir!!.listFiles()) {
Log.d(TAG, "Found file " + file.name + " with size " + file.length())
if (file.isDirectory) {
copyDir(file, currentUsbDir.createDirectory(file.name!!))
} else {
copyFile(file, currentUsbDir)
}
}
}
private fun copyFile(file: DocumentFile, currentUsbDir: UsbFile) {
try {
val usbFile = currentUsbDir.createFile(file.name!!)
size = file.length()
usbFile.length = file.length()
val inputStream = contentResolver.openInputStream(file.uri)
val outputStream: OutputStream = createBufferedOutputStream(usbFile, currentFs!!)
val bytes = ByteArray(1337)
var count: Int
var total: Long = 0
while (inputStream!!.read(bytes).also { count = it } != -1) {
outputStream.write(bytes, 0, count)
if (size > 0) {
total += count.toLong()
var progress = total.toInt()
if (file.length() > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
}
protected override fun doInBackground(vararg params: CopyToUsbTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
pickedDir = DocumentFile.fromTreeUri(this@MainActivity, param!!.from!!)
try {
copyDir(pickedDir, adapter.currentDir.createDirectory(pickedDir!!.name!!))
} catch (e: IOException) {
Log.e(TAG, "could not copy directory", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
try {
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "Error refreshing adapter", e)
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
dialog.apply {
isIndeterminate = false
max = size.toInt()
if (size > Int.MAX_VALUE) {
max = (size / 1024).toInt()
}
progress = values[0]!!
}
}
}
private var serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "on service connected $name")
val binder = service as ServiceBinder
serverService = binder.service
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "on service disconnected $name")
serverService = null
}
}
lateinit var listView: ListView
lateinit var drawerListView: ListView
lateinit var drawerLayout: DrawerLayout
lateinit var drawerToggle: ActionBarDrawerToggle
/* package */
lateinit var adapter: UsbFileListAdapter
private val dirs: Deque<UsbFile> = ArrayDeque()
lateinit var currentFs: FileSystem
lateinit var serviceIntent: Intent
var serverService: UsbFileHttpServerService? = null
lateinit var massStorageDevices: Array<UsbMassStorageDevice>
private var currentDevice = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
serviceIntent = Intent(this, UsbFileHttpServerService::class.java)
setContentView(R.layout.activity_main)
listView = findViewById<View>(R.id.listview) as ListView
drawerListView = findViewById<View>(R.id.left_drawer) as ListView
drawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout
drawerToggle = object : ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
override fun onDrawerClosed(view: View) {
super.onDrawerClosed(view)
supportActionBar!!.setTitle(massStorageDevices[currentDevice].partitions[0].volumeLabel)
}
/** Called when a drawer has settled in a completely open state. */
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
supportActionBar!!.setTitle("Devices")
}
}
// Set the drawer toggle as the DrawerListener
drawerLayout.addDrawerListener(drawerToggle)
drawerListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
selectDevice(position)
drawerLayout.closeDrawer(drawerListView)
drawerListView.setItemChecked(position, true)
}
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
listView.onItemClickListener = this
registerForContextMenu(listView)
val filter = IntentFilter(ACTION_USB_PERMISSION)
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
registerReceiver(usbReceiver, filter)
discoverDevice()
}
override fun onStart() {
super.onStart()
startService(serviceIntent)
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
unbindService(serviceConnection)
}
private fun selectDevice(position: Int) {
currentDevice = position
setupDevice()
}
/**
* Searches for connected mass storage devices, and initializes them if it
* could find some.
*/
private fun discoverDevice() {
val usbManager = getSystemService(USB_SERVICE) as UsbManager
massStorageDevices = getMassStorageDevices(this)
if (massStorageDevices.isEmpty()) {
Log.w(TAG, "no device found!")
val actionBar = supportActionBar
actionBar!!.title = "No device"
listView.adapter = null
return
}
drawerListView.adapter = DrawerListAdapter(this, R.layout.drawer_list_item, massStorageDevices)
drawerListView.setItemChecked(0, true)
currentDevice = 0
val usbDevice = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
Log.d(TAG, "received usb device via intent")
// requesting permission is not needed in this case
setupDevice()
} else {
// first request permission from user to communicate with the underlying UsbDevice
val permissionIntent = PendingIntent.getBroadcast(this, 0, Intent(
ACTION_USB_PERMISSION), 0)
usbManager.requestPermission(massStorageDevices[currentDevice].usbDevice, permissionIntent)
}
}
/**
* Sets the device up and shows the contents of the root directory.
*/
private fun setupDevice() {
try {
massStorageDevices[currentDevice].init()
// we always use the first partition of the device
currentFs = massStorageDevices[currentDevice].partitions[0].fileSystem.also {
Log.d(TAG, "Capacity: " + it.capacity)
Log.d(TAG, "Occupied Space: " + it.occupiedSpace)
Log.d(TAG, "Free Space: " + it.freeSpace)
Log.d(TAG, "Chunk size: " + it.chunkSize)
}
val root = currentFs.rootDirectory
val actionBar = supportActionBar
actionBar!!.title = currentFs.volumeLabel
listView.adapter = UsbFileListAdapter(this, root).apply { adapter = this }
} catch (e: IOException) {
Log.e(TAG, "error setting up device", e)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val cl = MoveClipboard
menu.findItem(R.id.paste).isEnabled = cl?.file != null
menu.findItem(R.id.stop_http_server).isEnabled = serverService != null && serverService!!.isServerRunning
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (drawerToggle.onOptionsItemSelected(item)) {
true
} else when (item.itemId) {
R.id.create_file -> {
NewFileDialog().show(fragmentManager, "NEW_FILE")
true
}
R.id.create_dir -> {
NewDirDialog().show(fragmentManager, "NEW_DIR")
true
}
R.id.create_big_file -> {
createBigFile()
true
}
R.id.paste -> {
move()
true
}
R.id.stop_http_server -> {
if (serverService != null) {
serverService!!.stopServer()
}
true
}
R.id.open_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (currentDevice != -1) {
Log.d(TAG, "Closing device first")
massStorageDevices[currentDevice].close()
}
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
val extraMimeTypes = arrayOf("image/*", "video/*")
intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeTypes)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(intent, OPEN_STORAGE_PROVIDER_RESULT)
}
true
}
R.id.copy_from_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(intent, COPY_STORAGE_PROVIDER_RESULT)
}
true
}
R.id.copy_folder_from_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT_TREE
startActivityForResult(intent, OPEN_DOCUMENT_TREE_RESULT)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo) {
super.onCreateContextMenu(menu, v, menuInfo)
val inflater = menuInflater
inflater.inflate(R.menu.context, menu)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as AdapterView.AdapterContextMenuInfo
val entry = adapter.getItem(info.id.toInt())
return when (item.itemId) {
R.id.delete_item -> {
try {
entry!!.delete()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error deleting!", e)
}
true
}
R.id.rename_item -> {
AlertDialog.Builder(this).apply {
setTitle("Rename")
setMessage("Please enter a name for renaming")
val input = EditText(this@MainActivity)
input.setText(entry!!.name)
setView(input)
setPositiveButton("Ok") { _, _ ->
try {
entry.name = input.text.toString()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error renaming!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
create()
show()
}
true
}
R.id.move_item -> {
val cl = MoveClipboard
cl.file = entry
true
}
R.id.start_http_server -> {
startHttpServer(entry)
true
}
else -> super.onContextItemSelected(item)
}
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, rowId: Long) {
val entry = adapter.getItem(position)
try {
if (entry.isDirectory) {
dirs.push(adapter.currentDir)
listView.adapter = UsbFileListAdapter(this, entry).also { adapter = it }
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, R.string.request_write_storage_perm, Toast.LENGTH_LONG).show()
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_EXT_STORAGE_WRITE_PERM)
}
return
}
val param = CopyTaskParam()
param.from = entry
val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
File(getExternalFilesDir(null)!!.absolutePath + "/usbfileman/cache")
} else {
File(Environment.getExternalStorageDirectory().absolutePath + "/usbfileman/cache")
}
f.mkdirs()
val index = if (entry.name.lastIndexOf(".") > 0) entry.name.lastIndexOf(".") else entry.name.length
var prefix = entry.name.substring(0, index)
val ext = entry.name.substring(index)
// prefix must be at least 3 characters
if (prefix.length < 3) {
prefix += "pad"
}
param.to = File.createTempFile(prefix, ext, f)
CopyTask().execute(param)
}
} catch (e: IOException) {
Log.e(TAG, "error starting to copy!", e)
}
}
private fun startHttpServer(file: UsbFile?) {
Log.d(TAG, "starting HTTP server")
if (serverService == null) {
Toast.makeText(this@MainActivity, "serverService == null!", Toast.LENGTH_LONG).show()
return
}
if (serverService!!.isServerRunning) {
Log.d(TAG, "Stopping existing server service")
serverService!!.stopServer()
}
// now start the server
try {
serverService!!.startServer(file!!, AsyncHttpServer(8000))
Toast.makeText(this@MainActivity, "HTTP server up and running", Toast.LENGTH_LONG).show()
} catch (e: IOException) {
Log.e(TAG, "Error starting HTTP server", e)
Toast.makeText(this@MainActivity, "Could not start HTTP server", Toast.LENGTH_LONG).show()
}
if (file!!.isDirectory) {
// only open activity when serving a file
return
}
val myIntent = Intent(Intent.ACTION_VIEW)
myIntent.data = Uri.parse(serverService!!.server!!.baseUrl + file.name)
try {
startActivity(myIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@MainActivity, "Could no find an app for that file!",
Toast.LENGTH_LONG).show()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_EXT_STORAGE_WRITE_PERM -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.permission_granted, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_LONG).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == RESULT_OK) {
Log.w(TAG, "Activity result is not ok")
return
}
if (intent == null) {
return
}
Log.i(TAG, "Uri: " + intent.data.toString())
val newIntent = Intent(Intent.ACTION_VIEW).apply { data = intent.data }
val params = CopyToUsbTaskParam().apply { from = intent.data }
when (requestCode) {
OPEN_STORAGE_PROVIDER_RESULT -> startActivity(newIntent)
COPY_STORAGE_PROVIDER_RESULT -> CopyToUsbTask().execute(params)
OPEN_DOCUMENT_TREE_RESULT -> CopyFolderToUsbTask().execute(params)
}
}
/**
* This methods creates a very big file for testing purposes. It writes only
* a small chunk of bytes in every loop iteration, so the offset where the
* write starts will not always be a multiple of the cluster or block size
* of the file system or block device. As a plus the file has to be grown
* after every loop iteration which tests for example on FAT32 the dynamic
* growth of a cluster chain.
*/
private fun createBigFile() {
val dir = adapter.currentDir
val file: UsbFile
try {
file = dir.createFile("big_file_test.txt")
val outputStream: OutputStream = createBufferedOutputStream(file, currentFs)
outputStream.write("START\n".toByteArray())
var i: Int
i = 6
while (i < 9000) {
outputStream.write("TEST\n".toByteArray())
i += 5
}
outputStream.write("END\n".toByteArray())
outputStream.close()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error creating big file!", e)
}
}
/**
* This method moves the file located in the [MoveClipboard] into the
* current shown directory.
*/
private fun move() {
val cl = MoveClipboard
val file = cl.file
try {
file?.moveTo(adapter.currentDir)
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error moving!", e)
}
cl.file = null
}
override fun onBackPressed() {
try {
val dir = dirs.pop()
listView.adapter = UsbFileListAdapter(this, dir).also { adapter = it }
} catch (e: NoSuchElementException) {
super.onBackPressed()
} catch (e: IOException) {
Log.e(TAG, "error initializing adapter!", e)
}
}
public override fun onDestroy() {
super.onDestroy()
unregisterReceiver(usbReceiver)
if (!serverService!!.isServerRunning) {
Log.d(TAG, "Stopping service")
stopService(serviceIntent)
if (currentDevice != -1) {
Log.d(TAG, "Closing device")
massStorageDevices[currentDevice].close()
}
}
}
} | apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/OverpassQLUtils.kt | 2 | 280 | package de.westnordost.streetcomplete.data.elementfilter
private val QUOTES_NOT_REQUIRED = Regex("[a-zA-Z_][a-zA-Z0-9_]*|-?[0-9]+")
fun String.quoteIfNecessary() =
if (QUOTES_NOT_REQUIRED.matches(this)) this else quote()
fun String.quote() = "'${this.replace("'", "\'")}'"
| gpl-3.0 |
dleppik/EgTest | kotlin-generator/src/main/kotlin/com/vocalabs/egtest/codegenerator/CodeUtil.kt | 1 | 263 | package com.vocalabs.egtest.codegenerator
fun annotationToString(annotationName: String, annotationBody: String?): String {
if (annotationBody == null) {
return "@$annotationName"
}else {
return "@$annotationName($annotationBody)"
}
} | apache-2.0 |
andrei-heidelbacher/algoventure-core | src/main/kotlin/com/aheidelbacher/algoventure/core/ui/UiHandler.kt | 1 | 761 | /*
* Copyright 2016 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aheidelbacher.algoventure.core.ui
interface UiHandler {
fun onGameOver(): Unit
fun onGameWon(): Unit
}
| apache-2.0 |
HendraAnggrian/breadknife | demo/src/com/hendraanggrian/preferencer/demo/test/Target2.kt | 1 | 172 | package com.hendraanggrian.preferencer.demo.test
import com.hendraanggrian.preferencer.Preference
class Target2 : Target1() {
@Preference lateinit var test2: String
} | mit |
deianvn/misc | vfu/course_3/android/CurrencyConverter/app/src/main/java/bg/vfu/rizov/currencyconverter/repo/CurrencyApi.kt | 1 | 211 | package bg.vfu.rizov.currencyconverter.repo
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.GET
interface CurrencyApi {
@GET("eur.json")
fun getCurrencies(): Call<ResponseBody>
}
| apache-2.0 |
davidwhitman/changelogs | app/src/main/java/com/thunderclouddev/changelogs/ui/StateRenderer.kt | 1 | 545 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui
/**
* Created by David Whitman on 07 May, 2017.
*/
interface StateRenderer<in S> {
/**
* Accepts a POKO representing the current state of the view in order to render it on to the screen of the user.
* @param state state to render
*/
fun render(state: S)
} | gpl-3.0 |
markspit93/Github-Feed-Sample | app/src/main/kotlin/com/github/feed/sample/ui/common/BaseFragment.kt | 1 | 342 | package com.github.feed.sample.ui.common
import android.content.Context
import android.support.v4.app.Fragment
import dagger.android.support.AndroidSupportInjection
abstract class BaseFragment : Fragment() {
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
} | apache-2.0 |
mercadopago/px-android | px-services/src/main/java/com/mercadopago/android/px/internal/core/LanguageInterceptor.kt | 1 | 767 | package com.mercadopago.android.px.internal.core
import android.content.Context
import com.mercadopago.android.px.internal.util.LocaleUtil
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
class LanguageInterceptor(context: Context) : Interceptor {
private val language by lazy { LocaleUtil.getLanguage(context.applicationContext) }
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val request = originalRequest.newBuilder()
.header(LANGUAGE_HEADER, language)
.build()
return chain.proceed(request)
}
companion object {
private const val LANGUAGE_HEADER = "Accept-Language"
}
} | mit |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/work/jobs/JobHandlerWorker.kt | 1 | 1983 | /*
* Copyright (C) 2019 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.work.jobs
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject
import kotlinx.coroutines.suspendCancellableCoroutine
import net.simonvt.cathode.sync.jobqueue.JobHandler
import net.simonvt.cathode.sync.jobqueue.JobHandler.JobHandlerListener
import net.simonvt.cathode.work.ChildWorkerFactory
class JobHandlerWorker @AssistedInject constructor(
@Assisted val context: Context,
@Assisted params: WorkerParameters,
private val jobHandler: JobHandler
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
if (jobHandler.hasJobs()) {
suspendCancellableCoroutine<Unit> { cont ->
val listener = object : JobHandlerListener {
override fun onQueueEmpty() {
cont.cancel()
}
override fun onQueueFailed() {
cont.cancel()
}
}
cont.invokeOnCancellation { jobHandler.unregisterListener(listener) }
jobHandler.registerListener(listener)
}
}
return Result.success()
}
@AssistedInject.Factory
interface Factory : ChildWorkerFactory
companion object {
const val TAG = "JobHandlerWorker"
const val TAG_DAILY = "JobHandlerWorker_daily"
}
}
| apache-2.0 |
McGars/percents | common/src/main/java/com/gars/percents/common/DimenExtension.kt | 1 | 161 | package com.gars.percents.common
import android.content.res.Resources
val Int.dp: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt() | apache-2.0 |
jamieadkins95/Roach | domain/src/main/java/com/jamieadkins/gwent/domain/update/model/Update.kt | 1 | 162 | package com.jamieadkins.gwent.domain.update.model
sealed class Update {
object UpToDate : Update()
class Available(val patchName: String) : Update()
} | apache-2.0 |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyFunctionBlock.kt | 1 | 1352 | package io.gitlab.arturbosch.detekt.rules.empty
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.isOpen
import io.gitlab.arturbosch.detekt.rules.isOverridden
import org.jetbrains.kotlin.psi.KtNamedFunction
/**
* Reports empty functions. Empty blocks of code serve no purpose and should be removed.
* This rule will not report functions overriding others.
*
* @configuration ignoreOverriddenFunctions - excludes overridden functions with an empty body (default: false)
*
* @active since v1.0.0
* @author Artur Bosch
* @author Marvin Ramin
* @author schalkms
*/
class EmptyFunctionBlock(config: Config) : EmptyRule(config) {
private val ignoreOverriddenFunctions = valueOrDefault(IGNORE_OVERRIDDEN_FUNCTIONS, false)
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.isOpen()) {
return
}
val bodyExpression = function.bodyExpression
if (!ignoreOverriddenFunctions) {
if (function.isOverridden()) {
bodyExpression?.addFindingIfBlockExprIsEmptyAndNotCommented()
} else {
bodyExpression?.addFindingIfBlockExprIsEmpty()
}
} else if (!function.isOverridden()) {
bodyExpression?.addFindingIfBlockExprIsEmpty()
}
}
companion object {
const val IGNORE_OVERRIDDEN_FUNCTIONS = "ignoreOverriddenFunctions"
}
}
| apache-2.0 |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/service/ExternalImportDatabaseService.kt | 3 | 1200 | package org.worshipsongs.service
import android.content.Intent
import android.net.Uri
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import org.worshipsongs.service.ImportDatabaseService
/**
* Author : Madasamy
* Version : 3.x
*/
class ExternalImportDatabaseService : ImportDatabaseService
{
private var objects: Map<String, Any>? = null
private var appCompatActivity: AppCompatActivity? = null
override fun loadDb(appCompatActivity: AppCompatActivity, objects: Map<String, Any>)
{
this.appCompatActivity = appCompatActivity
this.objects = objects
showFileChooser()
}
private fun showFileChooser()
{
val intent = Intent(Intent.ACTION_GET_CONTENT)
val uri = Uri.parse(Environment.getExternalStorageDirectory().path)
intent.setDataAndType(uri, "*/*")
try
{
appCompatActivity!!.startActivityForResult(Intent.createChooser(intent, "Select a File to Import"), 1)
} catch (ex: android.content.ActivityNotFoundException)
{
}
}
override val name: String get() = this.javaClass.simpleName
override val order: Int get() = 1
}
| gpl-3.0 |
AlbRoehm/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/extensions/Context-Extensions.kt | 1 | 272 | package com.habitrpg.android.habitica.extensions
import android.app.Service
import android.content.Context
import android.view.LayoutInflater
val Context.layoutInflater: LayoutInflater
get() = this.getSystemService(Service.LAYOUT_INFLATER_SERVICE) as LayoutInflater
| gpl-3.0 |
FHannes/intellij-community | platform/lang-impl/src/com/intellij/openapi/module/impl/moduleFileListener.kt | 1 | 4713 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module.impl
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.impl.ModuleRootManagerImpl
import com.intellij.openapi.roots.impl.storage.ClasspathStorage
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.util.PathUtilRt
import gnu.trove.THashSet
/**
* Why this class is required if we have StorageVirtualFileTracker?
* Because StorageVirtualFileTracker doesn't detect (intentionally) parent file changes -
*
* If module file is foo/bar/hello.iml and directory foo is renamed to oof then we must update module path.
* And StorageVirtualFileTracker doesn't help us here (and is not going to help by intention).
*/
internal class ModuleFileListener(private val moduleManager: ModuleManagerComponent) : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> propertyChanged(event)
is VFileMoveEvent -> fileMoved(event)
}
}
}
private fun propertyChanged(event: VFilePropertyChangeEvent) {
if (!event.file.isDirectory || event.requestor is StateStorage || event.propertyName != VirtualFile.PROP_NAME) {
return
}
val parentPath = event.file.parent?.path ?: return
var someModulePathIsChanged = false
val newAncestorPath = "${parentPath}/${event.newValue}"
for (module in moduleManager.modules) {
if (!module.isLoaded || module.isDisposed) {
continue
}
val ancestorPath = "$parentPath/${event.oldValue}"
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "$newAncestorPath/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
someModulePathIsChanged = true
}
// if ancestor path is a direct parent of module file - root will be serialized as $MODULE_DIR$ and, so, we don't need to mark it as changed to save
if (PathUtilRt.getParentPath(moduleFilePath) != ancestorPath) {
checkRootModification(module, newAncestorPath)
}
}
if (someModulePathIsChanged) {
moduleManager.incModificationCount()
}
}
private fun fileMoved(event: VFileMoveEvent) {
if (!event.file.isDirectory) {
return
}
val dirName = event.file.nameSequence
val ancestorPath = "${event.oldParent.path}/$dirName"
val newAncestorPath = "${event.newParent.path}/$dirName"
for (module in moduleManager.modules) {
if (!module.isLoaded || module.isDisposed) {
continue
}
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "${event.newParent.path}/$dirName/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
}
checkRootModification(module, newAncestorPath)
}
}
// https://youtrack.jetbrains.com/issue/IDEA-168933
private fun checkRootModification(module: Module, newAncestorPath: String) {
val moduleRootManager = module.rootManager as? ModuleRootManagerImpl ?: return
val roots = THashSet<String>()
moduleRootManager.contentRootUrls.forEach { roots.add(VfsUtilCore.urlToPath(it)) }
moduleRootManager.sourceRootUrls.forEach { roots.add(VfsUtilCore.urlToPath(it)) }
if (roots.contains(newAncestorPath)) {
moduleRootManager.stateChanged()
}
}
private fun setModuleFilePath(module: Module, newFilePath: String) {
ClasspathStorage.modulePathChanged(module, newFilePath)
module.stateStore.setPath(newFilePath)
}
} | apache-2.0 |
DSolyom/ViolinDS | ViolinDS/app/src/main/java/ds/violin/v1/app/violin/GoogleApiViolin.kt | 1 | 2225 | /*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.app.violin
import android.content.Context
import android.os.Bundle
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.Api
import com.google.android.gms.common.api.GoogleApiClient
/**
* Basic interface to use [GoogleApiClient] in Violins
*/
interface GoogleApiViolin {
/** = ArrayList(), required Apis */
val requiredApis: MutableList<Api<*>>
/** = null, #Private */
var googleApiClient: GoogleApiClient?
fun onCreate(savedInstanceState: Bundle?) {
if (!requiredApis.isEmpty() && googleApiClient == null) {
val builder = GoogleApiClient.Builder((this as PlayingViolin).violinActivity as Context)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnected(connectionHint: Bundle?) {
onGoogleApiConnected(connectionHint)
}
})
.addOnConnectionFailedListener { result -> onGoogleApiConnectionFailed(result) }
for(api in requiredApis) {
builder.addApi(api as Api<Api.ApiOptions.NotRequiredOptions>)
}
googleApiClient = builder.build()
}
}
fun onStart() {
googleApiClient?.connect()
}
fun onStop() {
googleApiClient?.disconnect()
}
fun onGoogleApiConnected(connectionHint: Bundle?)
fun onGoogleApiConnectionFailed(result: ConnectionResult)
} | apache-2.0 |
TeamAmaze/AmazeFileManager | app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt | 1 | 3053 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.compressed.extractcontents
import android.content.Context
import android.os.Environment
import androidx.test.core.app.ApplicationProvider
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil
import com.amaze.filemanager.fileoperations.utils.UpdatePosition
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.io.File
import java.util.concurrent.CountDownLatch
abstract class AbstractCompressedFileExtractorTest : AbstractExtractorTest() {
@Throws(Exception::class)
override fun doTestExtractFiles() {
val latch = CountDownLatch(1)
val extractor = extractorClass()
.getConstructor(
Context::class.java,
String::class.java,
String::class.java,
Extractor.OnUpdate::class.java,
UpdatePosition::class.java
)
.newInstance(
ApplicationProvider.getApplicationContext(),
archiveFile.absolutePath,
Environment.getExternalStorageDirectory().absolutePath,
object : Extractor.OnUpdate {
override fun onStart(totalBytes: Long, firstEntryName: String) = Unit
override fun onUpdate(entryPath: String) = Unit
override fun isCancelled(): Boolean = false
override fun onFinish() {
latch.countDown()
}
},
ServiceWatcherUtil.UPDATE_POSITION
)
extractor.extractEverything()
latch.await()
verifyExtractedArchiveContents()
}
private fun verifyExtractedArchiveContents() {
Environment.getExternalStorageDirectory().run {
File(this, "test.txt").let {
assertTrue(it.exists())
assertEquals("abcdefghijklmnopqrstuvwxyz1234567890", it.readText().trim())
}
}
}
override val archiveFile: File
get() = File(Environment.getExternalStorageDirectory(), "test.txt.$archiveType")
}
| gpl-3.0 |
googlearchive/android-constraint-layout-performance | app/src/main/java/com/example/android/perf/MainActivity.kt | 1 | 6406 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.android.perf
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.FrameMetrics
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import android.widget.TextView
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
private val frameMetricsHandler = Handler()
private val frameMetricsAvailableListener = Window.OnFrameMetricsAvailableListener {
_, frameMetrics, _ ->
val frameMetricsCopy = FrameMetrics(frameMetrics)
// Layout measure duration in Nano seconds
val layoutMeasureDurationNs = frameMetricsCopy.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION)
Log.d(TAG, "layoutMeasureDurationNs: " + layoutMeasureDurationNs)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_for_test)
val traditionalCalcButton = findViewById<Button>(R.id.button_start_calc_traditional)
val constraintCalcButton = findViewById<Button>(R.id.button_start_calc_constraint)
val textViewFinish = findViewById<TextView>(R.id.textview_finish)
traditionalCalcButton.setOnClickListener {
@SuppressLint("InflateParams")
constraintCalcButton.visibility = View.INVISIBLE
val container = layoutInflater
.inflate(R.layout.activity_traditional, null) as ViewGroup
val asyncTask = MeasureLayoutAsyncTask(
getString(R.string.executing_nth_iteration),
WeakReference(traditionalCalcButton),
WeakReference(textViewFinish),
WeakReference(container))
asyncTask.execute()
}
constraintCalcButton.setOnClickListener {
@SuppressLint("InflateParams")
traditionalCalcButton.visibility = View.INVISIBLE
val container = layoutInflater
.inflate(R.layout.activity_constraintlayout, null) as ViewGroup
val asyncTask = MeasureLayoutAsyncTask(
getString(R.string.executing_nth_iteration),
WeakReference(constraintCalcButton),
WeakReference(textViewFinish),
WeakReference(container))
asyncTask.execute()
}
}
override fun onResume() {
super.onResume()
window.addOnFrameMetricsAvailableListener(frameMetricsAvailableListener, frameMetricsHandler)
}
override fun onPause() {
super.onPause()
window.removeOnFrameMetricsAvailableListener(frameMetricsAvailableListener)
}
/**
* AsyncTask that triggers measure/layout in the background. Not to leak the Context of the
* Views, take the View instances as WeakReferences.
*/
private class MeasureLayoutAsyncTask(val executingNthIteration: String,
val startButtonRef: WeakReference<Button>,
val finishTextViewRef: WeakReference<TextView>,
val containerRef: WeakReference<ViewGroup>) : AsyncTask<Void?, Int, Void?>() {
override fun doInBackground(vararg voids: Void?): Void? {
for (i in 0 until TOTAL) {
publishProgress(i)
try {
Thread.sleep(100)
} catch (ignore: InterruptedException) {
// No op
}
}
return null
}
override fun onProgressUpdate(vararg values: Int?) {
val startButton = startButtonRef.get() ?: return
startButton.text = String.format(executingNthIteration, values[0], TOTAL)
val container = containerRef.get() ?: return
// Not to use the view cache in the View class, use the different measureSpecs
// for each calculation. (Switching the
// View.MeasureSpec.EXACT and View.MeasureSpec.AT_MOST alternately)
measureAndLayoutExactLength(container)
measureAndLayoutWrapLength(container)
}
override fun onPostExecute(aVoid: Void?) {
val finishTextView = finishTextViewRef.get() ?: return
finishTextView.visibility = View.VISIBLE
val startButton = startButtonRef.get() ?: return
startButton.visibility = View.GONE
}
private fun measureAndLayoutWrapLength(container: ViewGroup) {
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(WIDTH,
View.MeasureSpec.AT_MOST)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(HEIGHT,
View.MeasureSpec.AT_MOST)
container.measure(widthMeasureSpec, heightMeasureSpec)
container.layout(0, 0, container.measuredWidth,
container.measuredHeight)
}
private fun measureAndLayoutExactLength(container: ViewGroup) {
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(WIDTH,
View.MeasureSpec.EXACTLY)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(HEIGHT,
View.MeasureSpec.EXACTLY)
container.measure(widthMeasureSpec, heightMeasureSpec)
container.layout(0, 0, container.measuredWidth,
container.measuredHeight)
}
}
companion object {
private val TAG = "MainActivity"
private val TOTAL = 100
private val WIDTH = 1920
private val HEIGHT = 1080
}
}
| apache-2.0 |
tasks/tasks | app/src/main/java/org/tasks/data/ContentProviderDao.kt | 1 | 1499 | package org.tasks.data
import android.database.Cursor
import androidx.room.Dao
import androidx.room.Query
import androidx.room.RawQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.todoroo.astrid.data.Task
@Dao
interface ContentProviderDao {
@Query("SELECT name FROM tags WHERE task = :taskId ORDER BY UPPER(name) ASC")
suspend fun getTagNames(taskId: Long): List<String>
@Query("""
SELECT *
FROM tasks
WHERE completed = 0
AND deleted = 0
AND hideUntil < (strftime('%s', 'now') * 1000)
ORDER BY (CASE
WHEN (dueDate = 0) THEN
(strftime('%s', 'now') * 1000) * 2
ELSE ((CASE WHEN (dueDate / 1000) % 60 > 0 THEN dueDate ELSE (dueDate + 43140000) END)) END) +
172800000 * importance
ASC
LIMIT 100""")
suspend fun getAstrid2TaskProviderTasks(): List<Task>
@Query("SELECT * FROM tagdata WHERE name IS NOT NULL AND name != '' ORDER BY UPPER(name) ASC")
suspend fun tagDataOrderedByName(): List<TagData>
@Query("SELECT * FROM tasks")
fun getTasks(): Cursor
@Query("""
SELECT caldav_lists.*, caldav_accounts.cda_name
FROM caldav_lists
INNER JOIN caldav_accounts ON cdl_account = cda_uuid""")
fun getLists(): Cursor
@Query("SELECT * FROM google_task_lists")
fun getGoogleTaskLists(): Cursor
@RawQuery
fun rawQuery(query: SupportSQLiteQuery): Cursor
} | gpl-3.0 |
dafi/photoshelf | tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/photo/PhotoGridAdapter.kt | 1 | 1738 | package com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ternaryop.photoshelf.adapter.OnPhotoBrowseClickMultiChoice
import com.ternaryop.photoshelf.tumblr.ui.core.R
class PhotoGridAdapter(
context: Context,
private val colorCellByScheduleTimeType: Boolean
) : PhotoAdapter<PhotoGridViewHolder>(context) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoGridViewHolder {
return PhotoGridViewHolder(LayoutInflater.from(context).inflate(R.layout.grid_photo_item, parent, false))
}
override fun onBindViewHolder(holder: PhotoGridViewHolder, position: Int) {
val item = getItem(position)
holder.bindModel(item, selection.isSelected(position), colorCellByScheduleTimeType)
if (onPhotoBrowseClick == null) {
return
}
holder.setOnClickTags(this)
holder.setOnClickMenu(this)
holder.setOnClickThumbnail(this, this)
}
override fun onClick(v: View) {
val onPhotoBrowseClick = onPhotoBrowseClick ?: return
when (v.id) {
R.id.menu -> onPhotoBrowseClick.onOverflowClick(v.tag as Int, v)
R.id.thumbnail_image -> if (isActionModeOn) {
(onPhotoBrowseClick as OnPhotoBrowseClickMultiChoice).onItemClick(v.tag as Int)
} else {
onPhotoBrowseClick.onThumbnailImageClick(v.tag as Int)
}
R.id.tag_text_view -> {
val position = (v.parent as ViewGroup).tag as Int
onPhotoBrowseClick.onTagClick(position, v.tag as String)
}
}
}
}
| mit |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt | 2 | 7788 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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
* OWNER 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 io.spine.internal.gradle.javascript
import java.io.File
import org.apache.tools.ant.taskdefs.condition.Os
/**
* Describes the environment in which JavaScript code is assembled and processed during the build.
*
* Consists of three parts describing:
*
* 1. A module itself.
* 2. Tools and their input/output files.
* 3. Code generation.
*/
interface JsEnvironment {
/*
* A module itself
******************/
/**
* Module's root catalog.
*/
val projectDir: File
/**
* Module's version.
*/
val moduleVersion: String
/**
* Module's production sources directory.
*
* Default value: "$projectDir/main".
*/
val srcDir: File
get() = projectDir.resolve("main")
/**
* Module's test sources directory.
*
* Default value: "$projectDir/test".
*/
val testSrcDir: File
get() = projectDir.resolve("test")
/**
* A directory which all artifacts are generated into.
*
* Default value: "$projectDir/build".
*/
val buildDir: File
get() = projectDir.resolve("build")
/**
* A directory where artifacts for further publishing would be prepared.
*
* Default value: "$buildDir/npm-publication".
*/
val publicationDir: File
get() = buildDir.resolve("npm-publication")
/*
* Tools and their input/output files
*************************************/
/**
* Name of an executable for running `npm`.
*
* Default value:
*
* 1. "nmp.cmd" for Windows.
* 2. "npm" for other OSs.
*/
val npmExecutable: String
get() = if (isWindows()) "npm.cmd" else "npm"
/**
* An access token that allows installation and/or publishing modules.
*
* During installation a token is required only if dependencies from private
* repositories are used.
*
* Default value is read from the environmental variable - `NPM_TOKEN`.
* "PUBLISHING_FORBIDDEN" stub value would be assigned in case `NPM_TOKEN` variable is not set.
*
* See [Creating and viewing access tokens | npm Docs](https://docs.npmjs.com/creating-and-viewing-access-tokens).
*/
val npmAuthToken: String
get() = System.getenv("NPM_TOKEN") ?: "PUBLISHING_FORBIDDEN"
/**
* A directory where `npm` puts downloaded module's dependencies.
*
* Default value: "$projectDir/node_modules".
*/
val nodeModules: File
get() = projectDir.resolve("node_modules")
/**
* Module's descriptor used by `npm`.
*
* Default value: "$projectDir/package.json".
*/
val packageJson: File
get() = projectDir.resolve("package.json")
/**
* `npm` gets its configuration settings from the command line, environment variables,
* and `npmrc` file.
*
* Default value: "$projectDir/.npmrc".
*
* See [npmrc | npm Docs](https://docs.npmjs.com/cli/v8/configuring-npm/npmrc).
*/
val npmrc: File
get() = projectDir.resolve(".npmrc")
/**
* A cache directory in which `nyc` tool outputs raw coverage report.
*
* Default value: "$projectDir/.nyc_output".
*
* See [istanbuljs/nyc](https://github.com/istanbuljs/nyc).
*/
val nycOutput: File
get() = projectDir.resolve(".nyc_output")
/**
* A directory in which `webpack` would put a ready-to-use bundle.
*
* Default value: "$projectDir/dist"
*
* See [webpack - npm](https://www.npmjs.com/package/webpack).
*/
val webpackOutput: File
get() = projectDir.resolve("dist")
/**
* A directory where bundled artifacts for further publishing would be prepared.
*
* Default value: "$publicationDir/dist".
*/
val webpackPublicationDir: File
get() = publicationDir.resolve("dist")
/*
* Code generation
******************/
/**
* Name of a directory that contains generated code.
*
* Default value: "proto".
*/
val genProtoDirName: String
get() = "proto"
/**
* Directory with production Protobuf messages compiled into JavaScript.
*
* Default value: "$srcDir/$genProtoDirName".
*/
val genProtoMain: File
get() = srcDir.resolve(genProtoDirName)
/**
* Directory with test Protobuf messages compiled into JavaScript.
*
* Default value: "$testSrcDir/$genProtoDirName".
*/
val genProtoTest: File
get() = testSrcDir.resolve(genProtoDirName)
}
/**
* Allows overriding [JsEnvironment]'s defaults.
*
* All of declared properties can be split into two groups:
*
* 1. The ones that *define* something - can be overridden.
* 2. The ones that *describe* something - can NOT be overridden.
*
* Overriding a "defining" property affects the way `npm` tool works.
* In contrary, overriding a "describing" property does not affect the tool.
* Such properties just describe how the used tool works.
*
* Therefore, overriding of "describing" properties leads to inconsistency with expectations.
*
* The next properties could not be overridden:
*
* 1. [JsEnvironment.nodeModules].
* 2. [JsEnvironment.packageJson].
* 3. [JsEnvironment.npmrc].
* 4. [JsEnvironment.nycOutput].
*/
class ConfigurableJsEnvironment(initialEnvironment: JsEnvironment)
: JsEnvironment by initialEnvironment
{
/*
* A module itself
******************/
override var projectDir = initialEnvironment.projectDir
override var moduleVersion = initialEnvironment.moduleVersion
override var srcDir = initialEnvironment.srcDir
override var testSrcDir = initialEnvironment.testSrcDir
override var buildDir = initialEnvironment.buildDir
override var publicationDir = initialEnvironment.publicationDir
/*
* Tools and their input/output files
*************************************/
override var npmExecutable = initialEnvironment.npmExecutable
override var npmAuthToken = initialEnvironment.npmAuthToken
override var webpackOutput = initialEnvironment.webpackOutput
override var webpackPublicationDir = initialEnvironment.webpackPublicationDir
/*
* Code generation
******************/
override var genProtoDirName = initialEnvironment.genProtoDirName
override var genProtoMain = initialEnvironment.genProtoMain
override var genProtoTest = initialEnvironment.genProtoTest
}
internal fun isWindows(): Boolean = Os.isFamily(Os.FAMILY_WINDOWS)
| apache-2.0 |
free5ty1e/primestationone-control-android | app/src/androidTest/java/com/chrisprime/primestationonecontrol/bases/BaseAlternateMocksTest.kt | 1 | 1531 | package com.chrisprime.primestationonecontrol.bases
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.RecordedRequest
/**
* Use this test as your base class if you'd like to modify any of the default mocks for your test cases
* Created by cpaian on 10/3/16.
*/
abstract class BaseAlternateMocksTest @JvmOverloads protected constructor(clearUserDataBeforeLaunch: Boolean = false) : BaseUiTest(clearUserDataBeforeLaunch) {
override fun prepareBeforeActivityLaunchedLastThing() { //This occurs far before the @Before annotation and is required if one wants to modify any mock and not just those after the Minimum Version Service call
/*
val MockWebDispatcher: MockWebDispatcher = object: MockWebDispatcher() {
override fun dispatch(recordedRequest: RecordedRequest): MockResponse {
val mockResponse = super.dispatch(recordedRequest)
modifyResponse(mockResponse, recordedRequest)
return mockResponse
}
}
mMockWebServer!!.setDispatcher(MockWebDispatcher)
*/
}
/**
* Override this function and modify the mockresponse based on the recordedrequest with your own logic
* Allow the default value to pass through to ensure all the basic mocks are still in place.
*/
abstract fun modifyResponse(mockResponse: MockResponse, recordedRequest: RecordedRequest)
override fun cleanUpAfterActivityFinishedLastThing() {
// mMockWebServer!!.setDispatcher(MockWebDispatcher())
}
}
| mit |
robertwb/incubator-beam | learning/katas/kotlin/Common Transforms/Aggregation/Sum/test/org/apache/beam/learning/katas/commontransforms/aggregation/sum/TaskTest.kt | 9 | 1473 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.commontransforms.aggregation.sum
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.transforms.Create
import org.junit.Rule
import org.junit.Test
class TaskTest {
@get:Rule
@Transient
val testPipeline: TestPipeline = TestPipeline.create()
@Test
fun common_transforms_aggregation_sum() {
val values = Create.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val numbers = testPipeline.apply(values)
val results = Task.applyTransform(numbers)
PAssert.that(results).containsInAnyOrder(55)
testPipeline.run().waitUntilFinish()
}
} | apache-2.0 |
SpectraLogic/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/client/command/Ds3GetObjectPayloadCommandGenerator.kt | 2 | 1496 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.client.command
import com.spectralogic.ds3autogen.go.models.client.ReadCloserBuildLine
import com.spectralogic.ds3autogen.go.models.client.RequestBuildLine
import java.util.*
/**
* Generates commands with request payloads built from a list of Ds3PutObjects.
* Used to generate PutBulkJobSpectraS3 command.
*/
class Ds3GetObjectPayloadCommandGenerator : BaseCommandGenerator() {
/**
* Retrieves the request builder line for adding the request payload
* built from a list of Ds3GetObjects.
*/
override fun toReaderBuildLine(): Optional<RequestBuildLine> {
return Optional.of(ReadCloserBuildLine("buildDs3GetObjectListStream(request.Objects)"))
}
}
| apache-2.0 |
robertwb/incubator-beam | learning/katas/kotlin/Common Transforms/WithKeys/WithKeys/src/org/apache/beam/learning/katas/commontransforms/withkeys/Task.kt | 9 | 1862 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.commontransforms.withkeys
import org.apache.beam.learning.katas.util.Log
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.WithKeys
import org.apache.beam.sdk.values.KV
import org.apache.beam.sdk.values.PCollection
import org.apache.beam.sdk.values.TypeDescriptors
object Task {
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).create()
val pipeline = Pipeline.create(options)
val words = pipeline.apply(
Create.of("apple", "banana", "cherry", "durian", "guava", "melon")
)
val output = applyTransform(words)
output.apply(Log.ofElements())
pipeline.run()
}
@JvmStatic
fun applyTransform(input: PCollection<String>): PCollection<KV<String, String>> {
return input.apply(WithKeys
.of { fruit: String -> fruit.substring(0, 1) }
.withKeyType(TypeDescriptors.strings())
)
}
} | apache-2.0 |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/database/Label.kt | 1 | 1094 | /*
* Copyright 2016-2021 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.database
import androidx.annotation.NonNull
import androidx.room.ColumnInfo
import androidx.room.Entity
@Entity(primaryKeys = ["title", "archived"])
class Label(
@ColumnInfo(defaultValue = "")
@NonNull
var title: String,
@ColumnInfo(defaultValue = "0")
@NonNull
var colorId: Int) {
@ColumnInfo(defaultValue = "0")
@NonNull
var order: Int= 0
@ColumnInfo(defaultValue = "0")
@NonNull
var archived: Boolean = false
} | apache-2.0 |
Plastix/Kotlin-Android-Boilerplate | app/src/main/kotlin/io/github/plastix/kotlinboilerplate/extensions/ActivityExtensions.kt | 1 | 334 | package io.github.plastix.kotlinboilerplate.extensions
import android.support.v7.app.AppCompatActivity
/**
* Remember to set the android:parentActivityName attribute on the activity you are calling this
* from!
*/
fun AppCompatActivity.enableToolbarBackButton() {
delegate.supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
| mit |
voghDev/HelloKotlin | app/src/main/java/es/voghdev/hellokotlin/global/BaseActivity.kt | 1 | 958 | /*
* Copyright (C) 2017 Olmo Gallegos Hernández.
*
* 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 es.voghdev.hellokotlin.global
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutId())
}
abstract fun getLayoutId(): Int
}
| apache-2.0 |
chibatching/Kotpref | sample/src/main/kotlin/com/chibatching/kotprefsample/injectablecontext/InjectableContextSampleActivity.kt | 1 | 1042 | package com.chibatching.kotprefsample.injectablecontext
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.chibatching.kotprefsample.databinding.ActivityInjectableContextSampleBinding
class InjectableContextSampleActivity : AppCompatActivity() {
private val injectableContextData by lazy {
InjectableContextSample(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityInjectableContextSampleBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.saveButton.setOnClickListener {
injectableContextData.sampleData = binding.editText.text.toString()
binding.textView.text = injectableContextData.sampleData
}
}
override fun onSupportNavigateUp(): Boolean {
if (super.onSupportNavigateUp()) {
return true
}
finish()
return true
}
}
| apache-2.0 |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/inmemory/InMemoryNotificationChannelConfig.kt | 1 | 314 | package net.nemerosa.ontrack.extension.notifications.inmemory
import net.nemerosa.ontrack.model.annotations.APIDescription
import net.nemerosa.ontrack.model.annotations.APILabel
data class InMemoryNotificationChannelConfig(
@APILabel("Group")
@APIDescription("Group of messages")
val group: String,
) | mit |
BjoernPetersen/JMusicBot | src/main/kotlin/net/bjoernpetersen/musicbot/api/auth/Tokens.kt | 1 | 244 | package net.bjoernpetersen.musicbot.api.auth
/**
* A pair of tokens.
*
* @param accessToken a JWT access token
* @param refreshToken a refresh token, or null
*/
data class Tokens(val accessToken: String, val refreshToken: String? = null)
| mit |
nemerosa/ontrack | ontrack-service/src/test/java/net/nemerosa/ontrack/service/ValidationRunIT.kt | 1 | 16048 | package net.nemerosa.ontrack.service
import net.nemerosa.ontrack.extension.api.support.TestNumberValidationDataType
import net.nemerosa.ontrack.extension.api.support.TestValidationData
import net.nemerosa.ontrack.extension.api.support.TestValidationDataType
import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataInputException
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataStatusRequiredBecauseNoDataException
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataTypeNotFoundException
import net.nemerosa.ontrack.model.security.ValidationRunStatusChange
import net.nemerosa.ontrack.model.structure.*
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class ValidationRunIT : AbstractDSLTestJUnit4Support() {
@Autowired
private lateinit var testValidationDataType: TestValidationDataType
@Autowired
private lateinit var testNumberValidationDataType: TestNumberValidationDataType
@Test
fun validationRunWithData() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
// Build
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunData = TestValidationData(2, 4, 8)
)
// Loads the validation run
val loadedRun = asUserWithView(branch).call { structureService.getValidationRun(run.id) }
// Checks the data is still there
@Suppress("UNCHECKED_CAST")
val data: ValidationRunData<TestValidationData> = loadedRun.data as ValidationRunData<TestValidationData>
assertNotNull(data, "Data type is loaded")
assertEquals(TestValidationDataType::class.java.name, data.descriptor.id)
assertEquals(2, data.data.critical)
assertEquals(4, data.data.high)
assertEquals(8, data.data.medium)
// Checks the status
val status = loadedRun.lastStatus
assertNotNull(status)
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, status.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndForcedStatus() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
// Build
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_FAILED,
validationRunData = TestValidationData(0, 0, 8)
)
// Checks the status
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, run.lastStatus.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndStatusUpdate() {
project {
branch {
val vs = validationStamp("VS", testValidationDataType.config(null))
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunStatusID = ValidationRunStatusID.STATUS_FAILED,
validationRunData = TestValidationData(0, 0, 10)
)
// Checks the initial status
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, run.lastStatus.statusID.id)
// Updates the status
asUser().with(branch, ValidationRunStatusChange::class.java).execute {
structureService.newValidationRunStatus(
run,
ValidationRunStatus(
ID.NONE,
Signature.of("test"),
ValidationRunStatusID.STATUS_DEFECTIVE,
"This is a defect"
)
)
}
// Reloads
val newRun = asUser().withView(branch).call {
structureService.getValidationRun(run.id)
}
// Checks the new status
assertEquals(ValidationRunStatusID.STATUS_DEFECTIVE.id, newRun.lastStatus.statusID.id)
}
}
}
}
@Test
fun validationRunWithoutData() {
project {
branch {
// Creates a validation stamp with no required data
val vs = validationStamp("VS")
// Creates a validation run without data
build("1.0.0") {
val run = validate(vs)
// Loads the validation run
val loadedRun = asUserWithView(branch).call { structureService.getValidationRun(run.id) }
// Checks the data
val data = loadedRun.data
assertNull(data, "No data is loaded")
// Checks the status
val status = loadedRun.lastStatus
assertNotNull(status)
assertEquals(ValidationRunStatusID.STATUS_PASSED.id, status.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndNoDataTypeOnValidationStamp() {
project {
branch {
// Validation data without data
val vs = validationStamp("VS")
// Build
build("1.0.0") {
val run = validateWithData(
vs,
ValidationRunStatusID.STATUS_PASSED,
testValidationDataType.descriptor.id,
TestValidationData(0, 10, 100)
)
assertEquals(
ValidationRunStatusID.PASSED,
run.lastStatus.statusID.id
)
}
}
}
}
@Test(expected = ValidationRunDataInputException::class)
fun validationRunWithInvalidData() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
build("1.0.0") {
validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunData = TestValidationData(-1, 0, 0)
)
}
}
}
}
@Test
fun validationRunWithUnrequestedData() {
project {
branch {
// Creates a "normal" validation stamp
val vs = validationStamp("VS")
// Build
build("1.0.0") {
// Creates a validation run with data
validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 80
)
}
}
}
}
@Test
fun validationRunWithMissingDataOKWithStatus() {
project {
branch {
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
build("1.0.0") {
val run = validateWithData<Any>(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED
)
assertEquals(
ValidationRunStatusID.STATUS_PASSED.id,
run.lastStatus.statusID.id
)
}
}
}
}
@Test(expected = ValidationRunDataStatusRequiredBecauseNoDataException::class)
fun validationRunWithMissingDataNotOKWithoutStatus() {
project {
branch {
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
build("1.0.0") {
validateWithData<Any>(vs)
}
}
}
}
@Test
fun `Introducing a data type on existing validation runs`() {
// Creates a basic stamp, with no data type
val vs = doCreateValidationStamp()
// Creates a build
val build = doCreateBuild(vs.branch, NameDescription.nd("1", ""))
// ... and validates it
val runId = doValidateBuild(build, vs, ValidationRunStatusID.STATUS_PASSED).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(
testNumberValidationDataType.config(50)
)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still no data
assertNull(run.data, "No data associated with validation run after migration")
}
@Test
fun `Removing a data type from existing validation runs`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp(
"VS",
testNumberValidationDataType.config(50)
)
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId: ID = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(null)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Changing a data type for existing validation runs`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(
testValidationDataType.config(null)
)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Validation data still present when validation stamp has no longer a validation data type`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp to null
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(null)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Validation run data with unknown type`() {
project {
branch {
val vs = validationStamp("VS")
// Build
build("1.0.0") {
// Creates a validation run with data, and an unknown data type
assertFailsWith<ValidationRunDataTypeNotFoundException> {
validateWithData(
validationStamp = vs,
validationDataTypeId = "unknown",
validationRunData = TestValidationData(2, 4, 8)
)
}
}
}
}
}
} | mit |
dykstrom/jcc | src/test/kotlin/se/dykstrom/jcc/basic/code/statement/AddAssignCodeGeneratorTests.kt | 1 | 2039 | package se.dykstrom.jcc.basic.code.statement
import org.junit.Test
import se.dykstrom.jcc.basic.code.AbstractBasicCodeGeneratorComponentTests
import se.dykstrom.jcc.basic.compiler.BasicTypeManager
import se.dykstrom.jcc.common.assembly.base.Instruction
import se.dykstrom.jcc.common.ast.AddAssignStatement
import se.dykstrom.jcc.common.ast.ArrayAccessExpression
import se.dykstrom.jcc.common.ast.IdentifierNameExpression
import se.dykstrom.jcc.common.code.statement.AddAssignCodeGenerator
import kotlin.test.assertEquals
/**
* This class tests the common class [AddAssignCodeGenerator] but it uses Basic classes,
* for example the [BasicTypeManager] so it needs to be part of the Basic tests.
*/
class AddAssignCodeGeneratorTests : AbstractBasicCodeGeneratorComponentTests() {
private val generator = AddAssignCodeGenerator(context)
@Test
fun generateAddAssignToScalarIdentifier() {
// Given
val identifierExpression = IdentifierNameExpression(0, 0, IDENT_I64_FOO)
val statement = AddAssignStatement(0, 0, identifierExpression, IL_53)
// When
val lines = generator.generate(statement).filterIsInstance<Instruction>().map { it.toAsm() }
// Then
assertEquals(1, lines.size)
assertEquals("add [${IDENT_I64_FOO.mappedName}], ${IL_53.value}", lines[0])
}
@Test
fun generateAddAssignToArrayIdentifier() {
// Given
val identifierExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_ONE, listOf(IL_4))
val statement = AddAssignStatement(0, 0, identifierExpression, IL_53)
// When
val lines = generator.generate(statement).filterIsInstance<Instruction>().map { it.toAsm() }
// Then
assertEquals(2, lines.size)
val move = """mov (r[a-z0-9]+), ${IL_4.value}""".toRegex()
val offset = assertRegexMatches(move, lines[0])
val add = """add \[${IDENT_ARR_I64_ONE.mappedName}_arr\+8\*${offset}], ${IL_53.value}""".toRegex()
assertRegexMatches(add, lines[1])
}
}
| gpl-3.0 |
mobilejazz/Colloc | server/src/test/kotlin/com/mobilejazz/colloc/feature/encoder/domain/interactor/IosEncodeInteractorTest.kt | 1 | 2616 | package com.mobilejazz.colloc.feature.encoder.domain.interactor
import com.mobilejazz.colloc.domain.model.Language
import com.mobilejazz.colloc.randomString
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
internal class IosEncodeInteractorTest {
@TempDir
private val localizationDirectory: File = File("{src/test/resources}/encode_localization/")
@Test
fun `assert content encoded properly`() {
val rawTranslation = mapOf(
"#Generic" to randomString(),
"ls_key" to "ls_value",
"ls_key_2" to "ls_value_2"
)
val language = Language(code = randomString(), name = randomString())
val dictionary = mapOf(language to rawTranslation)
givenEncodeInteractor()(localizationDirectory, dictionary)
val actualTranslation = File(localizationDirectory, "${language.code}.lproj/Localizable.strings").readText()
assertActualExpectedTranslationsMatch(actualTranslation)
assertActualExpectedSwiftFileContentMatches()
assertActualExpectedHeaderFileContentMatches()
}
private fun assertActualExpectedTranslationsMatch(actualTranslation: String) {
val expectedTranslation =
IOS_DO_NOT_MODIFY_LINE +
"\n\n// #Generic" +
"\n\"ls_key\" = \"ls_value\";" +
"\n\"ls_key_2\" = \"ls_value_2\";"
assertEquals(expectedTranslation, actualTranslation)
}
private fun assertActualExpectedSwiftFileContentMatches() {
val expectedContent =
IOS_DO_NOT_MODIFY_LINE +
"\nimport Foundation" +
"\n\npublic protocol LocalizedEnum: CustomStringConvertible {}" +
"\n\nextension LocalizedEnum where Self: RawRepresentable, Self.RawValue == String {" +
"\n\tpublic var description: String {" +
"\n\t\tNSLocalizedString(rawValue, comment: \"\")" +
"\n\t}" +
"\n}" +
"\n\npublic enum Colloc: String, LocalizedEnum {" +
"\n\tcase ls_key" +
"\n\tcase ls_key_2" +
"\n}"
val actualContent = File(localizationDirectory, "Colloc.swift").readText()
assertEquals(expectedContent, actualContent)
}
private fun assertActualExpectedHeaderFileContentMatches() {
val expectedContent =
IOS_DO_NOT_MODIFY_LINE +
"\n#define ls_key NSLocalizedString(@\"ls_key\", nil)" +
"\n#define ls_key_2 NSLocalizedString(@\"ls_key_2\", nil)"
val actualContent = File(localizationDirectory, "Localization.h").readText()
assertEquals(expectedContent, actualContent)
}
private fun givenEncodeInteractor() = IosEncodeInteractor()
}
| apache-2.0 |
jraska/github-client | feature/push/src/main/java/com/jraska/github/client/push/PushTokenSynchronizer.kt | 1 | 1179 | package com.jraska.github.client.push
import android.os.Build
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.installations.FirebaseInstallations
import com.jraska.github.client.time.DateTimeProvider
import timber.log.Timber
import java.util.HashMap
import javax.inject.Inject
internal class PushTokenSynchronizer @Inject constructor(
private val database: FirebaseDatabase,
private val dateTimeProvider: DateTimeProvider
) {
fun synchronizeToken(token: String) {
val installationIdTask = FirebaseInstallations.getInstance().id
installationIdTask.addOnSuccessListener { saveToken(it, token) }
.addOnFailureListener { Timber.e(it, "installation Id couldn't be found.") }
}
private fun saveToken(id: String, pushToken: String) {
Timber.d("Id: %s, Token: %s", id, pushToken)
val map = HashMap<String, Any>()
map["date"] = dateTimeProvider.now().toString()
map["push_token"] = pushToken
map["android_os"] = Build.VERSION.RELEASE
map["manufacturer"] = Build.BRAND
map["model"] = Build.MODEL
val tokenReference = database.getReference("devices/$id")
tokenReference.setValue(map)
}
}
| apache-2.0 |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/ui/DesignerNewsViewModelFactory.kt | 1 | 1522 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.plaidapp.core.data.CoroutinesDispatcherProvider
import io.plaidapp.core.designernews.data.login.LoginRepository
import io.plaidapp.designernews.ui.login.LoginViewModel
import javax.inject.Inject
/**
* Factory for Designer News [ViewModel]s
*/
class DesignerNewsViewModelFactory @Inject constructor(
private val loginRepository: LoginRepository,
private val dispatcherProvider: CoroutinesDispatcherProvider
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass != LoginViewModel::class.java) {
throw IllegalArgumentException("Unknown ViewModel class")
}
return LoginViewModel(
loginRepository,
dispatcherProvider
) as T
}
}
| apache-2.0 |
nextcloud/android | app/src/main/java/com/nextcloud/client/media/ErrorFormat.kt | 1 | 5355 | /**
* Nextcloud Android client application
*
* @author David A. Velasco
* @author masensio
* @author Chris Narkiewicz
* Copyright (C) 2013 David A. Velasco
* Copyright (C) 2016 masensio
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.media
import android.content.Context
import android.media.MediaPlayer
import com.google.android.exoplayer2.PlaybackException
import com.owncloud.android.R
/**
* This code has been moved from legacy media player service.
*/
@Deprecated("This legacy helper should be refactored")
@Suppress("ComplexMethod") // it's legacy code
object ErrorFormat {
/** Error code for specific messages - see regular error codes at [MediaPlayer] */
const val OC_MEDIA_ERROR = 0
@JvmStatic
fun toString(context: Context?, what: Int, extra: Int): String {
val messageId: Int
if (what == OC_MEDIA_ERROR) {
messageId = extra
} else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
/* Added in API level 17
Bitstream is conforming to the related coding standard or file spec,
but the media framework does not support the feature.
Constant Value: -1010 (0xfffffc0e)
*/
messageId = R.string.media_err_unsupported
} else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
/* Added in API level 17
File or network related operation errors.
Constant Value: -1004 (0xfffffc14)
*/
messageId = R.string.media_err_io
} else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
/* Added in API level 17
Bitstream is not conforming to the related coding standard or file spec.
Constant Value: -1007 (0xfffffc11)
*/
messageId = R.string.media_err_malformed
} else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
/* Added in API level 17
Some operation takes too long to complete, usually more than 3-5 seconds.
Constant Value: -110 (0xffffff92)
*/
messageId = R.string.media_err_timeout
} else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
/* Added in API level 3
The video is streamed and its container is not valid for progressive playback i.e the video's index
(e.g moov atom) is not at the start of the file.
Constant Value: 200 (0x000000c8)
*/
messageId = R.string.media_err_invalid_progressive_playback
} else {
/* MediaPlayer.MEDIA_ERROR_UNKNOWN
Added in API level 1
Unspecified media player error.
Constant Value: 1 (0x00000001)
*/
/* MediaPlayer.MEDIA_ERROR_SERVER_DIED)
Added in API level 1
Media server died. In this case, the application must release the MediaPlayer
object and instantiate a new one.
Constant Value: 100 (0x00000064)
*/
messageId = R.string.media_err_unknown
}
return context?.getString(messageId) ?: "Media error"
}
fun toString(context: Context, exception: PlaybackException): String {
val messageId = when (exception.errorCode) {
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES -> {
R.string.media_err_unsupported
}
PlaybackException.ERROR_CODE_IO_UNSPECIFIED,
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
PlaybackException.ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE,
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS,
PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
PlaybackException.ERROR_CODE_IO_NO_PERMISSION,
PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE -> {
R.string.media_err_io
}
PlaybackException.ERROR_CODE_TIMEOUT -> {
R.string.media_err_timeout
}
PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED,
PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED -> {
R.string.media_err_malformed
}
else -> {
R.string.media_err_invalid_progressive_playback
}
}
return context.getString(messageId)
}
}
| gpl-2.0 |
olonho/carkot | server/src/main/java/net/web/server/handlers/DirectionOrder.kt | 1 | 1299 | package net.web.server.handlers
import CodedInputStream
import CodedOutputStream
import DirectionRequest
import GenericResponse
import Result
import net.Handler
import net.web.server.Server
class DirectionOrder : Handler {
override fun execute(bytesFromClient: ByteArray): ByteArray {
if (Server.serverMode != Server.ServerMode.MANUAL_MODE) {
println("Can't execute move order when not in manual mode")
val protoResponse = GenericResponse.BuilderGenericResponse(Result.BuilderResult(1).build()).build()
return protoBufToBytes(protoResponse)
}
val ins = CodedInputStream(bytesFromClient)
val order = DirectionRequest.BuilderDirectionRequest(DirectionRequest.Command.FORWARD, 0, false).parseFrom(ins)
if (order.stop) {
net.web.server.Server.changeMode(Server.ServerMode.IDLE)
val protoResponse = GenericResponse.BuilderGenericResponse(Result.BuilderResult(1).build()).build()
return protoBufToBytes(protoResponse)
}
return ByteArray(0)
}
private fun protoBufToBytes(protoMessage: GenericResponse): ByteArray {
val result = ByteArray(protoMessage.getSizeNoTag())
protoMessage.writeTo(CodedOutputStream(result))
return result
}
} | mit |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/adapter/SelectionRecyclerViewAdapter.kt | 2 | 2832 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import edu.berkeley.boinc.attach.ProjectInfoFragment.Companion.newInstance
import edu.berkeley.boinc.attach.SelectionListActivity
import edu.berkeley.boinc.databinding.AttachProjectListLayoutListItemBinding
import edu.berkeley.boinc.utils.Logging
class SelectionRecyclerViewAdapter(
private val activity: SelectionListActivity,
private val entries: List<ProjectListEntry>
) : RecyclerView.Adapter<SelectionRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = AttachProjectListLayoutListItemBinding.inflate(LayoutInflater.from(parent.context))
return ViewHolder(binding)
}
override fun getItemCount() = entries.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val listItem = entries[position]
// element is project option
holder.name.text = listItem.info?.name
holder.description.text = listItem.info?.generalArea
holder.summary.text = listItem.info?.summary
holder.checkBox.isChecked = listItem.isChecked
holder.checkBox.setOnClickListener { listItem.isChecked = !listItem.isChecked }
holder.textWrapper.setOnClickListener {
Logging.logDebug(Logging.Category.USER_ACTION, "SelectionListAdapter: onProjectClick open info for: " +
listItem.info?.name)
val dialog = newInstance(listItem.info)
dialog.show(activity.supportFragmentManager, "ProjectInfoFragment")
}
}
inner class ViewHolder(binding: AttachProjectListLayoutListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
val root = binding.root
val name = binding.name
val description = binding.description
val summary = binding.summary
val checkBox = binding.checkBox
val textWrapper = binding.textWrapper
}
}
| lgpl-3.0 |
adgvcxz/ViewModel | recyclerviewmodel/src/main/kotlin/com/adgvcxz/recyclerviewmodel/ItemClickObservable.kt | 1 | 1332 | package com.adgvcxz.recyclerviewmodel
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.android.MainThreadDisposable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
/**
* zhaowei
* Created by zhaowei on 2017/5/15.
*/
class ItemClickObservable(private val adapter: RecyclerAdapter) : Observable<Int>() {
override fun subscribeActual(observer: Observer<in Int>) {
adapter.notifyDataSetChanged()
adapter.itemClickListener = Listener(observer)
}
class Listener(private val observer: Observer<in Int>) : MainThreadDisposable(), View.OnClickListener {
var recyclerView: RecyclerView? = null
override fun onDispose() {
if (recyclerView != null) {
(0 until recyclerView!!.childCount)
.map { recyclerView!!.getChildAt(it) }
.forEach { it.setOnClickListener(null) }
}
}
override fun onClick(v: View) {
val parent = v.parent
if (parent is RecyclerView && recyclerView == null) {
recyclerView = parent
}
val holder = recyclerView?.getChildViewHolder(v)
observer.onNext(holder?.adapterPosition ?: -1)
}
}
} | apache-2.0 |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/utils/StateRestoringListAdapter.kt | 1 | 1942 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.ui.utils
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import timber.log.Timber
abstract class StateRestoringListAdapter<T : Any?, VH : RecyclerView.ViewHolder>(diffCallback: DiffUtil.ItemCallback<T>) :
ListAdapter<T, VH>(diffCallback) {
init {
stateRestorationPolicy = StateRestorationPolicy.PREVENT
}
abstract fun allowStateRestoring(): Boolean
override fun submitList(list: List<T>?) = submitList(list, null)
override fun submitList(list: List<T>?, commitCallback: Runnable?) {
val restore = allowStateRestoring()
super.submitList(list?.nullIfEmpty()) {
commitCallback?.run()
if (restore && stateRestorationPolicy == StateRestorationPolicy.PREVENT) {
Timber.i("commitCallback: restoring state")
stateRestorationPolicy = StateRestorationPolicy.ALLOW
onStateRestored()
}
}
}
protected open fun onStateRestored() {}
private companion object {
fun <T> List<T>.nullIfEmpty() = ifEmpty { null }
}
}
| gpl-3.0 |
MaTriXy/RxBinding | rxbinding/src/main/java/com/jakewharton/rxbinding3/widget/AutoCompleteTextViewItemClickEventObservable.kt | 1 | 1704 | @file:JvmName("RxAutoCompleteTextView")
@file:JvmMultifileClass
package com.jakewharton.rxbinding3.widget
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AutoCompleteTextView
import androidx.annotation.CheckResult
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.MainThreadDisposable
import com.jakewharton.rxbinding3.internal.checkMainThread
/**
* Create an observable of item click events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
fun AutoCompleteTextView.itemClickEvents(): Observable<AdapterViewItemClickEvent> {
return AutoCompleteTextViewItemClickEventObservable(this)
}
private class AutoCompleteTextViewItemClickEventObservable(
private val view: AutoCompleteTextView
) : Observable<AdapterViewItemClickEvent>() {
override fun subscribeActual(observer: Observer<in AdapterViewItemClickEvent>) {
if (!checkMainThread(observer)) {
return
}
val listener = Listener(view, observer)
observer.onSubscribe(listener)
view.onItemClickListener = listener
}
private class Listener(
private val view: AutoCompleteTextView,
private val observer: Observer<in AdapterViewItemClickEvent>
) : MainThreadDisposable(), OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (!isDisposed) {
observer.onNext(AdapterViewItemClickEvent(parent, view, position, id))
}
}
override fun onDispose() {
view.onItemClickListener = null
}
}
}
| apache-2.0 |
gameofbombs/kt-postgresql-async | db-async-common/src/main/kotlin/com/github/elizarov/async/CancellableDispatcher.kt | 2 | 1097 | package com.github.elizarov.async
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationDispatcher
class CancellableDispatcher(
cancellable: Cancellable,
dispatcher: ContinuationDispatcher? = null
) : Cancellable by cancellable, ContinuationDispatcher {
private val delegate: ContinuationDispatcher? =
if (dispatcher is CancellableDispatcher) dispatcher.delegate else dispatcher
override fun <T> dispatchResume(value: T, continuation: Continuation<T>): Boolean {
if (isCancelled) {
val exception = CancellationException()
if (dispatchResumeWithException(exception, continuation)) return true
continuation.resumeWithException(exception) // todo: stack overflow?
return true
}
return delegate != null && delegate.dispatchResume(value, continuation)
}
override fun dispatchResumeWithException(exception: Throwable, continuation: Continuation<*>): Boolean {
return delegate != null && delegate.dispatchResumeWithException(exception, continuation)
}
}
| apache-2.0 |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/12_嶺上開花.kt | 1 | 1625 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmahjan.rules.yaku.yakuimpl
import dev.yuriel.kotmahjan.models.PlayerContext
import dev.yuriel.kotmahjan.models.RoundContext
import dev.yuriel.kotmahjan.rules.MentsuSupport
/**
* Created by yuriel on 7/24/16.
*/
fun 嶺上開花Impl(r: RoundContext?, p: PlayerContext?, s: MentsuSupport): Boolean {
if (p == null) {
return false
}
if (s.kantsuCount == 0) {
return false
}
return p.isRinshankaihoh()
} | mit |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/serviceIntegration/underwriter/QuoteRequestDto.kt | 1 | 2789 | package com.hedvig.botService.serviceIntegration.underwriter
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import java.math.BigDecimal
import java.time.Instant
import java.time.LocalDate
import java.util.UUID
data class QuoteRequestDto(
val firstName: String?,
val lastName: String?,
val email: String?,
val currentInsurer: String?,
val birthDate: LocalDate?,
val ssn: String?,
val quotingPartner: Partner?,
val productType: ProductType?,
@field:JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@field:JsonSubTypes(
JsonSubTypes.Type(value = IncompleteApartmentQuoteDataDto::class, name = "apartment"),
JsonSubTypes.Type(value = IncompleteHouseQuoteDataDto::class, name = "house")
) val incompleteQuoteData: IncompleteQuoteRequestData?,
val memberId: String? = null,
val originatingProductId: UUID? = null,
val startDate: Instant? = null,
val dataCollectionId: UUID? = null,
val shouldComplete: Boolean,
val underwritingGuidelinesBypassedBy: String?
)
sealed class IncompleteQuoteRequestData
data class IncompleteHouseQuoteDataDto(
val street: String?,
val zipCode: String?,
val city: String?,
val livingSpace: Int?,
val householdSize: Int?,
val ancillaryArea: Int?,
val yearOfConstruction: Int?,
val numberOfBathrooms: Int?,
val extraBuildings: List<ExtraBuildingRequestDto>?,
@field:JsonProperty("subleted")
val isSubleted: Boolean?,
val floor: Int? = 0
) : IncompleteQuoteRequestData()
data class IncompleteApartmentQuoteDataDto(
val street: String?,
val zipCode: String?,
val city: String?,
val livingSpace: Int?,
val householdSize: Int?,
val floor: Int?,
val subType: ApartmentProductSubType?
) : IncompleteQuoteRequestData()
data class ExtraBuildingRequestDto(
val id: UUID?,
val type: ExtraBuildingType,
val area: Int,
val hasWaterConnected: Boolean
)
enum class Partner(val campaignCode: String? = null) {
HEDVIG,
INSPLANET,
COMPRICER,
INSURLEY
}
enum class ProductType {
APARTMENT,
HOUSE,
OBJECT,
UNKNOWN
}
enum class ExtraBuildingType {
GARAGE,
CARPORT,
SHED,
STOREHOUSE,
FRIGGEBOD,
ATTEFALL,
OUTHOUSE,
GUESTHOUSE,
GAZEBO,
GREENHOUSE,
SAUNA,
BARN,
BOATHOUSE,
OTHER
}
enum class ApartmentProductSubType {
BRF,
RENT,
RENT_BRF,
SUBLET_RENTAL,
SUBLET_BRF,
STUDENT_BRF,
STUDENT_RENT,
LODGER,
UNKNOWN
}
data class CompleteQuoteResponseDto(
val id: UUID,
val price: BigDecimal,
val validTo: Instant
)
| agpl-3.0 |
alfadur/antiques | src/Pixi.kt | 1 | 4063 | import org.w3c.dom.HTMLCanvasElement
//@suppress("UNUSED_PARAMETER")
@native object PIXI
{
@native class Point(val x: Number, val y: Number)
@native class Rectangle(val x: Number, val y: Number, val width: Number, val height: Number)
@native class Matrix
{
@native val a: Double = noImpl
@native val b: Double = noImpl
@native val c: Double = noImpl
@native val d: Double = noImpl
@native val tx: Double = noImpl
@native val ty: Double = noImpl
companion object
{
@native fun fromArray(array: Array<Double>): Matrix = noImpl
}
}
@native open class DisplayObject
{
@native var position: Point get() = noImpl; set(v) = noImpl
@native var rotation: Double get() = noImpl; set(v) = noImpl
@native var pivot: Point get() = noImpl; set(v) = noImpl
@native var scale: Point get() = noImpl; set(v) = noImpl
@native var worldTransform: Matrix get() = noImpl; set(v) = noImpl
@native var width: Number = noImpl
@native var height: Number = noImpl
@native var visible: Boolean get() = noImpl; set(v) = noImpl
}
@native open class DisplayObjectContainer: DisplayObject()
{
@native fun addChild(child: DisplayObject): DisplayObject = noImpl
@native fun removeChild(child: DisplayObject): DisplayObject = noImpl
@native fun removeChildren(): Unit = noImpl
}
@native class Stage(color: Number = 0): DisplayObjectContainer()
@native class CanvasRenderer(width: Number = 800, height: Number = 600)
{
@native val view: HTMLCanvasElement = noImpl
@native fun render(stage: Stage): Unit = noImpl
}
@native class Graphics: DisplayObject()
{
@native fun beginFill(color: Number = 0, alpha: Number = 1): Graphics = noImpl
@native fun endFill(): Graphics = noImpl
@native fun lineStyle(lineWidth: Number = 0, color: Number = 0, alpha: Number = 1): Graphics = noImpl
@native fun moveTo(x: Number, y: Number): Graphics = noImpl
@native fun lineTo(x: Number, y: Number): Graphics = noImpl
@native fun drawRect(x: Number, y: Number, width: Number, height: Number): Graphics = noImpl
@native fun drawCircle(x: Number, y: Number, radius: Number): Graphics = noImpl
@native fun clear(): Graphics = noImpl
}
@native class AssetLoader(assetUrls: Array<String>, crossorigin: Boolean)
{
@native fun load(): Unit = noImpl
@native var onComplete: () -> Unit = noImpl
}
@native class BaseTexture private constructor()
{
@native val width: Int = noImpl
@native val height: Int = noImpl
companion object
{
@native fun fromImage(imageUrl: String, crossorigin: Boolean): BaseTexture = noImpl
}
}
@native class Texture(baseTexture: BaseTexture, val frame: Rectangle)
{
companion object
{
@native fun fromFrame(frameId: String): Texture = noImpl
}
}
@native class Sprite(texture: Texture): DisplayObject()
@native class Text(var text: String, val style: TextStyle? = null): DisplayObject()
{
fun setStyle(style: TextStyle): Unit = noImpl
}
@native class SpriteBatch(): DisplayObjectContainer()
}
data class TextStyle(
val fill: String = "black",
val wordWrap: Boolean = false,
val wordWrapWidth: Number = 100,
val font: String? = null)
fun PIXI.BaseTexture.slice(vararg sizes: Int): Array<PIXI.Texture>
{
val result = arrayListOf<PIXI.Texture>()
var x = 0
var y = 0
for (height in sizes)
{
for (width in sizes)
{
result.add(PIXI.Texture(this, PIXI.Rectangle(x, y, width, height)))
x += width
}
y += height
x = 0
}
return result.toTypedArray()
}
operator fun PIXI.Point.plus(p: PIXI.Point) =
PIXI.Point(x.toDouble() + p.x.toDouble(),
y.toDouble() + p.y.toDouble()) | mit |
cashapp/sqldelight | sqldelight-compiler/src/test/kotlin/app/cash/sqldelight/core/tables/InterfaceGeneration.kt | 1 | 15389 | package app.cash.sqldelight.core.tables
import app.cash.sqldelight.core.compiler.SqlDelightCompiler
import app.cash.sqldelight.core.compiler.TableInterfaceGenerator
import app.cash.sqldelight.dialects.hsql.HsqlDialect
import app.cash.sqldelight.dialects.mysql.MySqlDialect
import app.cash.sqldelight.dialects.postgresql.PostgreSqlDialect
import app.cash.sqldelight.test.util.FixtureCompiler
import app.cash.sqldelight.test.util.withInvariantLineSeparators
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class InterfaceGeneration {
@get:Rule val tempFolder = TemporaryFolder()
@Test fun requiresAdapter() {
checkFixtureCompiles("requires-adapter")
}
@Test fun `annotation with values is preserved`() {
val result = FixtureCompiler.compileSql(
"""
|import com.sample.SomeAnnotation;
|import com.sample.SomeOtherAnnotation;
|import java.util.List;
|import kotlin.Int;
|
|CREATE TABLE test (
| annotated INTEGER AS @SomeAnnotation(
| cheese = ["havarti", "provalone"],
| age = 10,
| type = List::class,
| otherAnnotation = SomeOtherAnnotation("value")
| ) Int
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import app.cash.sqldelight.ColumnAdapter
|import com.sample.SomeAnnotation
|import com.sample.SomeOtherAnnotation
|import java.util.List
|import kotlin.Int
|import kotlin.Long
|
|public data class Test(
| @SomeAnnotation(
| cheese = ["havarti","provalone"],
| age = 10,
| type = List::class,
| otherAnnotation = SomeOtherAnnotation("value"),
| )
| public val annotated: Int?,
|) {
| public class Adapter(
| public val annotatedAdapter: ColumnAdapter<Int, Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `abstract class doesnt override kotlin functions unprepended by get`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test (
| is_cool TEXT NOT NULL,
| get_cheese TEXT,
| isle TEXT,
| stuff TEXT
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.String
|
|public data class Test(
| public val is_cool: String,
| public val get_cheese: String?,
| public val isle: String?,
| public val stuff: String?,
|)
|
""".trimMargin(),
)
}
@Test fun `complex generic type is inferred properly`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| mapValue INTEGER AS kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val mapValue: kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>?,
|) {
| public class Adapter(
| public val mapValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `type doesnt just use suffix to resolve`() {
val result = FixtureCompiler.parseSql(
"""
|import java.time.DayOfWeek;
|import com.gabrielittner.timetable.core.db.Week;
|import kotlin.collections.Set;
|
|CREATE TABLE test (
| _id INTEGER PRIMARY KEY AUTOINCREMENT,
| enabledDays TEXT AS Set<DayOfWeek>,
| enabledWeeks TEXT AS Set<Week>
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val _id: kotlin.Long,
| public val enabledDays: kotlin.collections.Set<java.time.DayOfWeek>?,
| public val enabledWeeks: kotlin.collections.Set<com.gabrielittner.timetable.core.db.Week>?,
|) {
| public class Adapter(
| public val enabledDaysAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Set<java.time.DayOfWeek>, kotlin.String>,
| public val enabledWeeksAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Set<com.gabrielittner.timetable.core.db.Week>, kotlin.String>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `escaped names is handled correctly`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE [group] (
| `index1` TEXT,
| 'index2' TEXT,
| "index3" TEXT,
| [index4] TEXT
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Group(
| public val index1: kotlin.String?,
| public val index2: kotlin.String?,
| public val index3: kotlin.String?,
| public val index4: kotlin.String?,
|)
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in MySQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| tinyIntValue TINYINT AS kotlin.Any NOT NULL,
| tinyIntBoolValue BOOLEAN AS kotlin.Any NOT NULL,
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| mediumIntValue MEDIUMINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| bitValue BIT AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = MySqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val tinyIntValue: kotlin.Any,
| public val tinyIntBoolValue: kotlin.Any,
| public val smallIntValue: kotlin.Any,
| public val mediumIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val bitValue: kotlin.Any,
|) {
| public class Adapter(
| public val tinyIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Byte>,
| public val tinyIntBoolValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val mediumIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val bitValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in PostgreSQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| smallSerialValue SMALLSERIAL AS kotlin.Any,
| serialValue SERIAL AS kotlin.Any NOT NULL,
| bigSerialValue BIGSERIAL AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = PostgreSqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val smallIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val smallSerialValue: kotlin.Any?,
| public val serialValue: kotlin.Any,
| public val bigSerialValue: kotlin.Any,
|) {
| public class Adapter(
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val smallSerialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val serialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigSerialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in HSQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| tinyIntValue TINYINT AS kotlin.Any NOT NULL,
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| booleanValue BOOLEAN AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = HsqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val tinyIntValue: kotlin.Any,
| public val smallIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val booleanValue: kotlin.Any,
|) {
| public class Adapter(
| public val tinyIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Byte>,
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val booleanValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `move annotations to the front of the property`() {
val result = FixtureCompiler.parseSql(
"""
|import java.lang.Deprecated;
|import java.util.Date;
|
|CREATE TABLE something (
| startDate INTEGER AS @Deprecated Date NOT NULL,
| endDate INTEGER AS @Deprecated Date NOT NULL
|);
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Something(
| @java.lang.Deprecated
| public val startDate: java.util.Date,
| @java.lang.Deprecated
| public val endDate: java.util.Date,
|) {
| public class Adapter(
| public val startDateAdapter: app.cash.sqldelight.ColumnAdapter<java.util.Date, kotlin.Long>,
| public val endDateAdapter: app.cash.sqldelight.ColumnAdapter<java.util.Date, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `value types correctly generated`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test (
| id INTEGER AS VALUE NOT NULL
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.Long
|import kotlin.jvm.JvmInline
|
|public data class Test(
| public val id: Id,
|) {
| @JvmInline
| public value class Id(
| public val id: Long,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `postgres primary keys are non null`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test(
| bioguide_id VARCHAR,
| score_year INTEGER,
| score INTEGER NOT NULL,
| PRIMARY KEY(bioguide_id, score_year)
|);
|
""".trimMargin(),
tempFolder,
overrideDialect = PostgreSqlDialect(),
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.Int
|import kotlin.String
|
|public data class Test(
| public val bioguide_id: String,
| public val score_year: Int,
| public val score: Int,
|)
|
""".trimMargin(),
)
}
private fun checkFixtureCompiles(fixtureRoot: String) {
val result = FixtureCompiler.compileFixture(
fixtureRoot = "src/test/table-interface-fixtures/$fixtureRoot",
compilationMethod = { _, _, sqlDelightQueriesFile, writer ->
SqlDelightCompiler.writeTableInterfaces(sqlDelightQueriesFile, writer)
},
generateDb = false,
)
for ((expectedFile, actualOutput) in result.compilerOutput) {
assertWithMessage("No file with name $expectedFile").that(expectedFile.exists()).isTrue()
assertWithMessage(expectedFile.name)
.that(expectedFile.readText().withInvariantLineSeparators())
.isEqualTo(actualOutput.toString())
}
}
}
| apache-2.0 |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityTabLayout.kt | 1 | 2198 | package com.tamsiree.rxdemo.activity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.adapter.AdapterRecyclerViewMain
import com.tamsiree.rxdemo.adapter.AdapterRecyclerViewMain.ContentListener
import com.tamsiree.rxdemo.model.ModelDemo
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxImageTool
import com.tamsiree.rxkit.RxRecyclerViewDividerTool
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_tablayout.*
import java.util.*
class ActivityTabLayout : ActivityBase() {
private val mItems = arrayOf("TGlideTabLayout", "CommonTabLayout", "TSectionTabLayout")
private val mColumnCount = 2
private lateinit var mData: MutableList<ModelDemo>
private lateinit var madapter: AdapterRecyclerViewMain
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tablayout)
}
override fun initView() {
rx_title.setLeftFinish(this)
if (mColumnCount <= 1) {
recyclerview.layoutManager = LinearLayoutManager(mContext)
} else {
recyclerview.layoutManager = GridLayoutManager(mContext, mColumnCount)
}
recyclerview.addItemDecoration(RxRecyclerViewDividerTool(RxImageTool.dp2px(5f)))
mData = ArrayList()
madapter = AdapterRecyclerViewMain(mData, object : ContentListener {
override fun setListener(position: Int) {
RxActivityTool.skipActivity(mContext, mData[position].activity)
}
})
recyclerview.adapter = madapter
}
override fun initData() {
mData.clear()
mData.add(ModelDemo("TTabLayout", R.drawable.circle_elves_ball, ActivityTTabLayout::class.java))
mData.add(ModelDemo("TGlideTabLayout", R.drawable.circle_elves_ball, ActivityTGlideTabLayout::class.java))
mData.add(ModelDemo("TSectionTabLayout", R.drawable.circle_elves_ball, ActivityTSectionTabLayout::class.java))
madapter.notifyDataSetChanged()
}
} | apache-2.0 |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/listener/OnMovieRemovedListener.kt | 1 | 157 | package de.cineaste.android.listener
import de.cineaste.android.entity.movie.Movie
interface OnMovieRemovedListener {
fun removeMovie(movie: Movie)
}
| gpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/settings/SettingsPreferenceLoader.kt | 1 | 6471 | package org.wikipedia.settings
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.auth.AccountUtil
import org.wikipedia.feed.configure.ConfigureActivity
import org.wikipedia.login.LoginActivity
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.settings.languages.WikipediaLanguagesActivity
import org.wikipedia.theme.ThemeFittingRoomActivity
/** UI code for app settings used by PreferenceFragment. */
internal class SettingsPreferenceLoader(fragment: PreferenceFragmentCompat) : BasePreferenceLoader(fragment) {
override fun loadPreferences() {
loadPreferences(R.xml.preferences)
if (RemoteConfig.config.disableReadingListSync) {
findPreference(R.string.preference_category_sync).isVisible = false
findPreference(R.string.preference_key_sync_reading_lists).isVisible = false
}
findPreference(R.string.preference_key_sync_reading_lists).onPreferenceChangeListener = SyncReadingListsListener()
findPreference(R.string.preference_key_eventlogging_opt_in).onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference: Preference, newValue: Any ->
if (!(newValue as Boolean)) {
Prefs.appInstallId = null
}
true
}
loadPreferences(R.xml.preferences_about)
updateLanguagePrefSummary()
findPreference(R.string.preference_key_language).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivityForResult(WikipediaLanguagesActivity.newIntent(activity, Constants.InvokeSource.SETTINGS),
Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE)
true
}
findPreference(R.string.preference_key_customize_explore_feed).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivityForResult(ConfigureActivity.newIntent(activity, Constants.InvokeSource.NAV_MENU.ordinal),
Constants.ACTIVITY_REQUEST_FEED_CONFIGURE)
true
}
findPreference(R.string.preference_key_color_theme).let {
it.setSummary(WikipediaApp.instance.currentTheme.nameId)
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivity(ThemeFittingRoomActivity.newIntent(activity))
true
}
}
findPreference(R.string.preference_key_about_wikipedia_app).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivity(Intent(activity, AboutActivity::class.java))
true
}
if (AccountUtil.isLoggedIn) {
loadPreferences(R.xml.preferences_account)
(findPreference(R.string.preference_key_logout) as LogoutPreference).activity = activity
}
}
fun updateLanguagePrefSummary() {
// TODO: resolve RTL vs LTR with multiple languages (e.g. list contains English and Hebrew)
findPreference(R.string.preference_key_language).summary = WikipediaApp.instance.languageState.appLanguageLocalizedNames
}
private inner class SyncReadingListsListener : Preference.OnPreferenceChangeListener {
override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
if (AccountUtil.isLoggedIn) {
if (newValue as Boolean) {
(preference as SwitchPreferenceCompat).isChecked = true
ReadingListSyncAdapter.setSyncEnabledWithSetup()
} else {
AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_title, AccountUtil.userName))
.setMessage(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_text, AccountUtil.userName))
.setPositiveButton(R.string.reading_lists_confirm_remote_delete_yes, DeleteRemoteListsYesListener(preference))
.setNegativeButton(R.string.reading_lists_confirm_remote_delete_no, null)
.show()
}
} else {
AlertDialog.Builder(activity)
.setTitle(R.string.reading_list_preference_login_to_enable_sync_dialog_title)
.setMessage(R.string.reading_list_preference_login_to_enable_sync_dialog_text)
.setPositiveButton(R.string.reading_list_preference_login_to_enable_sync_dialog_login
) { _: DialogInterface, _: Int ->
val loginIntent = LoginActivity.newIntent(activity,
LoginFunnel.SOURCE_SETTINGS)
activity.startActivity(loginIntent)
}
.setNegativeButton(R.string.reading_list_preference_login_to_enable_sync_dialog_cancel, null)
.show()
}
// clicks are handled and preferences updated accordingly; don't pass the result through
return false
}
}
fun updateSyncReadingListsPrefSummary() {
findPreference(R.string.preference_key_sync_reading_lists).let {
if (AccountUtil.isLoggedIn) {
it.summary = activity.getString(R.string.preference_summary_sync_reading_lists_from_account, AccountUtil.userName)
} else {
it.setSummary(R.string.preference_summary_sync_reading_lists)
}
}
}
private inner class DeleteRemoteListsYesListener(private val preference: Preference) : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
(preference as SwitchPreferenceCompat).isChecked = false
Prefs.isReadingListSyncEnabled = false
Prefs.isReadingListsRemoteSetupPending = false
Prefs.isReadingListsRemoteDeletePending = true
ReadingListSyncAdapter.manualSync()
}
}
}
| apache-2.0 |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/FakeFraudDetectionDataRepository.kt | 1 | 779 | package com.stripe.android
import com.stripe.android.networking.FraudDetectionData
import java.util.UUID
internal class FakeFraudDetectionDataRepository(
private val fraudDetectionData: FraudDetectionData?
) : FraudDetectionDataRepository {
@JvmOverloads constructor(
guid: UUID = UUID.randomUUID(),
muid: UUID = UUID.randomUUID(),
sid: UUID = UUID.randomUUID()
) : this(
FraudDetectionData(
guid = guid.toString(),
muid = muid.toString(),
sid = sid.toString()
)
)
override fun refresh() {
}
override fun getCached() = fraudDetectionData
override suspend fun getLatest() = fraudDetectionData
override fun save(fraudDetectionData: FraudDetectionData) {
}
}
| mit |
AndroidX/androidx | preference/preference-ktx/src/androidTest/java/androidx/preference/PreferenceTestHelperActivity.kt | 3 | 1851 | /*
* Copyright (C) 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.preference
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
/**
* Helper activity that inflates a preference hierarchy defined in a given XML resource with a
* [PreferenceFragmentCompat] to aid testing.
*/
class PreferenceTestHelperActivity : AppCompatActivity() {
/**
* Inflates the given XML resource and returns the created PreferenceFragmentCompat.
*
* @param preferenceLayoutId The XML resource ID to inflate
* @return The PreferenceFragmentCompat that contains the inflated hierarchy
*/
fun setupPreferenceHierarchy(@LayoutRes preferenceLayoutId: Int): PreferenceFragmentCompat {
val fragment = TestFragment(preferenceLayoutId)
supportFragmentManager
.beginTransaction()
.replace(android.R.id.content, fragment)
.commitNow()
return fragment
}
class TestFragment internal constructor(private val mPreferenceLayoutId: Int) :
PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(mPreferenceLayoutId, rootKey)
}
}
}
| apache-2.0 |
exponent/exponent | packages/expo-dev-menu-interface/android/src/main/java/expo/interfaces/devmenu/items/DevMenuItemsContainer.kt | 2 | 1477 | package expo.interfaces.devmenu.items
import java.util.*
open class DevMenuItemsContainer : DevMenuDSLItemsContainerInterface {
private val items = mutableListOf<DevMenuScreenItem>()
override fun getRootItems(): List<DevMenuScreenItem> {
items.sortedWith(compareBy { it.importance })
return items
}
override fun getAllItems(): List<DevMenuScreenItem> {
val result = LinkedList<DevMenuScreenItem>()
items.forEach {
result.add(it)
if (it is DevMenuItemsContainerInterface) {
result.addAll(it.getAllItems())
}
}
return result
}
private fun addItem(item: DevMenuScreenItem) {
items.add(item)
}
override fun group(init: DevMenuGroup.() -> Unit) = addItem(DevMenuGroup(), init)
override fun action(actionId: String, action: () -> Unit, init: DevMenuAction.() -> Unit) =
addItem(DevMenuAction(actionId, action), init)
override fun link(target: String, init: DevMenuLink.() -> Unit) = addItem(DevMenuLink(target), init)
override fun selectionList(init: DevMenuSelectionList.() -> Unit) = addItem(DevMenuSelectionList(), init)
private fun <T : DevMenuScreenItem> addItem(item: T, init: T.() -> Unit): T {
item.init()
addItem(item)
return item
}
companion object {
@JvmStatic
fun export(init: DevMenuDSLItemsContainerInterface.() -> Unit): DevMenuItemsContainer {
val container = DevMenuItemsContainer()
container.init()
return container
}
}
}
| bsd-3-clause |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/network/TelegramApi.kt | 1 | 2704 | /*
* <!--
* ~ Copyright (c) 2017. ThanksMister 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.thanksmister.iot.mqtt.alarmpanel.network
import android.graphics.Bitmap
import android.util.Base64
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.GsonBuilder
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit
import okhttp3.MultipartBody
import java.io.ByteArrayOutputStream
class TelegramApi(private val token: String, private val chat_id:String) {
private val service: TelegramRequest
init {
val base_url = "https://api.telegram.org/bot$token/"
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.HEADERS
val httpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(10000, TimeUnit.SECONDS)
.readTimeout(10000, TimeUnit.SECONDS)
.addNetworkInterceptor(StethoInterceptor())
.build()
val gson = GsonBuilder()
.create()
val retrofit = Retrofit.Builder()
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(base_url)
.build()
service = retrofit.create(TelegramRequest::class.java)
}
fun sendMessage(text: String, bitmap:Bitmap): Call<JSONObject> {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream)
val byteArray = stream.toByteArray()
return service.sendPhoto(
RequestBody.create(MediaType.parse("multipart/form-data"), chat_id),
RequestBody.create(MediaType.parse("multipart/form-data"), text),
RequestBody.create(MediaType.parse("multipart/form-data"), byteArray))
}
} | apache-2.0 |
AndroidX/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/RadioButton.kt | 3 | 9202 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.tokens.RadioButtonTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
/**
* <a href="https://m3.material.io/components/radio-button/overview" class="external" target="_blank">Material Design radio button</a>.
*
* Radio buttons allow users to select one option from a set.
*
* 
*
* @sample androidx.compose.material3.samples.RadioButtonSample
*
* [RadioButton]s can be combined together with [Text] in the desired layout (e.g. [Column] or
* [Row]) to achieve radio group-like behaviour, where the entire layout is selectable:
* @sample androidx.compose.material3.samples.RadioGroupSample
*
* @param selected whether this radio button is selected or not
* @param onClick called when this radio button is clicked. If `null`, then this radio button will
* not be interactable, unless something else handles its input events and updates its state.
* @param modifier the [Modifier] to be applied to this radio button
* @param enabled controls the enabled state of this radio button. When `false`, this component will
* not respond to user input, and it will appear visually disabled and disabled to accessibility
* services.
* @param colors [RadioButtonColors] that will be used to resolve the color used for this radio
* button in different states. See [RadioButtonDefaults.colors].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this radio button. You can create and pass in your own `remember`ed instance to observe
* [Interaction]s and customize the appearance / behavior of this radio button in different states.
*/
@Composable
fun RadioButton(
selected: Boolean,
onClick: (() -> Unit)?,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: RadioButtonColors = RadioButtonDefaults.colors(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) {
val dotRadius = animateDpAsState(
targetValue = if (selected) RadioButtonDotSize / 2 else 0.dp,
animationSpec = tween(durationMillis = RadioAnimationDuration)
)
val radioColor = colors.radioColor(enabled, selected)
val selectableModifier =
if (onClick != null) {
Modifier.selectable(
selected = selected,
onClick = onClick,
enabled = enabled,
role = Role.RadioButton,
interactionSource = interactionSource,
indication = rememberRipple(
bounded = false,
radius = RadioButtonTokens.StateLayerSize / 2
)
)
} else {
Modifier
}
Canvas(
modifier
.then(
if (onClick != null) {
Modifier.minimumTouchTargetSize()
} else {
Modifier
}
)
.then(selectableModifier)
.wrapContentSize(Alignment.Center)
.padding(RadioButtonPadding)
.requiredSize(RadioButtonTokens.IconSize)
) {
// Draw the radio button
val strokeWidth = RadioStrokeWidth.toPx()
drawCircle(
radioColor.value,
radius = (RadioButtonTokens.IconSize / 2).toPx() - strokeWidth / 2,
style = Stroke(strokeWidth)
)
if (dotRadius.value > 0.dp) {
drawCircle(radioColor.value, dotRadius.value.toPx() - strokeWidth / 2, style = Fill)
}
}
}
/**
* Defaults used in [RadioButton].
*/
object RadioButtonDefaults {
/**
* Creates a [RadioButtonColors] that will animate between the provided colors according to
* the Material specification.
*
* @param selectedColor the color to use for the RadioButton when selected and enabled.
* @param unselectedColor the color to use for the RadioButton when unselected and enabled.
* @param disabledSelectedColor the color to use for the RadioButton when disabled and selected.
* @param disabledUnselectedColor the color to use for the RadioButton when disabled and not
* selected.
* @return the resulting [RadioButtonColors] used for the RadioButton
*/
@Composable
fun colors(
selectedColor: Color = RadioButtonTokens.SelectedIconColor.toColor(),
unselectedColor: Color = RadioButtonTokens.UnselectedIconColor.toColor(),
disabledSelectedColor: Color = RadioButtonTokens.DisabledSelectedIconColor
.toColor()
.copy(alpha = RadioButtonTokens.DisabledSelectedIconOpacity),
disabledUnselectedColor: Color = RadioButtonTokens.DisabledUnselectedIconColor
.toColor()
.copy(alpha = RadioButtonTokens.DisabledUnselectedIconOpacity)
): RadioButtonColors = RadioButtonColors(
selectedColor,
unselectedColor,
disabledSelectedColor,
disabledUnselectedColor
)
}
/**
* Represents the color used by a [RadioButton] in different states.
*
* See [RadioButtonDefaults.colors] for the default implementation that follows Material
* specifications.
*/
@Immutable
class RadioButtonColors internal constructor(
private val selectedColor: Color,
private val unselectedColor: Color,
private val disabledSelectedColor: Color,
private val disabledUnselectedColor: Color
) {
/**
* Represents the main color used to draw the outer and inner circles, depending on whether
* the [RadioButton] is [enabled] / [selected].
*
* @param enabled whether the [RadioButton] is enabled
* @param selected whether the [RadioButton] is selected
*/
@Composable
internal fun radioColor(enabled: Boolean, selected: Boolean): State<Color> {
val target = when {
enabled && selected -> selectedColor
enabled && !selected -> unselectedColor
!enabled && selected -> disabledSelectedColor
else -> disabledUnselectedColor
}
// If not enabled 'snap' to the disabled state, as there should be no animations between
// enabled / disabled.
return if (enabled) {
animateColorAsState(target, tween(durationMillis = RadioAnimationDuration))
} else {
rememberUpdatedState(target)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is RadioButtonColors) return false
if (selectedColor != other.selectedColor) return false
if (unselectedColor != other.unselectedColor) return false
if (disabledSelectedColor != other.disabledSelectedColor) return false
if (disabledUnselectedColor != other.disabledUnselectedColor) return false
return true
}
override fun hashCode(): Int {
var result = selectedColor.hashCode()
result = 31 * result + unselectedColor.hashCode()
result = 31 * result + disabledSelectedColor.hashCode()
result = 31 * result + disabledUnselectedColor.hashCode()
return result
}
}
private const val RadioAnimationDuration = 100
private val RadioButtonPadding = 2.dp
private val RadioButtonDotSize = 12.dp
private val RadioStrokeWidth = 2.dp
| apache-2.0 |
AndroidX/androidx | lint-checks/src/test/java/androidx/build/lint/PrivateConstructorForUtilityClassDetectorTest.kt | 3 | 3041 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.build.lint
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class PrivateConstructorForUtilityClassDetectorTest : AbstractLintDetectorTest(
useDetector = PrivateConstructorForUtilityClassDetector(),
useIssues = listOf(PrivateConstructorForUtilityClassDetector.ISSUE),
) {
@Test
fun testInnerClassVisibilityJava() {
val input = java(
"src/androidx/PrivateConstructorForUtilityClassJava.java",
"""
public class PrivateConstructorForUtilityClassJava {
// This class has a default private constructor, which is allowed.
private static class PrivateInnerClass {
static void method() { }
}
// This class needs an explicit private constructor.
static class DefaultInnerClass {
static void method() { }
}
// This class needs an explicit private constructor.
protected static class ProtectedInnerClass {
static void method() { }
}
// This class needs an explicit private constructor.
public static class PublicInnerClass {
static void method() { }
}
}
""".trimIndent()
)
/* ktlint-disable max-line-length */
val expected = """
src/androidx/PrivateConstructorForUtilityClassJava.java:9: Error: Utility class is missing private constructor [PrivateConstructorForUtilityClass]
static class DefaultInnerClass {
~~~~~~~~~~~~~~~~~
src/androidx/PrivateConstructorForUtilityClassJava.java:14: Error: Utility class is missing private constructor [PrivateConstructorForUtilityClass]
protected static class ProtectedInnerClass {
~~~~~~~~~~~~~~~~~~~
src/androidx/PrivateConstructorForUtilityClassJava.java:19: Error: Utility class is missing private constructor [PrivateConstructorForUtilityClass]
public static class PublicInnerClass {
~~~~~~~~~~~~~~~~
3 errors, 0 warnings
""".trimIndent()
/* ktlint-enable max-line-length */
check(input).expect(expected)
}
}
| apache-2.0 |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/TeamPermissionCurrentPermissions.kt | 1 | 396 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Represents the current permission for a [TeamPermission].
*
* @param permissionPolicyUri The uri for the permission
*/
@JsonClass(generateAdapter = true)
data class TeamPermissionCurrentPermissions(
@Json(name = "permission_policy_uri")
val permissionPolicyUri: String? = null
)
| mit |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/layers/SlotLayer.kt | 1 | 1411 | package com.teamwizardry.librarianlib.facade.container.layers
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.facade.container.slot.FacadeSlot
import com.teamwizardry.librarianlib.facade.layer.GuiDrawContext
import com.teamwizardry.librarianlib.facade.layer.GuiLayer
import com.teamwizardry.librarianlib.facade.layer.supporting.ContainerSpace
import com.teamwizardry.librarianlib.facade.pastry.PastryBackgroundStyle
import com.teamwizardry.librarianlib.facade.pastry.layers.PastryBackground
import net.minecraft.screen.slot.Slot
/**
* A layer that defines the position and visibility of a container slot
*/
public class SlotLayer @JvmOverloads constructor(
public val slot: Slot,
posX: Int, posY: Int,
showBackground: Boolean = false
): GuiLayer(posX, posY, 16, 16) {
/**
* Whether to show the default slot background.
*/
public var showBackground: Boolean = showBackground
private val background: PastryBackground = PastryBackground(PastryBackgroundStyle.INPUT, -1, -1, 18, 18)
init {
add(background)
background.isVisible_im.set { this.showBackground }
}
override fun draw(context: GuiDrawContext) {
super.draw(context)
val rootPos = ContainerSpace.convertPointFrom(vec(0, 0), this)
FacadeSlot.setSlotX(slot, rootPos.xi)
FacadeSlot.setSlotY(slot, rootPos.yi)
}
}
| lgpl-3.0 |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/CargoCommandRunner.kt | 2 | 1978 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig
import com.intellij.execution.configurations.RunProfile
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.ui.RunContentDescriptor
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.getBuildConfiguration
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.isBuildConfiguration
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.isBuildToolWindowAvailable
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.command.hasRemoteTarget
open class CargoCommandRunner : RsDefaultProgramRunnerBase() {
override fun getRunnerId(): String = RUNNER_ID
override fun canRun(executorId: String, profile: RunProfile): Boolean {
if (executorId != DefaultRunExecutor.EXECUTOR_ID || profile !is CargoCommandConfiguration) return false
val cleaned = profile.clean().ok ?: return false
val isLocalRun = !profile.hasRemoteTarget || profile.buildTarget.isRemote
val isLegacyTestRun = !profile.isBuildToolWindowAvailable &&
cleaned.cmd.command == "test" &&
getBuildConfiguration(profile) != null
return isLocalRun && !isLegacyTestRun
}
override fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? {
val configuration = environment.runProfile
return if (configuration is CargoCommandConfiguration &&
!(isBuildConfiguration(configuration) && configuration.isBuildToolWindowAvailable)) {
super.doExecute(state, environment)
} else {
null
}
}
companion object {
const val RUNNER_ID: String = "CargoCommandRunner"
}
}
| mit |
charleskorn/batect | app/src/main/kotlin/batect/cli/options/OptionValueSource.kt | 1 | 686 | /*
Copyright 2017-2020 Charles Korn.
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 batect.cli.options
enum class OptionValueSource {
Default,
CommandLine
}
| apache-2.0 |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/PrefsActivity.kt | 2 | 2723 | package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.view.ViewGroup
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.ui.fragments.preferences.AccountPreferenceFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.EmailNotificationsPreferencesFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.PreferencesFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.PushNotificationsPreferencesFragment
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
class PrefsActivity : BaseActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback, SnackbarActivity {
override fun getLayoutResId(): Int = R.layout.activity_prefs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(findViewById(R.id.toolbar))
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, PreferencesFragment())
.commit()
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onSupportNavigateUp(): Boolean {
if (supportFragmentManager.backStackEntryCount > 0) {
onBackPressed()
return true
}
return super.onSupportNavigateUp()
}
override fun onPreferenceStartScreen(
preferenceFragment: PreferenceFragmentCompat,
preferenceScreen: PreferenceScreen
): Boolean {
val fragment = createNextPage(preferenceScreen)
if (fragment != null) {
val arguments = Bundle()
arguments.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.key)
fragment.arguments = arguments
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit()
return true
}
return false
}
private fun createNextPage(preferenceScreen: PreferenceScreen): PreferenceFragmentCompat? =
when (preferenceScreen.key) {
"my_account" -> AccountPreferenceFragment()
"pushNotifications" -> PushNotificationsPreferencesFragment()
"emailNotifications" -> EmailNotificationsPreferencesFragment()
else -> null
}
override fun snackbarContainer(): ViewGroup {
val v = findViewById<ViewGroup>(R.id.snackbar_container)
return v
}
}
| gpl-3.0 |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/management/controllers/EchoVosController.kt | 2 | 706 | package nl.rsdt.japp.jotial.maps.management.controllers
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 31-7-2016
* Description...
*/
class EchoVosController(jotiMap: IJotiMap) : VosController(jotiMap) {
override val team: String
get() = "e"
override val id: String
get() = CONTROLLER_ID
override val storageId: String
get() = STORAGE_ID
override val bundleId: String
get() = BUNDLE_ID
companion object {
val CONTROLLER_ID = "EchoVosController"
val STORAGE_ID = "STORAGE_VOS_E"
val BUNDLE_ID = "VOS_E"
val REQUEST_ID = "REQUEST_VOS_E"
}
}
| apache-2.0 |
androidx/androidx | room/room-compiler/src/test/kotlin/androidx/room/processor/InsertionMethodProcessorTest.kt | 3 | 3827 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.compiler.processing.XMethodElement
import androidx.room.compiler.processing.XType
import androidx.room.processor.ProcessorErrors.INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT
import androidx.room.processor.ProcessorErrors.CANNOT_FIND_INSERT_RESULT_ADAPTER
import androidx.room.processor.ProcessorErrors.INSERT_MULTI_PARAM_SINGLE_RETURN_MISMATCH
import androidx.room.processor.ProcessorErrors.INSERT_SINGLE_PARAM_MULTI_RETURN_MISMATCH
import androidx.room.vo.InsertionMethod
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
@RunWith(JUnit4::class)
class InsertionMethodProcessorTest :
InsertOrUpsertShortcutMethodProcessorTest<InsertionMethod>(Insert::class) {
override fun noParamsError(): String = INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT
override fun missingPrimaryKey(partialEntityName: String, primaryKeyName: List<String>):
String {
return ProcessorErrors.missingPrimaryKeysInPartialEntityForInsert(
partialEntityName,
primaryKeyName
)
}
override fun noAdapter(): String = CANNOT_FIND_INSERT_RESULT_ADAPTER
override fun multiParamAndSingleReturnMismatchError():
String = INSERT_MULTI_PARAM_SINGLE_RETURN_MISMATCH
override fun singleParamAndMultiReturnMismatchError():
String = INSERT_SINGLE_PARAM_MULTI_RETURN_MISMATCH
@Test
fun onConflict_Default() {
singleInsertUpsertShortcutMethod(
"""
@Insert
abstract public void foo(User user);
"""
) { insertion, _ ->
assertThat(insertion.onConflict).isEqualTo(OnConflictStrategy.ABORT)
}
}
@Test
fun onConflict_Invalid() {
singleInsertUpsertShortcutMethod(
"""
@Insert(onConflict = -1)
abstract public void foo(User user);
"""
) { _, invocation ->
invocation.assertCompilationResult {
hasErrorContaining(
ProcessorErrors.INVALID_ON_CONFLICT_VALUE
)
}
}
}
@Test
fun onConflict_EachValue() {
listOf(
Pair("NONE", 0),
Pair("REPLACE", 1),
Pair("ROLLBACK", 2),
Pair("ABORT", 3),
Pair("FAIL", 4),
Pair("IGNORE", 5)
).forEach { pair ->
singleInsertUpsertShortcutMethod(
"""
@Insert(onConflict=OnConflictStrategy.${pair.first})
abstract public void foo(User user);
"""
) { insertion, _ ->
assertThat(insertion.onConflict).isEqualTo(pair.second)
}
}
}
override fun process(
baseContext: Context,
containing: XType,
executableElement: XMethodElement
): InsertionMethod {
return InsertionMethodProcessor(baseContext, containing, executableElement).process()
}
}
| apache-2.0 |
androidx/androidx | window/window/src/testUtil/java/androidx/window/TestConsumer.kt | 3 | 1626 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window
import androidx.core.util.Consumer
import org.junit.Assert.assertEquals
/**
* A test [Consumer] to hold all the values and make assertions based on the values.
*/
public class TestConsumer<T> : Consumer<T> {
private val values: MutableList<T> = mutableListOf()
/**
* Add the value to the list of seen values.
*/
override fun accept(t: T) {
values.add(t)
}
/**
* Assert that there have been a fixed number of values
*/
public fun assertValueCount(count: Int) {
assertEquals(count, values.size)
}
/**
* Assert that there has been exactly one value.
*/
public fun assertValue(t: T) {
assertValueCount(1)
assertEquals(t, values[0])
}
public fun assertValues(vararg expected: T) {
assertValues(expected.toList())
}
fun assertValues(expected: List<T>) {
assertValueCount(expected.size)
assertEquals(expected.toList(), values.toList())
}
}
| apache-2.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/thread/CoroutineUnitTest.kt | 1 | 1248 | package com.baeldung.thread
import kotlinx.coroutines.*
import org.junit.jupiter.api.Test
class CoroutineUnitTest {
@Test
fun whenCreateCoroutineWithLaunchWithoutContext_thenRun() = runBlocking {
val job = launch {
println("${Thread.currentThread()} has run.")
}
}
@Test
fun whenCreateCoroutineWithLaunchWithDefaultContext_thenRun() = runBlocking {
val job = launch(Dispatchers.Default) {
println("${Thread.currentThread()} has run.")
}
}
@Test
fun whenCreateCoroutineWithLaunchWithUnconfinedContext_thenRun() = runBlocking {
val job = launch(Dispatchers.Unconfined) {
println("${Thread.currentThread()} has run.")
}
}
@Test
fun whenCreateCoroutineWithLaunchWithDedicatedThread_thenRun() = runBlocking {
val job = launch(newSingleThreadContext("dedicatedThread")) {
println("${Thread.currentThread()} has run.")
}
}
@Test
fun whenCreateAsyncCoroutine_thenRun() = runBlocking {
val deferred = async(Dispatchers.IO) {
return@async "${Thread.currentThread()} has run."
}
val result = deferred.await()
println(result)
}
} | gpl-3.0 |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/SimpleComment/1.kt | 1 | 121 | fun main() {
fun1()
<selection>//this is a standalone<caret> comment</selection>
fun2()
}
fun fun1() {}
fun fun2() {} | apache-2.0 |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/listeners/BucketEmptyListener.kt | 1 | 2382 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.listeners
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.magic.BucketCode
import com.demonwav.statcraft.querydsl.QBucketEmpty
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerBucketEmptyEvent
import org.bukkit.event.player.PlayerItemConsumeEvent
class BucketEmptyListener(private val plugin: StatCraft) : Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onBucketEmpty(event: PlayerBucketEmptyEvent) {
val uuid = event.player.uniqueId
val worldName = event.player.world.name
val code: BucketCode
if (event.bucket == Material.LAVA_BUCKET) {
code = BucketCode.LAVA
} else {
// default to water
code = BucketCode.WATER
}
plugin.threadManager.schedule<QBucketEmpty>(
uuid, worldName,
{ e, clause, id, worldId ->
clause.columns(e.id, e.worldId, e.type, e.amount)
.values(id, worldId, code.code, 1).execute()
}, { e, clause, id, worldId ->
clause.where(e.id.eq(id), e.worldId.eq(worldId), e.type.eq(code.code))
.set(e.amount, e.amount.add(1)).execute()
}
)
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onPlayerConsume(event: PlayerItemConsumeEvent) {
if (event.item.type == Material.MILK_BUCKET) {
val uuid = event.player.uniqueId
val worldName = event.player.world.name
val code = BucketCode.MILK
plugin.threadManager.schedule<QBucketEmpty>(
uuid, worldName,
{ e, clause, id, worldId ->
clause.columns(e.id, e.worldId, e.type, e.amount)
.values(id, worldId, code.code, 1).execute()
}, { e, clause, id, worldId ->
clause.where(e.id.eq(id), e.worldId.eq(worldId), e.type.eq(code.code))
.set(e.amount, e.amount.add(1)).execute()
}
)
}
}
}
| mit |
hidroh/tldroid | app/src/main/kotlin/io/github/hidroh/tldroid/MarkdownProcessor.kt | 1 | 3235 | package io.github.hidroh.tldroid
import android.content.ContentProviderOperation
import android.content.Context
import android.content.OperationApplicationException
import android.os.RemoteException
import android.support.annotation.WorkerThread
import android.text.TextUtils
import com.github.rjeschke.txtmark.Processor
import java.io.File
import java.io.IOException
import java.util.zip.ZipFile
class MarkdownProcessor(private val platform: String?) {
@WorkerThread
fun process(context: Context, commandName: String, lastModified: Long): String? {
val selection = "${TldrProvider.CommandEntry.COLUMN_NAME}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_PLATFORM}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_MODIFIED}>=?"
val selectionArgs = arrayOf(commandName, platform?: "", lastModified.toString())
val cursor = context.contentResolver.query(
TldrProvider.URI_COMMAND, null, selection, selectionArgs, null)
val markdown = if (cursor != null && cursor.moveToFirst()) {
cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_TEXT))
} else {
loadFromZip(context, commandName, platform ?: findPlatform(context, commandName), lastModified)
}
cursor?.close()
return if (TextUtils.isEmpty(markdown)) null else Processor.process(markdown)
.replace("{{", """<span class="literal">""")
.replace("}}", """</span>""")
}
private fun loadFromZip(context: Context, name: String, platform: String?, lastModified: Long): String? {
platform ?: return null
val markdown: String
try {
val zip = ZipFile(File(context.cacheDir, Constants.ZIP_FILENAME), ZipFile.OPEN_READ)
markdown = Utils.readUtf8(zip.getInputStream(zip.getEntry(
Constants.COMMAND_PATH.format(platform, name))))
zip.close()
} catch (e: IOException) {
return null
} catch (e: NullPointerException) {
return null
}
persist(context, name, platform, markdown, lastModified)
return markdown
}
private fun findPlatform(context: Context, name: String): String? {
val cursor = context.contentResolver.query(TldrProvider.URI_COMMAND, null,
"${TldrProvider.CommandEntry.COLUMN_NAME}=?", arrayOf(name), null)
val platform = if (cursor != null && cursor.moveToFirst()) {
cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_PLATFORM))
} else {
null
}
cursor?.close()
return platform
}
private fun persist(context: Context, name: String, platform: String, markdown: String, lastModified: Long) {
val operations = arrayListOf(ContentProviderOperation.newUpdate(TldrProvider.URI_COMMAND)
.withValue(TldrProvider.CommandEntry.COLUMN_TEXT, markdown)
.withValue(TldrProvider.CommandEntry.COLUMN_MODIFIED, lastModified)
.withSelection("${TldrProvider.CommandEntry.COLUMN_PLATFORM}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_NAME}=?",
arrayOf(platform, name))
.build())
try {
context.contentResolver.applyBatch(TldrProvider.AUTHORITY, operations)
} catch (e: RemoteException) {
// no op
} catch (e: OperationApplicationException) {
// no op
}
}
} | apache-2.0 |
collaction/freehkkai-android | app/src/main/java/hk/collaction/freehkkai/util/ext/NumberExt.kt | 1 | 1115 | package hk.collaction.freehkkai.util.ext
import android.content.res.Resources
import android.util.TypedValue
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.roundToInt
fun Float.dp2px(): Int =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this,
Resources.getSystem().displayMetrics
).toInt()
fun Float.px2dp(): Float {
val scale = Resources.getSystem().displayMetrics.density
return (this / scale + 0.5F)
}
fun Int.px2dp() = this.toFloat().px2dp().toInt()
fun Float.px2sp(): Float {
val fontScale = Resources.getSystem().displayMetrics.density
return (this / fontScale + 0.5F)
}
fun Int.px2sp() = this.toFloat().px2sp().toInt()
fun Float.roundTo(n: Int): Float {
return this.toDouble().roundTo(n).toFloat()
}
fun Double.roundTo(n: Int): Double {
if (this.isNaN()) return 0.0
return try {
BigDecimal(this).setScale(n, RoundingMode.HALF_EVEN).toDouble()
} catch (e: NumberFormatException) {
this.roundToInt().toDouble()
}
}
fun Double.format(digits: Int) = "%.${digits}f".format(this) | gpl-3.0 |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/roomfinder/model/RoomFinderCoordinate.kt | 1 | 201 | package de.tum.`in`.tumcampusapp.component.tumui.roomfinder.model
data class RoomFinderCoordinate(
var utm_zone: String = "",
var utm_easting: String = "",
var utm_northing: String = ""
)
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/ast/xslt/XsltNextMatch.kt | 1 | 787 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xslt.ast.xslt
import com.intellij.psi.PsiElement
/**
* An XSLT 2.0 `xsl:next-match` node in the XSLT AST.
*/
interface XsltNextMatch : PsiElement
| apache-2.0 |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bike_parking_cover/AddBikeParkingCover.kt | 1 | 1199 | package de.westnordost.streetcomplete.quests.bike_parking_cover
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBikeParkingCover : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes, ways with
amenity = bicycle_parking
and access !~ private|no
and !covered
and bicycle_parking !~ shed|lockers|building
"""
override val commitMessage = "Add bicycle parkings cover"
override val wikiLink = "Tag:amenity=bicycle_parking"
override val icon = R.drawable.ic_quest_bicycle_parking_cover
override val isDeleteElementEnabled = true
override fun getTitle(tags: Map<String, String>) =
R.string.quest_bicycleParkingCoveredStatus_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("covered", answer.toYesNo())
}
}
| gpl-3.0 |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/options/ShadowOptions.kt | 1 | 1822 | package com.reactnativenavigation.options
import android.content.Context
import com.reactnativenavigation.options.params.Fraction
import com.reactnativenavigation.options.params.NullFraction
import com.reactnativenavigation.options.params.NullThemeColour
import com.reactnativenavigation.options.params.ThemeColour
import com.reactnativenavigation.options.parsers.FractionParser
import org.json.JSONObject
fun parseShadowOptions(context: Context, shadowJson: JSONObject?): ShadowOptions = shadowJson?.let { json ->
ShadowOptions(
ThemeColour.parse(context, json.optJSONObject("color")), FractionParser.parse(json, "radius"),
FractionParser
.parse(
json,
"opacity"
)
)
} ?: NullShadowOptions
object NullShadowOptions : ShadowOptions() {
override fun hasValue(): Boolean = false
}
open class ShadowOptions(
var color: ThemeColour = NullThemeColour(), var radius: Fraction = NullFraction(), var opacity: Fraction =
NullFraction()
) {
fun copy(): ShadowOptions = ShadowOptions(this.color, this.radius, this.opacity)
fun mergeWith(other: ShadowOptions): ShadowOptions {
if(other.color.hasValue()) this.color = other.color;
if (other.opacity.hasValue()) this.opacity = other.opacity
if (other.radius.hasValue()) this.radius = other.radius
return this
}
fun mergeWithDefaults(defaultOptions: ShadowOptions = NullShadowOptions): ShadowOptions {
if(!this.color.hasValue()) this.color = defaultOptions.color;
if (!this.opacity.hasValue()) this.opacity = defaultOptions.opacity
if (!this.radius.hasValue()) this.radius = defaultOptions.radius
return this
}
open fun hasValue() = color.hasValue() || radius.hasValue() || opacity.hasValue()
} | mit |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/AttachPhotoFragment.kt | 1 | 5890 | package de.westnordost.streetcomplete.quests.note_discussion
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.ArrayList
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osmnotes.AttachPhotoUtils
import android.app.Activity.RESULT_OK
import de.westnordost.streetcomplete.ApplicationConstants.ATTACH_PHOTO_MAXWIDTH
import de.westnordost.streetcomplete.ApplicationConstants.ATTACH_PHOTO_QUALITY
import de.westnordost.streetcomplete.ktx.toast
import kotlinx.android.synthetic.main.fragment_attach_photo.*
class AttachPhotoFragment : Fragment() {
val imagePaths: List<String> get() = noteImageAdapter.list
private var currentImagePath: String? = null
private lateinit var noteImageAdapter: NoteImageAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_attach_photo, container, false)
if (!activity!!.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
view.visibility = View.GONE
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
takePhotoButton.setOnClickListener { takePhoto() }
val paths: ArrayList<String>
if (savedInstanceState != null) {
paths = savedInstanceState.getStringArrayList(PHOTO_PATHS)!!
currentImagePath = savedInstanceState.getString(CURRENT_PHOTO_PATH)
} else {
paths = ArrayList()
currentImagePath = null
}
noteImageAdapter = NoteImageAdapter(paths, context!!)
gridView.layoutManager = LinearLayoutManager(
context,
LinearLayoutManager.HORIZONTAL,
false
)
gridView.adapter = noteImageAdapter
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putStringArrayList(PHOTO_PATHS, ArrayList(imagePaths))
outState.putString(CURRENT_PHOTO_PATH, currentImagePath)
}
private fun takePhoto() {
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
activity?.packageManager?.let { packageManager ->
if (takePhotoIntent.resolveActivity(packageManager) != null) {
try {
val photoFile = createImageFile()
val photoUri = if (Build.VERSION.SDK_INT > 21) {
//Use FileProvider for getting the content:// URI, see: https://developer.android.com/training/camera/photobasics.html#TaskPath
FileProvider.getUriForFile(activity!!,getString(R.string.fileprovider_authority),photoFile)
} else {
Uri.fromFile(photoFile)
}
currentImagePath = photoFile.path
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO)
} catch (e: IOException) {
Log.e(TAG, "Unable to create file for photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Unable to create file for photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_TAKE_PHOTO) {
if (resultCode == RESULT_OK) {
try {
val path = currentImagePath!!
val bitmap = AttachPhotoUtils.resize(path, ATTACH_PHOTO_MAXWIDTH) ?: throw IOException()
val out = FileOutputStream(path)
bitmap.compress(Bitmap.CompressFormat.JPEG, ATTACH_PHOTO_QUALITY, out)
noteImageAdapter.list.add(path)
noteImageAdapter.notifyItemInserted(imagePaths.size - 1)
} catch (e: IOException) {
Log.e(TAG, "Unable to rescale the photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
removeCurrentImage()
}
} else {
removeCurrentImage()
}
currentImagePath = null
}
}
private fun removeCurrentImage() {
currentImagePath?.let {
val photoFile = File(it)
if (photoFile.exists()) {
photoFile.delete()
}
}
}
private fun createImageFile(): File {
val directory = activity!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile("photo", ".jpg", directory)
}
fun deleteImages() {
AttachPhotoUtils.deleteImages(imagePaths)
}
companion object {
private const val TAG = "AttachPhotoFragment"
private const val REQUEST_TAKE_PHOTO = 1
private const val PHOTO_PATHS = "photo_paths"
private const val CURRENT_PHOTO_PATH = "current_photo_path"
}
}
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathPragma.kt | 1 | 817 | /*
* Copyright (C) 2016, 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.ast.xpath
import com.intellij.psi.PsiLanguageInjectionHost
/**
* An XQuery 1.0 `Pragma` node in the XQuery AST.
*/
interface XPathPragma : PsiLanguageInjectionHost
| apache-2.0 |
huy-vuong/streamr | app/src/main/java/com/huyvuong/streamr/model/transport/photos/exif/GetExifResponse.kt | 1 | 1109 | package com.huyvuong.streamr.model.transport.photos.exif
import com.google.gson.annotations.SerializedName
/**
* Response from flickr.photos.getExif.
*/
data class GetExifResponse(
@SerializedName("photo") val exifSummary: ExifSummary,
@SerializedName("stat") val status: String,
@SerializedName("code") val code: Int)
data class ExifSummary(
@SerializedName("id") val photoId: String,
@SerializedName("camera") val camera: String,
@SerializedName("exif") val exifEntries: List<ExifEntry>) {
operator fun contains(tag: String): Boolean {
return exifEntries.any { it.tag == tag }
}
operator fun get(tag: String): String? {
return exifEntries.firstOrNull { it.tag == tag }?.rawContent?.content
}
}
data class ExifEntry(
@SerializedName("tag") val tag: String,
@SerializedName("label") val label: String,
@SerializedName("raw") val rawContent: ExifContent,
@SerializedName("clean") val cleanContent: ExifContent? = null)
data class ExifContent(@SerializedName("_content") val content: String) | gpl-3.0 |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/box2d/temp_components/wheel/BaseWheelImpl.kt | 1 | 2320 | package lt.markmerkk.app.box2d.temp_components.wheel
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import lt.markmerkk.app.box2d.CarBox2D
/**
* @author mariusmerkevicius
* @since 2016-08-28
*/
abstract class BaseWheelImpl(
override val world: World,
override val carBox2D: CarBox2D,
override var posX: Float,
override var posY: Float,
override val width: Float,
override val height: Float,
override val powered: Boolean
) : Wheel {
override val body: Body
init {
//init body
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.DynamicBody
bodyDef.position.set(carBox2D.body.getWorldPoint(Vector2(posX, posY)))
bodyDef.angle = carBox2D.body.angle
this.body = world.createBody(bodyDef)
//init shape
val fixtureDef = FixtureDef()
fixtureDef.density = 1.0f
fixtureDef.isSensor = true
val wheelShape = PolygonShape()
wheelShape.setAsBox(width / 2, height / 2)
fixtureDef.shape = wheelShape
this.body.createFixture(fixtureDef)
wheelShape.dispose()
initJoint(world, carBox2D)
}
abstract fun initJoint(world: World, carBox2D: CarBox2D)
override fun localVelocity(): Vector2 {
return carBox2D.body.getLocalVector(carBox2D.body.getLinearVelocityFromLocalPoint(body.position))
}
override fun directionVector(): Vector2 {
val directionVector: Vector2
if (localVelocity().y > 0)
directionVector = Vector2(0f, 1f)
else
directionVector = Vector2(0f, -1f)
return directionVector.rotate(Math.toDegrees(body.angle.toDouble()).toFloat())
}
override fun changeAngle(angle: Float) {
body.setTransform(body.position, carBox2D.body.angle + Math.toRadians(angle.toDouble()).toFloat())
}
override fun killSidewayVector() {
body.linearVelocity = killedLocalVelocity()
}
//region Convenience
private fun killedLocalVelocity(): Vector2 {
val velocity = body.linearVelocity
val sidewaysAxis = directionVector()
val dotprod = velocity.dot(sidewaysAxis)
return Vector2(sidewaysAxis.x * dotprod, sidewaysAxis.y * dotprod)
}
//endregion
} | apache-2.0 |
tommybuonomo/dotsindicator | viewpagerdotsindicator/src/main/kotlin/com/tbuonomo/viewpagerdotsindicator/BaseDotsIndicator.kt | 1 | 7025 | package com.tbuonomo.viewpagerdotsindicator
import android.content.Context
import android.graphics.Color
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.StyleableRes
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.tbuonomo.viewpagerdotsindicator.attacher.ViewPager2Attacher
import com.tbuonomo.viewpagerdotsindicator.attacher.ViewPagerAttacher
abstract class BaseDotsIndicator @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
companion object {
const val DEFAULT_POINT_COLOR = Color.CYAN
}
enum class Type(
val defaultSize: Float,
val defaultSpacing: Float,
@StyleableRes val styleableId: IntArray,
@StyleableRes val dotsColorId: Int,
@StyleableRes val dotsSizeId: Int,
@StyleableRes val dotsSpacingId: Int,
@StyleableRes val dotsCornerRadiusId: Int,
@StyleableRes val dotsClickableId: Int
) {
DEFAULT(
16f,
8f,
R.styleable.SpringDotsIndicator,
R.styleable.SpringDotsIndicator_dotsColor,
R.styleable.SpringDotsIndicator_dotsSize,
R.styleable.SpringDotsIndicator_dotsSpacing,
R.styleable.SpringDotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
),
SPRING(
16f,
4f,
R.styleable.DotsIndicator,
R.styleable.DotsIndicator_dotsColor,
R.styleable.DotsIndicator_dotsSize,
R.styleable.DotsIndicator_dotsSpacing,
R.styleable.DotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
),
WORM(
16f,
4f,
R.styleable.WormDotsIndicator,
R.styleable.WormDotsIndicator_dotsColor,
R.styleable.WormDotsIndicator_dotsSize,
R.styleable.WormDotsIndicator_dotsSpacing,
R.styleable.WormDotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
)
}
@JvmField
protected val dots = ArrayList<ImageView>()
var dotsClickable: Boolean = true
var dotsColor: Int = DEFAULT_POINT_COLOR
set(value) {
field = value
refreshDotsColors()
}
protected var dotsSize = dpToPxF(type.defaultSize)
protected var dotsCornerRadius = dotsSize / 2f
protected var dotsSpacing = dpToPxF(type.defaultSpacing)
init {
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs, type.styleableId)
dotsColor = a.getColor(type.dotsColorId, DEFAULT_POINT_COLOR)
dotsSize = a.getDimension(type.dotsSizeId, dotsSize)
dotsCornerRadius = a.getDimension(type.dotsCornerRadiusId, dotsCornerRadius)
dotsSpacing = a.getDimension(type.dotsSpacingId, dotsSpacing)
dotsClickable = a.getBoolean(type.dotsClickableId, true)
a.recycle()
}
}
var pager: Pager? = null
interface Pager {
val isNotEmpty: Boolean
val currentItem: Int
val isEmpty: Boolean
val count: Int
fun setCurrentItem(item: Int, smoothScroll: Boolean)
fun removeOnPageChangeListener()
fun addOnPageChangeListener(onPageChangeListenerHelper: OnPageChangeListenerHelper)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
post { refreshDots() }
}
private fun refreshDotsCount() {
if (dots.size < pager!!.count) {
addDots(pager!!.count - dots.size)
} else if (dots.size > pager!!.count) {
removeDots(dots.size - pager!!.count)
}
}
protected fun refreshDotsColors() {
for (i in dots.indices) {
refreshDotColor(i)
}
}
protected fun dpToPx(dp: Int): Int {
return (context.resources.displayMetrics.density * dp).toInt()
}
protected fun dpToPxF(dp: Float): Float {
return context.resources.displayMetrics.density * dp
}
protected fun addDots(count: Int) {
for (i in 0 until count) {
addDot(i)
}
}
private fun removeDots(count: Int) {
for (i in 0 until count) {
removeDot()
}
}
fun refreshDots() {
if (pager == null) {
return
}
post {
// Check if we need to refresh the dots count
refreshDotsCount()
refreshDotsColors()
refreshDotsSize()
refreshOnPageChangedListener()
}
}
private fun refreshOnPageChangedListener() {
if (pager!!.isNotEmpty) {
pager!!.removeOnPageChangeListener()
val onPageChangeListenerHelper = buildOnPageChangedListener()
pager!!.addOnPageChangeListener(onPageChangeListenerHelper)
onPageChangeListenerHelper.onPageScrolled(pager!!.currentItem, 0f)
}
}
private fun refreshDotsSize() {
dots.forEach { it.setWidth(dotsSize.toInt()) }
}
// ABSTRACT METHODS AND FIELDS
abstract fun refreshDotColor(index: Int)
abstract fun addDot(index: Int)
abstract fun removeDot()
abstract fun buildOnPageChangedListener(): OnPageChangeListenerHelper
abstract val type: Type
// PUBLIC METHODS
@Deprecated(
"Use setDotsColors(color) instead", ReplaceWith("setDotsColors(color)")
)
fun setPointsColor(color: Int) {
dotsColor = color
refreshDotsColors()
}
@Deprecated(
"Use attachTo(viewPager) instead", ReplaceWith("attachTo(viewPager)")
)
fun setViewPager(viewPager: ViewPager) {
ViewPagerAttacher().setup(this, viewPager)
}
@Deprecated(
"Use attachTo(viewPager) instead", ReplaceWith("attachTo(viewPager)")
)
fun setViewPager2(viewPager2: ViewPager2) {
ViewPager2Attacher().setup(this, viewPager2)
}
fun attachTo(viewPager: ViewPager) {
ViewPagerAttacher().setup(this, viewPager)
}
fun attachTo(viewPager2: ViewPager2) {
ViewPager2Attacher().setup(this, viewPager2)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1 && layoutDirection == View.LAYOUT_DIRECTION_RTL) {
layoutDirection = View.LAYOUT_DIRECTION_LTR
rotation = 180f
requestLayout()
}
}
override fun onRestoreInstanceState(state: Parcelable?) {
super.onRestoreInstanceState(state)
post { refreshDots() }
}
} | apache-2.0 |
ncruz8991/kotlin-koans | src/ii_collections/_14_FilterMap.kt | 1 | 537 | package ii_collections
fun example1(list: List<Int>) {
// If a lambda has exactly one parameter, that parameter can be accessed as 'it'
val positiveNumbers = list.filter { it > 0 }
val squares = list.map { it * it }
}
// Return the set of cities the customers are from
fun Shop.getCitiesCustomersAreFrom(): Set<City> = this.customers.map { it.city } .toSet()
// Return a list of the customers who live in the given city
fun Shop.getCustomersFrom(city: City): List<Customer> = this.customers.filter { it.city == city }
| mit |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowmapper/gui/preview/GlListener.kt | 1 | 6335 | package nl.shadowlink.tools.shadowmapper.gui.preview
import com.jogamp.opengl.*
import com.jogamp.opengl.fixedfunc.GLMatrixFunc
import com.jogamp.opengl.glu.GLU
import nl.shadowlink.tools.io.ByteReader
import nl.shadowlink.tools.shadowlib.model.model.Model
import nl.shadowlink.tools.shadowlib.texturedic.TextureDic
import nl.shadowlink.tools.shadowmapper.FileManager
import nl.shadowlink.tools.shadowmapper.render.Camera
import nl.shadowlink.tools.shadowmapper.utils.toGl
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.MouseWheelEvent
/**
* @author Shadow-Link
*/
class GlListener : GLEventListener {
var fm: FileManager? = null
var camera: Camera? = null
private var modelZoom = -20.0f
private var rotationX = 0.0f
private var rotationY = 0.0f
private var dragX = -1
private var dragY = -1
var mdl: Model? = Model()
var txd: TextureDic? = null
// public WBDFile wbd;
// public WBNFile wbn;
var type = -1
var size = -1
var br: ByteReader? = null
var load = false
private var selected = 0
private var selPoly = 0
fun mouseWheelMoved(evt: MouseWheelEvent) {
if (evt.scrollType == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
modelZoom -= (evt.wheelRotation / 1.5).toFloat()
}
}
fun mousePressed(evt: MouseEvent) {
dragX = evt.x
dragY = evt.y
}
fun keyPressed(evt: KeyEvent) {
if (evt.keyCode == KeyEvent.VK_UP) {
selPoly += 1
}
if (evt.keyCode == KeyEvent.VK_DOWN) {
selPoly -= 1
}
if (evt.keyCode == KeyEvent.VK_P) {
println("Sel poly: $selPoly")
}
}
fun mouseMoved(evt: MouseEvent) {
if (evt.modifiers == 4) {
val newX = dragX - evt.x
val newY = dragY - evt.y
dragX = evt.x
dragY = evt.y
rotationX += newX.toFloat()
rotationY += newY.toFloat()
}
}
private var txdArray: IntArray? = null
private fun loadModel(gl: GL2) {
mdl = null
mdl = Model()
when (type) {
0 -> mdl!!.loadWDR(br, size)
1 -> mdl!!.loadWFT(br, size)
2 -> mdl!!.loadWDD(br, size, null)
3 -> txdArray = txd!!.toGl(gl)
4 -> {}
5 -> {}
}
load = false
}
fun loadTxdIntoGl(txd: TextureDic?) {
this.txd = txd
type = 3
load = true
}
override fun display(drawable: GLAutoDrawable) {
val gl = drawable.gl.gL2
val glu = GLU()
if (load) {
loadModel(gl)
}
gl.glClear(GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
glu.gluLookAt(
camera!!.posX, camera!!.posY, camera!!.posZ, camera!!.viewX, camera!!.viewY,
camera!!.viewZ, camera!!.upX, camera!!.upY, camera!!.upZ
)
gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL)
if (type == 3 && txdArray != null) {
val height = 512
val width = 512
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0.0, height.toDouble(), 0.0, width.toDouble(), -1.0, 1.0)
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glTranslatef(0f, 512f, 0f)
gl.glRotatef(-90f, 0.0f, 0.0f, 1.0f)
// TODO: Fix this
gl.glBindTexture(GL.GL_TEXTURE_2D, txdArray!![selected])
gl.glBegin(GL2ES3.GL_QUADS)
gl.glTexCoord2d(0.0, 0.0)
gl.glVertex2f(0f, 0f)
gl.glTexCoord2d(0.0, 1.0)
gl.glVertex2f(txd!!.textures[selected].height.toFloat(), 0f)
gl.glTexCoord2d(1.0, 1.0)
gl.glVertex2f(txd!!.textures[selected].height.toFloat(), txd!!.textures[selected].width.toFloat())
gl.glTexCoord2d(1.0, 0.0)
gl.glVertex2f(0f, txd!!.textures[selected].width.toFloat())
gl.glEnd()
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW)
gl.glPopMatrix()
} else if (type == 4 || type == 5) {
// Do nothing yet
} else {
gl.glPushMatrix()
gl.glTranslatef(0f, 2f, modelZoom)
gl.glRotatef(270f, 1.0f, 0.0f, 0.0f)
gl.glRotatef(rotationX, 0.0f, 0.0f, 1.0f)
gl.glRotatef(rotationY, 0.0f, 1.0f, 0.0f)
gl.glColor3f(1.0f, 1.0f, 1.0f)
if (mdl!!.isLoaded) {
mdl!!.render(gl)
}
gl.glPopMatrix()
}
gl.glFlush()
}
override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) {
var height = height
val gl = drawable.gl.gL2
val glu = GLU()
if (height <= 0) { // avoid a divide by zero error!
height = 1
}
val h = width.toFloat() / height.toFloat()
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(GL2.GL_PROJECTION)
gl.glLoadIdentity()
glu.gluPerspective(45.0, h.toDouble(), 0.1, 1000.0)
gl.glMatrixMode(GL2.GL_MODELVIEW)
gl.glLoadIdentity()
}
override fun init(drawable: GLAutoDrawable) {
val glProfile = GLProfile.getDefault()
val caps = GLCapabilities(glProfile)
caps.hardwareAccelerated = true
caps.doubleBuffered = true
val gl = drawable.gl.gL2
System.err.println("INIT GL IS: " + gl.javaClass.name)
gl.glClearColor(0.250f, 0.250f, 0.250f, 0.0f)
gl.glEnable(GL.GL_TEXTURE_2D)
gl.glEnable(GL2.GL_DEPTH_TEST)
gl.glEnable(GL2.GL_CULL_FACE)
gl.glCullFace(GL2.GL_BACK)
gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL)
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(GL2.GL_BLEND)
// gl.glDisable(gl.GL_COLOR_MATERIAL);
camera = Camera(0f, 2f, 5f, 0f, 2.5f, 0f, 0f, 1f, 0f)
}
fun setSelected(sel: Int) {
selected = sel
}
override fun dispose(arg0: GLAutoDrawable) {
// TODO Auto-generated method stub
}
} | gpl-2.0 |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/browse/components/BrowseSourceDialogs.kt | 1 | 1273 | package eu.kanade.presentation.browse.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.R
@Composable
fun RemoveMangaDialog(
onDismissRequest: () -> Unit,
onConfirm: () -> Unit,
mangaToRemove: Manga,
) {
AlertDialog(
onDismissRequest = onDismissRequest,
dismissButton = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(android.R.string.cancel))
}
},
confirmButton = {
TextButton(
onClick = {
onDismissRequest()
onConfirm()
},
) {
Text(text = stringResource(R.string.action_remove))
}
},
title = {
Text(text = stringResource(R.string.are_you_sure))
},
text = {
Text(text = stringResource(R.string.remove_manga, mangaToRemove.title))
},
)
}
| apache-2.0 |
Heiner1/AndroidAPS | danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.kt | 1 | 511 | package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.danar.comm.MsgSettingMeal
import org.junit.Assert
import org.junit.Test
class MsgSettingMealTest : DanaRTestBase() {
@Test fun runTest() {
val packet = MsgSettingMeal(injector)
// test message decoding
packet.handleMessage(createArray(34, 1.toByte()))
Assert.assertEquals(packet.intFromBuff(createArray(10, 1.toByte()), 0, 1).toDouble() / 100.0, danaPump.bolusStep, 0.0)
}
} | agpl-3.0 |
jainsahab/AndroidSnooper | Snooper/src/main/java/com/prateekj/snooper/dbreader/view/DbReaderCallback.kt | 1 | 217 | package com.prateekj.snooper.dbreader.view
import com.prateekj.snooper.dbreader.model.Database
interface DbReaderCallback {
fun onDbFetchStarted()
fun onApplicationDbFetchCompleted(databases: List<Database>)
}
| apache-2.0 |
trevorwang/github-client-android | app/src/main/java/mingsin/github/LanguageUtility.kt | 1 | 785 | package mingsin.github
import android.content.Context
import android.support.v4.util.ArrayMap
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.orhanobut.logger.Logger
import java.io.InputStreamReader
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by trevorwang on 20/12/2016.
*/
@Singleton
class LanguageUtility @Inject constructor(val context: Context) {
var colorConfig: ArrayMap<String, String>
val gsonType = object : TypeToken<ArrayMap<String, String>>() {}.type
init {
val istream = context.resources.openRawResource(R.raw.language_colors)
val cc = InputStreamReader(istream)
colorConfig = Gson().fromJson<ArrayMap<String, String>>(cc, gsonType)
Logger.d(colorConfig)
}
} | mit |
jgrandja/spring-security | config/src/test/kotlin/org/springframework/security/config/web/server/AuthorizeExchangeDslTests.kt | 2 | 5877 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService
import org.springframework.security.core.userdetails.User
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.reactive.config.EnableWebFlux
import java.util.*
/**
* Tests for [AuthorizeExchangeDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class AuthorizeExchangeDslTests {
@JvmField
val spring = SpringTestContext(this)
private lateinit var client: WebTestClient
@Autowired
fun setup(context: ApplicationContext) {
this.client = WebTestClient
.bindToApplicationContext(context)
.configureClient()
.build()
}
@Test
fun `request when secured by matcher then responds with unauthorized`() {
this.spring.register(MatcherAuthenticatedConfig::class.java).autowire()
this.client.get()
.uri("/")
.exchange()
.expectStatus().isUnauthorized
}
@EnableWebFluxSecurity
@EnableWebFlux
open class MatcherAuthenticatedConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
}
}
}
@Test
fun `request when allowed by matcher then responds with ok`() {
this.spring.register(MatcherPermitAllConfig::class.java).autowire()
this.client.get()
.uri("/")
.exchange()
.expectStatus().isOk
}
@EnableWebFluxSecurity
@EnableWebFlux
open class MatcherPermitAllConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, permitAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/")
fun path() {
}
}
}
@Test
fun `request when secured by pattern then responds with unauthorized`() {
this.spring.register(PatternAuthenticatedConfig::class.java).autowire()
this.client.get()
.uri("/")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `request when allowed by pattern then responds with ok`() {
this.spring.register(PatternAuthenticatedConfig::class.java).autowire()
this.client.get()
.uri("/public")
.exchange()
.expectStatus().isOk
}
@EnableWebFluxSecurity
@EnableWebFlux
open class PatternAuthenticatedConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize("/public", permitAll)
authorize("/**", authenticated)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/public")
fun public() {
}
}
}
@Test
fun `request when missing required role then responds with forbidden`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.client
.get()
.uri("/")
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString("user:password".toByteArray()))
.exchange()
.expectStatus().isForbidden
}
@EnableWebFluxSecurity
@EnableWebFlux
open class HasRoleConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, hasRole("ADMIN"))
}
httpBasic { }
}
}
@Bean
open fun userDetailsService(): MapReactiveUserDetailsService {
val user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
return MapReactiveUserDetailsService(user)
}
}
}
| apache-2.0 |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/DrawerMenu.kt | 1 | 1287 | package com.sjn.stamp.ui
import android.support.v4.app.Fragment
import com.sjn.stamp.R
import com.sjn.stamp.ui.fragment.SettingFragment
import com.sjn.stamp.ui.fragment.media.*
enum class DrawerMenu(val menuId: Int) {
HOME(R.id.navigation_home) {
override val fragment: Fragment
get() = AllSongPagerFragment()
},
TIMELINE(R.id.navigation_timeline) {
override val fragment: Fragment
get() = TimelineFragment()
},
QUEUE(R.id.navigation_queue) {
override val fragment: Fragment
get() = QueueListFragment()
},
STAMP(R.id.navigation_stamp) {
override val fragment: Fragment
get() = StampPagerFragment()
},
RANKING(R.id.navigation_ranking) {
override val fragment: Fragment
get() = RankingPagerFragment()
},
SETTING(R.id.navigation_setting) {
override val fragment: Fragment
get() = SettingFragment()
};
abstract val fragment: Fragment
companion object {
fun of(menuId: Int): DrawerMenu? = DrawerMenu.values().firstOrNull { it.menuId == menuId }
fun of(menuId: Long): DrawerMenu? = DrawerMenu.values().firstOrNull { it.menuId.toLong() == menuId }
fun first(): DrawerMenu = HOME
}
}
| apache-2.0 |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSubEntityImpl.kt | 3 | 10332 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSubEntityImpl: ChildSubEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSubEntity::class.java, ChildSubEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ChildSubEntity::class.java, ChildSubSubEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
CHILD_CONNECTION_ID,
)
}
override val parentEntity: ParentSubEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override val child: ChildSubSubEntity
get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSubEntityData?): ModifiableWorkspaceEntityBase<ChildSubEntity>(), ChildSubEntity.Builder {
constructor(): this(ChildSubEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSubEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSubEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSubEntity#parentEntity should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildSubEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneChild<WorkspaceEntityBase>(CHILD_CONNECTION_ID, this) == null) {
error("Field ChildSubEntity#child should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] == null) {
error("Field ChildSubEntity#child should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: ParentSubEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSubEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSubEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var child: ChildSubSubEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildSubSubEntity
} else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildSubSubEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override fun getEntityData(): ChildSubEntityData = result ?: super.getEntityData() as ChildSubEntityData
override fun getEntityClass(): Class<ChildSubEntity> = ChildSubEntity::class.java
}
}
class ChildSubEntityData : WorkspaceEntityData<ChildSubEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSubEntity> {
val modifiable = ChildSubEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSubEntity {
val entity = ChildSubEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSubEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSubEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSubEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 |
onoderis/failchat | src/test/kotlin/failchat/handlers/SemicolonCodeProcessorTest.kt | 2 | 2372 | package failchat.handlers
import failchat.emoticon.ReplaceDecision
import failchat.emoticon.SemicolonCodeProcessor
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
class SemicolonCodeProcessorTest {
@Test
fun emptyString() {
val initialString = ""
val processedString = SemicolonCodeProcessor.process(initialString) {
error("shouldn't be invoked")
}
assertSame(initialString, processedString)
}
@Test
fun justSemicolons() {
val initialString = ":::::::::"
val processedString = SemicolonCodeProcessor.process(initialString) {
error("shouldn't be invoked")
}
assertSame(initialString, processedString)
}
@Test
fun replaceSingleCode() {
val processedString = SemicolonCodeProcessor.process(":code:") {
assertEquals("code", it)
ReplaceDecision.Replace("42")
}
assertEquals("42", processedString)
}
@Test
fun replaceSingleCodeAroundText() {
val processedString = SemicolonCodeProcessor.process("text1 :code: text2") {
assertEquals("code", it)
ReplaceDecision.Replace("42")
}
assertEquals("text1 42 text2", processedString)
}
@Test
fun skipSingleCode() {
val initialString = ":code:"
val processedString = SemicolonCodeProcessor.process(initialString) {
assertEquals("code", it)
ReplaceDecision.Skip
}
assertSame(initialString, processedString)
}
@Test
fun replaceMultipleCodes() {
val codes = mutableListOf<String>()
val processedString = SemicolonCodeProcessor.process("hello :one: :two: :)") {
codes.add(it)
ReplaceDecision.Replace("1")
}
assertEquals(listOf("one", "two"), codes)
assertEquals("hello 1 1 :)", processedString)
}
@Test
fun semicolonHell() {
val codes = mutableListOf<String>()
val processedString = SemicolonCodeProcessor.process(":w:wrong:right:w:w:") {
codes.add(it)
if (it == "right") ReplaceDecision.Replace("1") else ReplaceDecision.Skip
}
assertEquals(listOf("w", "wrong", "right", "w"), codes)
assertEquals(":w:wrong1w:w:", processedString)
}
}
| gpl-3.0 |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo14.kt | 2 | 1237 | package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.ServerSettingsSerializer
import com.fsck.k9.preferences.Protocols
/**
* Rewrite 'folderPushMode' value of non-IMAP accounts to 'NONE'.
*/
class StorageMigrationTo14(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
private val serverSettingsSerializer = ServerSettingsSerializer()
fun disablePushFoldersForNonImapAccounts() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
disablePushFolders(accountUuid)
}
}
private fun disablePushFolders(accountUuid: String) {
val json = migrationsHelper.readValue(db, "$accountUuid.incomingServerSettings") ?: return
val serverSettings = serverSettingsSerializer.deserialize(json)
if (serverSettings.type != Protocols.IMAP) {
migrationsHelper.writeValue(db, "$accountUuid.folderPushMode", "NONE")
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.