repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
webscene/webscene-client | src/main/kotlin/org/webscene/client/html/element/LinkElement.kt | 1 | 1717 | package org.webscene.client.html.element
import org.w3c.dom.Element
/**
* Represents a HTML **a** (anchor - also known as a link) element.
*/
class LinkElement : ParentHtmlElement() {
@Suppress("RedundantSetter")
override var tagName: String
get() = "a"
set(value) {}
/**
* The filename. Specifies that the target will be downloaded when a user clicks on the hyperlink if set
* (not empty).
*/
var download: String = ""
/**
* Specifies the URL of the page the link goes to.
*/
var href: String = ""
/**
* Specifies the language of the linked document.
*/
var hrefLang: String = ""
/**
* Specifies what media/device the linked document is optimized for.
*/
var media: String = ""
/**
* Specifies the relationship between the current document and the linked document.
*/
var rel: LinkRelationship = LinkRelationship.NONE
var target: String = ""
var type = ""
private fun updateAttributes() {
if (download.isNotEmpty()) attributes["download"] = download
if (href.isNotEmpty()) attributes["href"] = href
if (hrefLang.isNotEmpty()) attributes["hreflang"] = hrefLang
if (media.isNotEmpty()) attributes["media"] = media
if (rel != LinkRelationship.NONE) attributes["rel"] = rel.txt
if (target.isNotEmpty()) attributes["target"] = target
if (type.isNotEmpty()) attributes["type"] = type
}
override fun toDomElement(): Element {
updateAttributes()
return super.toDomElement()
}
override fun createText(indent: Int): String {
updateAttributes()
return super.createText(indent)
}
} | apache-2.0 | 8443758c2f0758e62c1f14da97168261 | 29.678571 | 108 | 0.620268 | 4.368957 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/client/google/GcToolResults.kt | 1 | 8871 | package ftl.client.google
import com.google.api.services.toolresults.ToolResults
import com.google.api.services.toolresults.model.Environment
import com.google.api.services.toolresults.model.Execution
import com.google.api.services.toolresults.model.History
import com.google.api.services.toolresults.model.ListEnvironmentsResponse
import com.google.api.services.toolresults.model.ListStepsResponse
import com.google.api.services.toolresults.model.ListTestCasesResponse
import com.google.api.services.toolresults.model.PerfMetricsSummary
import com.google.api.services.toolresults.model.Step
import com.google.api.services.toolresults.model.TestCase
import com.google.testing.model.TestExecution
import com.google.testing.model.ToolResultsExecution
import com.google.testing.model.ToolResultsHistory
import com.google.testing.model.ToolResultsStep
import ftl.args.IArgs
import ftl.config.FtlConstants
import ftl.config.FtlConstants.JSON_FACTORY
import ftl.config.FtlConstants.applicationName
import ftl.config.FtlConstants.httpTransport
import ftl.http.executeWithRetry
import ftl.run.exception.FTLProjectError
import ftl.run.exception.FailureToken
import ftl.run.exception.FlankGeneralError
import ftl.run.exception.PermissionDenied
import ftl.run.exception.ProjectNotFound
object GcToolResults {
val service: ToolResults by lazy {
val builder = ToolResults.Builder(httpTransport, JSON_FACTORY, httpCredential)
if (FtlConstants.useMock) builder.rootUrl = FtlConstants.localhost
builder.setApplicationName(applicationName)
.build()
}
// https://github.com/bootstraponline/gcloud_cli/blob/0752e88b155a417a18d244c242b4ab3fb9aa1c1f/google-cloud-sdk/lib/googlecloudsdk/api_lib/firebase/test/history_picker.py#L45
private fun listHistoriesByName(args: IArgs): List<History> {
val result = service
.projects()
.histories()
.list(args.project)
.setFilterByName(args.resultsHistoryName)
.executeWithRetry()
return result?.histories ?: emptyList()
}
private fun createHistory(args: IArgs): History {
val history = History()
.setName(args.resultsHistoryName)
.setDisplayName(args.resultsHistoryName)
return service
.projects()
.histories()
.create(args.project, history)
.execute()
}
fun createToolResultsHistory(args: IArgs): ToolResultsHistory {
return ToolResultsHistory()
.setHistoryId(createHistoryId(args))
.setProjectId(args.project)
}
private fun createHistoryId(args: IArgs): String? {
if (args.resultsHistoryName == null) return null
val histories = listHistoriesByName(args)
if (histories.isNotEmpty()) return histories.first().historyId
return createHistory(args).historyId
}
// FetchMatrixRollupOutcome - https://github.com/bootstraponline/gcloud_cli/blob/137d864acd5928baf25434cf59b0225c4d1f9319/google-cloud-sdk/lib/googlecloudsdk/api_lib/firebase/test/results_summary.py#L122
// Get the rolled-up outcome for a test execution from the Tool Results service.
// Prefer execution rollUp outcome over individual step outcome
// https://github.com/bootstraponline/gcloud_cli/blob/137d864acd5928baf25434cf59b0225c4d1f9319/google-cloud-sdk/lib/googlecloudsdk/third_party/apis/toolresults_v1beta3.json#L992
fun getExecutionResult(testExecution: TestExecution): Execution {
val toolResultsStep = testExecution.toolResultsStep
// Toolresults.Projects.Histories.Executions.GetRequest
return service
.projects()
.histories()
.executions()
.get(
toolResultsStep.projectId,
toolResultsStep.historyId,
toolResultsStep.executionId
)
.executeWithRetry()
}
fun getStepResult(toolResultsStep: ToolResultsStep): Step {
return service
.projects()
.histories()
.executions()
.steps()
.get(
toolResultsStep.projectId,
toolResultsStep.historyId,
toolResultsStep.executionId,
toolResultsStep.stepId
)
.executeWithRetry()
}
fun getPerformanceMetric(
toolResultsStep: ToolResultsStep
): PerfMetricsSummary = service
.projects()
.histories()
.executions()
.steps()
.getPerfMetricsSummary(
toolResultsStep.projectId,
toolResultsStep.historyId,
toolResultsStep.executionId,
toolResultsStep.stepId
)
.executeWithRetry()
// Lists Test Cases attached to a Step
fun listTestCases(
toolResultsStep: ToolResultsStep,
pageToken: String? = null
): ListTestCasesResponse {
return service
.projects()
.histories()
.executions()
.steps()
.testCases()
.list(
toolResultsStep.projectId,
toolResultsStep.historyId,
toolResultsStep.executionId,
toolResultsStep.stepId
)
.setPageToken(pageToken)
.executeWithRetry()
}
fun listAllTestCases(results: ToolResultsStep): List<TestCase> {
var response = listTestCases(results)
val testCases = response.testCases.orEmpty().toMutableList()
while (response.nextPageToken != null) {
response = listTestCases(results, response.nextPageToken)
testCases += response.testCases ?: emptyList()
}
return testCases
}
fun getDefaultBucket(projectId: String, source: String? = null): String? = try {
service.Projects().initializeSettings(projectId).executeWithRetry().defaultBucket
} catch (ftlProjectError: FTLProjectError) {
// flank needs to rewrap the exception with additional info about project
when (ftlProjectError) {
is PermissionDenied -> throw FlankGeneralError(permissionDeniedErrorMessage(projectId, source, ftlProjectError.message))
is ProjectNotFound -> throw FlankGeneralError(projectNotFoundErrorMessage(projectId, ftlProjectError.message))
is FailureToken -> UserAuth.throwAuthenticationError()
}
}
fun listAllEnvironments(results: ToolResultsExecution): List<Environment> {
var response = listEnvironments(results)
val environments = response.environments.toMutableList()
while (response.nextPageToken != null) {
response = listEnvironments(results, response.nextPageToken)
environments += response.environments ?: emptyList()
}
return environments
}
private fun listEnvironments(
results: ToolResultsExecution,
pageToken: String? = null
): ListEnvironmentsResponse = service
.projects()
.histories()
.executions()
.environments()
.list(
results.projectId,
results.historyId,
results.executionId
)
.setPageToken(pageToken)
.setPageSize(100)
.executeWithRetry()
fun listAllSteps(results: ToolResultsExecution): MutableList<Step> {
var response = listSteps(results)
val steps = response.steps.toMutableList()
while (response.nextPageToken != null) {
response = listSteps(results, response.nextPageToken)
steps += response.steps ?: emptyList()
}
return steps
}
private fun listSteps(
results: ToolResultsExecution,
pageToken: String? = null
): ListStepsResponse = service
.projects()
.histories()
.executions()
.steps()
.list(
results.projectId,
results.historyId,
results.executionId
)
.setPageToken(pageToken)
.setPageSize(100)
.executeWithRetry()
}
private val permissionDeniedErrorMessage = { projectId: String, projectIdSource: String?, message: String? ->
"""Flank encountered a 403 error when running on project $projectId${projectIdSource?.let {" (from $it)"} ?: ""}. Please verify this credential is authorized for the project and has the required permissions.
Consider authentication with a Service Account https://github.com/Flank/flank#authenticate-with-a-service-account
or with a Google account https://github.com/Flank/flank#authenticate-with-a-google-account
$message
""".trimIndent()
}
private val projectNotFoundErrorMessage = { projectId: String, message: String? ->
"""Flank was unable to find project $projectId. Please verify the project id.
$message
""".trimIndent()
}
| apache-2.0 | 39c0ebb8edbdbde9dbf6f6800d2d52a7 | 36.43038 | 211 | 0.672641 | 4.593993 | false | true | false | false |
kivensolo/UiUsingListView | app-Kotlin-Coroutines-Examples/src/main/java/com/kingz/coroutines/learn/errorhandling/supervisor/IgnoreErrorAndContinueViewModel.kt | 1 | 2991 | package com.kingz.coroutines.learn.errorhandling.supervisor
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kingz.base.response.ResponseResult
import com.kingz.coroutines.data.api.IUserAPIFunc
import com.kingz.coroutines.data.local.DatabaseHelper
import com.kingz.coroutines.data.model.ApiUser
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
class IgnoreErrorAndContinueViewModel(
private val apiHelper: IUserAPIFunc,
private val dbHelper: DatabaseHelper
) : ViewModel() {
private val users = MutableLiveData<ResponseResult<List<ApiUser>>>()
companion object{
const val TAG = "IgnoreErrorAndContinue"
}
init {
fetchUsers()
}
private fun fetchUsers() {
viewModelScope.launch {
users.postValue(ResponseResult.loading(null))
try {
/**
* supervisorScope is needed, so that we can ignore error and continue
* here, more than two child jobs are running in parallel under a supervisor,
* one child job gets failed, we can continue with other.
* 如果有两个及以上的子Job在一个supervisor下并行运行,
* 如果一个子job败,我们可以继续其他的子job。
*/
supervisorScope {
// supervisorScope 可以保证某个job失败,其他job可以继续执行。
val usersFromApiDeferred = async { apiHelper.getUsersWithError() }
val moreUsersFromApiDeferred = async { apiHelper.getMoreUsers() }
val usersFromApi = try {
usersFromApiDeferred.await()
} catch (e: Exception) {
Log.e(TAG,"usersFromApiDeferred failed.")
emptyList<ApiUser>()
}
val moreUsersFromApi = try {
moreUsersFromApiDeferred.await()
} catch (e: Exception) {
Log.e(TAG,"moreUsersFromApiDeferred failed.")
emptyList<ApiUser>()
}
val allUsersFromApi = mutableListOf<ApiUser>()
allUsersFromApi.addAll(usersFromApi)
allUsersFromApi.addAll(moreUsersFromApi)
Log.d(TAG,"All deferred done. postValue~~")
users.postValue(ResponseResult.success(allUsersFromApi))
}
} catch (e: Exception) {
Log.e(TAG,"All Deferred failed.")
users.postValue(ResponseResult.error("Something Went Wrong", null))
}
}
}
fun getUsers(): LiveData<ResponseResult<List<ApiUser>>> {
return users
}
} | gpl-2.0 | ab5f9cf00792916bff51211a35057098 | 35.481013 | 93 | 0.596321 | 5.045534 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/DebugLogManager.kt | 3 | 4738 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.containers.ContainerUtil
import java.util.logging.Level
import java.util.logging.Logger
/**
* Allows to apply & persist custom log debug categories which can be turned on by user via the [com.intellij.ide.actions.DebugLogConfigureAction].
* Applies these custom categories on startup.
*/
class DebugLogManager {
enum class DebugLogLevel { DEBUG, TRACE, ALL }
data class Category(val category: String, val level: DebugLogLevel)
companion object {
@JvmStatic
fun getInstance() = service<DebugLogManager>()
}
// java.util.logging keeps only weak references to loggers, so we need to store strong references to loggers we've customized to ensure
// that a logger can't get garbage-collected and then recreated with a default level instead of a customized one
private val customizedLoggers = mutableListOf<Logger>()
init {
val categories = mutableListOf<Category>()
categories.addAll(getSavedCategories())
// add categories from system properties (e.g. for tests on CI server)
categories.addAll(fromString(System.getProperty(LOG_DEBUG_CATEGORIES_SYSTEM_PROPERTY), DebugLogLevel.DEBUG))
categories.addAll(fromString(System.getProperty(LOG_TRACE_CATEGORIES_SYSTEM_PROPERTY), DebugLogLevel.TRACE))
categories.addAll(fromString(System.getProperty(LOG_ALL_CATEGORIES_SYSTEM_PROPERTY), DebugLogLevel.ALL))
applyCategories(categories)
}
fun getSavedCategories(): List<Category> {
val properties = PropertiesComponent.getInstance()
return ContainerUtil.concat(fromString(properties.getValue(LOG_DEBUG_CATEGORIES), DebugLogLevel.DEBUG),
fromString(properties.getValue(LOG_TRACE_CATEGORIES), DebugLogLevel.TRACE),
fromString(properties.getValue(LOG_ALL_CATEGORIES), DebugLogLevel.ALL))
}
fun clearCategories(categories: List<Category>) {
categories.forEach {
Logger.getLogger(it.category)?.level = null
}
customizedLoggers.clear()
}
fun applyCategories(categories: List<Category>) {
applyCategories(categories, DebugLogLevel.DEBUG, Level.FINE)
applyCategories(categories, DebugLogLevel.TRACE, Level.FINER)
applyCategories(categories, DebugLogLevel.ALL, Level.ALL)
}
private fun applyCategories(categories: List<Category>, level: DebugLogLevel, loggerLevel: Level) {
val filtered = categories.asSequence().filter { it.level == level }.map { it.category }.toList()
filtered.forEach {
val logger = Logger.getLogger(it)
logger.level = loggerLevel
customizedLoggers.add(logger)
}
if (filtered.isNotEmpty()) {
LOG.info("Set ${level.name} for the following categories: ${filtered.joinToString()}")
}
}
fun saveCategories(categories: List<Category>) {
val properties = PropertiesComponent.getInstance()
properties.setValue(LOG_DEBUG_CATEGORIES, toString(categories, DebugLogLevel.DEBUG), null)
properties.setValue(LOG_TRACE_CATEGORIES, toString(categories, DebugLogLevel.TRACE), null)
properties.setValue(LOG_ALL_CATEGORIES, toString(categories, DebugLogLevel.ALL), null)
}
private fun fromString(text: String?, level: DebugLogLevel): List<Category> {
return when {
text != null -> {
val byNewlines = text.lineSequence().toList()
val byCommas = text.split(",")
if (byCommas.size > 1 && byNewlines.size > 1) error("Do not mix commas and newlines as category separators: $text")
val categories = if (byCommas.size > byNewlines.size) byCommas else byNewlines
categories.mapNotNull { if (it.isBlank()) null else Category(it, level) }.toList()
}
else -> emptyList()
}
}
private fun toString(categories: List<Category>, level: DebugLogLevel): String? {
val filtered = categories.asSequence().filter { it.level == level }.map { it.category }.toList()
return if (filtered.isNotEmpty()) filtered.joinToString("\n") else null
}
}
private const val LOG_DEBUG_CATEGORIES = "log.debug.categories"
private const val LOG_TRACE_CATEGORIES = "log.trace.categories"
private const val LOG_ALL_CATEGORIES = "log.all.categories"
private const val LOG_DEBUG_CATEGORIES_SYSTEM_PROPERTY = "idea.$LOG_DEBUG_CATEGORIES"
private const val LOG_TRACE_CATEGORIES_SYSTEM_PROPERTY = "idea.$LOG_TRACE_CATEGORIES"
private const val LOG_ALL_CATEGORIES_SYSTEM_PROPERTY = "idea.$LOG_ALL_CATEGORIES"
private val LOG = logger<DebugLogManager>() | apache-2.0 | fdbd875baabb97905e99fbff4c9722f0 | 44.567308 | 147 | 0.735965 | 4.346789 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsRepository.kt | 1 | 2635 | package org.thoughtcrime.securesms.components.settings.app.internal
import android.content.Context
import org.signal.core.util.concurrent.SignalExecutors
import org.thoughtcrime.securesms.database.MessageDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.addStyle
import org.thoughtcrime.securesms.database.model.databaseprotos.BodyRangeList
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.emoji.EmojiFiles
import org.thoughtcrime.securesms.jobs.AttachmentDownloadJob
import org.thoughtcrime.securesms.jobs.CreateReleaseChannelJob
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.notifications.v2.ConversationId
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.releasechannel.ReleaseChannel
class InternalSettingsRepository(context: Context) {
private val context = context.applicationContext
fun getEmojiVersionInfo(consumer: (EmojiFiles.Version?) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(EmojiFiles.Version.readVersion(context))
}
}
fun addSampleReleaseNote() {
SignalExecutors.UNBOUNDED.execute {
ApplicationDependencies.getJobManager().runSynchronously(CreateReleaseChannelJob.create(), 5000)
val title = "Release Note Title"
val bodyText = "Release note body. Aren't I awesome?"
val body = "$title\n\n$bodyText"
val bodyRangeList = BodyRangeList.newBuilder()
.addStyle(BodyRangeList.BodyRange.Style.BOLD, 0, title.length)
val recipientId = SignalStore.releaseChannelValues().releaseChannelRecipientId!!
val threadId = SignalDatabase.threads.getOrCreateThreadIdFor(Recipient.resolved(recipientId))
val insertResult: MessageDatabase.InsertResult? = ReleaseChannel.insertReleaseChannelMessage(
recipientId = recipientId,
body = body,
threadId = threadId,
messageRanges = bodyRangeList.build(),
image = "/static/release-notes/signal.png",
imageWidth = 1800,
imageHeight = 720
)
SignalDatabase.sms.insertBoostRequestMessage(recipientId, threadId)
if (insertResult != null) {
SignalDatabase.attachments.getAttachmentsForMessage(insertResult.messageId)
.forEach { ApplicationDependencies.getJobManager().add(AttachmentDownloadJob(insertResult.messageId, it.attachmentId, false)) }
ApplicationDependencies.getMessageNotifier().updateNotification(context, ConversationId.forConversation(insertResult.threadId))
}
}
}
}
| gpl-3.0 | 03e2b0850008ef25f202febf0e0bd08f | 42.196721 | 137 | 0.783681 | 4.953008 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/vo/QueryMethod.kt | 3 | 2414 | /*
* Copyright (C) 2016 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.vo
import androidx.room.parser.ParsedQuery
import androidx.room.compiler.processing.XMethodElement
import androidx.room.compiler.processing.XType
import androidx.room.solver.prepared.binder.PreparedQueryResultBinder
import androidx.room.solver.query.result.QueryResultBinder
/**
* A class that holds information about a QueryMethod.
* It is self sufficient and must have all generics etc resolved once created.
*/
sealed class QueryMethod(
val element: XMethodElement,
val query: ParsedQuery,
val returnType: XType,
val parameters: List<QueryParameter>
) {
val sectionToParamMapping by lazy {
query.bindSections.map {
if (it.text.trim() == "?") {
Pair(it, parameters.firstOrNull())
} else if (it.text.startsWith(":")) {
val subName = it.text.substring(1)
Pair(
it,
parameters.firstOrNull {
it.sqlName == subName
}
)
} else {
Pair(it, null)
}
}
}
}
/**
* A query method who's query is a SELECT statement.
*/
class ReadQueryMethod(
element: XMethodElement,
query: ParsedQuery,
returnType: XType,
parameters: List<QueryParameter>,
val inTransaction: Boolean,
val queryResultBinder: QueryResultBinder
) : QueryMethod(element, query, returnType, parameters)
/**
* A query method who's query is a INSERT, UPDATE or DELETE statement.
*/
class WriteQueryMethod(
element: XMethodElement,
query: ParsedQuery,
returnType: XType,
parameters: List<QueryParameter>,
val preparedQueryResultBinder: PreparedQueryResultBinder
) : QueryMethod(element, query, returnType, parameters) | apache-2.0 | d6f12406a9e93c5570a8f5269d7788fa | 31.2 | 78 | 0.672742 | 4.60687 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/ui/GithubMergeCommitMessageDialog.kt | 5 | 1807 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.plugins.github.i18n.GithubBundle
import javax.swing.JComponent
import javax.swing.JLabel
class GithubMergeCommitMessageDialog(project: Project,
@NlsContexts.DialogTitle title: String,
subject: String,
body: String) : DialogWrapper(project) {
private val commitMessage = CommitMessage(project, false, false, true).apply {
setCommitMessage("$subject\n\n$body")
preferredSize = JBDimension(500, 85)
}
init {
Disposer.register(disposable, commitMessage)
setTitle(title)
setOKButtonText(GithubBundle.message("merge.commit.dialog.merge.button"))
init()
}
override fun createCenterPanel(): JComponent? {
return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP)
.addToTop(JLabel(GithubBundle.message("merge.commit.dialog.message")))
.addToCenter(commitMessage)
}
val message: Pair<String, String>
get() {
val text = commitMessage.comment
val idx = text.indexOf("\n\n")
return if (idx < 0) "" to text
else {
val subject = text.substring(0, idx)
if (subject.contains("\n")) "" to text
else subject to text.substring(idx + 2)
}
}
} | apache-2.0 | d139eaa51fc75c31e48bf259b266a83a | 33.769231 | 140 | 0.690094 | 4.251765 | false | false | false | false |
ReactiveX/RxKotlin | src/test/kotlin/io/reactivex/rxkotlin/FlowableTest.kt | 1 | 7512 | package io.reactivex.rxkotlin
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Flowable.create
import io.reactivex.FlowableEmitter
import io.reactivex.observers.LambdaConsumerIntrospection
import io.reactivex.subscribers.TestSubscriber
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Ignore
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
class FlowableTest {
private fun <T : Any> bufferedFlowable(source: (FlowableEmitter<T>) -> Unit) =
create(source, BackpressureStrategy.BUFFER)
@org.junit.Test fun testCreation() {
val o0: Flowable<Int> = Flowable.empty()
val list = bufferedFlowable<Int> { s ->
s.onNext(1)
s.onNext(777)
s.onComplete()
}.toList().blockingGet()
assertEquals(listOf(1, 777), list)
val o1: Flowable<Int> = listOf(1, 2, 3).toFlowable()
val o2: Flowable<List<Int>> = Flowable.just(listOf(1, 2, 3))
val o3: Flowable<Int> = Flowable.defer { bufferedFlowable<Int> { s -> s.onNext(1) } }
val o4: Flowable<Int> = Array(3) { 0 }.toFlowable()
val o5: Flowable<Int> = IntArray(3).toFlowable()
assertNotNull(o0)
assertNotNull(o1)
assertNotNull(o2)
assertNotNull(o3)
assertNotNull(o4)
assertNotNull(o5)
}
@org.junit.Test fun testExampleFromReadme() {
val result = bufferedFlowable<String> { subscriber ->
subscriber.onNext("H")
subscriber.onNext("e")
subscriber.onNext("l")
subscriber.onNext("")
subscriber.onNext("l")
subscriber.onNext("o")
subscriber.onComplete()
}.filter(String::isNotEmpty).
reduce(StringBuilder(), StringBuilder::append).
map { it.toString() }.
blockingGet()
assertEquals("Hello", result)
}
@Test fun iteratorFlowable() {
assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).iterator().toFlowable().toList().blockingGet())
}
@Test fun intProgressionStep1Empty() {
assertEquals(listOf(1), (1..1).toFlowable().toList().blockingGet())
}
@Test fun intProgressionStep1() {
assertEquals((1..10).toList(), (1..10).toFlowable().toList().blockingGet())
}
@Test fun intProgressionDownTo() {
assertEquals((1 downTo 10).toList(), (1 downTo 10).toFlowable().toList().blockingGet())
}
@Ignore("Too slow")
@Test fun intProgressionOverflow() {
assertEquals((0..10).toList().reversed(), (-10..Integer.MAX_VALUE).toFlowable().skip(Integer.MAX_VALUE.toLong()).map { Integer.MAX_VALUE - it }.toList().blockingGet())
}
@Test fun testFold() {
val result = listOf(1, 2, 3).toFlowable().reduce(0) { acc, e -> acc + e }.blockingGet()
assertEquals(6, result)
}
@Test fun `kotlin sequence should produce expected items and flowable be able to handle em`() {
generateSequence(0) { it + 1 }.toFlowable()
.take(3)
.toList()
.test()
.assertValues(listOf(0, 1, 2))
}
@Test fun `infinite iterable should not hang or produce too many elements`() {
val generated = AtomicInteger()
generateSequence { generated.incrementAndGet() }.toFlowable().
take(100).
toList().
subscribe()
assertEquals(100, generated.get())
}
@Test fun testFlatMapSequence() {
assertEquals(
listOf(1, 2, 3, 2, 3, 4, 3, 4, 5),
listOf(1, 2, 3).toFlowable().flatMapSequence { listOf(it, it + 1, it + 2).asSequence() }.toList().blockingGet()
)
}
@Test fun testCombineLatest() {
val list = listOf(1, 2, 3, 2, 3, 4, 3, 4, 5)
assertEquals(list, list.map { Flowable.just(it) }.combineLatest { it }.blockingFirst())
}
@Test fun testZip() {
val list = listOf(1, 2, 3, 2, 3, 4, 3, 4, 5)
assertEquals(list, list.map { Flowable.just(it) }.zip { it }.blockingFirst())
}
@Test fun testCast() {
val source = Flowable.just<Any>(1, 2)
val flowable = source.cast<Int>()
flowable.test()
.await()
.assertValues(1, 2)
.assertNoErrors()
.assertComplete()
}
@Test fun testCastWithWrongType() {
val source = Flowable.just<Any>(1, 2)
val flowable = source.cast<String>()
flowable.test()
.assertError(ClassCastException::class.java)
}
@Test fun combineLatestPair() {
Flowable.just(3)
.combineLatest(Flowable.just(10))
.map { (x, y) -> x * y }
.test()
.assertValues(30)
}
@Test fun combineLatestTriple() {
Flowable.just(3)
.combineLatest(Flowable.just(10), Flowable.just(20))
.map { (x, y, z) -> x * y * z }
.test()
.assertValues(600)
}
@Test
fun testSubscribeBy() {
val first = AtomicReference<String>()
Flowable.just("Alpha")
.subscribeBy {
first.set(it)
}
Assert.assertTrue(first.get() == "Alpha")
}
@Test
fun testSubscribeByErrorIntrospection() {
val disposable = Flowable.just(Unit)
.subscribeBy() as LambdaConsumerIntrospection
Assert.assertFalse(disposable.hasCustomOnError())
}
@Test
fun testSubscribeByErrorIntrospectionCustom() {
val disposable = Flowable.just(Unit)
.subscribeBy(onError = {}) as LambdaConsumerIntrospection
Assert.assertTrue(disposable.hasCustomOnError())
}
@Test
fun testSubscribeByErrorIntrospectionDefaultWithOnComplete() {
val disposable = Flowable.just(Unit)
.subscribeBy(onComplete = {}) as LambdaConsumerIntrospection
Assert.assertFalse(disposable.hasCustomOnError())
}
@Test
fun testBlockingSubscribeBy() {
val first = AtomicReference<String>()
Flowable.just("Alpha")
.blockingSubscribeBy {
first.set(it)
}
Assert.assertTrue(first.get() == "Alpha")
}
@Test
fun testPairZip() {
val testSubscriber = TestSubscriber<Pair<String,Int>>()
Flowables.zip(
Flowable.just("Alpha", "Beta", "Gamma"),
Flowable.range(1,4)
).subscribe(testSubscriber)
testSubscriber.assertValues(Pair("Alpha",1), Pair("Beta",2), Pair("Gamma",3))
}
@Test
fun testTripleZip() {
val testSubscriber = TestSubscriber<Triple<String,Int,Int>>()
Flowables.zip(
Flowable.just("Alpha", "Beta", "Gamma"),
Flowable.range(1,4),
Flowable.just(100,200,300)
).subscribe(testSubscriber)
testSubscriber.assertValues(Triple("Alpha",1, 100), Triple("Beta",2, 200), Triple("Gamma",3, 300))
}
@Test fun testConcatAll() {
(0 until 10)
.map { Flowable.just(it) }
.concatAll()
.toList()
.subscribe { result ->
Assert.assertEquals((0 until 10).toList(), result)
}
}
}
| apache-2.0 | f6daf018a51567db2c4f7d8f3027cd87 | 31.102564 | 175 | 0.572417 | 4.337182 | false | true | false | false |
jbmlaird/DiscogsBrowser | app/src/test/java/bj/vinylbrowser/marketplace/MarketplacePresenterTest.kt | 1 | 3332 | package bj.vinylbrowser.marketplace
import android.content.Context
import bj.vinylbrowser.model.listing.Listing
import bj.vinylbrowser.model.user.UserDetails
import bj.vinylbrowser.network.DiscogsInteractor
import bj.vinylbrowser.utils.schedulerprovider.TestSchedulerProvider
import com.nhaarman.mockito_kotlin.*
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
/**
* Created by Josh Laird on 22/05/2017.
*/
@RunWith(MockitoJUnitRunner::class)
class MarketplacePresenterTest {
lateinit var presenter: MarketplacePresenter
val context: Context = mock()
val view: MarketplaceContract.View = mock()
val discogsInteractor: DiscogsInteractor = mock()
val epxController: MarketplaceEpxController = mock()
lateinit var testScheduler: TestScheduler
val listingId = "123"
@Before
fun setUp() {
testScheduler = TestScheduler()
presenter = MarketplacePresenter(discogsInteractor, TestSchedulerProvider(testScheduler), epxController)
}
@After
fun tearDown() {
verifyNoMoreInteractions(view, discogsInteractor, epxController)
}
@Test
fun getListingDetailsError_displaysError() {
whenever(discogsInteractor.fetchListingDetails(listingId)).thenReturn(Single.error<Listing>(Throwable()))
presenter.getListingDetails(listingId)
testScheduler.triggerActions()
verify(epxController, times(1)).setLoading(true)
verify(discogsInteractor, times(1)).fetchListingDetails(listingId)
verify(epxController, times(1)).setError(true)
}
@Test
fun getListingDetailsValid_displayListingsAndUpdatesUser() {
val listing = Listing()
val userDetails = UserDetails()
whenever(discogsInteractor.fetchListingDetails(listingId)).thenReturn(Single.just(listing))
whenever(discogsInteractor.fetchUserDetails(listing.seller.username)).thenReturn(Single.just(userDetails))
presenter.getListingDetails(listingId)
testScheduler.triggerActions()
verify(epxController, times(1)).setLoading(true)
verify(discogsInteractor, times(1)).fetchListingDetails(listingId)
verify(discogsInteractor, times(1)).fetchUserDetails(listing.seller.username)
verify(epxController, times(1)).setListing(listing)
verify(epxController, times(1)).setSellerDetails(userDetails)
}
@Test
fun getListingDetailsError_displayListingsAndUpdatesUser() {
val listing = Listing()
val userDetails = UserDetails()
whenever(discogsInteractor.fetchListingDetails(listingId)).thenReturn(Single.just(listing))
whenever(discogsInteractor.fetchUserDetails(listing.seller.username)).thenReturn(Single.just(userDetails))
presenter.getListingDetails(listingId)
testScheduler.triggerActions()
verify(epxController, times(1)).setLoading(true)
verify(discogsInteractor, times(1)).fetchListingDetails(listingId)
verify(discogsInteractor, times(1)).fetchUserDetails(listing.seller.username)
verify(epxController, times(1)).setListing(listing)
verify(epxController, times(1)).setSellerDetails(userDetails)
}
} | mit | 85bd37f346f4faabd75172fe95391c8e | 37.755814 | 114 | 0.7491 | 4.794245 | false | true | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/ShortcutEditorViewState.kt | 1 | 1584 | package ch.rmy.android.http_shortcuts.activities.editor
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.data.enums.ShortcutExecutionType
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
data class ShortcutEditorViewState(
val dialogState: DialogState? = null,
val toolbarTitle: Localizable,
val toolbarSubtitle: Localizable? = null,
val shortcutExecutionType: ShortcutExecutionType = ShortcutExecutionType.APP,
val shortcutIcon: ShortcutIcon = ShortcutIcon.NoIcon,
val shortcutName: String = "",
val shortcutDescription: String = "",
val isExecutable: Boolean = false,
val hasChanges: Boolean = false,
val requestBodyButtonEnabled: Boolean = false,
val basicSettingsSubtitle: Localizable = Localizable.EMPTY,
val headersSubtitle: Localizable = Localizable.EMPTY,
val requestBodySubtitle: Localizable = Localizable.EMPTY,
val requestBodySettingsSubtitle: Localizable = Localizable.EMPTY,
val authenticationSettingsSubtitle: Localizable = Localizable.EMPTY,
val scriptingSubtitle: Localizable = Localizable.EMPTY,
val triggerShortcutsSubtitle: Localizable = Localizable.EMPTY,
val iconLoading: Boolean = false,
val isInputDisabled: Boolean = false,
) {
val isIconClickable
get() = !iconLoading && !isInputDisabled
val isSaveButtonVisible
get() = hasChanges && !isInputDisabled
val isExecuteButtonVisible
get() = isExecutable && !isInputDisabled
}
| mit | b184ca0999e3af8f5c28bec351111c32 | 41.810811 | 81 | 0.765783 | 4.844037 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 3 | 2475 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.diagnostic
import com.intellij.CommonBundle
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun showJetBrainsAccountDialog(parent: Component, project: Project? = null): DialogWrapper {
val credentials = ErrorReportConfigurable.getCredentials()
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.password?.toString())
// if no user name - never stored and so, defaults to remember. if user name set, but no password, so, previously was stored without password
val rememberCheckBox = CheckBox(CommonBundle.message("checkbox.remember.password"), selected = credentials?.userName == null || !credentials.password.isNullOrEmpty())
val panel = panel {
noteRow("Login to JetBrains Account to get notified when the submitted\nexceptions are fixed.")
row("Username:") { userField() }
row("Password:") { passwordField() }
row {
rememberCheckBox()
right {
link("Forgot password?") { BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=${userField.text.trim().encodeUrlQueryParameter()}") }
}
}
noteRow("""Do not have an account? <a href="https://account.jetbrains.com/login?signup">Sign Up</a>""")
}
return dialog(
title = DiagnosticBundle.message("error.report.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null) {
val userName = userField.text
if (!userName.isNullOrBlank()) {
PasswordSafe.getInstance().set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, if (rememberCheckBox.isSelected) passwordField.password else null))
}
return@dialog true
}
} | apache-2.0 | 1987493b2bdac559c33f4612a941ffc9 | 44.018182 | 196 | 0.756768 | 4.475588 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/PopupAlertManager.kt | 2 | 7935 | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector
import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import com.tapadoo.alerter.Alerter
import com.tapadoo.alerter.OnHideAlertListener
import im.vector.activity.SASVerificationActivity
import java.lang.ref.WeakReference
/**
* Responsible of displaying important popup alerts on top of the screen.
* Alerts are stacked and will be displayed sequentially
*/
object PopupAlertManager {
private var weakCurrentActivity: WeakReference<Activity>? = null
private var currentAlerter: VectorAlert? = null
private val alertFiFo = ArrayList<VectorAlert>()
private val LOG_TAG = PopupAlertManager::class.java.name
fun postVectorAlert(alert: VectorAlert) {
synchronized(alertFiFo) {
alertFiFo.add(alert)
}
displayNextIfPossible()
}
fun cancelAlert(uid: String) {
synchronized(alertFiFo) {
alertFiFo.listIterator().apply {
while (this.hasNext()) {
val next = this.next()
if (next.uid == uid) {
this.remove()
}
}
}
}
//it could also be the current one
if (currentAlerter?.uid == uid) {
Alerter.hide()
currentIsDismissed()
}
}
fun onNewActivityDisplayed(activity: Activity) {
//we want to remove existing popup on previous activity and display it on new one
if (currentAlerter != null) {
weakCurrentActivity?.get()?.let {
Alerter.clearCurrent(it)
}
}
if (shouldIgnoreActivity(activity)) {
return
}
weakCurrentActivity = WeakReference(activity)
if (currentAlerter != null) {
if (currentAlerter!!.expirationTimestamp != null && System.currentTimeMillis() > currentAlerter!!.expirationTimestamp!!) {
//this alert has expired, remove it
//perform dismiss
try {
currentAlerter?.dismissedAction?.run()
} catch (e: Exception) {
Log.e(LOG_TAG, "## failed to perform action")
}
currentAlerter = null
Handler(Looper.getMainLooper()).postDelayed({
displayNextIfPossible()
}, 2000)
} else {
showAlert(currentAlerter!!, activity, animate = false)
}
} else {
Handler(Looper.getMainLooper()).postDelayed({
displayNextIfPossible()
}, 2000)
}
}
private fun shouldIgnoreActivity(activity: Activity) = activity is SASVerificationActivity
private fun displayNextIfPossible() {
val currentActivity = weakCurrentActivity?.get()
if (Alerter.isShowing || currentActivity == null) {
//will retry later
return
}
val next: VectorAlert?
synchronized(alertFiFo) {
next = alertFiFo.firstOrNull()
if (next != null) alertFiFo.remove(next)
}
currentAlerter = next
next?.let {
val currentTime = System.currentTimeMillis()
if (next.expirationTimestamp != null && currentTime > next.expirationTimestamp!!) {
//skip
try {
next.dismissedAction?.run()
} catch (e: java.lang.Exception) {
Log.e(LOG_TAG, "## failed to perform action")
}
displayNextIfPossible()
} else {
showAlert(it, currentActivity)
}
}
}
private fun showAlert(alert: VectorAlert, activity: Activity, animate: Boolean = true) {
alert.weakCurrentActivity = WeakReference(activity)
Alerter.create(activity)
.setTitle(alert.title)
.setText(alert.description)
.apply {
if (!animate) {
setEnterAnimation(R.anim.anim_alerter_no_anim)
}
alert.iconId?.let {
setIcon(it)
}
alert.actions.forEach { action ->
addButton(action.title, R.style.AlerterButton, View.OnClickListener {
if (action.autoClose) {
currentIsDismissed()
Alerter.hide()
}
try {
action.action.run()
} catch (e: java.lang.Exception) {
Log.e(LOG_TAG, "## failed to perform action")
}
})
}
setOnClickListener(View.OnClickListener { _ ->
alert.contentAction?.let {
currentIsDismissed()
Alerter.hide()
try {
it.run()
} catch (e: java.lang.Exception) {
Log.e(LOG_TAG, "## failed to perform action")
}
}
})
}
.setOnHideListener(OnHideAlertListener {
//called when dismissed on swipe
try {
alert.dismissedAction?.run()
} catch (e: java.lang.Exception) {
Log.e(LOG_TAG, "## failed to perform action")
}
currentIsDismissed()
})
.enableSwipeToDismiss()
.enableInfiniteDuration(true)
.setBackgroundColorRes(alert.colorRes ?: R.color.notification_accent_color)
.show()
}
private fun currentIsDismissed() {
//current alert has been hidden
currentAlerter = null
Handler(Looper.getMainLooper()).postDelayed({
displayNextIfPossible()
}, 500)
}
/**
* Dataclass to describe an important alert with actions.
*/
data class VectorAlert(val uid: String,
val title: String,
val description: String,
@DrawableRes val iconId: Int?) {
data class Button(val title: String, val action: Runnable, val autoClose: Boolean)
//will be set by manager, and accessible by actions at runtime
var weakCurrentActivity: WeakReference<Activity>? = null
val actions = ArrayList<Button>()
var contentAction: Runnable? = null
var dismissedAction: Runnable? = null
/** If this timestamp is after current time, this alert will be skipped */
var expirationTimestamp: Long? = null
fun addButton(title: String, action: Runnable, autoClose: Boolean = true) {
actions.add(Button(title, action, autoClose))
}
@ColorRes
var colorRes: Int? = null
}
} | apache-2.0 | 91e9d3626b07a0061e128c996f58059e | 33.206897 | 134 | 0.529679 | 5.265428 | false | false | false | false |
etissieres/MoonPi | src/main/kotlin/moonpi/environment.kt | 1 | 1389 | package moonpi
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
private val homeFolder = Paths.get(System.getProperty("user.home"), ".moonpi")
private val configurationFile = Paths.get(homeFolder.toString(), "config.json")
private val historyFile = Paths.get(homeFolder.toString(), "history.json")
private val picturesFolder = Paths.get(homeFolder.toString(), "pictures")
private val defaultUsername = "pi"
private val defaultPrivateKey = Paths.get(System.getProperty("user.home"), ".ssh", "id_rsa")
open class Environment {
open fun getHomeFolder(): Path = homeFolder
open fun getConfigurationFile(): Path = configurationFile
open fun getHistoryFile(): Path = historyFile
open fun getPicturesFolder(): Path = picturesFolder
open fun getDefaultUsername(): String = defaultUsername
open fun getDefaultPrivateKey(): Path = defaultPrivateKey
fun prepare() {
createFolderIfNotExists(getHomeFolder())
createFileIfNotExists(getConfigurationFile())
createFileIfNotExists(getHistoryFile())
createFolderIfNotExists(getPicturesFolder())
}
}
private fun createFileIfNotExists(file: Path) {
if (!Files.exists(file)) {
Files.createFile(file)
}
}
private fun createFolderIfNotExists(folder: Path) {
if (!Files.exists(folder)) {
Files.createDirectories(folder)
}
}
| mit | 4ef91a63c7b5cba6bc4f56ff999be110 | 29.195652 | 92 | 0.728582 | 4.367925 | false | true | false | false |
gen0083/AdbFriendly | plugin/src/main/java/jp/gcreate/plugins/adbfriendly/adb/Command.kt | 1 | 1951 | /*
* ADB Friendly
* Copyright 2016 gen0083
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.gcreate.plugins.adbfriendly.adb
import com.android.ddmlib.IDevice
import com.android.ddmlib.IShellOutputReceiver
import jp.gcreate.plugins.adbfriendly.util.Logger
import java.util.*
import java.util.concurrent.TimeUnit
class Command(val device: IDevice,
val command: String,
val timeout: Long = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(2))
: IShellOutputReceiver {
private var outputs: ArrayList<String> = arrayListOf()
private var finished = false
fun execute(): ArrayList<String> {
if (finished) throw IllegalStateException("This command already used. Use new Command instance and execute.")
device.executeShellCommand(command, this)
while (!finished) {
if (System.currentTimeMillis() > timeout) {
Logger.e(this, "Command timeout ${outputs.joinToString("\n")}")
outputs.add(0, "Command timeout $timeout milliseconds.")
return outputs
}
}
return outputs
}
override fun addOutput(data: ByteArray?, offset: Int, length: Int) {
val str = java.lang.String(data, offset, length).toString()
outputs.add(str)
}
override fun flush() {
finished = true
}
override fun isCancelled(): Boolean {
return false
}
} | apache-2.0 | 20515564c2acb9a062dca2a16b643387 | 32.655172 | 117 | 0.677089 | 4.364653 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/ui/preference/SeekBarPreference.kt | 2 | 2602 | package com.quran.labs.androidquran.ui.preference
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.SeekBar
import android.widget.TextView
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.data.Constants
import com.quran.labs.androidquran.util.QuranUtils
open class SeekBarPreference(
context: Context,
attrs: AttributeSet
) : Preference(context, attrs), SeekBar.OnSeekBarChangeListener {
private lateinit var valueText: TextView
protected lateinit var previewText: TextView
protected lateinit var previewBox: View
private val suffix = attrs.getAttributeValue(ANDROID_NS, "text")
private val default = attrs.getAttributeIntValue(
ANDROID_NS,
"defaultValue",
Constants.DEFAULT_TEXT_SIZE
)
private val maxValue = attrs.getAttributeIntValue(ANDROID_NS, "max", 100)
private var currentValue = 0
protected var value = 0
init {
layoutResource = R.layout.seekbar_pref
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val seekBar = holder.findViewById(R.id.seekbar) as SeekBar
valueText = holder.findViewById(R.id.value) as TextView
previewText = holder.findViewById(R.id.pref_preview) as TextView
previewBox = holder.findViewById(R.id.preview_square)
previewText.visibility = getPreviewVisibility()
seekBar.setOnSeekBarChangeListener(this)
value = if (shouldDisableView) getPersistedInt(default) else 0
seekBar.apply {
max = maxValue
progress = value
}
}
override fun onSetInitialValue(defaultValue: Any?) {
super.onSetInitialValue(defaultValue)
value = if (shouldPersist()) {
getPersistedInt(default)
} else {
if (defaultValue != null) default else 0
}
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
val t = QuranUtils.getLocalizedNumber(context, progress)
valueText.text = if (suffix == null) t else "$t$suffix"
currentValue = progress
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
if (shouldPersist()) {
persistInt(currentValue)
callChangeListener(currentValue)
}
}
/**
* Visibility of the preview view under the seek bar
*/
protected open fun getPreviewVisibility(): Int = View.GONE
companion object {
private const val ANDROID_NS = "http://schemas.android.com/apk/res/android"
}
}
| gpl-3.0 | 6bc1e2dfc6f9e1251c710b90cedfe3b2 | 29.97619 | 86 | 0.743659 | 4.493955 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/pattern/url/PatternUrlChecker.kt | 1 | 3599 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.pattern.url
import android.content.Context
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.adblock.filter.fastmatch.FastMatcherFactory
import jp.hazuki.yuzubrowser.legacy.pattern.PatternAction
import jp.hazuki.yuzubrowser.legacy.pattern.PatternChecker
import jp.hazuki.yuzubrowser.legacy.utils.WebUtils
import java.io.IOException
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException
class PatternUrlChecker : PatternChecker {
var patternUrl: String? = null
private set
private var mPattern: Pattern? = null
private var enable = true
@Throws(PatternSyntaxException::class)
constructor(pattern_action: PatternAction, factory: FastMatcherFactory, pattern_url: String) : super(pattern_action) {
setPatternUrlWithThrow(factory, pattern_url)
}
@Throws(PatternSyntaxException::class, IOException::class)
constructor(reader: JsonReader, factory: FastMatcherFactory) : super(PatternAction.newInstance(reader)) {
//TODO not set mPattern
if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
FIELD_PATTERN_URL -> {
if (reader.peek() == JsonReader.Token.STRING) {
setPatternUrlWithThrow(factory, reader.nextString())
} else {
reader.skipValue()
}
}
FIELD_PATTERN_ENABLE -> {
enable = reader.nextBoolean()
}
else -> reader.skipValue()
}
}
reader.endObject()
}
@Throws(PatternSyntaxException::class)
private fun setPatternUrlWithThrow(factory: FastMatcherFactory, pattern_url: String) {
mPattern = WebUtils.makeUrlPatternWithThrow(factory, pattern_url)
this.patternUrl = pattern_url
}
fun isMatchUrl(url: String): Boolean {
return enable && mPattern != null && mPattern!!.matcher(url).find()
}
protected fun matcher(url: String): Matcher {
return mPattern!!.matcher(url)
}
override fun getTitle(context: Context): String? {
return patternUrl
}
override fun isEnable(): Boolean {
return enable
}
override fun setEnable(enable: Boolean) {
this.enable = enable
}
@Throws(IOException::class)
override fun write(writer: JsonWriter): Boolean {
action.write(writer)
writer.beginObject()
writer.name(FIELD_PATTERN_URL)
writer.value(patternUrl)
writer.name(FIELD_PATTERN_ENABLE)
writer.value(enable)
writer.endObject()
return true
}
companion object {
private const val FIELD_PATTERN_URL = "0"
private const val FIELD_PATTERN_ENABLE = "1"
}
}
| apache-2.0 | 418979a08150f9306a1e77180966ce49 | 32.635514 | 122 | 0.660739 | 4.476368 | false | false | false | false |
stoichoandreev/TensorFlowHackaton | app/src/main/java/com/gumtree/tensorflowexample/tensorflow/Classifier.kt | 1 | 1799 | package com.gumtree.tensorflowexample.tensorflow
import android.graphics.Bitmap
import android.graphics.RectF
interface Classifier {
/**
* An immutable result returned by a Classifier describing what was recognized.
*/
class Recognition(
/**
* A unique identifier for what has been recognized. Specific to the class, not the instance of
* the object.
*/
val id: String?,
/**
* Display name for the recognition.
*/
val title: String?,
/**
* A sortable score for how good the recognition is relative to others. Higher should be better.
*/
val confidence: Float?,
/**
* Optional location within the source image for the location of the recognized object.
*/
private var location: RectF?) {
fun getLocation(): RectF =
RectF(location)
fun setLocation(location: RectF) {
this.location = location
}
override fun toString(): String {
var resultString = ""
if (id != null) {
resultString += "[$id] "
}
if (title != null) {
resultString += title + " "
}
if (confidence != null) {
resultString += String.format("(%.1f%%) ", confidence * 100.0f)
}
if (location != null) {
resultString += location!!.toString() + " "
}
return resultString.trim { it <= ' ' }
}
}
fun recognizeImage(bitmap: Bitmap): List<Recognition>
fun enableStatLogging(debug: Boolean)
fun getStatString(): String?
fun close()
} | apache-2.0 | 9d3860fca73d6b042205eb2f892327d2 | 26.692308 | 108 | 0.511395 | 5.260234 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/AppStatusFragment.kt | 1 | 3540 | package org.eurofurence.connavigator.ui.fragments
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import io.reactivex.disposables.Disposables
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.util.extensions.fontAwesomeView
import org.eurofurence.connavigator.util.v2.compatAppearance
import org.eurofurence.connavigator.util.v2.plus
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
class AppStatusFragment : DisposingFragment(), HasDb {
val ui = AppStatusUi()
override val db by lazyLocateDb()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
UI { ui.createView(this) }.view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
db.subscribe {
val state = it.state
if (state == null || state.toLowerCase() == "live") {
ui.layout.visibility = View.GONE
} else {
ui.layout.visibility = View.VISIBLE
if (state.toLowerCase() == "past") {
ui.stateText.textResource = R.string.app_state_past
ui.stateLayout.backgroundColor = ContextCompat.getColor(context!!, R.color.errorBackground);
}
if (state.toLowerCase() == "preview") {
ui.stateText.textResource = R.string.app_state_preview
ui.stateLayout.backgroundColor = ContextCompat.getColor(context!!, R.color.warningBackground);
}
}
}.collectOnDestroyView()
}
}
class AppStatusUi : AnkoComponent<Fragment> {
lateinit var stateLayout: LinearLayout
lateinit var stateText: TextView
lateinit var layout: ViewGroup
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
scrollView {
[email protected] = this
lparams(matchParent, matchParent)
backgroundResource = R.color.lightBackground
verticalLayout {
stateLayout = linearLayout {
lparams(matchParent, wrapContent) {
setPadding(0, dip(20), 0, dip(20))
}
weightSum = 100f
fontAwesomeView {
text = "{fa-warning 30sp}"
textColor = ContextCompat.getColor(context, R.color.textBlack)
lparams(dip(0), matchParent, 15F)
gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
}
verticalLayout {
stateText = textView {
textResource = R.string.misc_version
compatAppearance = android.R.style.TextAppearance_Small
textColor = ContextCompat.getColor(context, R.color.textBlack)
}
}.lparams(dip(0), wrapContent) {
weight = 75F
}
}.lparams(matchParent, wrapContent) {
topMargin = dip(20)
}
}
}
}
} | mit | 1a284356b64373bc6d4356103cb87254 | 35.885417 | 114 | 0.598305 | 5.130435 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/create-mobile-geodatabase/src/main/java/com/esri/arcgisruntime/sample/createmobilegeodatabase/MainActivity.kt | 1 | 12489 | /* Copyright 2022 Esri
*
* 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.esri.arcgisruntime.sample.createmobilegeodatabase
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.concurrent.ListenableFuture
import com.esri.arcgisruntime.data.*
import com.esri.arcgisruntime.geometry.GeometryType
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.createmobilegeodatabase.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.createmobilegeodatabase.databinding.TableLayoutBinding
import com.esri.arcgisruntime.sample.createmobilegeodatabase.databinding.TableRowBinding
import java.io.File
import java.util.*
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val createButton: Button by lazy {
activityMainBinding.createButton
}
private val viewTableButton: Button by lazy {
activityMainBinding.viewTableButton
}
private val featureCount: TextView by lazy {
activityMainBinding.featureCount
}
// feature table created using mobile geodatabase and added to the MapView
private var featureTable: GeodatabaseFeatureTable? = null
// mobile geodatabase used to create and store the feature attributes (LocationHistory.geodatabase)
private var geodatabase: Geodatabase? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is
// required to access basemaps and other location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
mapView.apply {
// create a map with a topographic basemap and set the map to the mapview
map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
setViewpoint(Viewpoint(34.056295, -117.195800, 10000.0))
// listen for single taps on the map
onTouchListener =
object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
override fun onSingleTapConfirmed(motionEvent: MotionEvent?): Boolean {
motionEvent?.let { event ->
// get the map point from the screen point
val mapPoint = mapView.screenToLocation(
android.graphics.Point(
event.x.toInt(),
event.y.toInt()
)
)
// create a point from where the user clicked
addFeature(mapPoint)
}
return super.onSingleTapConfirmed(motionEvent)
}
}
}
viewTableButton.setOnClickListener {
// displays table dialog with the values in the feature table
displayTable()
}
// opens a share-sheet with the "LocationHistory.geodatabase" file
createButton.setOnClickListener {
try {
// close the mobile geodatabase before sharing
geodatabase?.close()
// get the URI of the geodatabase file using FileProvider
val geodatabaseURI = FileProvider.getUriForFile(
this, getString(R.string.file_provider_package), File(
geodatabase?.path.toString()
)
)
// set up the sharing intent with the geodatabase URI
val geodatabaseIntent = Intent(Intent.ACTION_SEND).apply {
type = "*/*"
putExtra(Intent.EXTRA_STREAM, geodatabaseURI)
}
// open the Android share sheet
startActivity(geodatabaseIntent)
} catch (e: Exception) {
showError("Error sharing file: ${e.message}")
}
}
}
/**
* Create and load a new geodatabase file with TableDescription fields
*/
private fun createGeodatabase() {
// define the path and name of the geodatabase file
// note: the path defined must be non-empty, available,
// allow read/write access, and end in ".geodatabase"
val file = File(getExternalFilesDir(null)?.path + "/LocationHistory.geodatabase")
if (file.exists()) {
file.delete()
}
// close the existing geodatabase
geodatabase?.close()
// create a geodatabase file at the file path
val geodatabaseFuture = Geodatabase.createAsync(file.path)
geodatabaseFuture.addDoneListener {
// get the instance of the mobile geodatabase
geodatabase = geodatabaseFuture.get()
// construct a table description which stores features as points on map
val tableDescription =
TableDescription(
"LocationHistory",
SpatialReferences.getWgs84(),
GeometryType.POINT
)
// set up the fields to the table,
// Field.Type.OID is the primary key of the SQLite table
// Field.Type.DATE is a date column used to store a Calendar date
// FieldDescriptions can be a SHORT, INTEGER, GUID, FLOAT, DOUBLE, DATE, TEXT, OID, GLOBALID, BLOB, GEOMETRY, RASTER, or XML.
tableDescription.fieldDescriptions.addAll(
listOf(
FieldDescription("oid", Field.Type.OID),
FieldDescription("collection_timestamp", Field.Type.DATE)
)
)
// set any properties not needed to false
tableDescription.apply {
setHasAttachments(false)
setHasM(false)
setHasZ(false)
}
// add a new table to the geodatabase by creating one from the tableDescription
val tableFuture = geodatabase?.createTableAsync(tableDescription)
if (tableFuture != null) {
setupMapFromGeodatabase(tableFuture)
} else {
showError("Error adding FieldDescriptions to the mobile geodatabase")
}
}
}
/**
* Set up the MapView to display the Feature layer
* using the loaded [tableFuture] GeodatabaseFeatureTable
*/
private fun setupMapFromGeodatabase(tableFuture: ListenableFuture<GeodatabaseFeatureTable>) {
tableFuture.addDoneListener {
// get the result of the loaded "LocationHistory" table
featureTable = tableFuture.get()
// create a feature layer for the map using the GeodatabaseFeatureTable
val featureLayer = FeatureLayer(featureTable)
mapView.map.operationalLayers.add(featureLayer)
// display the current count of features in the FeatureTable
featureCount.text = "Number of features added: ${featureTable?.totalFeatureCount}"
}
}
/**
* Create a feature with attributes on map click and it to the [featureTable]
* Also, updates the TotalFeatureCount on the screen
*/
private fun addFeature(mapPoint: Point) {
// set up the feature attributes
val featureAttributes = mutableMapOf<String, Any>()
featureAttributes["collection_timestamp"] = Calendar.getInstance()
// create a new feature at the mapPoint
val feature = featureTable?.createFeature(featureAttributes, mapPoint)
// add the feature to the feature table
val addFeatureFuture = featureTable?.addFeatureAsync(feature)
addFeatureFuture?.addDoneListener {
try {
// if feature wasn't added successfully "addFeatureFuture.get()" will throw an exception
addFeatureFuture.get()
// feature added successfully, update count
featureCount.text = "Number of features added: ${featureTable?.totalFeatureCount}"
// enable table button since at least 1 feature loaded on the GeodatabaseFeatureTable
viewTableButton.isEnabled = true
} catch (e: Exception) {
showError(e.message.toString())
}
}
}
/**
* Displays a dialog with the table of features
* added to the GeodatabaseFeatureTable [featureTable]
*/
private fun displayTable() {
// query all the features loaded to the table
val queryResultFuture = featureTable?.queryFeaturesAsync(QueryParameters())
queryResultFuture?.addDoneListener {
val queryResults = queryResultFuture.get()
// inflate the table layout
val tableLayoutBinding = TableLayoutBinding.inflate(layoutInflater)
// set up a dialog to be displayed
Dialog(this).apply {
setContentView(tableLayoutBinding.root)
setCancelable(true)
// grab the instance of the TableLayout
val table = tableLayoutBinding.tableLayout
// iterate through each feature to add to the TableLayout
queryResults.forEach { feature ->
// prepare the table row
val tableRowBinding = TableRowBinding.inflate(layoutInflater).apply {
oid.text = feature.attributes["oid"].toString()
collectionTimestamp.text = (feature.attributes["collection_timestamp"] as Calendar).time.toString()
}
// add the row to the TableLayout
table.addView(tableRowBinding.root)
}
}.show()
}
}
/**
* Called on app launch or when Android share sheet is closed
*/
private fun resetMap() {
mapView.map.addDoneLoadingListener {
if (mapView.map.loadStatus == LoadStatus.LOADED) {
// clear any feature layers displayed on the map
mapView.map.operationalLayers.clear()
// disable the button since no features are displayed
viewTableButton.isEnabled = false
// create a new geodatabase file to add features into the feature table
createGeodatabase()
} else {
showError("Error loading MapView: ${mapView.map.loadError.message}")
}
}
}
private fun showError(message: String?) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
Log.e(TAG, message.toString())
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
resetMap()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 47a876dfd0c83b5c296837bd02fe1011 | 39.680782 | 137 | 0.626151 | 5.221154 | false | false | false | false |
kingsleyadio/android_commons | demo/src/main/java/com/kingsleyadio/appcommons/demo/MainActivity.kt | 1 | 925 | package com.kingsleyadio.appcommons.demo
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.kingsleyadio.appcommons.demo.databinding.ActivityMainBinding
import java.util.Calendar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setTitle(R.string.app_name)
val cal = Calendar.getInstance().apply {
set(Calendar.YEAR, get(Calendar.YEAR) - 16)
}
with(binding) {
dateView.maxDate = cal.time
dateView.onDateChangeListener = {
Toast.makeText(this@MainActivity, "Date changed: $it", Toast.LENGTH_SHORT).show()
}
textDateView.isEnabled = false
}
}
}
| apache-2.0 | 4492942c49027b61fd16819cde82bfda | 30.896552 | 97 | 0.677838 | 4.512195 | false | false | false | false |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/ChronicleDataAnnotationProcessorKotlinTest.kt | 1 | 9653 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.processor
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinType
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeConnectionProvider
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeGeneratedStorageProviderModule
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReaderWithDataCache
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReaderWithDataCacheImpl
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriterWithDataCache
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriterWithDataCacheImpl
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes.EXPECTED_EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheReader
import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheStorage
import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheWriter
import com.google.android.libraries.pcc.chronicle.storage.datacache.DefaultManagedDataCacheConnectionProvider
import com.google.android.libraries.pcc.chronicle.storage.datacache.ManagedDataCache
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import java.time.Duration
import java.time.temporal.ChronoUnit
import javax.inject.Inject
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
/**
* Tests that Kotlin data classes annotated with @ChronicleData, and @DataCacheStore generate
* expected results.
*/
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
@Config(application = ChronicleDataAnnotationProcessorKotlinTest_Application::class)
class ChronicleDataAnnotationProcessorKotlinTest {
@get:Rule val hiltRule = HiltAndroidRule(this)
@Inject lateinit var dataCacheStorage: DataCacheStorage
@Inject lateinit var managedDataCache: ManagedDataCache<@JvmSuppressWildcards ExampleKotlinType>
@Inject lateinit var dtds: Set<DataTypeDescriptor>
@Before
fun setUp() {
hiltRule.inject()
}
@Test
fun generatedClass_equalsExpectedDTD() {
// Compare the generated DTD for ExampleKotlinType with the manually written, expected DTD.
assertThat(EXAMPLE_KOTLIN_TYPE_GENERATED_DTD)
.isEqualTo(EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD)
}
@Test
fun generatedNestedClass_equalsExpectedDTD() {
// Compare the generated DTD for ExampleNestedKotlinType with the manually written, expected
// DTD.
assertThat(EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD)
.isEqualTo(EXPECTED_EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD)
}
@Test
fun generatedClassWithIBinder_equalsExpectedDTD() {
// Compare the generated DTD for ExampleKotlinIBinderType with the manually written, expected
// DTD.
assertThat(EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD)
.isEqualTo(EXPECTED_EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD)
}
@Test
fun generatedSelfReferentialClass_equalsExpectedDTD() {
// Compare the generated DTD for ExampleSelfReferentialKotlinType with the manually written,
// expected DTD.
assertThat(EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD)
.isEqualTo(EXPECTED_EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD)
}
@Test
fun generatedDtds_injectedIntoSet() {
assertThat(dtds)
.containsAtLeast(
EXAMPLE_KOTLIN_TYPE_GENERATED_DTD,
EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD,
EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD,
EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD
)
}
@Test
fun generatedSet_equalsExpectedConnections() {
// Compare the generated connections for ExampleKotlinType and with the manually written,
// expected connections.
assertThat(EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS)
.isEqualTo(EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS)
}
@Test
fun generatedClass_equalsExpectedManagementStrategy() {
// Compare the generated ManagementStrategy for ExampleKotlinType with the manually written,
// expected ManagementStrategy.
assertThat(EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY)
.isEqualTo(EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY)
}
@Test
fun generatedInt_equalsExpectedMaxItems() {
// Compare the generated maxItems for ExampleKotlinType with the manually written,
// expected maxItems.
assertThat(EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS)
.isEqualTo(EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS)
}
@Test
fun generatedModuleFunctionCall_returnsExpectedStorage() {
// Compare the storage obtained by calling the provider function in the generated module for
// ExampleKotlinType with the manually written, expected storage.
val expectedStorage =
ManagedDataCache.create<ExampleKotlinType>(
dataCacheStorage,
ttl = Duration.of(2, ChronoUnit.DAYS),
maxSize = 1000,
dataTypeDescriptor = EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD,
)
val generatedStorage =
ExampleKotlinTypeGeneratedStorageProviderModule
.provideExampleKotlinTypeManagedDataCacheStorage(dataCacheStorage)
assertThat(generatedStorage.configEquals(expectedStorage)).isTrue()
}
@Test
fun generatedModule_providesExpectedStorageViaHilt() {
val expectedStorage =
ManagedDataCache.create<ExampleKotlinType>(
dataCacheStorage,
ttl = Duration.of(2, ChronoUnit.DAYS),
maxSize = 1000,
dataTypeDescriptor = EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD,
)
assertThat(managedDataCache.configEquals(expectedStorage)).isTrue()
}
@Test
fun generatedReader_isComposedOfReadConnectionAndDataCacheReader() {
val cls = ExampleKotlinTypeReaderWithDataCacheImpl::class.java
assertThat(cls).isAssignableTo(ExampleKotlinTypeReaderWithDataCache::class.java)
assertThat(cls).isAssignableTo(DataCacheReader::class.java)
}
@Test
fun generatedWriter_isComposedOfWriteConnectionAndDataCacheWriter() {
val cls = ExampleKotlinTypeWriterWithDataCacheImpl::class.java
assertThat(cls).isAssignableTo(ExampleKotlinTypeWriterWithDataCache::class.java)
assertThat(cls).isAssignableTo(DataCacheWriter::class.java)
}
@Test
fun generatedConnectionProvider_extendsDefaultManagedDataCacheConnectionProvider() {
val cls = ExampleKotlinTypeConnectionProvider::class.java
assertThat(cls).isAssignableTo(DefaultManagedDataCacheConnectionProvider::class.java)
}
}
| apache-2.0 | f02cda6448316d45088ad1ded0be688c | 48 | 175 | 0.81094 | 4.489767 | false | true | false | false |
gradle/gradle | .teamcity/src/main/kotlin/configurations/SanityCheck.kt | 3 | 708 | package configurations
import model.CIBuildModel
import model.Stage
class SanityCheck(model: CIBuildModel, stage: Stage) : BaseGradleBuildType(stage = stage, init = {
id(buildTypeId(model))
name = "Sanity Check"
description = "Static code analysis, checkstyle, release notes verification, etc."
features {
publishBuildStatusToGithub(model)
}
applyDefaults(
model,
this,
"sanityCheck",
extraParameters = "-DenableCodeQuality=true ${buildScanTag("SanityCheck")} " + "-Porg.gradle.java.installations.auto-download=false"
)
}) {
companion object {
fun buildTypeId(model: CIBuildModel) = "${model.projectId}_SanityCheck"
}
}
| apache-2.0 | 7333b4a29ae1ca1d6077d4bb0168f235 | 27.32 | 140 | 0.680791 | 4.37037 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/view/TrailParticleComponent.kt | 1 | 1247 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.components.view
import com.almasb.fxgl.particle.ParticleComponent
import com.almasb.fxgl.particle.ParticleEmitters
import com.almasb.fxgl.texture.Texture
import javafx.geometry.Point2D
import javafx.scene.effect.BlendMode
import javafx.util.Duration
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class TrailParticleComponent(t: Texture) : ParticleComponent(ParticleEmitters.newSparkEmitter()) {
init {
emitter.blendMode = BlendMode.SRC_OVER
emitter.isAllowParticleRotation = true
emitter.setSourceImage(t)
emitter.emissionRate = 0.4
emitter.numParticles = 1
emitter.setSize(t.width / 2, t.width / 2)
emitter.setVelocityFunction { Point2D.ZERO }
emitter.setScaleFunction { Point2D.ZERO }
emitter.setAccelerationFunction { Point2D.ZERO }
emitter.setSpawnPointFunction { entity.boundingBoxComponent.centerLocal.subtract(t.width / 2, t.width / 2) }
emitter.setExpireFunction { Duration.millis(150.0) }
}
override fun isComponentInjectionRequired(): Boolean = false
} | mit | 848e0f324442fb6dc13f86be844913f6 | 32.72973 | 116 | 0.725742 | 3.933754 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetNameCommand.kt | 1 | 6983 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.characters.bukkit.command.character.set
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.characters.bukkit.protocol.reloadPlayer
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.conversations.*
import org.bukkit.entity.Player
/**
* Character set name command.
* Sets character's name.
*/
class CharacterSetNameCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor {
private val conversationFactory: ConversationFactory
init {
conversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(NamePrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"])
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages["operation-cancelled"])
}
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (!sender.hasPermission("rpkit.characters.command.character.set.name")) {
sender.sendMessage(plugin.messages["no-permission-character-set-name"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character"])
return true
}
if (args.isEmpty()) {
conversationFactory.buildConversation(sender).begin()
return true
}
val nameBuilder = StringBuilder()
for (i in 0 until args.size - 1) {
nameBuilder.append(args[i]).append(" ")
}
nameBuilder.append(args[args.size - 1])
character.name = nameBuilder.toString()
characterService.updateCharacter(character).thenAccept { updatedCharacter ->
if (plugin.config.getBoolean("characters.set-player-nameplate")
&& plugin.server.pluginManager.getPlugin("ProtocolLib") != null) {
reloadPlayer(sender, character, plugin.server.onlinePlayers.filter { it.uniqueId != sender.uniqueId })
}
sender.sendMessage(plugin.messages["character-set-name-valid"])
updatedCharacter?.showCharacterCard(minecraftProfile)
}
return true
}
private inner class NamePrompt : StringPrompt() {
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-name-prompt"]
}
override fun acceptInput(context: ConversationContext, input: String?): Prompt {
val conversable = context.forWhom
if (conversable !is Player) return NameSetPrompt()
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return NameSetPrompt()
val characterService = Services[RPKCharacterService::class.java] ?: return NameSetPrompt()
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(conversable) ?: return NameSetPrompt()
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return NameSetPrompt()
if (input == null) return NameSetPrompt()
character.name = input
characterService.updateCharacter(character)
if (plugin.config.getBoolean("characters.set-player-nameplate")
&& plugin.server.pluginManager.getPlugin("ProtocolLib") != null) {
reloadPlayer(conversable, character, plugin.server.onlinePlayers.filter { it.uniqueId != conversable.uniqueId })
}
return NameSetPrompt()
}
}
private inner class NameSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
val conversable = context.forWhom
if (conversable !is Player) return END_OF_CONVERSATION
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
conversable.sendMessage(plugin.messages["no-minecraft-profile-service"])
return END_OF_CONVERSATION
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
conversable.sendMessage(plugin.messages["no-character-service"])
return END_OF_CONVERSATION
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(context.forWhom as Player)
if (minecraftProfile != null) {
characterService.getPreloadedActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile)
}
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-name-valid"]
}
}
}
| apache-2.0 | 34ed97b9cb693d21c6d7a1c64bc602ff | 44.344156 | 128 | 0.660318 | 5.230712 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/message/html/HtmlConverter.kt | 1 | 2244 | package com.fsck.k9.message.html
import org.jsoup.Jsoup
/**
* Contains common routines to convert html to text and vice versa.
*/
object HtmlConverter {
/**
* When generating previews, Spannable objects that can't be converted into a String are
* represented as 0xfffc. When displayed, these show up as undisplayed squares. These constants
* define the object character and the replacement character.
*/
private const val PREVIEW_OBJECT_CHARACTER = 0xfffc.toChar()
private const val PREVIEW_OBJECT_REPLACEMENT = 0x20.toChar() // space
/**
* toHtml() converts non-breaking spaces into the UTF-8 non-breaking space, which doesn't get
* rendered properly in some clients. Replace it with a simple space.
*/
private const val NBSP_CHARACTER = 0x00a0.toChar() // utf-8 non-breaking space
private const val NBSP_REPLACEMENT = 0x20.toChar() // space
/**
* Convert an HTML string to a plain text string.
*/
@JvmStatic
fun htmlToText(html: String): String {
val document = Jsoup.parse(html)
return HtmlToPlainText.toPlainText(document.body())
.replace(PREVIEW_OBJECT_CHARACTER, PREVIEW_OBJECT_REPLACEMENT)
.replace(NBSP_CHARACTER, NBSP_REPLACEMENT)
}
/**
* Convert a text string into an HTML document.
*
* No HTML headers or footers are added to the result. Headers and footers are added at display time.
*/
@JvmStatic
fun textToHtml(text: String): String {
return EmailTextToHtml.convert(text)
}
/**
* Convert a plain text string into an HTML fragment.
*/
@JvmStatic
fun textToHtmlFragment(text: String): String {
return TextToHtml.toHtmlFragment(text, retainOriginalWhitespace = false)
}
/**
* Convert a plain text string into an HTML fragment.
*
* This does not convert consecutive spaces to a series of non-breaking spaces followed by a regular space.
* Only use this in combination with CSS to properly display the whitespace.
*/
@JvmStatic
fun textToHtmlFragmentWithOriginalWhitespace(text: String): String {
return TextToHtml.toHtmlFragment(text, retainOriginalWhitespace = true)
}
}
| apache-2.0 | 48bcf72c2d24d2f5962f19e268a19409 | 34.619048 | 111 | 0.684046 | 4.426036 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RustItemsOwner.kt | 1 | 1286 | package org.rust.lang.core.psi
import org.rust.lang.core.parser.RustPsiTreeUtil
import org.rust.lang.core.resolve.scope.RustResolveScope
interface RustItemsOwner : RustResolveScope
private inline fun <reified I : RustItemElement> RustItemsOwner.items(): List<I> =
RustPsiTreeUtil.getStubChildrenOfTypeAsList(this, I::class.java)
val RustItemsOwner.allItems: List<RustItemElement> get() = items()
val RustItemsOwner.allItemDefinitions: List<RustNamedElement>
get() = listOf<List<RustNamedElement>>(
items<RustConstItemElement>(),
items<RustEnumItemElement>(),
items<RustFnItemElement>(),
items<RustModItemElement>(),
items<RustStaticItemElement>(),
items<RustStructItemElement>(),
items<RustTraitItemElement>(),
items<RustTypeItemElement>()
).flatten()
val RustItemsOwner.impls: List<RustImplItemElement> get() = items()
val RustItemsOwner.functions: List<RustFnItemElement> get() = items()
val RustItemsOwner.useDeclarations: List<RustUseItemElement> get() = items()
val RustItemsOwner.modDecls: List<RustModDeclItemElement> get() = items()
val RustItemsOwner.foreignMods: List<RustForeignModItemElement> get() = items()
val RustItemsOwner.externCrates: List<RustExternCrateItemElement> get() = items()
| mit | b1447614d7c3228bedbc50c6f4396ea8 | 40.483871 | 82 | 0.75661 | 4.08254 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidocommon/src/main/java/com/izeni/rapidocommon/network/NetworkCallback.kt | 1 | 1629 | package com.izeni.rapidocommon.network
import com.izeni.rapidocommon.d
import com.izeni.rapidocommon.e
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException
interface NetworkCallback<in T> {
fun onError(exception: HttpException)
fun onSuccess(data: T)
fun onFatal(exception: Throwable)
companion object {
fun <T> from(onSuccess: (T) -> Unit, onError: ((HttpException) -> Unit)? = null, onFatal: ((Throwable) -> Unit)? = null): NetworkCallback<T> {
return object: NetworkCallback<T> {
override fun onFatal(exception: Throwable) {
if(onFatal != null) onFatal(exception) else e("exception:", t = exception)
}
override fun onError(exception: HttpException) {
if(onError != null) onError(exception) else e("exception: ${exception.message()}", t = exception)
}
override fun onSuccess(data: T) {
onSuccess(data)
}
}
}
}
}
class SilentNetworkCallback(): NetworkCallback<Any?> {
override fun onError(exception: HttpException) {
}
override fun onFatal(exception: Throwable) {
}
override fun onSuccess(data: Any?) {
}
}
abstract class SimpleNetworkCallback<in T>(): NetworkCallback<T> {
override fun onError(exception: HttpException) {
e("exception: ${exception.message()}", t = exception)
}
override fun onFatal(exception: Throwable) {
e("exception:", t = exception)
}
override fun onSuccess(data: T) {
d("success: [$data]")
}
} | mit | 96890accce4c3436dbe461da335c62ac | 27.596491 | 150 | 0.605279 | 4.414634 | false | false | false | false |
JackParisi/DroidBox | droidbox/src/main/java/com/github/giacomoparisi/droidbox/validator/adapter/LenghtAdapters.kt | 1 | 2685 | package com.github.giacomoparisi.droidbox.validator.adapter
import androidx.databinding.BindingAdapter
import android.widget.TextView
import com.github.giacomoparisi.droidbox.R
import com.github.giacomoparisi.droidbox.utility.DroidResourcesHelper
import com.github.giacomoparisi.droidbox.validator.helper.DroidEditTextHelper
import com.github.giacomoparisi.droidbox.validator.helper.DroidViewTagHelper
import com.github.giacomoparisi.droidbox.validator.rule.EmptyDroidValidatorRule
import com.github.giacomoparisi.droidbox.validator.rule.MaxLengthDroidValidatorRule
import com.github.giacomoparisi.droidbox.validator.rule.MinLengthDroidValidatorRule
/**
* Created by Giacomo Parisi on 15/02/18.
* https://github.com/giacomoParisi
*/
@BindingAdapter("validator_empty", "validator_empty_ErrorMessage", "validator_empty_AutoDismiss", requireAll = false)
fun bindValidatorEmpty(view: TextView, empty: Boolean, errorMessage: String?, autoDismiss: Boolean?) {
if (autoDismiss != null && autoDismiss) {
DroidEditTextHelper.disableErrorOnChanged(view)
}
val handledErrorMessage = DroidResourcesHelper.getStringOrDefault(
view,
errorMessage,
R.string.error_message_empty_validation)
DroidViewTagHelper.appendValue(R.id.validator_rule, view, EmptyDroidValidatorRule(view, empty, handledErrorMessage))
}
@BindingAdapter("validator_maxLength", "validator_maxLength_ErrorMessage", "validator_maxLength_AutoDismiss", requireAll = false)
fun bindValidatorMaxLength(view: TextView, maxLength: Int, errorMessage: String?, autoDismiss: Boolean?) {
if (autoDismiss != null && autoDismiss) {
DroidEditTextHelper.disableErrorOnChanged(view)
}
val handledErrorMessage = DroidResourcesHelper.getStringOrDefault(
view,
errorMessage,
R.string.error_message_max_length,
maxLength)
DroidViewTagHelper.appendValue(R.id.validator_rule, view, MaxLengthDroidValidatorRule(view, maxLength, handledErrorMessage))
}
@BindingAdapter("validator_minLength", "validator_minLength_ErrorMessage", "validator_minLength_AutoDismiss", requireAll = false)
fun bindValidatorMinLength(view: TextView, minLength: Int, errorMessage: String?, autoDismiss: Boolean?) {
if (autoDismiss != null && autoDismiss) {
DroidEditTextHelper.disableErrorOnChanged(view)
}
val handledErrorMessage = DroidResourcesHelper.getStringOrDefault(
view,
errorMessage,
R.string.error_message_min_length,
minLength)
DroidViewTagHelper.appendValue(R.id.validator_rule, view, MinLengthDroidValidatorRule(view, minLength, handledErrorMessage))
} | apache-2.0 | 733170b37b9b94771d6a4e3c7256beb2 | 46.122807 | 129 | 0.768715 | 4.527825 | false | false | false | false |
lanhuaguizha/Christian | common/src/main/java/com/christian/common/data/source/local/GospelLocalDataSource.kt | 1 | 3138 | package com.christian.common.data.source.local
import androidx.lifecycle.LiveData
import androidx.lifecycle.map
import com.christian.common.data.Gospel
import com.christian.common.data.Result
import com.christian.common.data.source.GospelDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class GospelLocalDataSource internal constructor(
private val gospelDao: GospelDao,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : GospelDataSource {
// Insert
override suspend fun saveGospel(gospel: Gospel, selectedLanguage: String): Result<Void>? = withContext(ioDispatcher) {
Result.Success(gospelDao.insertGospel(gospel))
return@withContext null
}
// Delete
override suspend fun clearCompletedWritings() = withContext<Unit>(ioDispatcher) {
gospelDao.deleteCompletedWritings()
}
override suspend fun deleteAllWritings() = withContext(ioDispatcher) {
gospelDao.deleteWritings()
}
override suspend fun deleteWriting(writingId: String, selectedLanguage: String): Result<Void>? = withContext(ioDispatcher) {
Result.Success(gospelDao.deleteWritingById(writingId))
return@withContext null
}
// Update
override suspend fun completeWriting(gospel: Gospel) = withContext(ioDispatcher) {
gospelDao.updateCompleted(gospel.gospelId, true)
}
override suspend fun completeWriting(writingId: String) {
gospelDao.updateCompleted(writingId, true)
}
override suspend fun activateWriting(gospel: Gospel) = withContext(ioDispatcher) {
gospelDao.updateCompleted(gospel.gospelId, false)
}
override suspend fun activateWriting(writingId: String) {
gospelDao.updateCompleted(writingId, false)
}
// Query
override fun observeWritings(): LiveData<Result<List<Gospel>>> {
return gospelDao.observeWritings().map {
Result.Success(it)
}
}
override fun observeWriting(writingId: String): LiveData<Result<Gospel>> {
return gospelDao.observeWritingById(writingId).map {
Result.Success(it)
}
}
override suspend fun getGospels(): Result<List<Gospel>> = withContext(ioDispatcher) {
return@withContext try {
Result.Success(gospelDao.getWritings())
} catch (e: Exception) {
Result.Error(e)
}
}
override suspend fun getGospel(writingId: String): Result<Gospel> =
withContext(ioDispatcher) {
try {
val writing = gospelDao.getWritingById(writingId)
// if (writing != null) {
return@withContext Result.Success(writing)
// } else {
// return@withContext Error(Exception("Task not found!"))
// }
} catch (e: Exception) {
return@withContext Result.Error(e)
}
}
override suspend fun refreshWritings() {
// NO-OP
}
override suspend fun refreshWriting(writingId: String) {
// NO-OP
}
} | gpl-3.0 | 469183cd3310d4c624da0cbddf8df15d | 32.042105 | 128 | 0.670809 | 4.547826 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/fo/EpisodeFO.kt | 1 | 1212 | package cz.vhromada.catalog.web.fo
import org.hibernate.validator.constraints.Range
import java.io.Serializable
import java.util.Objects
import javax.validation.Valid
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull
/**
* A class represents FO for episode.
*
* @author Vladimir Hromada
*/
data class EpisodeFO(
/**
* ID
*/
val id: Int?,
/**
* Number of episode
*/
@field:Range(min = 1, max = 500)
val number: String?,
/**
* Name
*/
@field:NotBlank
val name: String?,
/**
* Length
*/
@field:NotNull
@field:Valid
var length: TimeFO?,
/**
* Note
*/
val note: String?,
/**
* Position
*/
val position: Int?) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return if (other !is EpisodeFO || id == null) {
false
} else id == other.id
}
override fun hashCode(): Int {
return Objects.hashCode(id)
}
}
| mit | 509bcda3f2125d08946f2612f78b6c91 | 17.9375 | 55 | 0.510726 | 4.423358 | false | false | false | false |
fabmax/calculator | app/src/main/kotlin/de/fabmax/calc/ParallaxHelper.kt | 1 | 17060 | package de.fabmax.calc
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.opengl.Matrix
import android.util.Log
import android.view.Display
import android.view.Surface
import android.view.WindowManager
import de.fabmax.lightgl.util.GlMath
/**
* ParallaxHelper uses the gyro to compute an orientation matrix which can be used to update
* a camera position and light direction. If no gyro is available on the device the acceleration
* sensor is used as fallback.
*/
class ParallaxHelper(context: Context) : SensorEventListener {
private val mDisplay: Display
private val mSensorManager: SensorManager
private val mGyro: Sensor?
private val mAcceleration: Sensor?
private var mRegistered = false
private var mTimestamp = 0L
// delta rotation measured by sensor
private val mSensorRotation = FloatArray(3)
private val mAccelSensorRotation = FloatArray(12)
// rotation quaternion computed on sensor update
private val mDeltaRotationVector = FloatArray(4)
// 3x3 rotation matrix computed from quaternion on sensor update
private val mDeltaRotationMatrix = FloatArray(9)
// OpenGL transform matrices for camera, light and temp buffers
private val mRotationMatrix = FloatArray(64)
private val mTestVec = FloatArray(3)
// controls how strong the gyro affects the rotation matrix
private var mIntensity = 1.0f
private var mIntensityLight = 1.0f
private var mInvertX = false;
private var mInvertY = false;
var rotation = 0f
init {
mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
mGyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
if (mGyro == null) {
// use acceleration sensor as fallback
mAcceleration = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
} else {
mAcceleration = null
}
// we need the window manager to get the screen rotation
mDisplay = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
}
fun onResume() {
if (!mRegistered) {
mTimestamp = 0
Matrix.setIdentityM(mRotationMatrix, ROT_CAMERA_OFF)
Matrix.setIdentityM(mRotationMatrix, ROT_LIGHT_OFF)
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF] = 0f
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 1] = 0f
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 2] = 0f
mAccelSensorRotation[ACCEL_LAST_VEC_OFF] = 0f
mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 1] = 0f
mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 2] = 0f
if (mGyro != null) {
Log.d(TAG, "register gyro listener")
mSensorManager.registerListener(this, mGyro, SensorManager.SENSOR_DELAY_GAME)
mRegistered = true
} else if (mAcceleration != null) {
Log.d(TAG, "register acceleration listener")
mSensorManager.registerListener(this, mAcceleration, SensorManager.SENSOR_DELAY_GAME)
mRegistered = true
}
}
}
fun onPause() {
if (mRegistered) {
Log.d(TAG, "unregister gyro listener")
mSensorManager.unregisterListener(this)
mRegistered = false
}
}
fun setIntensity(intensityObj: Float, intensityLight: Float) {
mIntensity = intensityObj
mIntensityLight = intensityLight
}
fun invertAxis(invertX: Boolean, invertY: Boolean) {
mInvertX = invertX
mInvertY = invertY
}
fun clearLightRotationMatrix() {
Matrix.setIdentityM(mRotationMatrix, ROT_LIGHT_OFF)
}
fun transformLightVector(vec3: FloatArray) {
synchronized (mRotationMatrix) {
transformVec3(vec3, mRotationMatrix, ROT_LIGHT_OFF)
}
}
fun transformCameraVector(vec3: FloatArray) {
synchronized (mRotationMatrix) {
transformVec3(vec3, mRotationMatrix, ROT_CAMERA_OFF)
}
}
override fun onSensorChanged(event: SensorEvent) {
// compute time since last method call in seconds
val dT = (event.timestamp - mTimestamp) * 1e-9f
if (mTimestamp != 0L && dT != 0f) {
if (event.sensor.type == Sensor.TYPE_GYROSCOPE) {
mSensorRotation[0] = event.values[0]
mSensorRotation[1] = event.values[1]
mSensorRotation[2] = event.values[2]
if (mInvertX) {
mSensorRotation[0] = -mSensorRotation[0]
}
if (mInvertY) {
mSensorRotation[1] = -mSensorRotation[1]
}
// convert rotation axis from device coordinates to screen coordinates
considerDisplayRotation(mSensorRotation, 0)
} else if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
// make some magic
computeDeltaAccelRotation(event.values)
}
// compute rotation matrices for camera and light
integrateSensorRotation(dT)
}
mTimestamp = event.timestamp
}
private fun computeDeltaAccelRotation(accelValues: FloatArray) {
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF] = accelValues[0]
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 1] = accelValues[1]
mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 2] = accelValues[2]
// convert rotation axis from device coordinates to screen coordinates
considerDisplayRotation(mAccelSensorRotation, ACCEL_CURRENT_VEC_OFF)
val x = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF]
val y = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 1]
val z = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 2]
val lx = mAccelSensorRotation[ACCEL_LAST_VEC_OFF]
val ly = mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 1]
val lz = mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 2]
mAccelSensorRotation[ACCEL_LAST_VEC_OFF] = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF]
mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 1] = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 1]
mAccelSensorRotation[ACCEL_LAST_VEC_OFF + 2] = mAccelSensorRotation[ACCEL_CURRENT_VEC_OFF + 2]
// determine delta rotation around x-axis
var rot = 0f
var m = y * y + z * z
var ml = ly * ly + lz * lz
if (m > EPSILON_ACCEL && ml > EPSILON_ACCEL) {
m = Math.sqrt(m.toDouble()).toFloat()
ml = Math.sqrt(ml.toDouble()).toFloat()
var cos = y / m * (lz / ml) + z / m * (-ly / ml)
if (cos > 1) {
cos = 1f
} else if (cos < -1) {
cos = -1f
}
rot = 90.0f - Math.acos(cos.toDouble()).toFloat() / GlMath.PI * 180.0f
}
// integrate rotation
mAccelSensorRotation[ACCEL_ROT_OFF] = (mAccelSensorRotation[ACCEL_ROT_OFF] + rot) * (1 - PULL_BACK * 2)
// filter integrated rotation
rot = mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF] * 0.85f + mAccelSensorRotation[ACCEL_ROT_OFF] * 0.15f
// compute delta of integrated rotation
mSensorRotation[0] = (rot - mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF]) / 1.5f
mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF] = rot
// determine delta rotation around y-axis
rot = 0f
m = x * x + z * z
ml = lx * lx + lz * lz
if (m > EPSILON_ACCEL && ml > EPSILON_ACCEL) {
m = Math.sqrt(m.toDouble()).toFloat()
ml = Math.sqrt(ml.toDouble()).toFloat()
var cos = x / m * (-lz / ml) + z / m * (lx / ml)
if (cos > 1) {
cos = 1f
} else if (cos < -1) {
cos = -1f
}
rot = 90.0f - Math.acos(cos.toDouble()).toFloat() / GlMath.PI * 180.0f
}
// integrate rotation
mAccelSensorRotation[ACCEL_ROT_OFF + 1] = (mAccelSensorRotation[ACCEL_ROT_OFF + 1] + rot) * (1 - PULL_BACK * 2)
// filter integrated rotation
rot = mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF + 1] * 0.85f + mAccelSensorRotation[ACCEL_ROT_OFF + 1] * 0.15f
// compute delta of integrated rotation
mSensorRotation[1] = (rot - mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF + 1]) / 1.5f
mAccelSensorRotation[ACCEL_FILTERED_ROT_OFF + 1] = rot
}
private fun integrateSensorRotation(dT: Float) {
val rotX = mSensorRotation[0]
val rotY = mSensorRotation[1]
val rotZ = mSensorRotation[2]
// integrate object rotation
mSensorRotation[0] *= mIntensity
mSensorRotation[1] *= mIntensity
mSensorRotation[2] *= mIntensity
integrateRotationMatrix(mSensorRotation, dT, ROT_CAMERA_OFF, MAX_SIN)
// integrate light rotation
mSensorRotation[0] = rotX * mIntensityLight
mSensorRotation[1] = rotY * mIntensityLight
mSensorRotation[2] = rotZ * mIntensityLight
integrateRotationMatrix(mSensorRotation, dT, ROT_LIGHT_OFF, MAX_SIN_LIGHT)
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
// good to know, but actually we don't care
}
private fun considerDisplayRotation(sample: FloatArray, off: Int) {
val f: Float
when (mDisplay.rotation) {
Surface.ROTATION_90 -> {
f = sample[off + 1]
sample[off + 1] = sample[off]
sample[off] = -f
}
Surface.ROTATION_180 -> {
sample[off + 1] = -sample[off + 1]
sample[off] = -sample[off]
}
Surface.ROTATION_270 -> {
f = sample[off + 1]
sample[off + 1] = -sample[off]
sample[off] = f
}
}
val x = sample[off];
val y = sample[off + 1];
val c = Math.cos(-rotation.toDouble()).toFloat();
val s = Math.sin(-rotation.toDouble()).toFloat();
sample[off] = x * c + y * -s
sample[off + 1] = x * s + y * c
}
private fun integrateRotationMatrix(deltaAxis: FloatArray, dT: Float, destOff: Int, maxSin: Float) {
var axisX = deltaAxis[0]
var axisY = deltaAxis[1]
var axisZ = deltaAxis[2]
// Calculate the angular speed of the sample
val omegaMagnitude = Math.sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ.toDouble()).toFloat()
// Normalize the rotation vector if it's big enough to get the axis
if (omegaMagnitude > EPSILON) {
axisX /= omegaMagnitude
axisY /= omegaMagnitude
axisZ /= omegaMagnitude
}
// Integrate around this axis with the angular speed by the timestep
// in order to get a delta rotation from this sample over the timestep
// We will convert this axis-angle representation of the delta rotation
// into a quaternion before turning it into the rotation matrix.
val thetaOverTwo = omegaMagnitude * dT / 2.0f
val sinThetaOverTwo = Math.sin(thetaOverTwo.toDouble()).toFloat()
val cosThetaOverTwo = Math.cos(thetaOverTwo.toDouble()).toFloat()
mDeltaRotationVector[0] = sinThetaOverTwo * axisX
mDeltaRotationVector[1] = sinThetaOverTwo * axisY
mDeltaRotationVector[2] = sinThetaOverTwo * axisZ
mDeltaRotationVector[3] = cosThetaOverTwo
// compute 3x3 delta rotation matrix and convert it to 4x4
SensorManager.getRotationMatrixFromVector(mDeltaRotationMatrix, mDeltaRotationVector)
convert3x3to4x4(mDeltaRotationMatrix, mRotationMatrix, ROT_DELTA_OFF)
// integrate delta rotation to rotation matrix
Matrix.multiplyMM(mRotationMatrix, ROT_TEMP_OFF, mRotationMatrix, destOff, mRotationMatrix, ROT_DELTA_OFF)
synchronized (mRotationMatrix) {
System.arraycopy(mRotationMatrix, ROT_TEMP_OFF, mRotationMatrix, destOff, 16)
filterOutMatrix(destOff, maxSin)
}
}
private fun convert3x3to4x4(m3x3: FloatArray, m4x4: FloatArray, off: Int) {
m4x4[off] = m3x3[0]
m4x4[off + 1] = m3x3[1]
m4x4[off + 2] = m3x3[2]
m4x4[off + 3] = 0f
m4x4[off + 4] = m3x3[3]
m4x4[off + 5] = m3x3[4]
m4x4[off + 6] = m3x3[5]
m4x4[off + 7] = 0f
m4x4[off + 8] = m3x3[6]
m4x4[off + 9] = m3x3[7]
m4x4[off + 10] = m3x3[8]
m4x4[off + 11] = 0f
m4x4[off + 12] = 0f
m4x4[off + 13] = 0f
m4x4[off + 14] = 0f
m4x4[off + 15] = 1f
}
private fun filterOutMatrix(destOff: Int, maxSin: Float) {
// slowly pull matrix to identity
val f0 = 1 - PULL_BACK
mRotationMatrix[destOff] = mRotationMatrix[destOff] * f0 + PULL_BACK
mRotationMatrix[destOff + 5] = mRotationMatrix[destOff + 5] * f0 + PULL_BACK
mRotationMatrix[destOff + 10] = mRotationMatrix[destOff + 10] * f0 + PULL_BACK
mRotationMatrix[destOff + 1] *= f0
mRotationMatrix[destOff + 2] *= f0
mRotationMatrix[destOff + 4] *= f0
mRotationMatrix[destOff + 6] *= f0
mRotationMatrix[destOff + 8] *= f0
mRotationMatrix[destOff + 9] *= f0
mTestVec[0] = 0f
mTestVec[1] = 0f
mTestVec[2] = 1f
transformVec3(mTestVec, mRotationMatrix, destOff)
val sinx = mTestVec[0]
val siny = mTestVec[1]
if (sinx > maxSin) {
val a = (Math.asin(sinx.toDouble()) - Math.asin(maxSin.toDouble())).toFloat() / GlMath.PI * 180
Matrix.rotateM(mRotationMatrix, destOff, -a, 0f, 1f, 0f)
} else if (sinx < -maxSin) {
val a = (Math.asin(sinx.toDouble()) - Math.asin((-maxSin).toDouble())).toFloat() / GlMath.PI * 180
Matrix.rotateM(mRotationMatrix, destOff, -a, 0f, 1f, 0f)
}
if (siny > maxSin) {
val a = (Math.asin(siny.toDouble()) - Math.asin(maxSin.toDouble())).toFloat() / GlMath.PI * 180
Matrix.rotateM(mRotationMatrix, destOff, a, 1f, 0f, 0f)
} else if (siny < -maxSin) {
val a = (Math.asin(siny.toDouble()) - Math.asin((-maxSin).toDouble())).toFloat() / GlMath.PI * 180
Matrix.rotateM(mRotationMatrix, destOff, a, 1f, 0f, 0f)
}
// ortho-normalize rotation matrix
// normalize X
GlMath.normalize(mRotationMatrix, destOff)
// Z = X x Y
cross(mRotationMatrix, destOff + 8, mRotationMatrix, destOff, mRotationMatrix, destOff + 4)
GlMath.normalize(mRotationMatrix, destOff + 8)
// Y = Z x X
cross(mRotationMatrix, destOff + 4, mRotationMatrix, destOff + 8, mRotationMatrix, destOff)
}
private fun cross(result: FloatArray, resultOff: Int, lhs: FloatArray, lhsOff: Int, rhs: FloatArray, rhsOff: Int) {
result[resultOff] = lhs[lhsOff + 1] * rhs[rhsOff + 2] - lhs[lhsOff + 2] * rhs[rhsOff + 1]
result[resultOff + 1] = lhs[lhsOff + 2] * rhs[rhsOff] - lhs[lhsOff] * rhs[rhsOff + 2]
result[resultOff + 2] = lhs[lhsOff] * rhs[rhsOff + 1] - lhs[lhsOff + 1] * rhs[rhsOff]
}
private fun transformVec3(vec3: FloatArray, mat: FloatArray, matOff: Int) {
val x = vec3[0] * mat[matOff] + vec3[1] * mat[matOff + 4] + vec3[2] * mat[matOff + 8]
val y = vec3[0] * mat[matOff + 1] + vec3[1] * mat[matOff + 5] + vec3[2] * mat[matOff + 9]
val z = vec3[0] * mat[matOff + 2] + vec3[1] * mat[matOff + 6] + vec3[2] * mat[matOff + 10]
vec3[0] = x
vec3[1] = y
vec3[2] = z
}
companion object {
private val TAG = "ParallaxHelper"
val NO_ROT_AVAILABLE = 0
val GYRO_AVAILABLE = 1
val ACCEL_AVAILABLE = 2
private val EPSILON = 0.001f
private val EPSILON_ACCEL = 2.0f
private val MAX_SIN = 0.2f
private val MAX_SIN_LIGHT = 0.7f
private val PULL_BACK = 0.005f
// offsets for mRotationMatrix
private val ROT_CAMERA_OFF = 0
private val ROT_LIGHT_OFF = 16
private val ROT_DELTA_OFF = 32
private val ROT_TEMP_OFF = 48
// offsets for acceleration sensor based rotation
private val ACCEL_ROT_OFF = 0
private val ACCEL_FILTERED_ROT_OFF = 3
private val ACCEL_CURRENT_VEC_OFF = 6
private val ACCEL_LAST_VEC_OFF = 9
fun availableRotationMode(context: Context): Int {
val sm = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
if (sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null) {
return GYRO_AVAILABLE
} else if (sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
return ACCEL_AVAILABLE
} else {
return NO_ROT_AVAILABLE
}
}
}
}
| apache-2.0 | ee0323b4e4edd3a8331cbdaef6865a1a | 38.7669 | 120 | 0.606506 | 3.760194 | false | false | false | false |
albertoruibal/karballo | karballo-common/src/main/kotlin/karballo/search/Node.kt | 1 | 1001 | package karballo.search
import karballo.Move
import karballo.bitboard.AttacksInfo
import karballo.evaluation.Evaluator
/**
* Stores the elements to be kept in each node of the search tree
*
* Other nodes may access this elements
*/
class Node(searchEngine: SearchEngine, var distanceToInitialPly: Int) {
// Current move
var move: Int = 0
// Transposition table move
var ttMove: Int = 0
// Two killer move slots
var killerMove1: Int = 0
var killerMove2: Int = 0
// The static node eval
var staticEval: Int = 0
// The Move iterator
var attacksInfo: AttacksInfo = AttacksInfo()
var moveIterator: MoveIterator
init {
moveIterator = MoveIterator(searchEngine, attacksInfo, distanceToInitialPly)
clear()
}
fun clear() {
ttMove = Move.NONE
killerMove1 = Move.NONE
killerMove2 = Move.NONE
staticEval = Evaluator.NO_VALUE
}
fun destroy() {
moveIterator.destroy()
}
} | mit | 2306aadf0d8d152461c87c8591a000dc | 19.875 | 84 | 0.658342 | 4.069106 | false | false | false | false |
xfournet/intellij-community | java/compiler/impl/src/com/intellij/compiler/impl/CleanStaleModuleOutputsActivity.kt | 7 | 5821 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.compiler.impl
import com.intellij.CommonBundle
import com.intellij.compiler.server.BuildManager
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.compiler.CompilerBundle
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.CompilerModuleExtension
import com.intellij.openapi.roots.CompilerProjectExtension
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
/**
* Shows notification which suggests to delete stale output directories corresponding to renamed or deleted modules. Such directories may
* be kept on disk because of a bug (https://youtrack.jetbrains.com/issue/IDEA-185574) in previous IntelliJ IDEA versions.
*/
class CleanStaleModuleOutputsActivity : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
val markerFile = File(BuildManager.getInstance().getProjectSystemDirectory(project), "stale_outputs_checked")
if (markerFile.exists()) return
fun createMarker() {
FileUtil.createIfDoesntExist(markerFile)
}
val staleOutputs = runReadAction { collectStaleOutputs(project) }
if (staleOutputs.isEmpty()) {
createMarker()
return
}
runReadAction {
val outputPath = CompilerProjectExtension.getInstance(project)!!.compilerOutput!!.presentableUrl
val notification = Notification(
"Build", CompilerBundle.message("notification.title.delete.old.output.directories"),
CompilerBundle.message("notification.content.delete.old.output.directories", staleOutputs.size, outputPath),
NotificationType.INFORMATION
).addAction(object : NotificationAction(CompilerBundle.message("notification.action.text.cleanup")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
notification.expire()
runCleanup(staleOutputs, project, ::createMarker)
}
}).addAction(object : NotificationAction(CompilerBundle.message("notification.action.text.do.not.ask")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
notification.expire()
createMarker()
}
})
Notifications.Bus.notify(notification, project)
}
}
private fun runCleanup(outputs: List<VirtualFile>, project: Project, onSuccess: () -> Unit) {
val outputsString: String
val threshold = 50
if (outputs.size <= threshold + 2) {
outputsString = outputs.joinToString("<br>") { it.presentableUrl }
}
else {
val parents = outputs.subList(threshold, outputs.size).mapTo(LinkedHashSet()) {it.parent}.toList()
outputsString = (outputs.subList(0, threshold).map {it.presentableUrl}
+ listOf("${outputs.size - threshold} more directories under ${parents.first().presentableUrl}")
+ parents.drop(1).map { "and ${it.presentableUrl}" }
).joinToString("<br>")
}
//until IDEA-186296 is fixed we need to use IDEA's message dialog for potentially long messages
val answer = Messages.showIdeaMessageDialog(project, CompilerBundle.message("dialog.text.delete.old.outputs", outputs.size, outputsString),
CompilerBundle.message("dialog.title.delete.old.outputs"),
arrayOf(CompilerBundle.message("button.text.delete.old.outputs"), CommonBundle.getCancelButtonText()), 0,null, null)
if (answer == Messages.CANCEL) return
val filesToDelete = outputs.map { VfsUtil.virtualToIoFile(it) }
object : Task.Backgroundable(project, CompilerBundle.message("dialog.title.delete.old.outputs")) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
filesToDelete.forEachIndexed { i, file ->
indicator.checkCanceled()
indicator.fraction = i.toDouble() / filesToDelete.size
indicator.text = CompilerBundle.message("progress.text.deleting.directory", file.absolutePath)
FileUtil.delete(file)
}
onSuccess()
indicator.text = CompilerBundle.message("progress.text.synchronizing.output.directories")
LocalFileSystem.getInstance().refreshIoFiles(filesToDelete, true, false, null)
}
}.queue()
}
private fun collectStaleOutputs(project: Project): List<VirtualFile> {
val projectOutput = CompilerProjectExtension.getInstance(project)?.compilerOutput
if (projectOutput == null) return emptyList()
val outputsOnDisk = listOf(CompilerModuleExtension.PRODUCTION, CompilerModuleExtension.TEST)
.flatMap { projectOutput.findChild(it)?.children?.asIterable() ?: emptyList() }
val currentOutputs = ModuleManager.getInstance(project).modules.flatMap {
val extension = CompilerModuleExtension.getInstance(it)
listOfNotNull(extension?.compilerOutputPath, extension?.compilerOutputPathForTests)
}
return outputsOnDisk - currentOutputs
}
} | apache-2.0 | 17f151604d4ba759877185a9d87ccc77 | 47.92437 | 161 | 0.731318 | 4.87113 | false | false | false | false |
tinypass/piano-sdk-for-android | id/id/src/main/java/io/piano/android/id/models/PianoIdToken.kt | 1 | 815 | package io.piano.android.id.models
import android.os.Parcelable
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import java.util.Date
@Parcelize
class PianoIdToken(
@JvmField val accessToken: String,
@JvmField val refreshToken: String = "",
@JvmField val info: @RawValue Map<String, Any> = emptyMap(),
) : Parcelable {
@IgnoredOnParcel
@JvmField
val expiresInTimestamp: Long = getInfoField("exp") ?: 0
@IgnoredOnParcel
@JvmField
val emailConfirmationRequired: Boolean = getInfoField("email_confirmation_required") ?: false
@IgnoredOnParcel
@JvmField
val expiresIn: Date = Date(expiresInTimestamp * 1000)
@Suppress("UNCHECKED_CAST")
fun <T> getInfoField(name: String): T? = info[name] as? T
}
| apache-2.0 | 7a9951775514c6c2843b2cabec34c62e | 27.103448 | 97 | 0.728834 | 4.267016 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/backend/AsmToAst.kt | 1 | 8837 | package com.jtransc.backend
import com.jtransc.ast.*
import com.jtransc.ds.Concat
import com.jtransc.ds.cast
import com.jtransc.ds.createPairs
import com.jtransc.ds.hasFlag
import com.jtransc.error.invalidOp
import com.jtransc.injector.Singleton
import com.jtransc.lang.ReflectedArray
import com.jtransc.org.objectweb.asm.ClassReader
import com.jtransc.org.objectweb.asm.Handle
import com.jtransc.org.objectweb.asm.Opcodes
import com.jtransc.org.objectweb.asm.tree.*
import java.io.IOException
import java.util.*
@Singleton
abstract class BaseAsmToAst(val types: AstTypes, val settings: AstBuildSettings) : AstClassGenerator {
open val expandFrames = false
override fun generateClass(program: AstProgram, fqname: FqName): AstClass {
val cr = try {
ClassReader(program.getClassBytes(fqname))
} catch (e: IOException) {
invalidOp("generateClass: Can't find class $fqname")
}
val classNode = ClassNode()
cr.accept(classNode, if (expandFrames) ClassReader.EXPAND_FRAMES else ClassReader.SKIP_FRAMES)
// SourceFile
//val cw = ClassWriter(cr, ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES);
//classNode.accept(cw);
val astClass = AstClass(
source = classNode.sourceDebug ?: "${classNode.name}.java",
program = program,
name = FqName.fromInternal(classNode.name),
modifiers = AstModifiers(classNode.access),
annotations = classNode.getAnnotations(types),
extending = if (classNode.hasSuperclass() && !classNode.isInterface()) FqName.fromInternal(classNode.superName) else null,
implementing = classNode.getInterfaces().map { FqName.fromInternal(it) }
)
program.add(astClass)
classNode.getMethods().withIndex().forEach { astClass.add(generateMethod(astClass, it.value)) }
classNode.getFields().withIndex().forEach { astClass.add(generateField(astClass, it.value)) }
return astClass
}
fun generateMethod(containingClass: AstClass, method: MethodNode): AstMethod {
val mods = AstModifiers(method.access)
val methodRef = method.astRef(containingClass.ref, types)
return AstMethod(
containingClass = containingClass,
annotations = method.getAnnotations(types),
parameterAnnotations = method.getParameterAnnotations(types),
name = method.name,
methodType = methodRef.type,
signature = methodRef.type.mangle(),
genericSignature = method.signature,
defaultTag = AstAnnotationValue(method.annotationDefault, visible = true, types = types),
modifiers = mods,
generateBody = {
if (mods.isConcrete) {
try {
genBody(containingClass.ref, method, types, containingClass.source)
} catch (e: Throwable) {
println("Error trying to generate ${containingClass.name}::${method.name} ${method.desc}")
e.printStackTrace()
null
}
} else {
null
}
}
)
}
abstract fun genBody(classRef: AstType.REF, methodNode: MethodNode, types: AstTypes, source: String): AstBody
fun generateField(containingClass: AstClass, field: FieldNode): AstField = AstField(
containingClass = containingClass,
name = field.name,
annotations = field.getAnnotations(types),
type = types.demangle(field.desc),
desc = field.desc,
genericSignature = field.signature,
modifiers = AstModifiers(field.access),
constantValue = field.value,
types = types
)
}
fun AstAnnotationValue(value: Any?, visible: Boolean, types: AstTypes): Any? {
if (value == null) return null
val clazz = value.javaClass
if (clazz.isArray && clazz.componentType == java.lang.String::class.java) {
val array = value as Array<String>
return AstFieldWithoutTypeRef((types.demangle(array[0]) as AstType.REF).name, array[1])
}
if (value is ArrayList<*>) {
return value.map { AstAnnotationValue(it, visible, types) }
}
if (clazz.isArray) {
return ReflectedArray(value).toList().map { AstAnnotationValue(it, visible, types) }
}
if (value is AnnotationNode) {
val type = types.demangle(value.desc) as AstType.REF
val fields = hashMapOf<String, Any?>()
if (value.values != null) {
val values = value.values
var n = 0
while (n < values.size) {
val name = values[n++] as String
val value = values[n++]
fields[name] = AstAnnotationValue(value, visible, types)
}
//println(node.values)
//println(node.values)
}
return AstAnnotation(type, fields, visible)
}
return value
}
fun AstAnnotationBuilder(node: AnnotationNode, visible: Boolean, types: AstTypes): AstAnnotation {
return AstAnnotationValue(node, visible, types) as AstAnnotation
}
val ANNOTATIONS_BLACKLIST = listOf(
"java.lang.annotation.Documented", "java.lang.Deprecated",
"java.lang.annotation.Target", "java.lang.annotation.Retention",
"kotlin.jvm.internal.KotlinLocalClass", "kotlin.jvm.internal.KotlinSyntheticClass",
"kotlin.jvm.internal.KotlinClass", "kotlin.jvm.internal.KotlinFunction",
"kotlin.jvm.internal.KotlinFileFacade", "kotlin.jvm.internal.KotlinMultifileClassPart",
"kotlin.jvm.internal.KotlinMultifileClass", "kotlin.annotation.MustBeDocumented",
"kotlin.annotation.Target", "kotlin.annotation.Retention",
"kotlin.jvm.JvmStatic", "kotlin.Deprecated", "kotlin.Metadata", "org.jetbrains.annotations.NotNull",
"kotlin.internal.InlineExposed"
).map { AstType.REF(it) }.toSet()
fun List<AstAnnotation>.filterBlackList(): List<AstAnnotation> {
return this.filter { it.type !in com.jtransc.backend.ANNOTATIONS_BLACKLIST }
}
fun Handle.ast(types: AstTypes): AstMethodRef = AstMethodRef(FqName.fromInternal(this.owner), this.name, types.demangleMethod(this.desc))
fun AnnotationNode.toAst(types: AstTypes): AstAnnotation {
val ref = types.demangle(this.desc) as AstType.REF
return AstAnnotation(ref, this.values.createPairs().map { Pair(it.first as String, it.second as String) }.toMap(), true)
}
fun ClassNode.isInterface() = this.access hasFlag Opcodes.ACC_INTERFACE
fun ClassNode.isAbstract() = this.access hasFlag Opcodes.ACC_ABSTRACT
fun ClassNode.hasSuperclass() = this.superName != null
fun ClassNode.getInterfaces() = this.interfaces.cast<String>()
fun ClassNode.getMethods() = this.methods.cast<MethodNode>()
fun ClassNode.getFields() = this.fields.cast<FieldNode>()
private fun getAnnotations(visibleAnnotations: List<AnnotationNode>?, invisibleAnnotations: List<AnnotationNode>?, types: AstTypes): List<AstAnnotation> {
val visible = Concat(visibleAnnotations).filterNotNull().filterIsInstance<AnnotationNode>().map { AstAnnotationBuilder(it, visible = true, types = types) }.filterBlackList()
val invisible = Concat(invisibleAnnotations).filterNotNull().filterIsInstance<AnnotationNode>().map { AstAnnotationBuilder(it, visible = false, types = types) }.filterBlackList()
return visible + invisible
}
fun ClassNode.getAnnotations(types: AstTypes) = getAnnotations(this.visibleAnnotations, this.invisibleAnnotations, types)
fun MethodNode.getAnnotations(types: AstTypes) = getAnnotations(this.visibleAnnotations, this.invisibleAnnotations, types)
fun FieldNode.getAnnotations(types: AstTypes) = getAnnotations(this.visibleAnnotations, this.invisibleAnnotations, types)
@Suppress("UNNECESSARY_SAFE_CALL")
private fun MethodNode._getParameterAnnotations(type: AstType.METHOD, annotations: Array<List<AnnotationNode>>?, types: AstTypes, visible: Boolean): List<List<AstAnnotation>> {
return annotations?.toList()
?.map {
it?.filterNotNull()?.filterIsInstance<AnnotationNode>()
?.map { AstAnnotationBuilder(it, visible = visible, types = types) }
?.filterBlackList()
?: listOf()
}
?: (0 until type.argCount).map { listOf<AstAnnotation>() }
}
fun MethodNode.getParameterAnnotations(types: AstTypes): List<List<AstAnnotation>> {
val type = types.demangleMethod(this.desc)
val visible = this._getParameterAnnotations(type, this.visibleParameterAnnotations, types, visible = true)
val invisible = this._getParameterAnnotations(type, this.invisibleParameterAnnotations, types, visible = false)
return (0 until type.argCount).map { visible[it] + invisible[it] }
}
fun MethodNode.isStatic() = this.access hasFlag Opcodes.ACC_STATIC
fun MethodNode.isNative() = this.access hasFlag Opcodes.ACC_NATIVE
fun MethodNode.hasBody() = this.instructions.first != null
fun MethodNode.visibility() = if (this.access hasFlag Opcodes.ACC_PUBLIC) {
AstVisibility.PUBLIC
} else if (this.access hasFlag Opcodes.ACC_PROTECTED) {
AstVisibility.PROTECTED
} else {
AstVisibility.PRIVATE
}
fun MethodNode.astRef(clazz: AstType.REF, types: AstTypes) = AstMethodRef(clazz.name, this.name, types.demangleMethod(this.desc))
fun AbstractInsnNode.isEndOfBasicBlock(): Boolean = when (this.opcode) {
in Opcodes.IFEQ..Opcodes.IF_ACMPNE -> true
else -> isEnd()
}
fun AbstractInsnNode.isEnd(): Boolean = when (this.opcode) {
in Opcodes.TABLESWITCH..Opcodes.LOOKUPSWITCH -> true
Opcodes.GOTO -> true
Opcodes.ATHROW -> true
in Opcodes.IRETURN..Opcodes.RETURN -> true
else -> false
}
| apache-2.0 | fda19d986b9b6e50b9cfcaca2c3e0511 | 39.723502 | 179 | 0.754781 | 3.742906 | false | false | false | false |
pyamsoft/zaptorch | app/src/main/java/com/pyamsoft/zaptorch/main/HowToDialog.kt | 1 | 2881 | /*
* Copyright 2020 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.zaptorch.main
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CheckResult
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import coil.ImageLoader
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.inject.Injector
import com.pyamsoft.pydroid.ui.app.makeFullWidth
import com.pyamsoft.pydroid.ui.theme.ThemeProvider
import com.pyamsoft.pydroid.ui.theme.Theming
import com.pyamsoft.pydroid.ui.util.show
import com.pyamsoft.zaptorch.R
import com.pyamsoft.zaptorch.ZapTorchComponent
import com.pyamsoft.zaptorch.ZapTorchTheme
import javax.inject.Inject
class HowToDialog : DialogFragment() {
@JvmField @Inject internal var imageLoader: ImageLoader? = null
@JvmField @Inject internal var theming: Theming? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val act = requireActivity()
Injector.obtainFromApplication<ZapTorchComponent>(act).inject(this)
val themeProvider = ThemeProvider { theming.requireNotNull().isDarkTheme(act) }
return ComposeView(act).apply {
id = R.id.dialog_accessibility
setContent {
ZapTorchTheme(themeProvider) {
HowToScreen(
modifier = Modifier.fillMaxWidth(),
onClose = { dismiss() },
)
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
makeFullWidth()
}
override fun onDestroyView() {
super.onDestroyView()
(view as? ComposeView)?.disposeComposition()
imageLoader = null
theming = null
}
companion object {
private const val TAG = "HowToDialog"
@JvmStatic
@CheckResult
private fun newInstance(): DialogFragment {
return HowToDialog().apply { arguments = Bundle().apply {} }
}
@JvmStatic
fun show(activity: FragmentActivity) {
newInstance().show(activity, TAG)
}
}
}
| apache-2.0 | b6c2f32109a3075f844ee6e6c4c56e33 | 29.010417 | 83 | 0.734814 | 4.391768 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseActivity.kt | 1 | 2444 | package eu.kanade.tachiyomi.ui.base.activity
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import eu.kanade.tachiyomi.App
import eu.kanade.tachiyomi.R
open class BaseActivity : AppCompatActivity() {
protected fun setupToolbar(toolbar: Toolbar, backNavigation: Boolean = true) {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (backNavigation) {
toolbar.setNavigationOnClickListener { onBackPressed() }
}
}
fun setAppTheme() {
when (app.appTheme) {
2 -> setTheme(R.style.Theme_Tachiyomi_Dark)
else -> setTheme(R.style.Theme_Tachiyomi)
}
}
fun setToolbarTitle(title: String) {
supportActionBar?.title = title
}
fun setToolbarTitle(titleResource: Int) {
supportActionBar?.title = getString(titleResource)
}
fun setToolbarSubtitle(title: String) {
supportActionBar?.subtitle = title
}
fun setToolbarSubtitle(titleResource: Int) {
supportActionBar?.subtitle = getString(titleResource)
}
/**
* Requests read and write permissions on Android M and higher.
*/
fun requestPermissionsOnMarshmallow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
1)
}
}
}
protected val app: App
get() = App.get(this)
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
val textView = snack.view.findViewById(android.support.design.R.id.snackbar_text) as TextView
textView.setTextColor(Color.WHITE)
snack.f()
snack.show()
}
} | apache-2.0 | 41dc25f41b31f425c38aeb09d2958afd | 30.753247 | 119 | 0.675941 | 4.542751 | false | false | false | false |
bertilxi/Chilly_Willy_Delivery | mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/model/Sauce.kt | 1 | 1423 | package dam.isi.frsf.utn.edu.ar.delivery.model
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import dam.isi.frsf.utn.edu.ar.delivery.constants.appConstants
data class Sauce(
@SerializedName("label")
@Expose
override var label: String = "",
@SerializedName("imgURL")
@Expose
var imgURL: String = ""
) : Addin, Parcelable {
fun withLabel(label: String): Sauce {
this.label = label
return this
}
fun withImgURL(imgURL: String): Sauce {
this.imgURL = imgURL
return this
}
override val completeImgURL: String
get() = appConstants.staticPath + "sauceImages/" + imgURL
override fun toString(): String {
return label
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<Sauce> = object : Parcelable.Creator<Sauce> {
override fun createFromParcel(source: Parcel): Sauce = Sauce(source)
override fun newArray(size: Int): Array<Sauce?> = arrayOfNulls(size)
}
}
constructor(source: Parcel) : this(
source.readString(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(label)
dest.writeString(imgURL)
}
} | mit | eda6d43338c76f77921f2ce074778d8c | 26.384615 | 95 | 0.640197 | 4.173021 | false | false | false | false |
SpryServers/sprycloud-android | src/main/java/com/nextcloud/client/logger/ThreadLoop.kt | 3 | 2277 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* 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.logger
/**
* This utility runs provided loop body continuously in a loop on a background thread
* and allows start and stop the loop thread in a safe way.
*/
internal class ThreadLoop {
private val lock = Object()
private var thread: Thread? = null
private var loopBody: (() -> Unit)? = null
/**
* Start running [loopBody] in a loop on a background [Thread].
* If loop is already started, it no-ops.
*
* This method is thread safe.
*
* @throws IllegalStateException if loop is already running
*/
fun start(loopBody: () -> Unit) {
synchronized(lock) {
if (thread == null) {
this.loopBody = loopBody
this.thread = Thread(this::loop)
this.thread?.start()
}
}
}
/**
* Stops the background [Thread] by interrupting it and waits for [Thread.join].
* If loop is not started, it no-ops.
*
* This method is thread safe.
*
* @throws IllegalStateException if thread is not running
*/
fun stop() {
synchronized(lock) {
if (thread != null) {
thread?.interrupt()
thread?.join()
}
}
}
private fun loop() {
try {
while (true) {
loopBody?.invoke()
}
} catch (ex: InterruptedException) {
return
}
}
}
| gpl-2.0 | fae24923331fb31e86c746baa2d1a53f | 28.960526 | 85 | 0.607817 | 4.438596 | false | false | false | false |
udevbe/westmalle | compositor/src/main/kotlin/org/westford/compositor/gles2/Gles2Renderer.kt | 3 | 47179 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* 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 org.westford.compositor.gles2
import org.freedesktop.jaccall.JNI
import org.freedesktop.jaccall.Pointer
import org.freedesktop.jaccall.Pointer.malloc
import org.freedesktop.jaccall.Pointer.wrap
import org.freedesktop.jaccall.Size.sizeof
import org.freedesktop.wayland.server.Display
import org.freedesktop.wayland.server.ShmBuffer
import org.freedesktop.wayland.server.WlBufferResource
import org.freedesktop.wayland.server.WlSurfaceResource
import org.freedesktop.wayland.shared.WlShmFormat
import org.westford.compositor.core.*
import org.westford.compositor.core.calc.Mat4
import org.westford.compositor.gles2.Gles2Shaders.FRAGMENT_SHADER_EGL_EXTERNAL
import org.westford.compositor.gles2.Gles2Shaders.FRAGMENT_SHADER_EGL_Y_UV
import org.westford.compositor.gles2.Gles2Shaders.FRAGMENT_SHADER_EGL_Y_U_V
import org.westford.compositor.gles2.Gles2Shaders.FRAGMENT_SHADER_EGL_Y_XUXV
import org.westford.compositor.gles2.Gles2Shaders.VERTEX_SHADER
import org.westford.compositor.protocol.WlOutput
import org.westford.compositor.protocol.WlSurface
import org.westford.nativ.libEGL.*
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_ALPHA_SIZE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_BLUE_SIZE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_GREEN_SIZE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_HEIGHT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NONE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_CONTEXT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_DISPLAY
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_IMAGE_KHR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_OPENGL_ES2_BIT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_OPENGL_ES_API
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_RED_SIZE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_RENDERABLE_TYPE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_SURFACE_TYPE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_EXTERNAL_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_FORMAT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_RGB
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_RGBA
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_Y_UV_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_Y_U_V_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_TEXTURE_Y_XUXV_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_WAYLAND_BUFFER_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_WAYLAND_PLANE_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_WAYLAND_Y_INVERTED_WL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_WIDTH
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_WINDOW_BIT
import org.westford.nativ.libGLESv2.GlEGLImageTargetTexture2DOES
import org.westford.nativ.libGLESv2.LibGLESv2
import java.util.concurrent.TimeUnit.NANOSECONDS
import java.util.logging.Logger
import javax.inject.Inject
import javax.inject.Singleton
@Singleton class Gles2Renderer @Inject internal constructor(private val libEGL: LibEGL,
private val libGLESv2: LibGLESv2,
private val display: Display) : GlRenderer {
private val textureArgs = IntArray(3)
private var eglQueryWaylandBufferWL: EglQueryWaylandBufferWL? = null
private var eglCreateImageKHR: EglCreateImageKHR? = null
private var eglDestroyImageKHR: EglDestroyImageKHR? = null
private var glEGLImageTargetTexture2DOES: GlEGLImageTargetTexture2DOES? = null
//shader programs
//used by shm & egl
private var argb8888ShaderProgram: Int = 0
//used by shm
private var xrgb8888ShaderProgram: Int = 0
//used by egl
private var y_u_vShaderProgram: Int = 0
private var y_uvShaderProgram: Int = 0
private var y_xuxvShaderProgram: Int = 0
private var externalImageShaderProgram: Int = 0
//shader args:
//used by shm & egl
private var projectionArg: Int = 0
private var transformArg: Int = 0
private var positionArg: Int = 0
private var textureCoordinateArg: Int = 0
private var eglDisplay = EGL_NO_DISPLAY
private var hasWlEglDisplay = false
private var init = false
private var eglOutputState: EglOutputState? = null
private var newEglOutputState: EglOutputState = EglOutputState(Mat4.IDENTITY)
override fun onDestroy(wlSurfaceResource: WlSurfaceResource) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
wlSurface.surface.renderState?.accept(object : SurfaceRenderStateVisitor {
override fun visit(shmSurfaceState: ShmSurfaceState): SurfaceRenderState? {
destroy(shmSurfaceState)
return null
}
override fun visit(eglSurfaceState: EglSurfaceState): SurfaceRenderState? {
destroy(eglSurfaceState)
return null
}
})
}
private fun destroy(eglSurfaceState: EglSurfaceState) {
//delete textures & egl images
for (texture in eglSurfaceState.textures) {
this.libGLESv2.glDeleteTextures(1,
Pointer.nref(texture).address)
}
for (eglImage in eglSurfaceState.eglImages) {
this.eglDestroyImageKHR?.let {
it(this.eglDisplay,
eglImage)
}
}
}
private fun destroy(shmSurfaceState: ShmSurfaceState) {
//delete texture
this.libGLESv2.glDeleteTextures(1,
Pointer.nref(shmSurfaceState.texture).address)
}
override fun queryBuffer(wlBufferResource: WlBufferResource): Buffer {
val buffer: Buffer
val shmBuffer = ShmBuffer.get(wlBufferResource)
if (shmBuffer != null) {
buffer = SmBuffer(shmBuffer.width,
shmBuffer.height,
wlBufferResource,
shmBuffer)
}
else if (this.eglQueryWaylandBufferWL != null) {
val queryWlEglBuffer = this.eglQueryWaylandBufferWL
val textureFormatP = Pointer.nref(0)
val bufferPointer = wlBufferResource.pointer
if (queryWlEglBuffer != null) {
queryWlEglBuffer(this.eglDisplay,
bufferPointer!!,
EGL_TEXTURE_FORMAT,
textureFormatP.address)
}
val textureFormat = textureFormatP.get()
if (textureFormat != 0) {
val widthP = Pointer.nref(0)
val heightP = Pointer.nref(0)
if (queryWlEglBuffer != null) {
queryWlEglBuffer(this.eglDisplay,
bufferPointer,
EGL_WIDTH,
widthP.address)
}
if (queryWlEglBuffer != null) {
queryWlEglBuffer(this.eglDisplay,
bufferPointer,
EGL_HEIGHT,
heightP.address)
}
val width = widthP.get()
val height = heightP.get()
buffer = EglBuffer(width,
height,
wlBufferResource,
textureFormat)
}
else {
buffer = UnsupportedBuffer(wlBufferResource)
}
}
else {
//TODO dma buffer.
buffer = UnsupportedBuffer(wlBufferResource)
}
return buffer
}
override fun eglConfig(eglDisplay: Long,
eglExtensions: String): Long {
assert(eglDisplay != EGL_NO_DISPLAY)
if (this.libEGL.eglBindAPI(EGL_OPENGL_ES_API).toLong() == 0L) {
throw RuntimeException("eglBindAPI failed")
}
val configs_size = 256 * sizeof(null as Pointer<*>?)
val configs = malloc(configs_size,
Pointer::class.java)
val num_configs = Pointer.nref(0)
val egl_config_attribs = Pointer.nref(//@formatter:off
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 0,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
//@formatter:on
)
if (this.libEGL.eglChooseConfig(eglDisplay,
egl_config_attribs.address,
configs.address,
configs_size,
num_configs.address) == 0) {
throw RuntimeException("eglChooseConfig() failed")
}
if (num_configs.get() == 0) {
throw RuntimeException("failed to find suitable EGLConfig")
}
bindWlEglDisplay(eglDisplay,
eglExtensions)
this.eglDisplay = eglDisplay
return configs.get().address
}
private fun bindWlEglDisplay(eglDisplay: Long,
eglExtensions: String) {
if (bindDisplay(eglDisplay,
eglExtensions)) {
this.eglQueryWaylandBufferWL = wrap(EglQueryWaylandBufferWL::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglQueryWaylandBufferWL").address)).get()
//FIXME we need to check this gl extension before we can be 100% sure we support wayland egl.
this.glEGLImageTargetTexture2DOES = wrap(GlEGLImageTargetTexture2DOES::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("glEGLImageTargetTexture2DOES").address)).get()
if (eglExtensions.contains("EGL_KHR_image_base")) {
this.eglCreateImageKHR = wrap(EglCreateImageKHR::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglCreateImageKHR").address)).get()
this.eglDestroyImageKHR = wrap(EglDestroyImageKHR::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglDestroyImageKHR").address)).get()
this.hasWlEglDisplay = true
}
else {
LOGGER.warning("Extension EGL_KHR_image_base not available. Required for client side egl support.")
}
}
}
private fun bindDisplay(eglDisplay: Long,
extensions: String): Boolean {
if (extensions.contains("EGL_WL_bind_wayland_display")) {
val eglBindWaylandDisplayWL = Pointer.wrap<EglBindWaylandDisplayWL>(EglBindWaylandDisplayWL::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglBindWaylandDisplayWL").address))
return eglBindWaylandDisplayWL.get()(eglDisplay,
this.display.pointer) != 0
}
else {
LOGGER.warning("Extension EGL_WL_bind_wayland_display not available. Required for client side egl support.")
return false
}
}
/**
* Prepare the renderer for drawing.
*
*
* This makes sure all subsequent calls to [.drawView] have the correct transformations set up for the given output.
* @param eglOutput
* *
* @param wlOutput
*/
fun prepareDraw(eglOutput: EglOutput,
wlOutput: WlOutput) {
this.libEGL.eglMakeCurrent(this.eglDisplay,
eglOutput.eglSurface,
eglOutput.eglSurface,
eglOutput.eglContext)
if (!this.init) {
//one time init because we need a current context
assert(eglOutput.eglContext != EGL_NO_CONTEXT)
initRenderer()
}
setupEglOutputState(eglOutput,
wlOutput)
//TODO comment out these 2 calls when we have a shell that provides a solid background.
this.libGLESv2.glClearColor(1.0f,
1.0f,
1.0f,
1.0f)
this.libGLESv2.glClear(LibGLESv2.GL_COLOR_BUFFER_BIT)
}
/**
* Flush all pending drawing commands and signal any listeners that drawing has finish for the given output.
* @param eglOutput
*/
fun finishDraw(eglOutput: EglOutput) {
flushRenderState(eglOutput)
}
private fun initRenderer() {
//check for required texture glExtensions
val glExtensions = wrap<String>(String::class.java,
this.libGLESv2.glGetString(LibGLESv2.GL_EXTENSIONS)).get()
//init shm shaders
LOGGER.info("GLESv2 glExtensions: " + glExtensions)
if (!glExtensions.contains("GL_EXT_texture_format_BGRA8888")) {
LOGGER.severe("Required extension GL_EXT_texture_format_BGRA8888 not available")
System.exit(1)
}
//this shader is reused in wl egl
this.argb8888ShaderProgram = createShaderProgram(VERTEX_SHADER,
Gles2Shaders.FRAGMENT_SHADER_ARGB8888,
1)
this.xrgb8888ShaderProgram = createShaderProgram(VERTEX_SHADER,
Gles2Shaders.FRAGMENT_SHADER_XRGB8888,
1)
//compile wl egl shaders
if (this.hasWlEglDisplay) {
this.y_u_vShaderProgram = createShaderProgram(VERTEX_SHADER,
FRAGMENT_SHADER_EGL_Y_U_V,
3)
this.y_uvShaderProgram = createShaderProgram(VERTEX_SHADER,
FRAGMENT_SHADER_EGL_Y_UV,
2)
this.y_xuxvShaderProgram = createShaderProgram(VERTEX_SHADER,
FRAGMENT_SHADER_EGL_Y_XUXV,
2)
if (glExtensions.contains("GL_OES_EGL_image_external")) {
this.externalImageShaderProgram = createShaderProgram(VERTEX_SHADER,
FRAGMENT_SHADER_EGL_EXTERNAL,
1)
}
else {
LOGGER.warning("Extension GL_OES_EGL_image_external not available.")
}
}
//configure texture blending
this.libGLESv2.glBlendFunc(LibGLESv2.GL_ONE,
LibGLESv2.GL_ONE_MINUS_SRC_ALPHA)
this.init = true
}
private fun setupEglOutputState(eglOutput: EglOutput,
wlOutput: WlOutput) {
//to be used state
val eglOutputState = eglOutput.state ?: initOutputRenderState(eglOutput,
wlOutput)
//updates to state are registered with the builder
this.newEglOutputState = eglOutputState
this.eglOutputState = eglOutputState
}
private fun flushRenderState(eglOutput: EglOutput) {
eglOutput.state = this.newEglOutputState
this.libEGL.eglSwapBuffers(this.eglDisplay,
eglOutput.eglSurface)
}
private fun createShaderProgram(vertexShaderSource: String,
fragmentShaderSource: String,
nroTextures: Int): Int {
val vertexShader = compileShader(vertexShaderSource,
LibGLESv2.GL_VERTEX_SHADER)
val fragmentShader = compileShader(fragmentShaderSource,
LibGLESv2.GL_FRAGMENT_SHADER)
//shader program
val shaderProgram = this.libGLESv2.glCreateProgram()
this.libGLESv2.glAttachShader(shaderProgram,
vertexShader)
this.libGLESv2.glAttachShader(shaderProgram,
fragmentShader)
this.libGLESv2.glLinkProgram(shaderProgram)
//check the link status
val linked = Pointer.nref(0)
this.libGLESv2.glGetProgramiv(shaderProgram,
LibGLESv2.GL_LINK_STATUS,
linked.address)
if (linked.get() == 0) {
val infoLen = Pointer.nref(0)
this.libGLESv2.glGetProgramiv(shaderProgram,
LibGLESv2.GL_INFO_LOG_LENGTH,
infoLen.address)
var logSize = infoLen.get()
if (logSize <= 0) {
//some drivers report incorrect log size
logSize = 1024
}
val log = Pointer.nref(String(CharArray(logSize)))
this.libGLESv2.glGetProgramInfoLog(shaderProgram,
logSize,
0L,
log.address)
this.libGLESv2.glDeleteProgram(shaderProgram)
System.err.println("Error compiling the vertex shader: " + log.get())
System.exit(1)
}
//find shader arguments
this.projectionArg = this.libGLESv2.glGetUniformLocation(shaderProgram,
Pointer.nref("u_projection").address)
this.transformArg = this.libGLESv2.glGetUniformLocation(shaderProgram,
Pointer.nref("u_transform").address)
this.positionArg = this.libGLESv2.glGetAttribLocation(shaderProgram,
Pointer.nref("a_position").address)
this.textureCoordinateArg = this.libGLESv2.glGetAttribLocation(shaderProgram,
Pointer.nref("a_texCoord").address)
for (i in 0..nroTextures - 1) {
this.textureArgs[i] = this.libGLESv2.glGetUniformLocation(shaderProgram,
Pointer.nref("u_texture" + i).address)
}
return shaderProgram
}
private fun initOutputRenderState(eglOutput: EglOutput,
wlOutput: WlOutput): EglOutputState {
val eglOutputState = EglOutputState(Mat4.IDENTITY)
val output = wlOutput.output
updateTransform(eglOutputState,
output)
eglOutput.state = eglOutputState
//listen for external updates
output.transformSignal.connect {
handleOutputUpdate(eglOutput,
wlOutput)
}
output.modeSignal.connect {
handleOutputUpdate(eglOutput,
wlOutput)
}
return eglOutputState
}
private fun compileShader(shaderSource: String,
shaderType: Int): Int {
val shader = this.libGLESv2.glCreateShader(shaderType)
val shaders = Pointer.nref(Pointer.nref(shaderSource))
this.libGLESv2.glShaderSource(shader,
1,
shaders.address,
0L)
this.libGLESv2.glCompileShader(shader)
checkShaderCompilation(shader)
return shader
}
private fun updateTransform(eglOutputState: EglOutputState,
output: Output) {
val mode = output.mode
val width = mode.width
val height = mode.height
//first time render for this output, clear it.
this.libGLESv2.glViewport(0,
0,
width,
height)
this.libGLESv2.glClearColor(1.0f,
1.0f,
1.0f,
1.0f)
this.libGLESv2.glClear(LibGLESv2.GL_COLOR_BUFFER_BIT)
eglOutputState.glTransform = createGlTransform(output)
}
private fun handleOutputUpdate(eglOutput: EglOutput,
wlOutput: WlOutput) {
eglOutput.state?.let {
updateTransform(it,
wlOutput.output)
eglOutput.state = it
//schedule new render
eglOutput.render(wlOutput)
}
}
private fun checkShaderCompilation(shader: Int) {
val vstatus = Pointer.nref(0)
this.libGLESv2.glGetShaderiv(shader,
LibGLESv2.GL_COMPILE_STATUS,
vstatus.address)
if (vstatus.get() == 0) {
//failure!
//get log length
val logLength = Pointer.nref(0)
this.libGLESv2.glGetShaderiv(shader,
LibGLESv2.GL_INFO_LOG_LENGTH,
logLength.address)
//get log
var logSize = logLength.get()
if (logSize == 0) {
//some drivers report incorrect log size
logSize = 1024
}
val log = Pointer.nref(String(CharArray(logSize)))
this.libGLESv2.glGetShaderInfoLog(shader,
logSize,
0L,
log.address)
System.err.println("Error compiling the vertex shader: " + log.get())
System.exit(1)
}
}
private fun createGlTransform(output: Output): Mat4 {
val mode = output.mode
val width = mode.width
val height = mode.height
//@formatter:off
return Mat4(2.0f / width, 0f, 0f, -1f,
0f, 2.0f / -height, 0f, 1f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f) * output.inverseTransform
//@formatter:on
}
fun drawView(surfaceView: SurfaceView) {
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
wlSurface.surface.state.buffer?.let {
drawView(surfaceView,
it)
}
}
private fun drawView(surfaceView: SurfaceView,
wlBufferResource: WlBufferResource) {
queryBuffer(wlBufferResource).accept(object : BufferVisitor {
override fun visit(buffer: Buffer) {
LOGGER.warning("Unsupported buffer.")
}
override fun visit(eglBuffer: EglBuffer) {
drawEgl(surfaceView,
eglBuffer)
}
override fun visit(smBuffer: SmBuffer) {
drawShm(surfaceView,
smBuffer)
}
})
}
private fun drawShm(surfaceView: SurfaceView,
smBuffer: SmBuffer) {
queryShmSurfaceRenderState(surfaceView,
smBuffer.shmBuffer)?.accept(object : SurfaceRenderStateVisitor {
override fun visit(shmSurfaceState: ShmSurfaceState): SurfaceRenderState? {
drawShm(surfaceView,
shmSurfaceState)
return null
}
})
}
private fun queryShmSurfaceRenderState(surfaceView: SurfaceView,
shmBuffer: ShmBuffer): SurfaceRenderState? {
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val renderStateOptional = surface.renderState?.accept(object : SurfaceRenderStateVisitor {
override fun visit(shmSurfaceState: ShmSurfaceState): SurfaceRenderState? {
//the surface already has an shm render state associated. update it.
return createShmSurfaceRenderState(surfaceView,
shmBuffer,
shmSurfaceState)
}
override fun visit(eglSurfaceState: EglSurfaceState): SurfaceRenderState? {
//the surface was previously associated with an egl render state but is now using an shm render state. create it.
destroy(eglSurfaceState)
//TODO we could reuse the texture id from the egl surface render state
return createShmSurfaceRenderState(surfaceView,
shmBuffer,
oldRenderState = null)
}
}) ?: createShmSurfaceRenderState(surfaceView,
shmBuffer,
oldRenderState = null)
if (renderStateOptional != null) {
surface.renderState = renderStateOptional
}
else {
onDestroy(surfaceView.wlSurfaceResource)
}
return renderStateOptional
}
private fun createShmSurfaceRenderState(surfaceView: SurfaceView,
shmBuffer: ShmBuffer,
oldRenderState: ShmSurfaceState?): SurfaceRenderState? {
//new values
val pitch: Int
val height = shmBuffer.height
val target = LibGLESv2.GL_TEXTURE_2D
val shaderProgram: Int
val glFormat: Int
val glPixelType: Int
val texture: Int
val shmBufferFormat = shmBuffer.format
val argb8888 = WlShmFormat.ARGB8888.value
val xrgb8888 = WlShmFormat.XRGB8888.value
if (argb8888 == shmBufferFormat) {
shaderProgram = this.argb8888ShaderProgram
pitch = shmBuffer.stride / 4
glFormat = LibGLESv2.GL_BGRA_EXT
glPixelType = LibGLESv2.GL_UNSIGNED_BYTE
}
else if (xrgb8888 == shmBufferFormat) {
shaderProgram = this.xrgb8888ShaderProgram
pitch = shmBuffer.stride / 4
glFormat = LibGLESv2.GL_BGRA_EXT
glPixelType = LibGLESv2.GL_UNSIGNED_BYTE
}
else {
LOGGER.warning(String.format("Unknown shm buffer format: %d",
shmBufferFormat))
return null
}
val newShmSurfaceState: ShmSurfaceState
if (oldRenderState != null) {
val oldShmSurfaceState = oldRenderState
texture = oldShmSurfaceState.texture
newShmSurfaceState = ShmSurfaceState(pitch,
height,
target,
shaderProgram,
glFormat,
glPixelType,
texture)
if (pitch != oldShmSurfaceState.pitch || height != oldShmSurfaceState.height || glFormat != oldShmSurfaceState.glFormat || glPixelType != oldShmSurfaceState.glPixelType) {
//state needs full texture updating
shmUpdateAll(surfaceView,
shmBuffer,
newShmSurfaceState)
}
else {
//partial texture update
shmUpdateDamaged(surfaceView,
shmBuffer,
newShmSurfaceState)
}
}
else {
//allocate new texture id & upload full texture
texture = genTexture(target)
newShmSurfaceState = ShmSurfaceState(pitch,
height,
target,
shaderProgram,
glFormat,
glPixelType,
texture)
shmUpdateAll(surfaceView,
shmBuffer,
newShmSurfaceState)
}
return newShmSurfaceState
}
private fun shmUpdateDamaged(wlSurfaceResource: SurfaceView,
shmBuffer: ShmBuffer,
newShmSurfaceState: ShmSurfaceState) {
//TODO implement damage
shmUpdateAll(wlSurfaceResource,
shmBuffer,
newShmSurfaceState)
}
private fun shmUpdateAll(surfaceView: SurfaceView,
shmBuffer: ShmBuffer,
newShmSurfaceState: ShmSurfaceState) {
this.libGLESv2.glBindTexture(newShmSurfaceState.target,
newShmSurfaceState.texture)
shmBuffer.beginAccess()
this.libGLESv2.glTexImage2D(newShmSurfaceState.target,
0,
newShmSurfaceState.glFormat,
newShmSurfaceState.pitch,
newShmSurfaceState.height,
0,
newShmSurfaceState.glFormat,
newShmSurfaceState.glPixelType,
JNI.unwrap(shmBuffer.data))
shmBuffer.endAccess()
this.libGLESv2.glBindTexture(newShmSurfaceState.target,
0)
//FIXME firing the paint callback here is actually wrong since we might still need to draw on a different output. Only when all views of a surface are processed, we can call the fire paint callback.
//TODO Introduce the concept of views => output <-- view (=many2many) --> surface
//FIXME we should only fire the callback once all views are rendered
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
wlSurface.surface.firePaintCallbacks(NANOSECONDS.toMillis(System.nanoTime()).toInt())
}
private fun drawShm(surfaceView: SurfaceView,
shmSurfaceState: ShmSurfaceState) {
val shaderProgram = shmSurfaceState.shaderProgram
//activate & setup shader
this.libGLESv2.glUseProgram(shaderProgram)
setupVertexParams(surfaceView,
shmSurfaceState.pitch.toFloat(),
shmSurfaceState.height.toFloat())
//set the buffer in the shader
this.libGLESv2.glActiveTexture(LibGLESv2.GL_TEXTURE0)
this.libGLESv2.glBindTexture(shmSurfaceState.target,
shmSurfaceState.texture)
this.libGLESv2.glUniform1i(this.textureArgs[0],
0)
//draw
//enable texture blending
this.libGLESv2.glEnable(LibGLESv2.GL_BLEND)
this.libGLESv2.glDrawArrays(LibGLESv2.GL_TRIANGLES,
0,
6)
//cleanup
this.libGLESv2.glDisable(LibGLESv2.GL_BLEND)
this.libGLESv2.glDisableVertexAttribArray(this.positionArg)
this.libGLESv2.glDisableVertexAttribArray(this.textureArgs[0])
this.libGLESv2.glUseProgram(0)
}
private fun queryEglSurfaceRenderState(surfaceView: SurfaceView,
eglBuffer: EglBuffer): SurfaceRenderState? {
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val renderStateOptional = surface.renderState?.accept(object : SurfaceRenderStateVisitor {
override fun visit(shmSurfaceState: ShmSurfaceState): SurfaceRenderState? {
//the surface was previously associated with an shm render state but is now using an egl render state. create it.
destroy(shmSurfaceState)
return createEglSurfaceRenderState(eglBuffer,
oldRenderState = null)
}
override fun visit(eglSurfaceState: EglSurfaceState): SurfaceRenderState? {
//TODO we could reuse the texture id
//the surface already has an egl render state associated. update it.
return createEglSurfaceRenderState(eglBuffer,
eglSurfaceState)
}
}) ?: createEglSurfaceRenderState(eglBuffer,
oldRenderState = null)
if (renderStateOptional != null) {
surface.renderState = renderStateOptional
}
else {
onDestroy(surfaceView.wlSurfaceResource)
}
return renderStateOptional
}
private fun createEglSurfaceRenderState(eglBuffer: EglBuffer,
oldRenderState: EglSurfaceState?): SurfaceRenderState? {
//surface egl render states:
val pitch = eglBuffer.width
val height = eglBuffer.height
var yInverted: Boolean = false
val shaderProgram: Int
val target: Int
val textures: IntArray
val eglImages: LongArray
//gather render states:
val buffer = eglBuffer.wlBufferResource.pointer
val queryWaylandBuffer = this.eglQueryWaylandBufferWL
val yInvertedP = Pointer.nref(0)
if (queryWaylandBuffer != null) {
yInverted = queryWaylandBuffer(this.eglDisplay,
buffer,
EGL_WAYLAND_Y_INVERTED_WL,
yInvertedP.address) == 0 || yInvertedP.get() != 0
}
when (eglBuffer.textureFormat) {
EGL_TEXTURE_RGB, EGL_TEXTURE_RGBA -> {
textures = IntArray(1)
eglImages = LongArray(1)
target = LibGLESv2.GL_TEXTURE_2D
shaderProgram = this.argb8888ShaderProgram
}
EGL_TEXTURE_EXTERNAL_WL -> {
textures = IntArray(1)
eglImages = LongArray(1)
target = LibGLESv2.GL_TEXTURE_EXTERNAL_OES
shaderProgram = this.externalImageShaderProgram
}
EGL_TEXTURE_Y_UV_WL -> {
textures = IntArray(2)
eglImages = LongArray(2)
target = LibGLESv2.GL_TEXTURE_2D
shaderProgram = this.y_uvShaderProgram
}
EGL_TEXTURE_Y_U_V_WL -> {
textures = IntArray(3)
eglImages = LongArray(3)
target = LibGLESv2.GL_TEXTURE_2D
shaderProgram = this.y_u_vShaderProgram
}
EGL_TEXTURE_Y_XUXV_WL -> {
textures = IntArray(2)
eglImages = LongArray(2)
target = LibGLESv2.GL_TEXTURE_2D
shaderProgram = this.y_xuxvShaderProgram
}
else -> {
throw UnsupportedOperationException("Texture format ${eglBuffer.textureFormat} is not supported.")
}
}
//delete old egl images
oldRenderState?.let {
for (oldEglImage in it.eglImages) {
this.eglDestroyImageKHR?.let {
it(eglDisplay,
oldEglImage)
}
}
}
//create egl images
val attribs = IntArray(3)
for (i in eglImages.indices) {
attribs[0] = EGL_WAYLAND_PLANE_WL
attribs[1] = i
attribs[2] = EGL_NONE
val eglImage = this.eglCreateImageKHR?.let {
it(this.eglDisplay,
EGL_NO_CONTEXT,
EGL_WAYLAND_BUFFER_WL,
buffer,
Pointer.nref(*attribs).address)
} ?: 0L
if (eglImage == EGL_NO_IMAGE_KHR) {
return null
}
else {
eglImages[i] = eglImage
}
//make sure we have valid texture ids
oldRenderState?.let {
val oldTextures = it.textures
val deltaNewTextures = textures.size - oldTextures.size
val needNewTextures = deltaNewTextures > 0
//reuse old texture ids
System.arraycopy(oldTextures,
0,
textures,
0,
if (needNewTextures) oldTextures.size else textures.size)
if (needNewTextures) {
//generate missing texture ids
for (j in textures.size - 1 downTo textures.size - deltaNewTextures) {
textures[j] = genTexture(target)
}
}
else if (deltaNewTextures < 0) {
//cleanup old unused texture ids
for (j in oldTextures.size - 1 downTo oldTextures.size + deltaNewTextures) {
this.libGLESv2.glDeleteTextures(1,
Pointer.nref(oldTextures[j]).address)
}
}
}
this.libGLESv2.glActiveTexture(LibGLESv2.GL_TEXTURE0 + i)
this.libGLESv2.glBindTexture(target,
textures[i])
this.glEGLImageTargetTexture2DOES?.let {
it(target,
eglImage)
}
}
return EglSurfaceState(pitch,
height,
target,
shaderProgram,
yInverted,
textures,
eglImages)
}
private fun drawEgl(surfaceView: SurfaceView,
eglBuffer: EglBuffer) {
queryEglSurfaceRenderState(surfaceView,
eglBuffer)?.accept(object : SurfaceRenderStateVisitor {
override fun visit(eglSurfaceState: EglSurfaceState): SurfaceRenderState? {
drawEgl(surfaceView,
eglSurfaceState)
return null
}
})
}
private fun drawEgl(surfaceView: SurfaceView,
eglSurfaceState: EglSurfaceState) {
//TODO unify with drawShm
val shaderProgram = eglSurfaceState.shaderProgram
//activate & setup shader
this.libGLESv2.glUseProgram(shaderProgram)
setupVertexParams(surfaceView,
eglSurfaceState.pitch.toFloat(),
eglSurfaceState.height.toFloat())
//set the buffer in the shader
val textures = eglSurfaceState.textures
run {
var i = 0
val texturesLength = textures.size
while (i < texturesLength) {
val texture = textures[i]
val target = eglSurfaceState.target
this.libGLESv2.glActiveTexture(LibGLESv2.GL_TEXTURE0 + i)
this.libGLESv2.glBindTexture(target,
texture)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_MIN_FILTER,
LibGLESv2.GL_NEAREST)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_MAG_FILTER,
LibGLESv2.GL_NEAREST)
this.libGLESv2.glUniform1i(this.textureArgs[i],
0)
i++
}
}
//draw
//enable texture blending
this.libGLESv2.glEnable(LibGLESv2.GL_BLEND)
this.libGLESv2.glDrawArrays(LibGLESv2.GL_TRIANGLES,
0,
6)
//cleanup
this.libGLESv2.glDisable(LibGLESv2.GL_BLEND)
this.libGLESv2.glDisableVertexAttribArray(this.positionArg)
var i = 0
val texturesLength = textures.size
while (i < texturesLength) {
this.libGLESv2.glDisableVertexAttribArray(this.textureArgs[i])
i++
}
this.libGLESv2.glUseProgram(0)
//FIXME firing the paint callback here is actually wrong since we might still need to draw on a different output. Only when all views of a surface are processed, we can call the fire paint callback.
//FIXME we should only fire the callback once all views are rendered
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
wlSurface.surface.firePaintCallbacks(NANOSECONDS.toMillis(System.nanoTime()).toInt())
}
private fun genTexture(target: Int): Int {
val texture = Pointer.nref(0)
this.libGLESv2.glGenTextures(1,
texture.address)
val textureId = texture.get()
this.libGLESv2.glBindTexture(target,
textureId)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_WRAP_S,
LibGLESv2.GL_CLAMP_TO_EDGE)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_WRAP_T,
LibGLESv2.GL_CLAMP_TO_EDGE)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_MIN_FILTER,
LibGLESv2.GL_NEAREST)
this.libGLESv2.glTexParameteri(target,
LibGLESv2.GL_TEXTURE_MAG_FILTER,
LibGLESv2.GL_NEAREST)
this.libGLESv2.glBindTexture(target,
0)
return textureId
}
private fun setupVertexParams(surfaceView: SurfaceView,
bufferWidth: Float,
bufferHeight: Float) {
val wlSurface = surfaceView.wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val transform = (surfaceView.positionTransform * surface.transform).toArray()
//define vertex data
val vertexData = vertexData(bufferWidth,
bufferHeight)
//upload uniform vertex data
val projectionBuffer = Pointer.nref(*this.eglOutputState!!.glTransform.toArray())
this.libGLESv2.glUniformMatrix4fv(this.projectionArg,
1,
0,
projectionBuffer.address)
val transformBuffer = Pointer.nref(*transform)
this.libGLESv2.glUniformMatrix4fv(this.transformArg,
1,
0,
transformBuffer.address)
//set vertex data in shader
this.libGLESv2.glEnableVertexAttribArray(this.positionArg)
this.libGLESv2.glVertexAttribPointer(this.positionArg,
2,
LibGLESv2.GL_FLOAT,
0,
4 * java.lang.Float.BYTES,
vertexData.address)
this.libGLESv2.glEnableVertexAttribArray(this.textureCoordinateArg)
this.libGLESv2.glVertexAttribPointer(this.textureCoordinateArg,
2,
LibGLESv2.GL_FLOAT,
0,
4 * java.lang.Float.BYTES,
(vertexData + 2).address)
}
private fun vertexData(bufferWidth: Float,
bufferHeight: Float): Pointer<Float> {
//first pair => attribute vec2 a_position
//second pair => attribute vec2 a_texCoord
return Pointer.nref(//top left:
0f,
0f,
0f,
0f, //top right:
bufferWidth,
0f,
1f,
0f, //bottom right:
bufferWidth,
bufferHeight,
1f,
1f, //bottom right:
bufferWidth,
bufferHeight,
1f,
1f, //bottom left:
0f,
bufferHeight,
0f,
1f, //top left:
0f,
0f,
0f,
0f)
}
companion object {
private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
}
}
| agpl-3.0 | d41c4b9b911aabfd0e336a12fd13a477 | 40.494283 | 206 | 0.526548 | 5.287347 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/store/stats/time/PostAndPageViewsStoreTest.kt | 1 | 4807 | package org.wordpress.android.fluxc.store.stats.time
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.LimitMode
import org.wordpress.android.fluxc.model.stats.time.PostAndPageViewsModel
import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.PostAndPageViewsRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.PostAndPageViewsRestClient.PostAndPageViewsResponse
import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS
import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.PostsAndPagesSqlUtils
import org.wordpress.android.fluxc.store.StatsStore.FetchStatsPayload
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.API_ERROR
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import java.util.Date
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
private const val ITEMS_TO_LOAD = 8
private val DATE = Date(0)
@RunWith(MockitoJUnitRunner::class)
class PostAndPageViewsStoreTest {
@Mock lateinit var site: SiteModel
@Mock lateinit var restClient: PostAndPageViewsRestClient
@Mock lateinit var sqlUtils: PostsAndPagesSqlUtils
@Mock lateinit var mapper: TimeStatsMapper
private lateinit var store: PostAndPageViewsStore
@Before
fun setUp() {
store = PostAndPageViewsStore(
restClient,
sqlUtils,
mapper,
initCoroutineEngine()
)
}
@Test
fun `returns post and page views per site`() = test {
val fetchInsightsPayload = FetchStatsPayload(
POST_AND_PAGE_VIEWS_RESPONSE
)
val forced = true
whenever(restClient.fetchPostAndPageViews(site, DAYS, DATE, ITEMS_TO_LOAD + 1, forced)).thenReturn(
fetchInsightsPayload
)
val model = mock<PostAndPageViewsModel>()
whenever(mapper.map(POST_AND_PAGE_VIEWS_RESPONSE, LimitMode.Top(ITEMS_TO_LOAD))).thenReturn(model)
val responseModel = store.fetchPostAndPageViews(site, DAYS, LimitMode.Top(ITEMS_TO_LOAD), DATE, forced)
assertThat(responseModel.model).isEqualTo(model)
verify(sqlUtils).insert(site, POST_AND_PAGE_VIEWS_RESPONSE, DAYS, DATE, ITEMS_TO_LOAD)
}
@Test
fun `returns cached data per site`() = test {
whenever(sqlUtils.hasFreshRequest(site, DAYS, DATE, ITEMS_TO_LOAD)).thenReturn(true)
whenever(sqlUtils.select(site, DAYS, DATE)).thenReturn(POST_AND_PAGE_VIEWS_RESPONSE)
val model = mock<PostAndPageViewsModel>()
whenever(mapper.map(POST_AND_PAGE_VIEWS_RESPONSE, LimitMode.Top(ITEMS_TO_LOAD))).thenReturn(model)
val forced = false
val responseModel = store.fetchPostAndPageViews(site, DAYS, LimitMode.Top(ITEMS_TO_LOAD), DATE, forced)
assertThat(responseModel.model).isEqualTo(model)
assertThat(responseModel.cached).isTrue()
verify(sqlUtils, never()).insert(any(), any(), any(), any<Date>(), isNull())
}
@Test
fun `returns error when post and page day views call fail`() = test {
val type = API_ERROR
val message = "message"
val errorPayload = FetchStatsPayload<PostAndPageViewsResponse>(StatsError(type, message))
val forced = true
whenever(restClient.fetchPostAndPageViews(site, DAYS, DATE, ITEMS_TO_LOAD + 1, forced)).thenReturn(
errorPayload
)
val responseModel = store.fetchPostAndPageViews(site, DAYS, LimitMode.Top(ITEMS_TO_LOAD), DATE, forced)
assertNotNull(responseModel.error)
val error = responseModel.error!!
assertEquals(type, error.type)
assertEquals(message, error.message)
}
@Test
fun `returns post and page day views from db`() {
whenever(sqlUtils.select(site, DAYS, DATE)).thenReturn(POST_AND_PAGE_VIEWS_RESPONSE)
val model = mock<PostAndPageViewsModel>()
whenever(mapper.map(POST_AND_PAGE_VIEWS_RESPONSE, LimitMode.Top(ITEMS_TO_LOAD))).thenReturn(model)
val result = store.getPostAndPageViews(site, DAYS, LimitMode.Top(ITEMS_TO_LOAD), DATE)
assertThat(result).isEqualTo(model)
}
}
| gpl-2.0 | c2879786509204ac3d89e8b58dc6e56a | 41.539823 | 116 | 0.731849 | 4.227792 | false | true | false | false |
lure0xaos/CoffeeTime | app/src/main/kotlin/gargoyle/ct/ui/impl/CTControl.kt | 1 | 8917 | package gargoyle.ct.ui.impl
import gargoyle.ct.config.CTConfig
import gargoyle.ct.config.CTConfigs
import gargoyle.ct.messages.locale.CTPreferencesLocaleProvider
import gargoyle.ct.task.CTTaskUpdatable
import gargoyle.ct.task.impl.CTTask
import gargoyle.ct.ui.CTApp
import gargoyle.ct.ui.CTBlockerTextProvider
import gargoyle.ct.ui.CTControlActions
import gargoyle.ct.ui.CTControlWindow
import gargoyle.ct.ui.impl.control.*
import gargoyle.ct.util.messages.impl.CTMessages
import gargoyle.ct.util.pref.CTPropertyChangeEvent
import gargoyle.ct.util.pref.CTPropertyChangeListener
import gargoyle.ct.util.util.getResourceBundle
import java.awt.Frame
import java.awt.event.ActionEvent
import java.util.*
import javax.swing.*
class CTControl(app: CTApp, owner: Frame) : CTControlActions, CTTaskUpdatable, CTPropertyChangeListener<Any> {
private val app: CTControlActions
private val controlWindow: CTControlWindow
private val group: ButtonGroup
private val textProvider: CTBlockerTextProvider
private lateinit var menu: JPopupMenu
private lateinit var stopMenuItem: CTLocalizableMenuItem
init {
this.app = app
val preferences = app.preferences
textProvider = CTBlockerTextProviderImpl(preferences)
group = ButtonGroup()
controlWindow = CTControlWindowImpl(
owner, preferences, app,
createMenu(
CTMessages(
{ CTApp::class.getResourceBundle(LOC_MESSAGES, it) },
CTPreferencesLocaleProvider(preferences)
), app.loadConfigs(false)
)
)
controlWindow.showMe()
}
private fun createMenu(messages: CTMessages, configs: CTConfigs): JPopupMenu {
menu = JPopupMenu()
addConfigs(menu, configs, null)
menu.add(JSeparator(SwingConstants.HORIZONTAL))
menu.add(
CTLocalizableMenuItem(messages,
object : CTLocalizableAction(messages, STR_NEW_CONFIG, STR_NEW_CONFIG_TOOLTIP) {
override fun actionPerformed(e: ActionEvent) {
onNewConfig(configs, menu)
}
})
)
menu.add(JSeparator(SwingConstants.HORIZONTAL))
stopMenuItem = CTLocalizableMenuItem(messages, object : CTLocalizableAction(
messages, STR_UNARM,
STR_UNARM_TOOLTIP
) {
override fun actionPerformed(e: ActionEvent) {
unarm()
}
})
stopMenuItem.isEnabled = false
menu.add(stopMenuItem)
menu.add(JSeparator(SwingConstants.HORIZONTAL))
menu.add(
CTLocalizableMenuItem(messages,
object : CTLocalizableAction(messages, STR_BROWSE_CONFIGS, STR_BROWSE_CONFIGS_TOOLTIP) {
override fun actionPerformed(e: ActionEvent) {
browseConfigs()
}
})
)
menu.add(JSeparator(SwingConstants.HORIZONTAL))
menu.add(
CTLocalizableMenuItem(messages,
object : CTLocalizableAction(messages, STR_PREFERENCES, STR_PREFERENCES_TOOLTIP) {
override fun actionPerformed(e: ActionEvent) {
showPreferences()
}
})
)
menu.add(CTLocalizableMenuItem(messages, object : CTLocalizableAction(messages, STR_HELP, STR_HELP_TOOLTIP) {
override fun actionPerformed(e: ActionEvent) {
help()
}
}))
menu.add(CTLocalizableMenuItem(messages, object : CTLocalizableAction(messages, STR_ABOUT, "") {
override fun actionPerformed(e: ActionEvent) {
about()
}
}))
menu.add(CTLocalizableMenuItem(messages, object : CTLocalizableAction(messages, STR_EXIT, STR_EXIT_TOOLTIP) {
override fun actionPerformed(e: ActionEvent) {
exit()
}
}))
return menu
}
private fun addConfigs(menu: JPopupMenu, configs: CTConfigs, toArm: CTConfig?) {
require(toArm == null || configs.hasConfig(toArm)) { "invalid config" }
configs.getConfigs().forEach { addConfig(menu, it) }
toArm?.let { arm(it) }
}
private fun addConfig(menu: JPopupMenu, config: CTConfig) {
val menuItem = CTConfigMenuItem(CTConfigAction(this, config))
group.add(menuItem)
menu.insert(menuItem, group.buttonCount - 1)
}
private fun onNewConfig(configs: CTConfigs, menu: JPopupMenu) {
val config = showNewConfig()
if (config != null && config.isValid && !configs.hasConfig(config)) {
configs.addConfig(config)
addConfig(menu, config)
saveConfigs(configs)
}
}
override fun about() {
app.about()
}
override fun arm(config: CTConfig) {
val item = findItem(config)
if (item != null) {
stopMenuItem.isEnabled = true
group.clearSelection()
group.setSelected(item.model, true)
if (item.action is CTConfigAction) {
app.arm((item.action as CTConfigAction).config)
}
}
}
override fun browseConfigs() {
app.browseConfigs()
}
override fun exit() {
controlWindow.destroy()
app.unarm()
app.exit()
}
override fun help() {
app.help()
}
override fun loadConfigs(reload: Boolean): CTConfigs {
val configs = app.loadConfigs(reload)
if (reload) {
replaceConfigs(menu, configs)
}
return configs
}
override fun saveConfigs(configs: CTConfigs) {
app.saveConfigs(configs)
}
override fun showNewConfig(): CTConfig? = app.showNewConfig()
override fun showPreferences(): Unit = app.showPreferences()
override fun unarm() {
stopMenuItem.isEnabled = false
group.clearSelection()
app.unarm()
}
private fun replaceConfigs(menu: JPopupMenu, configs: CTConfigs) {
val selectedConfig = selectedConfig
removeConfigs(menu)
addConfigs(menu, configs, selectedConfig)
// if (selectedConfig != null && findItem(selectedConfig) != null) {
// arm(selectedConfig);
// }
}
private val selectedConfig: CTConfig?
get() {
var selectedConfig: CTConfig? = null
val elements: List<AbstractButton> = Collections.list(group.elements)
for (element in elements) {
require(element is CTConfigMenuItem) { "not a config added" }
if (element.model.isSelected && element.action is CTConfigAction) {
selectedConfig = (element.action as CTConfigAction).config
}
}
return selectedConfig
}
private fun removeConfigs(menu: JPopupMenu) {
group.elements.toList().forEach { element ->
require(element is CTConfigMenuItem) { "not a config to remove" }
group.remove(element)
menu.remove(element)
}
}
private fun findItem(config: CTConfig): AbstractButton? =
group.elements.toList().firstOrNull {
it.action is CTConfigAction && (it.action as CTConfigAction).config == config
}
override fun doUpdate(task: CTTask, currentMillis: Long) {
controlWindow.setToolTipText(textProvider.getToolTipText(task, currentMillis))
// lblInfo.setText(textProvider.getInfoText(task, currentMillis));
val visible = textProvider.isVisible(task, currentMillis)
controlWindow.setTextMode(visible)
if (visible) {
controlWindow.showText(
textProvider.getColor(task, currentMillis),
textProvider.getBlockerText(task, currentMillis, false)
)
}
}
override fun onPropertyChange(event: CTPropertyChangeEvent<Any>) {
controlWindow.onPropertyChange(event)
}
companion object {
private const val LOC_MESSAGES = "control"
private const val STR_ABOUT = "about"
private const val STR_BROWSE_CONFIGS = "browse-configs"
private const val STR_BROWSE_CONFIGS_TOOLTIP = "browse-configs.tooltip"
private const val STR_EXIT = "exit"
private const val STR_EXIT_TOOLTIP = "exit.tooltip"
private const val STR_HELP = "help"
private const val STR_HELP_TOOLTIP = "help.tooltip"
private const val STR_NEW_CONFIG = "new-config"
private const val STR_NEW_CONFIG_TOOLTIP = "new-config.tooltip"
private const val STR_PREFERENCES = "preferences"
private const val STR_PREFERENCES_TOOLTIP = "preferences.tooltip"
private const val STR_UNARM = "unarm"
private const val STR_UNARM_TOOLTIP = "unarm.tooltip"
}
}
| unlicense | 246376bfff8a3304e194c2892ae0eab8 | 35.101215 | 117 | 0.619827 | 4.613037 | false | true | false | false |
xmbaby/DrinkNongYao | babyutils/src/main/java/com/xmbaby/babyutils/MyFunction.kt | 1 | 629 | package com.xmbaby.babyutils
import android.app.Activity
/**
* Created by yhz on 2017/1/10.
* 简化系统的方法
*/
fun android.support.v4.app.Fragment.Log(msg: String) = activity.Log(msg)
fun android.support.v4.app.Fragment.Log(tag: String, msg: String) = activity.Log(tag, msg)
fun android.app.Fragment.Log(tag: String) = activity.Log(tag)
fun android.app.Fragment.Log(tag: String, msg: String) = activity.Log(tag, msg)
fun Activity.Log(msg: String) = android.util.Log.e("look", msg)
fun Activity.Log(tag: String, msg: String) = android.util.Log.e(tag, msg)
fun Log(msg: String) = android.util.Log.e("look", msg) | apache-2.0 | 0f928f6d44f89a589e38bf428d6c5491 | 27 | 90 | 0.718699 | 2.721239 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/inventory/container/layout/RootShulkerBoxContainerLayout.kt | 1 | 1488 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.container.layout
import org.lanternpowered.api.item.inventory.container.layout.GridContainerLayout
import org.lanternpowered.api.text.textOf
import org.lanternpowered.server.inventory.container.ClientWindowTypes
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.vanilla.packet.type.play.OpenWindowPacket
class RootShulkerBoxContainerLayout : LanternTopBottomContainerLayout<GridContainerLayout>(
title = TITLE, slotFlags = ALL_INVENTORY_FLAGS
) {
companion object {
private const val WIDTH = 9
private const val HEIGHT = 3
private val TITLE = textOf("container.shulkerBox")
private val TOP_INVENTORY_FLAGS = IntArray(WIDTH * HEIGHT) { Flags.REVERSE_SHIFT_INSERTION }
private val ALL_INVENTORY_FLAGS = TOP_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS
}
override fun createOpenPackets(data: ContainerData): List<Packet> =
listOf(OpenWindowPacket(data.containerId, ClientWindowTypes.SHULKER_BOX, this.title))
override val top: GridContainerLayout = SubGridContainerLayout(0, WIDTH, HEIGHT, this)
}
| mit | 62011e52e56bde65a166ebd225d8cbe6 | 37.153846 | 100 | 0.756048 | 4.179775 | false | false | false | false |
valsinats42/meditate | mobile/src/main/java/me/stanislav_nikolov/meditate/ui/StatsFragment.kt | 1 | 1405 | package me.stanislav_nikolov.meditate.ui
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.stanislav_nikolov.meditate.R
import me.stanislav_nikolov.meditate.adapters.StatsAdapter
import me.stanislav_nikolov.meditate.graph
import javax.inject.Inject
class StatsFragment : Fragment() {
@Inject lateinit var adapter: StatsAdapter
var recyclerView: RecyclerView? = null
companion object {
fun newInstance(): StatsFragment = StatsFragment()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
graph().inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_stats, container, false)
recyclerView = view!!.findViewById(R.id.recyclerView) as RecyclerView
with(recyclerView!!) {
layoutManager = LinearLayoutManager(activity)
setHasFixedSize(true)
adapter = [email protected]
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
recyclerView = null
}
}
| mit | de053e9634bf7ba7930e2c981f48607e | 27.673469 | 116 | 0.721708 | 4.460317 | false | false | false | false |
shadowfox-ninja/ShadowUtils | shadow-android/src/main/java/tech/shadowfox/shadow/android/view/ViewExtentions.kt | 1 | 4630 | @file:Suppress("unused")
package tech.shadowfox.shadow.android.view
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.StringRes
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v7.widget.RecyclerView
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import tech.shadowfox.shadow.android.utils.inputMethodManager
/**
* Copyright 2017 Camaron Crowe
*
* 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.
**/
fun View.recyclerParams(apply_params: (RecyclerView.LayoutParams) -> Unit) {
lprams(apply_params)
}
fun View.relativeParams(apply_params: (RelativeLayout.LayoutParams) -> Unit) {
lprams(apply_params)
}
fun View.linearParams(apply_params: (LinearLayout.LayoutParams) -> Unit) {
lprams(apply_params)
}
fun View.frameParams(apply_params: (FrameLayout.LayoutParams) -> Unit) {
lprams(apply_params)
}
fun View.viewGroupParams(apply_params: (ViewGroup.LayoutParams) -> Unit) {
lprams(apply_params)
}
fun View.onClick(listener: View.OnClickListener) {
setOnClickListener(listener)
}
fun View.onClick(onClick: (v: View) -> Unit) {
setOnClickListener(onClick)
}
fun View.setVisible(visible: Boolean, hide: Boolean = true) {
when {
visible -> show()
hide -> hide()
else -> invisible()
}
}
fun TextView.setOrHide(value: String?) {
if(!value.isNullOrBlank()) {
show()
text = value
} else {
hide()
}
}
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun View.disable() {
isEnabled = false
}
fun View.enable() {
isEnabled = true
}
val View.dm: DisplayMetrics
get() = resources.displayMetrics
fun View.dpToPx(dp: Int) = (dp * this.dm.density + 0.5).toInt()
fun View.pxToDp(px: Int) = (px / this.dm.density + 0.5).toInt()
fun View.hideSoftKeyboard() {
context.inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun TextInputEditText.focusEnabled(state: Boolean) {
isFocusable = state
isClickable = state
isFocusableInTouchMode = state
}
fun EditText.showSoftKeyboard() {
if (requestFocus()) context.inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.toggleSoftKeyboard() {
if (requestFocus()) context.inputMethodManager.toggleSoftInput(0, 0)
}
fun ProgressBar.tint(color: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
indeterminateDrawable = indeterminateDrawable.tint(color)
} else {
indeterminateDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
}
inline fun <reified T : ViewGroup.LayoutParams> View.lprams(apply_params: (T) -> Unit) {
lprams<T>().let { apply_params.invoke(it); this.layoutParams = it }
}
inline fun <reified T : ViewGroup.LayoutParams> View.lprams() = layoutParams as T
fun RecyclerView.ViewHolder.stringRes(@StringRes strRes: Int): String? = itemView.context.getString(strRes)
fun ImageView.tintCurrentDrawable(color: Int) {
setImageDrawable(drawable.tint(color))
}
fun Drawable.tint(color: Int): Drawable {
DrawableCompat.wrap(this).let {
it.mutate()
DrawableCompat.setTintList(it, ColorStateList.valueOf(color))
return it
}
}
fun Array<View>.bulkClick(_onClick: (View) -> Unit) {
forEach { it.apply { onClick { v -> _onClick.invoke(v) } } }
}
fun EditText.getString(): String = text.toString()
fun TextInputLayout.getString(): String? = editText?.getString()
fun TextInputEditText.getString(): String = text.toString()
fun EditText.matches(value: String?) = getString() == value ?: ""
fun TextInputEditText.matches(value: String?) = getString() == value ?: ""
fun EditText.isBlank(): Boolean = getString().isBlank() | apache-2.0 | c78e8aa762f89168359042b622e7e9ba | 27.237805 | 107 | 0.724622 | 3.864775 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/poll/text/TextPollBlockView.kt | 1 | 1567 | package io.rover.sdk.experiences.ui.blocks.poll.text
import android.content.Context
import android.graphics.Canvas
import android.widget.LinearLayout
import io.rover.sdk.experiences.ui.blocks.concerns.ViewComposition
import io.rover.sdk.experiences.ui.blocks.concerns.background.ViewBackground
import io.rover.sdk.experiences.ui.blocks.concerns.border.ViewBorder
import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableView
import io.rover.sdk.experiences.ui.blocks.concerns.layout.ViewBlock
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
import io.rover.sdk.experiences.ui.concerns.ViewModelBinding
internal class TextPollBlockView(context: Context?) : LinearLayout(context),
LayoutableView<TextPollBlockViewModel> {
// mixins
private val viewComposition = ViewComposition()
private val viewBackground = ViewBackground(this)
private val viewBorder = ViewBorder(this, viewComposition)
private val viewBlock = ViewBlock(this)
private val viewTextPoll = ViewTextPoll(this)
init {
orientation = VERTICAL
}
override var viewModelBinding: MeasuredBindableView.Binding<TextPollBlockViewModel>? by ViewModelBinding { binding, _ ->
viewBorder.viewModelBinding = binding
viewBlock.viewModelBinding = binding
viewBackground.viewModelBinding = binding
viewTextPoll.viewModelBinding = binding
}
override fun draw(canvas: Canvas) {
viewComposition.beforeDraw(canvas)
super.draw(canvas)
viewComposition.afterDraw(canvas)
}
}
| apache-2.0 | 23498a35a07d1f0741a859b8e8d4de27 | 38.175 | 124 | 0.774729 | 4.281421 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/viewmodel/AppPostViewModel.kt | 1 | 5188 | package me.ykrank.s1next.viewmodel
import androidx.databinding.Observable
import androidx.databinding.ObservableField
import androidx.fragment.app.FragmentActivity
import androidx.appcompat.widget.PopupMenu
import android.view.MenuItem
import android.view.View
import com.github.ykrank.androidtools.util.ContextUtils
import com.github.ykrank.androidtools.util.L
import com.github.ykrank.androidtools.widget.RxBus
import me.ykrank.s1next.R
import me.ykrank.s1next.data.User
import me.ykrank.s1next.data.api.Api
import me.ykrank.s1next.data.api.app.model.AppPost
import me.ykrank.s1next.data.api.app.model.AppThread
import me.ykrank.s1next.view.activity.UserHomeActivity
import me.ykrank.s1next.view.activity.WebViewActivity
import me.ykrank.s1next.view.event.EditAppPostEvent
import me.ykrank.s1next.view.event.QuoteEvent
import me.ykrank.s1next.view.event.RateEvent
import me.ykrank.s1next.view.internal.BlacklistMenuAction
import me.ykrank.s1next.widget.glide.AvatarUrlsCache
class AppPostViewModel(private val rxBus: RxBus, private val user: User) {
val post = ObservableField<AppPost>()
val thread = ObservableField<AppThread>()
val floor = ObservableField<CharSequence>()
private val postFloor: CharSequence?
get() {
val p = post.get() ?: return null
return "#${p.position}"
}
init {
post.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(observable: Observable, i: Int) {
floor.set(postFloor)
}
})
}
fun onAvatarClick(v: View) {
post.get()?.let {
//Clear avatar false cache
AvatarUrlsCache.clearUserAvatarCache("" + it.authorId)
//个人主页
UserHomeActivity.start(v.context as androidx.fragment.app.FragmentActivity, "" + it.authorId, it.author, v)
}
}
fun onLongClick(v: View): Boolean {
//长按显示抹布菜单
val popup = PopupMenu(v.context, v)
val postData = post.get()
popup.setOnMenuItemClickListener { menuitem: MenuItem ->
when (menuitem.itemId) {
R.id.menu_popup_blacklist -> {
if (menuitem.title == v.context.getString(R.string.menu_blacklist_remove)) {
BlacklistMenuAction.removeBlacklist(rxBus, postData?.authorId
?: 0, postData?.author)
} else {
val context = ContextUtils.getBaseContext(v.context)
if (context is androidx.fragment.app.FragmentActivity) {
BlacklistMenuAction.addBlacklist(context,
postData?.authorId ?: 0, postData?.author)
} else {
L.report(IllegalStateException("抹布时头像Context不为FragmentActivity$context"))
}
}
return@setOnMenuItemClickListener true
}
else -> return@setOnMenuItemClickListener false
}
}
popup.inflate(R.menu.popup_blacklist)
if (postData?.hide == true) {
popup.menu.findItem(R.id.menu_popup_blacklist).setTitle(R.string.menu_blacklist_remove)
}
popup.show()
return true
}
//click floor textView, show popup menu
fun showFloorActionMenu(v: View) {
val popup = PopupMenu(v.context, v)
popup.setOnMenuItemClickListener { menuitem: MenuItem ->
when (menuitem.itemId) {
R.id.menu_popup_reply -> {
onReplyClick(v)
return@setOnMenuItemClickListener true
}
R.id.menu_popup_rate -> {
onRateClick(v)
return@setOnMenuItemClickListener true
}
R.id.menu_popup_edit -> {
onEditClick(v)
return@setOnMenuItemClickListener true
}
else -> return@setOnMenuItemClickListener false
}
}
popup.inflate(R.menu.popup_post_floor)
val editPostMenuItem = popup.menu.findItem(R.id.menu_popup_edit)
editPostMenuItem.isVisible = user.isLogged && user.uid == post.get()?.authorId?.toString()
popup.show()
}
fun onReplyClick(v: View) {
post.get()?.let {
rxBus.post(QuoteEvent(it.pid.toString(), it.position.toString()))
}
}
fun onRateClick(v: View) {
post.get()?.let {
rxBus.post(RateEvent(it.tid.toString(), it.pid.toString()))
}
}
fun onEditClick(v: View) {
val p = post.get()
val t = thread.get()
if (p != null && t != null) {
rxBus.post(EditAppPostEvent(p, t))
}
}
fun onTradeHtmlClick(v: View) {
post.get()?.let {
val url = String.format("%sforum.php?mod=viewthread&do=tradeinfo&tid=%s&pid=%s", Api.BASE_URL, it.tid, it.pid + 1)
WebViewActivity.start(v.context, url, true, true)
}
}
}
| apache-2.0 | 3984a16b54760d9d11721ad45ffaa042 | 35.785714 | 126 | 0.596117 | 4.309623 | false | false | false | false |
if710/if710.github.io | 2019-08-28/Threads/app/src/main/java/br/ufpe/cin/android/threads/AsyncTaskActivity.kt | 1 | 2675 | package br.ufpe.cin.android.threads
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import android.widget.ProgressBar
import android.widget.Toast
import kotlinx.android.synthetic.main.async.*
class AsyncTaskActivity : Activity() {
private val mDelay = 500
internal var toasts = 0
private val TAG = "ThreadingAsyncTask"
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.async)
loadButton.setOnClickListener {
LoadIconTask().execute(R.drawable.painter, R.drawable.ok, R.drawable.delete)
}
otherButton.setOnClickListener {
toasts++
contadorToasts!!.text = getString(R.string.contador_de_toasts) + toasts
Toast.makeText(applicationContext, "Estou trabalhando... ($toasts)", Toast.LENGTH_SHORT).show()
}
}
//<Entrada, Progresso, Resultado>
internal inner class LoadIconTask : AsyncTask<Int, Int, Bitmap>() {
//garantido de rodar na thread principal
override fun onPreExecute() {
progressBar.visibility = ProgressBar.VISIBLE
progressBar.progress = 0
toasts = 0
contadorToasts.text = getString(R.string.contador_de_toasts) + toasts
}
protected override fun doInBackground(vararg resId: Int?): Bitmap {
if (resId!=null) {
val res = resId[0]
if (res!=null) {
val tmp = BitmapFactory.decodeResource(resources, res)
// fazendo o migué!
for (i in 1..10) {
sleep()
publishProgress(i * 10)
}
return tmp
}
}
return BitmapFactory.decodeResource(resources, R.drawable.painter)
}
protected override fun onProgressUpdate(vararg values: Int?) {
if (values!=null && values[0]!=null) {
val x = values[0]
if (x!=null) {
progressBar.progress = x
}
}
}
override fun onPostExecute(result: Bitmap) {
progressBar.visibility = ProgressBar.INVISIBLE
imageView.setImageBitmap(result)
}
private fun sleep() {
try {
Thread.sleep(mDelay.toLong())
} catch (e: InterruptedException) {
Log.e(TAG, e.toString())
}
}
}
}
| mit | 6850d528c597816476f5b431903c2287 | 29.386364 | 107 | 0.571055 | 4.800718 | false | false | false | false |
neyb/swak | core/src/main/kotlin/swak/http/response/SimpleResponse.kt | 1 | 820 | package swak.http.response
import swak.body.writer.BodyWriter
import swak.http.MutableHeaders
class SimpleResponse<out Body>(
override val status: Code = Code.OK,
override val headers: MutableHeaders = MutableHeaders(),
override val body: Body
) : NotWritableResponse<Body> {
companion object {
fun withoutBody(status: Code = Code.OK, headers: MutableHeaders = MutableHeaders()) = SimpleResponse(status, headers, Unit)
}
override fun withWriter(bodyWriter: BodyWriter<Body>): WritableResponse<Body> =
if (body is String)
@Suppress("UNCHECKED_CAST") //this is safe because body is a string
StringResponse(status, headers, body) as WritableResponse<Body>
else
SimpleWritableResponse(this, bodyWriter)
} | apache-2.0 | 54d556ad52ed4925742609453cfd3b0f | 36.318182 | 131 | 0.678049 | 4.480874 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/ui/VideoDetailsPresenter.kt | 1 | 2968 | /*
* ************************************************************************
* VideoDetailsPresenter.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.television.ui
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.leanback.graphics.ColorOverlayDimmer
import org.videolan.television.databinding.TvVideoDetailsBinding
import org.videolan.television.R
class VideoDetailsPresenter(private val context: Context, private val screenWidth: Int) : org.videolan.television.ui.FullWidthRowPresenter() {
private lateinit var binding: TvVideoDetailsBinding
override fun createRowViewHolder(parent: ViewGroup): VideoDetailsViewHolder {
binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.tv_video_details, parent, false)
binding.container.minWidth = (screenWidth - (context.resources.getDimension(R.dimen.tv_overscan_horizontal) * 2)).toInt()
return VideoDetailsViewHolder(binding.root)
}
override fun onBindRowViewHolder(viewHolder: ViewHolder, item: Any?) {
super.onBindRowViewHolder(viewHolder, item)
val vh = viewHolder as VideoDetailsViewHolder
val metadata = (item as org.videolan.television.ui.VideoDetailsOverviewRow).item
binding.item = metadata
}
override fun onSelectLevelChanged(holder: ViewHolder) {
// super.onSelectLevelChanged(holder)
// if (selectEffectEnabled) {
// val vh = holder as VideoDetailsViewHolder
// val dimmedColor = vh.colorDimmer.paint.color
// (vh.container.background.mutate() as ColorDrawable).color = dimmedColor
// }
}
inner class VideoDetailsViewHolder(view: View) : ViewHolder(view) {
val colorDimmer = ColorOverlayDimmer.createDefault(view.context)
val container = view.findViewById<ConstraintLayout>(R.id.container)
}
} | gpl-2.0 | cd658db0c87fb6d88b2dbe89f8032c35 | 42.647059 | 142 | 0.692282 | 4.832248 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/game/query/repository/impl/RedisGameListRepository.kt | 1 | 2175 | package com.flexpoker.game.query.repository.impl
import com.flexpoker.config.ProfileNames
import com.flexpoker.game.query.dto.GameInListDTO
import com.flexpoker.game.query.dto.GameStage
import com.flexpoker.game.query.repository.GameListRepository
import org.springframework.context.annotation.Profile
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Repository
import java.util.UUID
import javax.inject.Inject
@Profile(ProfileNames.REDIS, ProfileNames.GAME_QUERY_REDIS)
@Repository
class RedisGameListRepository @Inject constructor(private val redisTemplate: RedisTemplate<String, GameInListDTO?>) :
GameListRepository {
companion object {
private const val GAME_LIST_NAMESPACE = "game-list:"
}
override fun saveNew(gameInListDTO: GameInListDTO) {
redisTemplate.opsForValue()[GAME_LIST_NAMESPACE + gameInListDTO.id] = gameInListDTO
}
override fun fetchAll(): List<GameInListDTO> {
val allKeys = redisTemplate.keys("$GAME_LIST_NAMESPACE*")
return redisTemplate.opsForValue().multiGet(allKeys) as List<GameInListDTO>
}
override fun incrementRegisteredPlayers(aggregateId: UUID) {
val existingGameInListDTO = fetchById(aggregateId)!!
val updatedGameInListDTO = existingGameInListDTO.copy(
numberOfRegisteredPlayers = existingGameInListDTO.numberOfRegisteredPlayers + 1)
removeGame(aggregateId)
saveNew(updatedGameInListDTO)
}
override fun fetchGameName(aggregateId: UUID): String {
return fetchById(aggregateId)!!.name
}
override fun changeGameStage(aggregateId: UUID, gameStage: GameStage) {
val existingGameInListDTO = fetchById(aggregateId)!!
val updatedGameInListDTO = existingGameInListDTO.copy(stage = gameStage.toString())
removeGame(aggregateId)
saveNew(updatedGameInListDTO)
}
private fun fetchById(aggregateId: UUID): GameInListDTO? {
return redisTemplate.opsForValue()[GAME_LIST_NAMESPACE + aggregateId]
}
private fun removeGame(aggregateId: UUID) {
redisTemplate.delete(GAME_LIST_NAMESPACE + aggregateId)
}
} | gpl-2.0 | 1b03d4793b5317dde5cd9ef1a35278bc | 36.517241 | 117 | 0.751724 | 4.358717 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/ImplicitDefaultLocale.kt | 1 | 4279 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import org.jetbrains.kotlin.builtins.KotlinBuiltIns.isStringOrNullableString
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
/**
* Prefer passing [java.util.Locale] explicitly than using implicit default value when formatting
* strings or performing a case conversion.
*
* The default locale is almost always not appropriate for machine-readable text like HTTP headers.
* For example, if locale with tag `ar-SA-u-nu-arab` is a current default then `%d` placeholders
* will be evaluated to numbers consisting of Eastern-Arabic (non-ASCII) digits.
* [java.util.Locale.US] is recommended for machine-readable output.
*
* <noncompliant>
* String.format("Timestamp: %d", System.currentTimeMillis())
*
* val str: String = getString()
* str.toUpperCase()
* str.toLowerCase()
* </noncompliant>
*
* <compliant>
* String.format(Locale.US, "Timestamp: %d", System.currentTimeMillis())
*
* val str: String = getString()
* str.toUpperCase(Locale.US)
* str.toLowerCase(Locale.US)
* </compliant>
*/
@ActiveByDefault(since = "1.16.0")
class ImplicitDefaultLocale(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
"ImplicitDefaultLocale",
Severity.CodeSmell,
"Implicit default locale used for string processing. Consider using explicit locale.",
Debt.FIVE_MINS
)
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
super.visitDotQualifiedExpression(expression)
checkStringFormatting(expression)
checkCaseConversion(expression)
}
override fun visitSafeQualifiedExpression(expression: KtSafeQualifiedExpression) {
super.visitSafeQualifiedExpression(expression)
checkStringFormatting(expression)
checkCaseConversion(expression)
}
private fun checkStringFormatting(expression: KtQualifiedExpression) {
if (expression.receiverExpression.text == "String" &&
expression.getCalleeExpressionIfAny()?.text == "format" &&
expression.containsStringTemplate()
) {
report(
CodeSmell(
issue,
Entity.from(expression),
"${expression.text} uses implicitly default locale for string formatting."
)
)
}
}
private fun checkCaseConversion(expression: KtQualifiedExpression) {
if (isStringOrNullableString(expression.receiverExpression.getType(bindingContext)) &&
expression.isCalleeCaseConversion() &&
expression.isCalleeNoArgs()
) {
report(
CodeSmell(
issue,
Entity.from(expression),
"${expression.text} uses implicitly default locale for case conversion."
)
)
}
}
}
private fun KtQualifiedExpression.isCalleeCaseConversion(): Boolean {
return getCalleeExpressionIfAny()?.text in arrayOf("toLowerCase", "toUpperCase")
}
private fun KtQualifiedExpression.isCalleeNoArgs(): Boolean {
val lastCallExpression = lastChild as? KtCallExpression
return lastCallExpression?.valueArguments.isNullOrEmpty()
}
private fun KtQualifiedExpression.containsStringTemplate(): Boolean {
val lastCallExpression = lastChild as? KtCallExpression
return lastCallExpression?.valueArguments
?.firstOrNull()
?.run { children.firstOrNull() } is KtStringTemplateExpression
}
| apache-2.0 | 441f410d6de60770adfd306d47ef0d3e | 37.205357 | 99 | 0.716523 | 4.8625 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnnecessaryApplySpec.kt | 1 | 13735 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UnnecessaryApplySpec : Spek({
setupKotlinEnvironment()
val subject by memoized { UnnecessaryApply(Config.empty) }
val env: KotlinCoreEnvironment by memoized()
describe("UnnecessaryApply rule") {
context("unnecessary apply expressions that can be changed to ordinary method call") {
it("reports an apply on non-nullable type") {
val findings = subject.compileAndLintWithContext(
env,
"""
fun f() {
val a: Int = 0
a.apply {
plus(1)
}
}
"""
)
assertThat(findings).hasSize(1)
assertThat(findings.first().message).isEqualTo("apply expression can be omitted")
}
it("reports an apply on nullable type") {
val findings = subject.compileAndLintWithContext(
env,
"""
fun f() {
val a: Int? = null
// Resolution: we can't say here if plus is on 'this' or just a side effect when a is not null
// However such cases should be better handled with an if-null check instead of misusing apply
a?.apply {
plus(1)
}
}
"""
)
assertThat(findings).hasSize(1)
assertThat(findings.first().message).isEqualTo("apply can be replaced with let or an if")
}
it("reports a false negative apply on nullable type - #1485") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
val a: Any? = Any()
fun Any.b() = Unit
fun main() {
a?.apply {
b()
}
}
"""
)
).hasSize(1)
}
it("does not report an apply with lambda block") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
fun f() {
val a: Int? = null
a?.apply({
plus(1)
})
}
"""
)
).isEmpty()
}
it("does not report single statement in apply used as function argument") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
fun b(i: Int?) {}
fun main() {
val a: Int? = null
b(a.apply {
toString()
})
}
"""
)
).isEmpty()
}
it("does not report single assignment statement in apply used as function argument - #1517") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
var prop = 0
}
fun main() {
val list = ArrayList<C>()
list.add(
if (true) {
C().apply {
prop = 1
}
} else {
C()
}
)
}
"""
)
).isEmpty()
}
it("does not report if result of apply is used - #2938") {
assertThat(
subject.compileAndLint(
"""
fun main() {
val a = listOf(mutableListOf(""))
.map { it.apply { add("") } }
}
"""
)
).isEmpty()
}
it("does not report applies with lambda body containing more than one statement") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
fun b(i: Int?) {}
fun main() {
val a: Int? = null
a?.apply {
plus(1)
plus(2)
}
a?.apply {
plus(1)
plus(2)
}
b(1.apply {
plus(1)
plus(2)
})
}
"""
)
).isEmpty()
}
it("reports when lambda has a dot qualified expression") {
val findings = subject.compileAndLintWithContext(
env,
"""
fun test(foo: Foo) {
foo.apply {
bar.bar()
}
}
class Foo(val bar: Bar)
class Bar {
fun bar() {}
}
"""
)
assertThat(findings).hasSize(1)
}
it("reports when lambda has a dot qualified expression which has 'this' receiver") {
val findings = subject.compileAndLintWithContext(
env,
"""
fun test(foo: Foo) {
foo.apply {
this.bar.bar()
}
}
class Foo(val bar: Bar)
class Bar {
fun bar() {}
}
"""
)
assertThat(findings).hasSize(1)
}
it("reports when lambda has a 'this' expression") {
val findings = subject.compileAndLintWithContext(
env,
"""
fun test() {
"foo".apply {
this
}
}
"""
)
assertThat(findings).hasSize(1)
}
}
context("reported false positives - #1305") {
it("is used within an assignment expr itself") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
fun f() = true
}
val a = C().apply { f() }
"""
)
).isEmpty()
}
it("is used as return type of extension function") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C(var prop: Int)
fun Int.f() = C(5).apply { prop = 10 }
"""
)
).isEmpty()
}
it("should not flag apply when assigning property on this") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C(var prop: Int) {
private val c by lazy {
C(1).apply { prop = 3 }
}
}
"""
)
).isEmpty()
}
it("should not report apply when using it after returning something") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C(var prop: Int)
fun f() = (C(5)).apply { prop = 10 }
"""
)
).isEmpty()
}
it("should not report apply usage inside safe chained expressions") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
fun f() {
val arguments = listOf(1,2,3)
?.map { it * 2 }
?.apply { if (true) 4 }
?: listOf(0)
}
"""
)
).isEmpty()
}
}
context("false positive in single nesting expressions - #1473") {
it("should not report the if expression") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
fun has() = true
}
fun f() {
C().apply {
if (has()) {
// actions
}
}
}
"""
)
).isEmpty()
}
it("should report reference expressions") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
val prop = 5
}
fun f() {
C().apply {
prop
}
C().apply {
this.prop
}
}
"""
)
).hasSize(2)
}
}
context("false positive when it's used as an expression - #2435") {
it("do not report when it's used as an assignment") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
fun f() {}
}
fun main() {
val c = if (5 >= 3) {
C().apply { f() }
} else {
C()
}
}
"""
)
).isEmpty()
}
it("do not report when it's used as the last statement of a block inside lambda") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
class C {
fun f() {}
}
fun print(block: () -> C) {
println(block())
}
fun main() {
print {
println("Does nothing")
C().apply { f() }
}
}
"""
)
).isEmpty()
}
}
context("false positive when lambda has multiple member references - #3561") {
it("do not report when lambda has multiple member references") {
assertThat(
subject.compileAndLintWithContext(
env,
"""
fun test(foo: Foo) {
foo.apply {
bar {
baz = 2
}
}
}
class Foo {
fun bar(f: () -> Unit) {
}
var baz = 1
}
"""
)
).isEmpty()
}
}
}
})
| apache-2.0 | 67d5fb5bec2ca1dadab84ebb5445a2ab | 31.166276 | 118 | 0.306079 | 7.025575 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-general/src/test/java/net/nemerosa/ontrack/extension/general/MessagePropertyMutationProviderIT.kt | 1 | 4594 | package net.nemerosa.ontrack.extension.general
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.nameValues
import net.nemerosa.ontrack.model.structure.typeName
import net.nemerosa.ontrack.model.structure.varName
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class MessagePropertyMutationProviderIT : AbstractQLKTITJUnit4Support() {
@Test
fun `Setting the message property at different levels`() {
multiLevelTest {
testMessagePropertyById()
}
}
@Test
fun `Setting the message property using names at different levels`() {
multiLevelTest {
testMessagePropertyByName()
}
}
private fun ProjectEntity.testMessagePropertyById() {
run("""
mutation {
set${projectEntityType.typeName}MessagePropertyById(input: {id: $id, type: "INFO", text: "My message"}) {
${projectEntityType.varName} {
id
}
errors {
message
}
}
}
""").let { data ->
val nodeName = "set${projectEntityType.typeName}MessagePropertyById"
assertNoUserError(data, nodeName)
val returnedEntityId = data.path(nodeName).path(projectEntityType.varName).path("id").asInt()
assertEquals(this.id(), returnedEntityId)
val property = getProperty(this, MessagePropertyType::class.java)
assertNotNull(property) {
assertEquals(MessageType.INFO, property.type)
assertEquals("My message", property.text)
}
}
// Deleting the property
run("""
mutation {
delete${projectEntityType.typeName}MessagePropertyById(input: {id: $id}) {
${projectEntityType.varName} {
id
}
errors {
message
}
}
}
""").let { data ->
val nodeName = "delete${projectEntityType.typeName}MessagePropertyById"
assertNoUserError(data, nodeName)
val returnedEntityId = data.path(nodeName).path(projectEntityType.varName).path("id").asInt()
assertEquals(this.id(), returnedEntityId)
val property = getProperty(this, MessagePropertyType::class.java)
assertNull(property)
}
}
private fun ProjectEntity.testMessagePropertyByName() {
val input = nameValues.map { (field, value) -> """$field: "$value""""}.joinToString(", ")
run("""
mutation {
set${projectEntityType.typeName}MessageProperty(input: {$input, type: "INFO", text: "My message"}) {
${projectEntityType.varName} {
id
}
errors {
message
}
}
}
""").let { data ->
val nodeName = "set${projectEntityType.typeName}MessageProperty"
assertNoUserError(data, nodeName)
val returnedEntityId = data.path(nodeName).path(projectEntityType.varName).path("id").asInt()
assertEquals(this.id(), returnedEntityId)
val property = getProperty(this, MessagePropertyType::class.java)
assertNotNull(property) {
assertEquals(MessageType.INFO, property.type)
assertEquals("My message", property.text)
}
}
// Deleting the property
run("""
mutation {
delete${projectEntityType.typeName}MessageProperty(input: {$input}) {
${projectEntityType.varName} {
id
}
errors {
message
}
}
}
""").let { data ->
val nodeName = "delete${projectEntityType.typeName}MessageProperty"
assertNoUserError(data, nodeName)
val returnedEntityId = data.path(nodeName).path(projectEntityType.varName).path("id").asInt()
assertEquals(this.id(), returnedEntityId)
val property = getProperty(this, MessagePropertyType::class.java)
assertNull(property)
}
}
} | mit | 997aa09be836caa187b80e570fe241bc | 35.468254 | 121 | 0.551589 | 5.411072 | false | true | false | false |
nemerosa/ontrack | ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/support/LoginController.kt | 1 | 1605 | package net.nemerosa.ontrack.boot.support
import net.nemerosa.ontrack.common.Document
import net.nemerosa.ontrack.extension.api.ExtensionManager
import net.nemerosa.ontrack.extension.api.UILogin
import net.nemerosa.ontrack.extension.api.UILoginExtension
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.ResponseBody
@Controller
class LoginController(
private val extensionManager: ExtensionManager
) {
@GetMapping("/login")
fun login(model: Model): String {
val extensions = loginExtensions
model.addAttribute("extensions", extensions)
model.addAttribute("extensionsEnabled", extensions.isNotEmpty())
return "login"
}
/**
* Getting an image associated with a [login extension][UILoginExtension].
*
* @param id [ID][UILogin.id] of the extension
*/
@GetMapping("/login/extension/{id}/image")
@ResponseBody
fun loginExtensionImage(@PathVariable id: String): Document {
val extensions = loginExtensions
val extension = extensions.find { it.id == id }
return if (extension != null && extension.image) {
extension.imageLoader() ?: Document.EMPTY
} else {
Document.EMPTY
}
}
private val loginExtensions: List<UILogin>
get() = extensionManager.getExtensions(UILoginExtension::class.java).flatMap {
it.contributions
}
} | mit | 3570714e784ef12cb4c9a47a0252137c | 32.458333 | 86 | 0.709034 | 4.638728 | false | false | false | false |
olivierg13/EtherTracker | app/src/main/java/com/og/finance/ether/utilities/SharedPreferencesUtilities.kt | 1 | 6636 | /**
* Copyright 2013 Olivier Goutay (olivierg13)
*
*
* 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.og.finance.ether.utilities
import android.content.Context
import android.content.SharedPreferences
/**
* Created by oliviergoutay on 11/21/14.
*/
object SharedPreferencesUtilities {
/**
* The key for SharedPreferences (private mode, internal system storage)
*/
val SHARED_PREFERENCES = "ETHER_SHARED_PREFERENCES"
/**
* The float that is gonna be compared to the current value in the notification.
*/
val SHARED_BUYING_VALUE = "SHARED_BUYING_VALUE"
/**
* The boolean to know if we run the [com.og.finance.ether.services.AutoUpdateService]
* or not.
*/
val SHARED_ENDPOINT_ID = "SHARED_ENDPOINT_ID"
/**
* The boolean to know if we run the [com.og.finance.ether.services.AutoUpdateService]
* or not.
*/
val SHARED_SERVICE_ACTIVE = "SHARED_SERVICE_ACTIVE"
/**
* Store a String into the private [SharedPreferences] of the app.
* @param context The current context of the app
* *
* @param key The key we want to be used to store the string
* *
* @param value The String we want to be stored
*/
fun storeStringForKey(context: Context?, key: String, value: String) {
if (context == null) {
return
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putString(key, value)
editor.apply()
}
/**
* Get a String from the private [SharedPreferences] of the app
* @param context The current context of the app
* *
* @param key The key we want to request
* *
* @return The string retrieved from the given key
*/
fun getStringForKey(context: Context?, key: String): String? {
if (context == null) {
return null
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
return sharedPref.getString(key, null)
}
/**
* Store a boolean into the private [SharedPreferences] of the app.
* @param context The current context of the app
* *
* @param key The key we want to be used to store the string
* *
* @param value The boolean we want to be stored
*/
fun storeBooleanForKey(context: Context?, key: String, value: Boolean) {
if (context == null) {
return
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putBoolean(key, value)
editor.apply()
}
/**
* Get a boolean from the private [SharedPreferences] of the app
* @param context The current context of the app
* *
* @param key The key we want to request
* *
* @return The boolean retrieved from the given key, or true by default
*/
fun getBooleanForKey(context: Context?, key: String): Boolean {
if (context == null) {
return false
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
return sharedPref.getBoolean(key, true)
}
/**
* Store a float into the private [SharedPreferences] of the app.
* @param context The current context of the app
* *
* @param key The key we want to be used to store the string
* *
* @param value The float we want to be stored
*/
fun storeFloatForKey(context: Context?, key: String, value: Float) {
if (context == null) {
return
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putFloat(key, value)
editor.apply()
}
/**
* Get a float from the private [SharedPreferences] of the app
* @param context The current context of the app
* *
* @param key The key we want to request
* *
* @return The float retrieved from the given key, or true by default
*/
fun getFloatForKey(context: Context?, key: String): Float {
if (context == null) {
return 0.0f
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
return sharedPref.getFloat(key, 0.0f)
}
/**
* Store a int into the private [SharedPreferences] of the app.
* @param context The current context of the app
* *
* @param key The key we want to be used to store the string
* *
* @param value The int we want to be stored
*/
fun storeIntForKey(context: Context?, key: String, value: Int) {
if (context == null) {
return
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putInt(key, value)
editor.apply()
}
/**
* Get a int from the private [SharedPreferences] of the app
* @param context The current context of the app
* *
* @param key The key we want to request
* *
* @return The int retrieved from the given key, or 1 by default
*/
fun getIntForKey(context: Context?, key: String): Int {
if (context == null) {
return 1
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
return sharedPref.getInt(key, 1)
}
/**
* Delete a key from the private [SharedPreferences] of the app
* @param context The current context of the app
* *
* @param key The key we want to delete
*/
fun deleteKey(context: Context?, key: String) {
if (context == null) {
return
}
val sharedPref = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.remove(key)
editor.apply()
}
}
| apache-2.0 | 324c57fbada3a0e48c32ef4258cb0c61 | 30.301887 | 95 | 0.624171 | 4.340092 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/proto_crossbranch_test/proto_crossbranch_test.kt | 1 | 48604 | class CrossBranch private constructor () {
//========== Properties ===========
var errorCode: Int = 0
//========== Nested classes declarations ===========
class Grandfather private constructor (var rf: CrossBranch.Grandfather.RightFather) {
//========== Properties ===========
//message rf = 1
var errorCode: Int = 0
//========== Nested classes declarations ===========
class LeftFather private constructor () {
//========== Properties ===========
var errorCode: Int = 0
//========== Nested classes declarations ===========
class LeftLeftSon private constructor (var son_field: Int) {
//========== Properties ===========
//int32 son_field = 1
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 son_field = 1
if (son_field != 0) {
output.writeInt32 (1, son_field)
}
}
fun mergeWith (other: CrossBranch.Grandfather.LeftFather.LeftLeftSon) {
son_field = other.son_field
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0)
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0)
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
return size
}
//========== Builder ===========
class BuilderLeftLeftSon constructor (var son_field: Int) {
//========== Properties ===========
//int32 son_field = 1
fun setSon_field(value: Int): CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon {
son_field = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 son_field = 1
if (son_field != 0) {
output.writeInt32 (1, son_field)
}
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.LeftFather.LeftLeftSon {
val res = CrossBranch.Grandfather.LeftFather.LeftLeftSon(son_field)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
son_field = input.readInt32NoTag()
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
return size
}
}
}
class LeftRightSon private constructor (var son_field: Int) {
//========== Properties ===========
//int32 son_field = 1
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 son_field = 1
if (son_field != 0) {
output.writeInt32 (1, son_field)
}
}
fun mergeWith (other: CrossBranch.Grandfather.LeftFather.LeftRightSon) {
son_field = other.son_field
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0)
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0)
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
return size
}
//========== Builder ===========
class BuilderLeftRightSon constructor (var son_field: Int) {
//========== Properties ===========
//int32 son_field = 1
fun setSon_field(value: Int): CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon {
son_field = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 son_field = 1
if (son_field != 0) {
output.writeInt32 (1, son_field)
}
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.LeftFather.LeftRightSon {
val res = CrossBranch.Grandfather.LeftFather.LeftRightSon(son_field)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
son_field = input.readInt32NoTag()
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != 0) {
size += WireFormat.getInt32Size(1, son_field)
}
return size
}
}
}
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
}
fun mergeWith (other: CrossBranch.Grandfather.LeftFather) {
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.LeftFather.BuilderLeftFather()
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.LeftFather.BuilderLeftFather()
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
val size = 0
return size
}
//========== Builder ===========
class BuilderLeftFather constructor () {
//========== Properties ===========
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.LeftFather {
val res = CrossBranch.Grandfather.LeftFather()
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.LeftFather.BuilderLeftFather {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.LeftFather.BuilderLeftFather {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
val size = 0
return size
}
}
}
class RightFather private constructor (var rls: CrossBranch.Grandfather.RightFather.RightLeftSon, var rrs: CrossBranch.Grandfather.RightFather.RightRightSon) {
//========== Properties ===========
//message rls = 1
//message rrs = 2
var errorCode: Int = 0
//========== Nested classes declarations ===========
class RightLeftSon private constructor (var son_field: CrossBranch.Grandfather.LeftFather.LeftLeftSon) {
//========== Properties ===========
//message son_field = 1
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message son_field = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(son_field.getSizeNoTag())
son_field.writeTo(output)
}
fun mergeWith (other: CrossBranch.Grandfather.RightFather.RightLeftSon) {
son_field = other.son_field
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build())
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build())
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()) {
size += son_field.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()) {
size += son_field.getSize(1)
}
return size
}
//========== Builder ===========
class BuilderRightLeftSon constructor (var son_field: CrossBranch.Grandfather.LeftFather.LeftLeftSon) {
//========== Properties ===========
//message son_field = 1
fun setSon_field(value: CrossBranch.Grandfather.LeftFather.LeftLeftSon): CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon {
son_field = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message son_field = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(son_field.getSizeNoTag())
son_field.writeTo(output)
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.RightFather.RightLeftSon {
val res = CrossBranch.Grandfather.RightFather.RightLeftSon(son_field)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
do {
val expectedSize = input.readInt32NoTag()
son_field.mergeFromWithSize(input, expectedSize)
if (expectedSize != son_field.getSizeNoTag()) { errorCode = 3; return false }
} while(false)
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()) {
size += son_field.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()) {
size += son_field.getSize(1)
}
return size
}
}
}
class RightRightSon private constructor (var son_field: CrossBranch.Grandfather.LeftFather.LeftRightSon) {
//========== Properties ===========
//message son_field = 1
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message son_field = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(son_field.getSizeNoTag())
son_field.writeTo(output)
}
fun mergeWith (other: CrossBranch.Grandfather.RightFather.RightRightSon) {
son_field = other.son_field
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build())
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build())
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()) {
size += son_field.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()) {
size += son_field.getSize(1)
}
return size
}
//========== Builder ===========
class BuilderRightRightSon constructor (var son_field: CrossBranch.Grandfather.LeftFather.LeftRightSon) {
//========== Properties ===========
//message son_field = 1
fun setSon_field(value: CrossBranch.Grandfather.LeftFather.LeftRightSon): CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon {
son_field = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message son_field = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(son_field.getSizeNoTag())
son_field.writeTo(output)
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.RightFather.RightRightSon {
val res = CrossBranch.Grandfather.RightFather.RightRightSon(son_field)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
do {
val expectedSize = input.readInt32NoTag()
son_field.mergeFromWithSize(input, expectedSize)
if (expectedSize != son_field.getSizeNoTag()) { errorCode = 3; return false }
} while(false)
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()) {
size += son_field.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (son_field != CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()) {
size += son_field.getSize(1)
}
return size
}
}
}
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message rls = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rls.getSizeNoTag())
rls.writeTo(output)
//message rrs = 2
output.writeTag(2, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rrs.getSizeNoTag())
rrs.writeTo(output)
}
fun mergeWith (other: CrossBranch.Grandfather.RightFather) {
rls = other.rls
rrs = other.rrs
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build())
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build())
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (rls != CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build()) {
size += rls.getSize(1)
}
if (rrs != CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()) {
size += rrs.getSize(2)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (rls != CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build()) {
size += rls.getSize(1)
}
if (rrs != CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()) {
size += rrs.getSize(2)
}
return size
}
//========== Builder ===========
class BuilderRightFather constructor (var rls: CrossBranch.Grandfather.RightFather.RightLeftSon, var rrs: CrossBranch.Grandfather.RightFather.RightRightSon) {
//========== Properties ===========
//message rls = 1
fun setRls(value: CrossBranch.Grandfather.RightFather.RightLeftSon): CrossBranch.Grandfather.RightFather.BuilderRightFather {
rls = value
return this
}
//message rrs = 2
fun setRrs(value: CrossBranch.Grandfather.RightFather.RightRightSon): CrossBranch.Grandfather.RightFather.BuilderRightFather {
rrs = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message rls = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rls.getSizeNoTag())
rls.writeTo(output)
//message rrs = 2
output.writeTag(2, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rrs.getSizeNoTag())
rrs.writeTo(output)
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather.RightFather {
val res = CrossBranch.Grandfather.RightFather(rls, rrs)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
do {
val expectedSize = input.readInt32NoTag()
rls.mergeFromWithSize(input, expectedSize)
if (expectedSize != rls.getSizeNoTag()) { errorCode = 3; return false }
} while(false)
}
2 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
do {
val expectedSize = input.readInt32NoTag()
rrs.mergeFromWithSize(input, expectedSize)
if (expectedSize != rrs.getSizeNoTag()) { errorCode = 3; return false }
} while(false)
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.RightFather.BuilderRightFather {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.RightFather.BuilderRightFather {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (rls != CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build()) {
size += rls.getSize(1)
}
if (rrs != CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()) {
size += rrs.getSize(2)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (rls != CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build()) {
size += rls.getSize(1)
}
if (rrs != CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()) {
size += rrs.getSize(2)
}
return size
}
}
}
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message rf = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rf.getSizeNoTag())
rf.writeTo(output)
}
fun mergeWith (other: CrossBranch.Grandfather) {
rf = other.rf
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.Grandfather.BuilderGrandfather(CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build())
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.Grandfather.BuilderGrandfather(CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build())
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (rf != CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build()) {
size += rf.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (rf != CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build()) {
size += rf.getSize(1)
}
return size
}
//========== Builder ===========
class BuilderGrandfather constructor (var rf: CrossBranch.Grandfather.RightFather) {
//========== Properties ===========
//message rf = 1
fun setRf(value: CrossBranch.Grandfather.RightFather): CrossBranch.Grandfather.BuilderGrandfather {
rf = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//message rf = 1
output.writeTag(1, WireType.LENGTH_DELIMITED)
output.writeInt32NoTag(rf.getSizeNoTag())
rf.writeTo(output)
}
//========== Mutating methods ===========
fun build(): CrossBranch.Grandfather {
val res = CrossBranch.Grandfather(rf)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
do {
val expectedSize = input.readInt32NoTag()
rf.mergeFromWithSize(input, expectedSize)
if (expectedSize != rf.getSizeNoTag()) { errorCode = 3; return false }
} while(false)
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.Grandfather.BuilderGrandfather {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.Grandfather.BuilderGrandfather {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (rf != CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build()) {
size += rf.getSize(1)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (rf != CrossBranch.Grandfather.RightFather.BuilderRightFather(CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(0).build()).build(), CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(0).build()).build()).build()) {
size += rf.getSize(1)
}
return size
}
}
}
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
}
fun mergeWith (other: CrossBranch) {
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = CrossBranch.BuilderCrossBranch()
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = CrossBranch.BuilderCrossBranch()
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
val size = 0
return size
}
//========== Builder ===========
class BuilderCrossBranch constructor () {
//========== Properties ===========
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
}
//========== Mutating methods ===========
fun build(): CrossBranch {
val res = CrossBranch()
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): CrossBranch.BuilderCrossBranch {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): CrossBranch.BuilderCrossBranch {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
val size = 0
return size
}
}
}
fun compareGrandfathers(lhs: CrossBranch.Grandfather, rhs: CrossBranch.Grandfather): Boolean {
return (lhs.rf.rls.son_field.son_field == rhs.rf.rls.son_field.son_field) and
(lhs.rf.rrs.son_field.son_field == rhs.rf.rrs.son_field.son_field)
}
fun buildGrandfather(val1: Int, val2: Int): CrossBranch.Grandfather {
return CrossBranch.Grandfather.BuilderGrandfather(
CrossBranch.Grandfather.RightFather.BuilderRightFather(
CrossBranch.Grandfather.RightFather.RightLeftSon.BuilderRightLeftSon(
CrossBranch.Grandfather.LeftFather.LeftLeftSon.BuilderLeftLeftSon(
val1
).build()
).build()
,
CrossBranch.Grandfather.RightFather.RightRightSon.BuilderRightRightSon(
CrossBranch.Grandfather.LeftFather.LeftRightSon.BuilderLeftRightSon(
val2
).build()
).build()
).build()
).build()
}
fun checkGFSerializationIdentity(msg: CrossBranch.Grandfather): Int {
val outs = CodedOutputStream(ByteArray(msg.getSizeNoTag()))
msg.writeTo(outs)
val ins = CodedInputStream(outs.buffer)
val readMsg = buildGrandfather(0, 0)
readMsg.mergeFrom(ins)
if (readMsg.errorCode != 0) {
return 1
}
if (compareGrandfathers(msg, readMsg)) {
return 0
} else {
return 1
}
}
fun testTrivialValues(): Int {
val msg = buildGrandfather(3213213, -217864283)
return checkGFSerializationIdentity(msg)
}
fun testMaxValues(): Int {
val msg = buildGrandfather(2147483647, 2147483647)
return checkGFSerializationIdentity(msg)
}
fun testMinValues(): Int {
val msg = buildGrandfather(-2147483647, -2147483647)
return checkGFSerializationIdentity(msg)
} | mit | 4a030b941a79657bd255e49cdd20bd6a | 44.298229 | 448 | 0.496934 | 6.149291 | false | false | false | false |
jsilverMDX/GlobalChat2 | GlobalChat-Kotlin-Android/app/src/main/java/com/lookrative/globalchat2androidkotlin/MainActivity.kt | 1 | 2036 | package com.lookrative.globalchat2androidkotlin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.net.URL
var msl = "http://nexus-msl.herokuapp.com/msl"
class MainActivity : AppCompatActivity() {
data class ServerListItem(
val name: String,
val ip: String,
val port: Number
) {
override fun toString(): String = name
}
var list : ArrayList<ServerListItem> = arrayListOf<ServerListItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
serverList.setOnItemClickListener { adapterView, view, i, l ->
val listItem = list[i]
// start the connection attempt
// did it succeeed?
// yes, change over
val intent = Intent(this, GlobalChat::class.java)
intent.putExtra("serverName", listItem.name)
intent.putExtra("serverIp", listItem.ip)
intent.putExtra("serverPort", listItem.port)
startActivity(intent)
}
GlobalScope.launch {
list.clear()
URL(msl).readText().split("\n").forEach {
var parts = it.split("::!!::")
if (parts[0] == "SERVER" && parts.count() == 4) {
var item = ServerListItem(parts[1], parts[2], parts[3].toInt())
list.add(item)
}
runOnUiThread {
populateServerList(list)
}
}
}
}
private fun populateServerList(servers : ArrayList<ServerListItem>) {
serverList.adapter = ArrayAdapter<ServerListItem>(this, R.layout.server_list_item, servers)
}
} | gpl-3.0 | bdeee3d597f115d648e6aee8ebe165b2 | 28.1 | 99 | 0.614931 | 4.585586 | false | false | false | false |
samtstern/quickstart-android | mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/custommodel/CustomImageClassifierProcessor.kt | 1 | 2883 | // 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 com.google.firebase.samples.apps.mlkit.kotlin.custommodel
import android.app.Activity
import android.graphics.Bitmap
import android.util.Log
import com.google.firebase.ml.common.FirebaseMLException
import com.google.firebase.samples.apps.mlkit.common.VisionImageProcessor
import com.google.firebase.samples.apps.mlkit.common.FrameMetadata
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay
import com.google.firebase.samples.apps.mlkit.common.BitmapUtils
import com.google.firebase.samples.apps.mlkit.common.CameraImageGraphic
import java.lang.ref.WeakReference
import java.nio.ByteBuffer
/**
* Custom Image Classifier Demo.
*/
class CustomImageClassifierProcessor
@Throws(FirebaseMLException::class)
constructor(activity: Activity, useQuantizedModel: Boolean) : VisionImageProcessor {
private val classifier: CustomImageClassifier =
CustomImageClassifier(activity, useQuantizedModel)
private val activityRef = WeakReference(activity)
@Throws(FirebaseMLException::class)
override fun process(
data: ByteBuffer,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
activityRef.get()?.let { activity ->
classifier
.classifyFrame(data, frameMetadata.width, frameMetadata.height)
.addOnSuccessListener(
activity
) { result ->
val labelGraphic = LabelGraphic(
graphicOverlay,
result
)
val bitmap = BitmapUtils.getBitmap(data, frameMetadata)
val imageGraphic = CameraImageGraphic(graphicOverlay, bitmap)
graphicOverlay.clear()
graphicOverlay.add(imageGraphic)
graphicOverlay.add(labelGraphic)
graphicOverlay.postInvalidate()
}
.addOnFailureListener { e ->
Log.d(TAG, "Custom classifier failed: $e")
e.printStackTrace()
}
}
}
override fun process(bitmap: Bitmap, graphicOverlay: GraphicOverlay) = Unit
override fun stop() = Unit
companion object {
private const val TAG = "Custom"
}
}
| apache-2.0 | ca1bf96ab7f248897089c4b852fd8a96 | 37.44 | 84 | 0.67187 | 4.945111 | false | false | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/decode/ApkIconBitmapDecoder.kt | 1 | 3739 | /*
* Copyright (C) 2022 panpf <[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.github.panpf.sketch.decode
import android.content.pm.PackageManager
import androidx.annotation.WorkerThread
import androidx.exifinterface.media.ExifInterface
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.datasource.DataFrom.LOCAL
import com.github.panpf.sketch.decode.internal.appliedResize
import com.github.panpf.sketch.decode.internal.logString
import com.github.panpf.sketch.fetch.FetchResult
import com.github.panpf.sketch.request.internal.RequestContext
import com.github.panpf.sketch.util.toNewBitmap
import java.io.IOException
/**
* Extract the icon of the Apk file and convert it to Bitmap
*/
class ApkIconBitmapDecoder(
private val sketch: Sketch,
private val requestContext: RequestContext,
private val fetchResult: FetchResult
) : BitmapDecoder {
companion object {
const val MODULE = "ApkIconBitmapDecoder"
const val MIME_TYPE = "application/vnd.android.package-archive"
}
@WorkerThread
override suspend fun decode(): BitmapDecodeResult {
val request = requestContext.request
// Currently running on a limited number of IO contexts, so this warning can be ignored
@Suppress("BlockingMethodInNonBlockingContext")
val file = fetchResult.dataSource.file()
val packageManager = request.context.packageManager
val packageInfo =
packageManager.getPackageArchiveInfo(file.path, PackageManager.GET_ACTIVITIES)
?: throw IOException("getPackageArchiveInfo return null. ${file.path}")
packageInfo.applicationInfo.sourceDir = file.path
packageInfo.applicationInfo.publicSourceDir = file.path
val drawable = packageManager.getApplicationIcon(packageInfo.applicationInfo)
val bitmap = drawable.toNewBitmap(
bitmapPool = sketch.bitmapPool,
disallowReuseBitmap = request.disallowReuseBitmap,
preferredConfig = request.bitmapConfig?.getConfig(MIME_TYPE)
)
val imageInfo =
ImageInfo(bitmap.width, bitmap.height, MIME_TYPE, ExifInterface.ORIENTATION_UNDEFINED)
sketch.logger.d(MODULE) {
"decode. successful. ${bitmap.logString}. ${imageInfo}. '${requestContext.key}'"
}
return BitmapDecodeResult(bitmap, imageInfo, LOCAL, null, null)
.appliedResize(sketch, requestContext)
}
class Factory : BitmapDecoder.Factory {
override fun create(
sketch: Sketch,
requestContext: RequestContext,
fetchResult: FetchResult
): BitmapDecoder? = if (MIME_TYPE.equals(fetchResult.mimeType, ignoreCase = true)) {
ApkIconBitmapDecoder(sketch, requestContext, fetchResult)
} else {
null
}
override fun toString(): String = "ApkIconBitmapDecoder"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return true
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
} | apache-2.0 | baf0caefea409680b3301922b8c9fbda | 38.368421 | 98 | 0.699385 | 4.887582 | false | false | false | false |
mswift42/apg | Wo4/app/src/main/java/mswift42/com/github/wo4/MainActivity.kt | 1 | 1150 | package mswift42.com.github.wo4
import android.content.Intent
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity(), WorkoutListFragment.WorkoutListListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun itemClicked(id: Long) {
val fragmentContainer = findViewById(R.id.fragment_container)
if (fragmentContainer != null) {
val details = WorkoutDetailFragment()
val ft = supportFragmentManager.beginTransaction()
details.setWorkoutId(id)
ft.replace(R.id.fragment_container, details)
ft.addToBackStack(null)
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
ft.commit()
} else {
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_WORKOUT_ID, id.toInt())
startActivity(intent)
}
}
}
| gpl-3.0 | 16b5b4cc111ad87e15342e4ea940d4ae | 34.9375 | 83 | 0.686087 | 4.73251 | false | false | false | false |
cnevinc/AnkoSample | app/src/main/java/com/nevinchen/myapplication/example/main.kt | 1 | 3043 | package com.nevinchen.myapplication.example
import java.util.*
fun swap(array: IntArray, a: Int, b: Int) {
val temp = array[a]
array[a] = array[b]
array[b] = temp
}
fun insertionSort(array: IntArray) {
for ((index, value) in array.withIndex()) {
// println("the element at $index is $value")
var j = index
while (j > 0 ) {
// swap if smaller than sorted[j]
if (array[j] < array[j - 1]) {
swap(array, j, j - 1)
}
j--
}
}
}
fun selectionSort(a: IntArray) {
if (a.size() < 1) {
return
}
for (j in 0..a.size() - 1) {
var minp = j
for (i in j..a.size() - 1) {
if (a[minp] > a[i]) {
minp = i
}
}
println("min started from $j is ${a[minp]} @ $minp")
swap(a, j, minp)
}
}
// ============== merge sort start ==============
var numbers: IntArray = intArrayOf()
var temp: IntArray = intArrayOf()
fun merge(low: Int, middle: Int, high: Int) {
for (i in low..high) {
temp[i] = numbers[i];
}
var i = low;
var j = middle + 1;
var k = low;
while (i <= middle && j <= high) {
if (temp[i] <= temp[j]) {
numbers[k] = temp[i];
i++;
} else {
numbers[k] = temp[j];
j++;
}
k++;
}
while (i <= middle) {
numbers[k] = temp[i];
k++;
i++;
}
}
fun mergesortImpl(low: Int, high: Int) {
if (low < high) {
var mid: Int = low + (high - low) / 2;
mergesortImpl(low, mid);
mergesortImpl(mid + 1, high);
merge(low, mid, high);
}
}
fun mergetSort(a: IntArray) {
numbers = a;
temp = a.copyOf();
mergesortImpl(0, a.size() - 1);
}
// ============== merge sort end ==============
// ============== Quick sort start 20151015==============
fun quickSort(a: IntArray, lowOffset: Int, highOffset: Int) {
if (lowOffset > highOffset ) return;
// find pivot
var pivot: Int = a[highOffset]
var nextSmallTail = lowOffset;
// partition
for (i in lowOffset..highOffset - 1) {
if ( a[i] <= pivot ) {
swap(a, i, nextSmallTail)
nextSmallTail++
}
}
swap(a, nextSmallTail, highOffset)
pivot = nextSmallTail
quickSort(a, lowOffset, pivot - 1)
quickSort(a, pivot + 1, highOffset)
}
// ============== Quick sort end 20151015==============
fun main(args: Array<String>) {
// var array = intArrayOf( 6,5,4,3,2,1)
// array.forEach { i -> print(i) }
// println("")
// quickSort(array,0,array.size()-1)
// array.forEach { i -> print(i) }
// var b = Base("b")
// var d = Derived("d")
// var d: ArrayList<Derived> = ArrayList<Derived>();
// var b: ArrayList<in Base> = ArrayList<Base>()
// print(b)
// list = ar
// print(ar.toString())
// foo(list)
}
fun foo(p: ArrayList<in Any>){
}
| apache-2.0 | 41261889a8d685568746cc637a7c0663 | 19.422819 | 61 | 0.469931 | 3.244136 | false | false | false | false |
AndroidX/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/InternalXAnnotationValue.kt | 3 | 5990 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compiler.processing
import com.squareup.javapoet.TypeName
internal abstract class InternalXAnnotationValue : XAnnotationValue {
/**
* The kind of an annotation value.
*
* Note that a kind, say [Kind.STRING], is used for both `String` and `String[]` types. To
* distinguish between `String` and `String[]` you can check `valueType.isArray()`.
*/
private enum class Kind {
BOOLEAN, INT, SHORT, LONG, FLOAT, DOUBLE, BYTE, CHAR, STRING, ENUM, ANNOTATION, TYPE;
companion object {
fun of(type: XType): Kind {
if (type.isArray()) {
return of(type.componentType)
}
return when {
type.typeName == TypeName.BOOLEAN -> BOOLEAN
type.typeName == TypeName.INT -> INT
type.typeName == TypeName.SHORT -> SHORT
type.typeName == TypeName.LONG -> LONG
type.typeName == TypeName.FLOAT -> FLOAT
type.typeName == TypeName.DOUBLE -> DOUBLE
type.typeName == TypeName.BYTE -> BYTE
type.typeName == TypeName.CHAR -> CHAR
type.typeName == InternalXAnnotationValue.STRING -> STRING
type.typeName.rawTypeName() == CLASS -> TYPE
type.typeName.rawTypeName() == KCLASS -> TYPE
type.typeElement?.isEnum() == true -> ENUM
type.typeElement?.isAnnotationClass() == true -> ANNOTATION
else -> error("Unexpected type: $type")
}
}
}
}
/** The kind of the value. */
private val kind: Kind by lazy {
Kind.of(valueType)
}
final override fun hasListValue() = valueType.isArray()
/** Returns true if the value is an [XType] */
final override fun hasTypeValue() = kind == Kind.TYPE && !hasListValue()
/** Returns true if the value is a list of [XType] */
final override fun hasTypeListValue() = kind == Kind.TYPE && hasListValue()
/** Returns true if the value is an [XAnnotation] */
final override fun hasAnnotationValue() = kind == Kind.ANNOTATION && !hasListValue()
/** Returns true if the value is a list of [XAnnotation] */
final override fun hasAnnotationListValue() = kind == Kind.ANNOTATION && hasListValue()
/** Returns true if the value is an [XEnumEntry] */
final override fun hasEnumValue() = kind == Kind.ENUM && !hasListValue()
/** Returns true if the value is a list of [XEnumEntry] */
final override fun hasEnumListValue() = kind == Kind.ENUM && hasListValue()
/** Returns true if the value is an [Boolean] */
final override fun hasBooleanValue() = kind == Kind.BOOLEAN && !hasListValue()
/** Returns true if the value is a list of [Boolean] */
final override fun hasBooleanListValue() = kind == Kind.BOOLEAN && hasListValue()
/** Returns true if the value is an [Boolean] */
final override fun hasStringValue() = kind == Kind.STRING && !hasListValue()
/** Returns true if the value is a list of [String] */
final override fun hasStringListValue() = kind == Kind.STRING && hasListValue()
/** Returns true if the value is an [Int] */
final override fun hasIntValue() = kind == Kind.INT && !hasListValue()
/** Returns true if the value is a list of [Int] */
final override fun hasIntListValue() = kind == Kind.INT && hasListValue()
/** Returns true if the value is an [Long] */
final override fun hasLongValue() = kind == Kind.LONG && !hasListValue()
/** Returns true if the value is a list of [Long] */
final override fun hasLongListValue() = kind == Kind.LONG && hasListValue()
/** Returns true if the value is an [Short] */
final override fun hasShortValue() = kind == Kind.SHORT && !hasListValue()
/** Returns true if the value is a list of [Short] */
final override fun hasShortListValue() = kind == Kind.SHORT && hasListValue()
/** Returns true if the value is an [Float] */
final override fun hasFloatValue() = kind == Kind.FLOAT && !hasListValue()
/** Returns true if the value is a list of [Float] */
final override fun hasFloatListValue() = kind == Kind.FLOAT && hasListValue()
/** Returns true if the value is an [Double] */
final override fun hasDoubleValue() = kind == Kind.DOUBLE && !hasListValue()
/** Returns true if the value is a list of [Double] */
final override fun hasDoubleListValue() = kind == Kind.DOUBLE && hasListValue()
/** Returns true if the value is an [Char] */
final override fun hasCharValue() = kind == Kind.CHAR && !hasListValue()
/** Returns true if the value is a list of [Char] */
final override fun hasCharListValue() = kind == Kind.CHAR && hasListValue()
/** Returns true if the value is an [Byte] */
final override fun hasByteValue() = kind == Kind.BYTE && !hasListValue()
/** Returns true if the value is a list of [Byte] */
final override fun hasByteListValue() = kind == Kind.BYTE && hasListValue()
private companion object {
val STRING: TypeName = TypeName.get(String::class.java)
val CLASS: TypeName = TypeName.get(Class::class.java)
val KCLASS: TypeName = TypeName.get(kotlin.reflect.KClass::class.java)
}
} | apache-2.0 | 1a95fa640bea90e174b558661d29f9c8 | 42.100719 | 94 | 0.628214 | 4.362709 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/modules/PedometerModule.kt | 2 | 2007 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi43_0_0.expo.modules.sensors.modules
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.SensorEvent
import android.os.Bundle
import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi43_0_0.expo.modules.interfaces.sensors.services.PedometerServiceInterface
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
class PedometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
private var stepsAtTheBeginning: Int? = null
override val eventName: String = "Exponent.pedometerUpdate"
override fun getName(): String {
return "ExponentPedometer"
}
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(PedometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
if (stepsAtTheBeginning == null) {
stepsAtTheBeginning = sensorEvent.values[0].toInt() - 1
}
return Bundle().apply {
putDouble("steps", (sensorEvent.values[0] - stepsAtTheBeginning!!).toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
promise.resolve(context.packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER))
}
@ExpoMethod
fun getStepCountAsync(startDate: Int?, endDate: Int?, promise: Promise) {
promise.reject("E_NOT_AVAILABLE", "Getting step count for date range is not supported on Android yet.")
}
}
| bsd-3-clause | 8c3229d93594f2fc69af62d42fb4ddbc | 30.857143 | 107 | 0.758346 | 4.1639 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowValueMappingRule.kt | 1 | 4988 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.isNd4jTensorName
import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.ValueMapping
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor
import org.tensorflow.framework.*
@MappingRule("tensorflow","valuemapping","attribute")
class TensorflowValueMappingRule(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) :
ValueMapping<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) {
override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> {
return TensorflowIRAttr(attrDef, attributeValueType)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowTensorName(name, opDef)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowAttributeName(name, opDef)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor)
}
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef)
}
} | apache-2.0 | 964791d441646a2e3321e7fa0f87884f | 59.841463 | 221 | 0.769246 | 4.988 | false | false | false | false |
AndroidX/androidx | tv/tv-material/src/main/java/androidx/tv/material/carousel/CarouselItem.kt | 3 | 6418 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tv.material.carousel
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusState
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalFocusManager
import androidx.tv.material.ExperimentalTvMaterialApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
/**
* This composable is intended for use in Carousel.
* A composable that has
* - a [background] layer that is rendered as soon as the composable is visible.
* - an [overlay] layer that is rendered after a delay of
* [overlayEnterTransitionStartDelayMillis].
*
* @param overlayEnterTransitionStartDelayMillis time between the rendering of the
* background and the overlay.
* @param overlayEnterTransition animation used to bring the overlay into view.
* @param overlayExitTransition animation used to remove the overlay from view.
* @param background composable defining the background of the slide.
* @param overlay composable defining the content overlaid on the background.
*/
@Suppress("IllegalExperimentalApiUsage")
@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)
@ExperimentalTvMaterialApi
@Composable
fun CarouselItem(
background: @Composable () -> Unit,
modifier: Modifier = Modifier,
overlayEnterTransitionStartDelayMillis: Long =
CarouselItemDefaults.OverlayEnterTransitionStartDelayMillis,
overlayEnterTransition: EnterTransition = CarouselItemDefaults.OverlayEnterTransition,
overlayExitTransition: ExitTransition = CarouselItemDefaults.OverlayExitTransition,
overlay: @Composable () -> Unit
) {
val overlayVisible = remember { MutableTransitionState(initialState = false) }
var focusState: FocusState? by remember { mutableStateOf(null) }
val focusManager = LocalFocusManager.current
val bringIntoViewRequester = remember { BringIntoViewRequester() }
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(overlayVisible) {
overlayVisible.onAnimationCompletion {
// slide has loaded completely.
if (focusState?.isFocused == true) {
// Using bringIntoViewRequester here instead of in Carousel.kt as when the focusable
// item is within an animation, bringIntoView scrolls excessively and loses focus.
// b/241591211
// By using bringIntoView inside the snapshotFlow, we ensure that the focusable has
// completed animating into position.
bringIntoViewRequester.bringIntoView()
focusManager.moveFocus(FocusDirection.Enter)
}
}
}
Box(modifier = modifier
.bringIntoViewRequester(bringIntoViewRequester)
.onFocusChanged {
focusState = it
if (it.isFocused && overlayVisible.isIdle && overlayVisible.currentState) {
coroutineScope.launch {
bringIntoViewRequester.bringIntoView()
focusManager.moveFocus(FocusDirection.Enter)
}
}
}
.focusable()) {
background()
LaunchedEffect(overlayVisible) {
// After the delay, set overlay-visibility to true and trigger the animation to show the
// overlay.
delay(overlayEnterTransitionStartDelayMillis)
overlayVisible.targetState = true
}
AnimatedVisibility(
modifier = Modifier
.align(Alignment.BottomStart)
.onFocusChanged {
if (it.isFocused) {
focusManager.moveFocus(FocusDirection.Enter)
}
}
.focusable(),
visibleState = overlayVisible,
enter = overlayEnterTransition,
exit = overlayExitTransition
) {
overlay.invoke()
}
}
}
private suspend fun MutableTransitionState<Boolean>.onAnimationCompletion(
action: suspend () -> Unit
) {
snapshotFlow { isIdle && currentState }.first { it }
action.invoke()
}
@ExperimentalTvMaterialApi
object CarouselItemDefaults {
/**
* Default delay between the background being rendered and the overlay being rendered.
*/
val OverlayEnterTransitionStartDelayMillis: Long = 1500
/**
* Default transition to bring the overlay into view.
*/
val OverlayEnterTransition: EnterTransition = slideInHorizontally(initialOffsetX = { it * 4 })
/**
* Default transition to remove overlay from view.
*/
val OverlayExitTransition: ExitTransition = slideOutHorizontally()
}
| apache-2.0 | 321f5f9ddcb76dd5fa11bbbcd4dfa3fa | 39.1125 | 100 | 0.725927 | 5.226384 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/config/RunAsCurrentUserConfigSpec.kt | 1 | 4134 | /*
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.config
import batect.testutils.on
import batect.testutils.withColumn
import batect.testutils.withLineNumber
import batect.testutils.withMessage
import com.charleskorn.kaml.Yaml
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.isA
import com.natpryce.hamkrest.throws
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object RunAsCurrentUserConfigSpec : Spek({
describe("'run as current user' configuration") {
describe("deserializing from YAML") {
on("parsing a valid configuration that enables 'run as current user'") {
val config = fromYaml(
"""
enabled: true
home_directory: /home/the_user
""".trimIndent()
)
it("returns a configuration that runs as the current user") {
assertThat(config, isA<RunAsCurrentUserConfig.RunAsCurrentUser>())
}
it("returns the correct home directory") {
assertThat((config as RunAsCurrentUserConfig.RunAsCurrentUser).homeDirectory, equalTo("/home/the_user"))
}
}
on("parsing a valid configuration that disables 'run as current user'") {
val config = fromYaml(
"""
enabled: false
""".trimIndent()
)
it("returns a configuration that runs as the default container user") {
assertThat(config, isA<RunAsCurrentUserConfig.RunAsDefaultContainerUser>())
}
}
on("parsing a configuration that enables 'run as current user' but does not provide a home directory") {
val yaml = """
enabled: true
""".trimIndent()
it("throws an appropriate exception") {
assertThat({ fromYaml(yaml) }, throws(withMessage("Running as the current user has been enabled, but a home directory for that user has not been provided.") and withLineNumber(1) and withColumn(1)))
}
}
on("parsing a configuration that disables 'run as current user' but also provides a home directory") {
val yaml = """
enabled: false
home_directory: /home/the_user
""".trimIndent()
it("throws an appropriate exception") {
assertThat({ fromYaml(yaml) }, throws(withMessage("Running as the current user has not been enabled, but a home directory for that user has been provided.") and withLineNumber(1) and withColumn(1)))
}
}
on("parsing a configuration that does not enable 'run as current user' but provides a home directory") {
val yaml = """
home_directory: /home/the_user
""".trimIndent()
it("throws an appropriate exception") {
assertThat({ fromYaml(yaml) }, throws(withMessage("Running as the current user has not been enabled, but a home directory for that user has been provided.") and withLineNumber(1) and withColumn(1)))
}
}
}
}
})
private fun fromYaml(yaml: String) = Yaml.default.parse(RunAsCurrentUserConfig.serializer(), yaml)
| apache-2.0 | d3ea496e631f573bb8ee235337b1e1fb | 41.183673 | 218 | 0.608128 | 5.219697 | false | true | false | false |
androidx/androidx | datastore/datastore-rxjava3/src/main/java/androidx/datastore/rxjava3/RxDataStoreBuilder.kt | 3 | 6982 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.rxjava3
import android.annotation.SuppressLint
import android.content.Context
import androidx.datastore.core.DataMigration
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.core.Serializer
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.dataStoreFile
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.rx3.asCoroutineDispatcher
import kotlinx.coroutines.rx3.await
import java.io.File
import java.util.concurrent.Callable
/**
* Builder class for an RxDataStore that works on a single process.
*/
@SuppressLint("TopLevelBuilder")
public class RxDataStoreBuilder<T : Any> {
/**
* Create a RxDataStoreBuilder with the callable which returns the File that DataStore acts on.
* The user is responsible for ensuring that there is never more than one DataStore acting on
* a file at a time.
*
* @param produceFile Function which returns the file that the new DataStore will act on. The
* function must return the same path every time. No two instances of DataStore should act on
* the same file at the same time.
* @param serializer the serializer for the type that this DataStore acts on.
*/
public constructor(produceFile: Callable<File>, serializer: Serializer<T>) {
this.produceFile = produceFile
this.serializer = serializer
}
/**
* Create a RxDataStoreBuilder with the Context and name from which to derive the DataStore
* file. The file is generated by File(this.filesDir, "datastore/$fileName"). The user is
* responsible for ensuring that there is never more than one DataStore acting on a file at a
* time.
*
* @param context the context from which we retrieve files directory.
* @param fileName the filename relative to Context.applicationContext.filesDir that DataStore
* acts on. The File is obtained from [dataStoreFile]. It is created in the "/datastore"
* subdirectory.
* @param serializer the serializer for the type that this DataStore acts on.
*/
public constructor(context: Context, fileName: String, serializer: Serializer<T>) {
this.context = context
this.name = fileName
this.serializer = serializer
}
// Either produceFile or context & name must be set, but not both. This is enforced by the
// two constructors.
private var produceFile: Callable<File>? = null
private var context: Context? = null
private var name: String? = null
// Required. This is enforced by the constructors.
private var serializer: Serializer<T>? = null
// Optional
private var ioScheduler: Scheduler = Schedulers.io()
private var corruptionHandler: ReplaceFileCorruptionHandler<T>? = null
private val dataMigrations: MutableList<DataMigration<T>> = mutableListOf()
/**
* Set the Scheduler on which to perform IO and transform operations. This is converted into
* a CoroutineDispatcher before being added to DataStore.
*
* This parameter is optional and defaults to Schedulers.io().
*
* @param ioScheduler the scheduler on which IO and transform operations are run
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun setIoScheduler(ioScheduler: Scheduler): RxDataStoreBuilder<T> =
apply { this.ioScheduler = ioScheduler }
/**
* Sets the corruption handler to install into the DataStore.
*
* This parameter is optional and defaults to no corruption handler.
*
* @param corruptionHandler
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun setCorruptionHandler(corruptionHandler: ReplaceFileCorruptionHandler<T>):
RxDataStoreBuilder<T> = apply { this.corruptionHandler = corruptionHandler }
/**
* Add an RxDataMigration to the DataStore. Migrations are run in the order they are added.
*
* @param rxDataMigration the migration to add.
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun addRxDataMigration(rxDataMigration: RxDataMigration<T>): RxDataStoreBuilder<T> =
apply {
this.dataMigrations.add(DataMigrationFromRxDataMigration(rxDataMigration))
}
/**
* Add a DataMigration to the Datastore. Migrations are run in the order they are added.
*
* @param dataMigration the migration to add
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun addDataMigration(dataMigration: DataMigration<T>): RxDataStoreBuilder<T> = apply {
this.dataMigrations.add(dataMigration)
}
/**
* Build the DataStore.
*
* @return the DataStore with the provided parameters
*/
public fun build(): RxDataStore<T> {
val scope = CoroutineScope(ioScheduler.asCoroutineDispatcher() + Job())
val delegateDs = if (produceFile != null) {
DataStoreFactory.create(
produceFile = { produceFile!!.call() },
serializer = serializer!!,
scope = scope,
corruptionHandler = corruptionHandler,
migrations = dataMigrations
)
} else if (context != null && name != null) {
DataStoreFactory.create(
produceFile = { context!!.dataStoreFile(name!!) },
serializer = serializer!!,
scope = scope,
corruptionHandler = corruptionHandler,
migrations = dataMigrations
)
} else {
error("Either produceFile or context and name must be set. This should never happen.")
}
return RxDataStore.create(delegateDs, scope)
}
}
internal class DataMigrationFromRxDataMigration<T>(private val migration: RxDataMigration<T>) :
DataMigration<T> {
override suspend fun shouldMigrate(currentData: T): Boolean {
return migration.shouldMigrate(currentData).await()
}
override suspend fun migrate(currentData: T): T {
return migration.migrate(currentData).await()
}
override suspend fun cleanUp() {
migration.cleanUp().await()
}
}
| apache-2.0 | 507d5979ee5f61810e7c88258e0a075d | 37.362637 | 99 | 0.693354 | 4.983583 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/analysis/ComposableDeclarationCheckerTests.kt | 3 | 8905 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.analysis
import androidx.compose.compiler.plugins.kotlin.AbstractComposeDiagnosticsTest
class ComposableDeclarationCheckerTests : AbstractComposeDiagnosticsTest() {
fun testPropertyWithInitializer() {
doTest(
"""
import androidx.compose.runtime.Composable
val <!COMPOSABLE_PROPERTY_BACKING_FIELD!>bar<!>: Int = 123
@Composable get() = field
"""
)
}
fun testComposableFunctionReferences() {
doTest(
"""
import androidx.compose.runtime.Composable
@Composable fun A() {}
val aCallable: () -> Unit = <!COMPOSABLE_FUNCTION_REFERENCE!>::A<!>
val bCallable: @Composable () -> Unit = <!COMPOSABLE_FUNCTION_REFERENCE,TYPE_MISMATCH!>::A<!>
val cCallable = <!COMPOSABLE_FUNCTION_REFERENCE!>::A<!>
fun doSomething(fn: () -> Unit) { print(fn) }
@Composable fun B(content: @Composable () -> Unit) {
content()
doSomething(<!COMPOSABLE_FUNCTION_REFERENCE!>::A<!>)
B(<!COMPOSABLE_FUNCTION_REFERENCE,TYPE_MISMATCH!>::A<!>)
}
"""
)
}
fun testNonComposableFunctionReferences() {
doTest(
"""
import androidx.compose.runtime.Composable
fun A() {}
val aCallable: () -> Unit = ::A
val bCallable: @Composable () -> Unit = <!TYPE_MISMATCH!>::A<!>
val cCallable = ::A
fun doSomething(fn: () -> Unit) { print(fn) }
@Composable fun B(content: @Composable () -> Unit) {
content()
doSomething(::A)
B(<!TYPE_MISMATCH!>::A<!>)
}
"""
)
}
fun testPropertyWithGetterAndSetter() {
doTest(
"""
import androidx.compose.runtime.Composable
var <!COMPOSABLE_VAR!>bam2<!>: Int
@Composable get() { return 123 }
set(value) { print(value) }
var <!COMPOSABLE_VAR!>bam3<!>: Int
@Composable get() { return 123 }
<!WRONG_ANNOTATION_TARGET!>@Composable<!> set(value) { print(value) }
var <!COMPOSABLE_VAR!>bam4<!>: Int
get() { return 123 }
<!WRONG_ANNOTATION_TARGET!>@Composable<!> set(value) { print(value) }
"""
)
}
fun testPropertyGetterAllForms() {
doTest(
"""
import androidx.compose.runtime.Composable
val bar2: Int @Composable get() = 123
@get:Composable val bar3: Int get() = 123
interface Foo {
val bar2: Int @Composable get() = 123
@get:Composable val bar3: Int get() = 123
}
"""
)
}
fun testSuspendComposable() {
doTest(
"""
import androidx.compose.runtime.Composable
@Composable suspend fun <!COMPOSABLE_SUSPEND_FUN!>Foo<!>() {}
fun acceptSuspend(fn: suspend () -> Unit) { print(fn) }
fun acceptComposableSuspend(fn: <!COMPOSABLE_SUSPEND_FUN!>@Composable suspend () -> Unit<!>) { print(fn.hashCode()) }
val foo: suspend () -> Unit = <!TYPE_MISMATCH!>@Composable {}<!>
val bar: suspend () -> Unit = {}
fun Test() {
val composableLambda = @Composable {}
acceptSuspend <!TYPE_MISMATCH!>@Composable {}<!>
acceptComposableSuspend @Composable {}
acceptComposableSuspend(composableLambda)
acceptSuspend(<!COMPOSABLE_SUSPEND_FUN, TYPE_MISMATCH!>@Composable suspend fun() { }<!>)
}
"""
)
}
fun testComposableMainFun() {
doTest(
"""
import androidx.compose.runtime.Composable
@Composable fun <!COMPOSABLE_FUN_MAIN!>main<!>() {}
"""
)
doTest(
"""
import androidx.compose.runtime.Composable
@Composable fun <!COMPOSABLE_FUN_MAIN!>main<!>(args: Array<String>) {
print(args)
}
"""
)
doTest(
"""
import androidx.compose.runtime.Composable
class Foo
@Composable fun main(foo: Foo) {
print(foo)
}
"""
)
}
fun testMissingComposableOnOverride() {
doTest(
"""
import androidx.compose.runtime.Composable
interface Foo {
@Composable
fun composableFunction(param: Boolean): Boolean
fun nonComposableFunction(param: Boolean): Boolean
val nonComposableProperty: Boolean
}
object FakeFoo : Foo {
<!CONFLICTING_OVERLOADS!>override fun composableFunction(param: Boolean)<!> = true
<!CONFLICTING_OVERLOADS!>@Composable override fun nonComposableFunction(param: Boolean)<!> = true
<!CONFLICTING_OVERLOADS!>override val nonComposableProperty: Boolean<!> <!CONFLICTING_OVERLOADS!>@Composable get()<!> = true
}
interface Bar {
@Composable
fun composableFunction(param: Boolean): Boolean
@get:Composable val composableProperty: Boolean
fun nonComposableFunction(param: Boolean): Boolean
val nonComposableProperty: Boolean
}
object FakeBar : Bar {
<!CONFLICTING_OVERLOADS!>override fun composableFunction(param: Boolean)<!> = true
<!CONFLICTING_OVERLOADS!>override val composableProperty: Boolean<!> <!CONFLICTING_OVERLOADS!>get()<!> = true
<!CONFLICTING_OVERLOADS!>@Composable override fun nonComposableFunction(param: Boolean)<!> = true
<!CONFLICTING_OVERLOADS!>override val nonComposableProperty: Boolean<!> <!CONFLICTING_OVERLOADS!>@Composable get()<!> = true
}
"""
)
}
fun testInferenceOverComplexConstruct1() {
doTest(
"""
import androidx.compose.runtime.Composable
val composable: @Composable ()->Unit = if(true) { { } } else { { } }
"""
)
}
fun testInferenceOverComplexConstruct2() {
doTest(
"""
import androidx.compose.runtime.Composable
@Composable fun foo() { }
val composable: @Composable ()->Unit = if(true) { { } } else { { foo() } }
"""
)
}
fun testInterfaceComposablesWithDefaultParameters() {
doTest(
"""
import androidx.compose.runtime.Composable
interface A {
@Composable fun foo(x: Int = <!ABSTRACT_COMPOSABLE_DEFAULT_PARAMETER_VALUE!>0<!>)
}
"""
)
}
fun testAbstractComposablesWithDefaultParameters() {
doTest(
"""
import androidx.compose.runtime.Composable
abstract class A {
@Composable abstract fun foo(x: Int = <!ABSTRACT_COMPOSABLE_DEFAULT_PARAMETER_VALUE!>0<!>)
}
"""
)
}
fun testInterfaceComposablesWithoutDefaultParameters() {
doTest(
"""
import androidx.compose.runtime.Composable
interface A {
@Composable fun foo(x: Int)
}
"""
)
}
fun testAbstractComposablesWithoutDefaultParameters() {
doTest(
"""
import androidx.compose.runtime.Composable
abstract class A {
@Composable abstract fun foo(x: Int)
}
"""
)
}
fun testOverrideWithoutComposeAnnotation() {
doTest(
"""
import androidx.compose.runtime.Composable
interface Base {
fun compose(content: () -> Unit)
}
class Impl : Base {
<!CONFLICTING_OVERLOADS!>override fun compose(content: @Composable () -> Unit)<!> {}
}
"""
)
}
}
| apache-2.0 | 12937820d01080fcfb2e08741319bd69 | 31.619048 | 140 | 0.532622 | 5.094394 | false | true | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCOnFire.kt | 1 | 1940 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.TimeResponseBuilder
import com.demonwav.statcraft.querydsl.QOnFire
import com.demonwav.statcraft.querydsl.QPlayers
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCOnFire(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("onfire", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.onfire")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return TimeResponseBuilder.build(plugin) {
playerName { name }
statName { "On Fire" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val o = QOnFire.onFire
val result = query.from(o).where(o.id.eq(id)).uniqueResult(o.time.sum()) ?: 0
return TimeResponseBuilder.build(plugin) {
playerName { name }
statName { "On Fire" }
stats["Total"] = result.toString()
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val o = QOnFire.onFire
val p = QPlayers.players
val list = query
.from(o)
.innerJoin(p)
.on(o.id.eq(p.id))
.groupBy(p.name)
.orderBy(o.time.sum().desc())
.limit(num)
.list(p.name, o.time.sum())
return topListTimeResponse("On Fire", list)
}
}
| mit | f98a15b51cb729f0bc8dc839b2c4e4bf | 29.793651 | 127 | 0.640206 | 4.07563 | false | false | false | false |
mplatvoet/progress | projects/core/src/main/kotlin/nl/komponents/progress/progress-jvm.kt | 1 | 5903 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package nl.komponents.progress
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
public fun concreteSingleProgressControl(executor: (() -> Unit) -> Unit): SingleProgressControl = JvmSingleProgress(executor)
public fun concreteContainerProgressControl(executor: (() -> Unit) -> Unit): ContainerProgressControl = JvmContainerProgress(executor)
private class JvmSingleProgress(executor: (() -> Unit) -> Unit) : SingleProgressControl, CallbackSupport(executor), Progress {
private val atomicVal = AtomicReference(0.0)
override val progress: Progress = object : Progress by this {}
override fun markAsDone() {
value = 1.0
}
public override val done: Boolean
get() = value >= 1.0
public override var value: Double
get() = atomicVal.get()
set(suggestedValue) {
if (suggestedValue !in (0.0..1.0)) throw OutOfRangeException("[$value] must be within bounds (0.0 .. 1.0)")
var notify: Boolean
do {
val currentVal = atomicVal.get()
notify = currentVal != suggestedValue
} while (!atomicVal.compareAndSet(currentVal, suggestedValue))
if (notify) notifyUpdate()
}
override fun contains(progress: Progress): Boolean = this == progress
}
private class JvmContainerProgress(executor: (() -> Unit) -> Unit) : ContainerProgressControl, CallbackSupport(executor), Progress {
private val childProgresses = ConcurrentLinkedQueue<ChildProgress>()
private val atomicVal = AtomicReference(0.0)
private val self = this
override val progress: Progress = object : Progress by this {
override fun equals(other: Any?): Boolean = self.equals(other)
override fun hashCode(): Int = self.hashCode()
}
public override val value: Double
get() = atomicVal.get()
override fun contains(progress: Progress): Boolean {
if (this == progress) return true
return childProgresses.any { child -> child.progress.contains(progress) }
}
override fun addChild(progress: Progress, weight: Double) {
if (weight < 0.0) throw ArgumentException("weight can not be negative")
if (progress.contains(this)) throw ArgumentException("circular reference")
childProgresses.add(ChildProgress(progress, weight))
progress.update { updateValue() }
}
private fun updateValue() {
var notify: Boolean
do {
val currentVal = atomicVal.get()
val newValue = calculateProgressFromChildren()
notify = newValue != value
} while (!atomicVal.compareAndSet(currentVal, newValue))
if (notify) notifyUpdate()
}
private fun calculateProgressFromChildren(): Double {
var totalWeight = 0.0
var totalWeightValue = 0.0
for ((p, w) in childProgresses) {
totalWeight += w
totalWeightValue += p.value * w
}
return if (totalWeight > 0.0 && totalWeightValue > 0.0) totalWeightValue / totalWeight else 0.0
}
}
private abstract class CallbackSupport(override val executor: (() -> Unit) -> Unit) : Progress {
private val callbacks = ConcurrentLinkedQueue<Callback>()
protected fun notifyUpdate() {
callbacks.forEach { cb -> cb.execute(this) }
}
override fun update(executor: (() -> Unit) -> Unit,
notifyOnAdd: Boolean,
callbackType: CallbackType,
body: Progress.() -> Unit) {
val callback = when (callbackType) {
CallbackType.BUFFERED -> JoinedCallback(executor, body)
CallbackType.ALWAYS -> AlwaysCallback(executor, body)
}
if (notifyOnAdd) {
callback.execute(this)
}
callbacks.add(callback)
}
}
private interface Callback {
fun execute(progress: Progress)
}
private class AlwaysCallback(private val executor: (() -> Unit) -> Unit,
private val cb: Progress.() -> Unit) : Callback {
override fun execute(progress: Progress) {
executor {
progress.cb()
}
}
}
private class JoinedCallback(private val executor: (() -> Unit) -> Unit,
private val cb: Progress.() -> Unit) : Callback {
private val scheduled = AtomicInteger(0)
override fun execute(progress: Progress) {
val count = scheduled.incrementAndGet()
if (count == 1) {
executor {
scheduled.decrementAndGet()
progress.cb()
}
} else {
scheduled.decrementAndGet()
}
}
}
| mit | ead7b96ec20112f34479c0ef942ec91e | 34.993902 | 134 | 0.650008 | 4.703586 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/util/data/UniqueQueue.kt | 1 | 1596 | package me.proxer.app.util.data
import java.util.Queue
/**
* @author Ruben Gees
*/
class UniqueQueue<T> : Queue<T> {
private val internalList = LinkedHashSet<T>()
override val size: Int
get() = internalList.size
override fun containsAll(elements: Collection<T>) = internalList.containsAll(elements)
override fun removeAll(elements: Collection<T>) = internalList.removeAll(elements)
override fun retainAll(elements: Collection<T>) = internalList.retainAll(elements)
override fun addAll(elements: Collection<T>) = internalList.addAll(elements)
override fun contains(element: T) = internalList.contains(element)
override fun remove(element: T) = internalList.remove(element)
override fun add(element: T) = internalList.add(element)
override fun iterator() = internalList.iterator()
override fun isEmpty() = internalList.isEmpty()
override fun clear() = internalList.clear()
override fun element() = internalList.firstOrNull() ?: throw NoSuchElementException()
override fun peek() = internalList.firstOrNull()
override fun offer(element: T): Boolean {
internalList.add(element)
return true
}
override fun poll() = iterator().let { iterator ->
when {
iterator.hasNext() -> iterator.next().apply { iterator.remove() }
else -> null
}
}
override fun remove() = iterator().let { iterator ->
when {
iterator.hasNext() -> iterator.next().apply { iterator.remove() }
else -> throw NoSuchElementException()
}
}
}
| gpl-3.0 | 0a5bb393258ad0c57a9e4ab3026b6a63 | 32.25 | 90 | 0.664787 | 4.421053 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/provider/rest/DataManager.kt | 2 | 30020 | package ru.fantlab.android.provider.rest
import com.github.kittinunf.fuel.*
import com.github.kittinunf.fuel.core.*
import com.github.kittinunf.fuel.rx.rxObject
import com.github.kittinunf.fuel.rx.rxResponsePair
import com.github.kittinunf.fuel.rx.rxString
import com.github.kittinunf.result.map
import com.google.gson.Gson
import com.google.gson.JsonElement
import io.reactivex.Single
import ru.fantlab.android.BuildConfig
import ru.fantlab.android.data.dao.model.AttachUrl
import ru.fantlab.android.data.dao.model.Login
import ru.fantlab.android.data.dao.response.*
import java.io.File
object DataManager {
val gson = Gson()
fun getAuthors(sort: Int): Single<AuthorsResponse> =
getAuthorsPath(sort)
.httpGet()
.rxObject(AuthorsResponse.Deserializer())
.map { it.get() }
fun getAwards(
nonfant: Boolean,
sortOption: AwardsSortOption = AwardsSortOption.BY_NAME
): Single<AwardsResponse> =
getAwardsPath(nonfant, sortOption)
.httpGet()
.rxObject(AwardsResponse.Deserializer())
.map { it.get() }
fun getForums(): Single<ForumsResponse> =
getForumsPath()
.httpGet()
.rxObject(ForumsResponse.Deserializer())
.map { it.get() }
fun getTopics(id: Int,
page: Int,
perPage: Int
): Single<ForumResponse> =
getTopicsPath(id, page, perPage)
.httpGet()
.rxObject(ForumResponse.Deserializer())
.map { it.get() }
fun getTopicMessages(id: Int,
page: Int,
order: TopicMessagesSortOption = TopicMessagesSortOption.BY_NEW,
perPage: Int
): Single<ForumTopicResponse> =
getTopicMessagesPath(id, page, order, perPage)
.httpGet()
.rxObject(ForumTopicResponse.Deserializer())
.map { it.get() }
fun getCommunities(): Single<CommunitiesResponse> =
getCommunitiesPath()
.httpGet()
.rxObject(CommunitiesResponse.Deserializer())
.map { it.get() }
fun getBlogs(page: Int,
limit: Int,
sortOption: BlogsSortOption
): Single<BlogsResponse> =
getBlogsPath(page, limit, sortOption)
.httpGet()
.rxObject(BlogsResponse.Deserializer())
.map { it.get() }
fun getBlogArticles(id: Int,
page: Int,
limit: Int
): Single<BlogArticlesResponse> =
getBlogArticlesPath(id, page, limit)
.httpGet()
.rxObject(BlogArticlesResponse.Deserializer())
.map { it.get() }
fun getBlogArticle(id: Int
): Single<BlogArticleResponse> =
getBlogArticlePath(id)
.httpGet()
.rxObject(BlogArticleResponse.Deserializer())
.map { it.get() }
fun getAuthor(
id: Int,
showBiography: Boolean = false,
showAwards: Boolean = false,
showLinguaProfile: Boolean = false,
showBiblioBlocks: Boolean = false,
showClassificatory: Boolean = false,
sortOption: BiblioSortOption = BiblioSortOption.BY_YEAR
): Single<AuthorResponse> =
getAuthorPath(id, showBiography, showAwards, showLinguaProfile, showBiblioBlocks, showClassificatory, sortOption)
.httpGet()
.rxObject(AuthorResponse.Deserializer())
.map { it.get() }
fun getAuthorEditions(
authorId: Int,
showEditionsBlocks: Boolean = false
): Single<AuthorEditionsResponse> =
getAuthorEditionsPath(authorId, showEditionsBlocks)
.httpGet()
.rxObject(AuthorEditionsResponse.Deserializer())
.map { it.get() }
fun getAuthorResponses(
authorId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
): Single<ResponsesResponse> =
getAuthorResponsesPath(authorId, page, sortOption)
.httpGet()
.rxObject(ResponsesResponse.Deserializer(perPage = 50))
.map { it.get() }
fun getAward(
id: Int,
showNomi: Boolean,
showContests: Boolean,
sortOption: AwardSortOption = AwardSortOption.BY_CONTEST
): Single<AwardResponse> =
getAwardPath(id, showNomi, showContests, sortOption)
.httpGet()
.rxObject(AwardResponse.Deserializer())
.map { it.get() }
fun getPersonAwards(
personId: Int,
personType: String
): Single<PersonAwardsResponse> =
getPersonAwardsPath(personId, personType)
.httpGet()
.rxObject(PersonAwardsResponse.Deserializer())
.map { it.get() }
fun getWork(
id: Int,
showAwards: Boolean = false,
showChildren: Boolean = false,
showClassificatory: Boolean = false,
showEditionsBlocks: Boolean = false,
showEditionsInfo: Boolean = false,
showFilms: Boolean = false,
showLinguaProfile: Boolean = false,
showParents: Boolean = false,
showTranslations: Boolean = false
): Single<WorkResponse> =
getWorkPath(id, showAwards, showChildren, showClassificatory, showEditionsBlocks,
showEditionsInfo, showFilms, showLinguaProfile, showParents, showTranslations)
.httpGet()
.rxObject(WorkResponse.Deserializer())
.map { it.get() }
fun getWorkResponses(
workId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
): Single<ResponsesResponse> =
getWorkResponsesPath(workId, page, sortOption)
.httpGet()
.rxObject(ResponsesResponse.Deserializer(perPage = 15))
.map { it.get() }
fun getWorkAnalogs(
workId: Int
): Single<WorkAnalogsResponse> =
getWorkAnalogsPath(workId)
.httpGet()
.rxObject(WorkAnalogsResponse.Deserializer())
.map { it.get() }
fun getEdition(
id: Int,
showContent: Boolean = false,
showAdditionalImages: Boolean = false
): Single<EditionResponse> =
getEditionPath(id, showContent, showAdditionalImages)
.httpGet()
.rxObject(EditionResponse.Deserializer())
.map { it.get() }
fun getUser(
id: Int
): Single<UserResponse> =
getUserPath(id)
.httpGet()
.rxObject(UserResponse.Deserializer())
.map { it.get() }
fun getTranslatorInformation(
id: Int,
showBio: Boolean = false,
showAwards: Boolean = false,
showTranslated: Boolean = false
): Single<TranslatorResponse> =
getTranslatorInformationPath(id, showBio, showAwards, showTranslated)
.httpGet()
.rxObject(TranslatorResponse.Deserializer())
.map { it.get() }
fun getUserMarks(
userId: Int,
page: Int = 1,
typeOption: MarksTypeOption = MarksTypeOption.ALL,
sortOption: MarksSortOption = MarksSortOption.BY_MARK
): Single<MarksResponse> =
getUserMarksPath(userId, page, typeOption, sortOption)
.httpGet()
.rxObject(MarksResponse.Deserializer(perPage = 200))
.map { it.get() }
fun getUserMarksMini(
userId: Int,
workIds: String
): Single<MarksMiniResponse> =
getUserMarksMiniPath(userId, workIds)
.httpGet()
.rxObject(MarksMiniResponse.Deserializer())
.map { it.get() }
fun getUserResponses(
userId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
): Single<ResponsesResponse> =
getUserResponsesPath(userId, page, sortOption)
.httpGet()
.rxObject(ResponsesResponse.Deserializer(perPage = 50))
.map { it.get() }
fun getUserBookcases(
userId: Int
): Single<BookcasesResponse> =
getUserBookcasesPath(userId)
.httpGet()
.rxObject(BookcasesResponse.Deserializer())
.map { it.get() }
fun getPersonalBookcases(
): Single<BookcasesResponse> =
getPersonalBookcasesPath()
.httpGet()
.rxObject(BookcasesResponse.Deserializer())
.map { it.get() }
fun getPersonalBookcaseInformation(
bookcaseId: Int
): Single<BookcaseInformationResponse> =
getPersonalBookcaseInformationPath(bookcaseId)
.httpGet()
.rxObject(BookcaseInformationResponse.Deserializer())
.map { it.get() }
fun getPersonalEditionBookcase(
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseEditionsResponse> =
getPersonalBookcasePath(bookcaseId, offset)
.httpGet()
.rxObject(BookcaseEditionsResponse.Deserializer(perPage = 10))
.map { it.get() }
fun getPersonalWorkBookcase(
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseWorksResponse> =
getPersonalBookcasePath(bookcaseId, offset)
.httpGet()
.rxObject(BookcaseWorksResponse.Deserializer(perPage = 10))
.map { it.get() }
fun getPersonalFilmBookcase(
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseFilmsResponse> =
getPersonalBookcasePath(bookcaseId, offset)
.httpGet()
.rxObject(BookcaseFilmsResponse.Deserializer(perPage = 10))
.map { it.get() }
fun getUserEditionBookcase(
userId: Int,
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseEditionsResponse> =
getUserBookcasePath(userId, bookcaseId, offset)
.httpGet()
.rxObject(BookcaseEditionsResponse.Deserializer(perPage = 10))
.map { it.get() }
fun getUserWorkBookcase(
userId: Int,
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseWorksResponse> =
getUserBookcasePath(userId, bookcaseId, offset)
.httpGet()
.rxObject(BookcaseWorksResponse.Deserializer(perPage = 10))
.map { it.get() }
fun getUserFilmBookcase(
userId: Int,
bookcaseId: Int,
offset: Int = 0
): Single<BookcaseFilmsResponse> =
getUserBookcasePath(userId, bookcaseId, offset)
.httpGet()
.rxObject(BookcaseFilmsResponse.Deserializer(perPage = 10))
.map { it.get() }
fun createBookcase(
type: String,
name: String,
publicBookcase: String,
bookcaseComment: String?
): Single<String> =
createBookcasePath()
.httpPost(listOf(
"name" to name,
"type" to type,
"shared" to publicBookcase,
"comment" to bookcaseComment
))
.rxString()
.map { it.get() }
fun updateBookcase(
bookcaseId: Int,
type: String,
name: String,
publicBookcase: String,
bookcaseComment: String?
): Single<String> =
updateBookcasePath(bookcaseId)
.httpPost(listOf(
"name" to name,
"type" to type,
"shared" to publicBookcase,
"comment" to bookcaseComment
))
.rxString()
.map { it.get() }
fun deletePersonalBookcase(
bookcaseId: Int
): Single<String> =
deletePersonalBookcasePath(bookcaseId)
.httpDelete()
.rxString()
.map { it.get() }
fun includeItemToBookcase(
bookcaseId: Int,
entityId: Int,
include: String
): Single<String> =
includeItemToBookcasePath(bookcaseId, entityId, include)
.httpPost()
.rxString()
.map { it.get() }
fun updateBookcaseItemComment(
bookcaseId: Int,
entityId: Int,
text: String
): Single<String> =
updateBookcaseItemCommentPath(bookcaseId, entityId)
.httpPost(listOf(
"txt" to text
))
.rxString()
.map { it.get() }
fun getBookcaseInclusions(
bookcaseType: String,
entityId: Int
): Single<BookcaseInclusionResponse> =
getBookcaseInclusionsPath(bookcaseType, entityId)
.httpGet()
.rxObject(BookcaseInclusionResponse.Deserializer())
.map { it.get() }
fun sendUserMark(
workId: Int,
toWorkId: Int,
mark: Int
): Single<MarkResponse> =
sendUserMarkPath(workId, toWorkId, mark)
.httpGet()
.rxObject(MarkResponse.Deserializer())
.map { it.get() }
fun sendResponseVote(
responseId: Int,
voteType: String
): Single<String> =
sendResponseVotePath(responseId, voteType)
.httpGet()
.rxString()
.map { it.get() }
fun sendArticleLike(
articleId: Int,
likeType: Boolean
): Single<BlogArticlesVoteResponse> =
sendArticleLikePath(articleId)
.httpPut(listOf("like" to likeType))
.rxObject(BlogArticlesVoteResponse.Deserializer())
.map { it.get() }
fun sendMessage(
userId: Int,
message: CharSequence?,
mode: String
): Single<String> =
sendMessagePath(userId)
.httpPost(listOf(
"message" to message,
"mode" to mode,
"action" to "/user$userId/sendprivatemessage"
))
.rxString()
.map { it.get() }
fun sendTopicMessage(
topicId: Int,
message: CharSequence?
): Single<TopicMessageResponse> =
sendTopicMessagePath(topicId)
.httpPost(listOf(
"id" to topicId,
"message" to message
))
.rxObject(TopicMessageResponse.Deserializer())
.map { it.get() }
fun sendTopicMessageDraft(
topicId: Int,
message: CharSequence?
): Single<TopicMessageDraftResponse> =
topicDraftPath(topicId)
.httpPut(listOf(
"id" to topicId,
"message" to message
))
.rxObject(TopicMessageDraftResponse.Deserializer())
.map { it.get() }
fun deleteTopicMessage(
messageId: Int
): Single<String> =
topicMessagePath(messageId)
.httpDelete(listOf(
"id" to messageId
))
.rxString()
.map { it.get() }
fun editTopicMessage(
messageId: Int,
message: CharSequence?
): Single<String> =
topicMessagePath(messageId)
.httpPut(listOf(
"id" to messageId,
"message" to message
))
.rxString()
.map { it.get() }
fun confirmTopicDraft(
topicId: Int
): Single<TopicMessageResponse> =
topicDraftPath(topicId)
.httpPost()
.rxObject(TopicMessageResponse.Deserializer())
.map { it.get() }
fun deleteTopicDraft(
topicId: Int
): Single<String> =
topicDraftPath(topicId)
.httpDelete()
.rxString()
.map { it.get() }
fun getTopicAttachUrl(
messageId: String,
filename: String,
filepath: String
): Single<Triple<String, String, String>> =
attachTopicUrlPath(messageId)
.httpGet(listOf(
"file_name" to filename
))
.rxObject(AttachUrlResponse.Deserializer())
.map { Triple(it.get().url, filename, filepath) }
fun getTopicDraftAttachUrl(
topicId: Int,
filename: String,
filepath: String
): Single<Triple<String, String, String>> =
attachTopicDraftUrlPath(topicId)
.httpGet(listOf(
"file_name" to filename
))
.rxObject(AttachUrlResponse.Deserializer())
.map { Triple(it.get().url, filename, filepath) }
fun sendTopicAttach(
url: String,
filename: String,
file: File,
requestHandler: ProgressCallback
): Single<Pair<Int, String>> =
url
.httpUpload(method = Method.PUT)
.add(FileDataPart(file))
.requestProgress(requestHandler)
.rxResponsePair()
.map { Pair(it.first.statusCode, filename) }
fun sendResponse(
workId: Int,
message: CharSequence?,
mode: String
): Single<String> =
sendResponsePath(workId)
.httpPost(listOf(
"message" to message,
"mode" to mode,
"autosave" to "0"
))
.rxString()
.map { it.get() }
fun editResponse(
workId: Int,
commentId: Int,
newText: CharSequence?
): Single<String> =
editResponsePath(workId, commentId)
.httpPost(listOf(
"message" to newText
))
.rxString()
.map { it.get() }
fun sendClassification(
workId: Int,
query: String
): Single<String> =
sendClassificationPath(workId, query)
.httpGet()
.rxString()
.map { it.get() }
fun login(
login: String,
password: String
): Single<LoginResponse> =
loginPath()
.httpPost(listOf(
"login" to login,
"password" to password
))
.rxObject(LoginResponse.Deserializer())
.map { it.get() }
fun refreshToken(
refreshToken: String
): Login =
refreshTokenPath()
.httpPost(listOf(
"refresh_token" to refreshToken
))
.responseObject(LoginResponse.Deserializer())
.third
.map { it.login }
.get()
fun searchAuthors(
query: String,
page: Int = 1
): Single<SearchAuthorsResponse> =
searchAuthorsPath(query, page)
.httpGet()
.rxObject(SearchAuthorsResponse.Deserializer(perPage = 25))
.map { it.get() }
fun searchWorks(
query: String,
page: Int = 1
): Single<SearchWorksResponse> =
searchWorksPath(query, page)
.httpGet()
.rxObject(SearchWorksResponse.Deserializer(perPage = 25))
.map { it.get() }
fun searchEditions(
query: String,
page: Int = 1
): Single<SearchEditionsResponse> =
searchEditionsPath(query, page)
.httpGet()
.rxObject(SearchEditionsResponse.Deserializer(perPage = 25))
.map { it.get() }
fun searchAwards(
query: String,
page: Int = 1
): Single<SearchAwardsResponse> =
searchAwardsPath(query, page)
.httpGet()
.rxObject(SearchAwardsResponse.Deserializer(perPage = 25))
.map { it.get() }
fun getLastResponses(
page: Int = 1
): Single<ResponsesResponse> =
getLastResponsesPath(page)
.httpGet()
.rxObject(ResponsesResponse.Deserializer(perPage = 50))
.map { it.get() }
fun getPublishers(
page: Int = 1,
sort: String = PublishersSortOption.BY_NAME.value,
countryId: Int = 0,
type: Int = 0
): Single<PublishersResponse> =
getPublishersPath(page, sort, countryId, type)
.httpGet()
.rxObject(PublishersResponse.Deserializer(perPage = 250))
.map { it.get() }
fun getPubnews(
page: Int = 1,
sort: String = PubnewsSortOption.BY_DATE.value,
lang: Int,
pubId: Int
): Single<PubnewsResponse> =
getPubnewsPath(page, sort, lang, pubId)
.httpGet()
.rxObject(PubnewsResponse.Deserializer())
.map { it.get() }
fun getPubplans(
page: Int = 1,
sort: String = PubplansSortOption.BY_CORRECT.value,
lang: Int,
pubId: Int
): Single<PubplansResponse> =
getPubplansPath(page, sort, lang, pubId)
.httpGet()
.rxObject(PubplansResponse.Deserializer())
.map { it.get() }
fun getAutplans(
page: Int = 1,
sort: String = AutplansSortOption.BY_CORRECT.value,
lang: Int
): Single<AutplansResponse> =
getAutplansPath(page, sort, lang)
.httpGet()
.rxObject(AutplansResponse.Deserializer())
.map { it.get() }
fun getNews(
page: Int = 1,
perPage: Int = 15
): Single<NewsResponse> =
getNewsPath(page, perPage)
.httpGet()
.rxObject(NewsResponse.Deserializer(perPage = perPage))
.map { it.get() }
fun getContest(
contestId: Int,
includeWorks: Boolean
): Single<ContestResponse> =
getContestPath(contestId, includeWorks)
.httpGet()
.rxObject(ContestResponse.Deserializer())
.map { it.get() }
fun getWorkTypes(
): Single<String> =
getWorkTypesPath()
.httpGet()
.rxString()
.map { it.get() }
}
//region Sort options
enum class BiblioSortOption(val value: String) {
BY_YEAR("year"),
BY_RATING("rating"),
BY_MARK_COUNT("markcount"),
BY_RUS_NAME("rusname"),
BY_NAME("name"),
BY_WRITE_YEAR("writeyear")
}
enum class MarksTypeOption(val value: String) {
ALL("all"),
NOVEL("novel"),
STORY("story")
}
enum class MarksSortOption(val value: String) {
BY_MARK("mark"),
BY_NAME("name"),
BY_AUTHOR("autor"),
BY_DATE("date"),
BY_YEAR("year")
}
enum class TranslationsSortOption(val value: String) {
BY_YEAR("year"),
BY_AUTHOR("autor"),
BY_TYPE("type")
}
enum class ResponsesSortOption(val value: String) {
BY_DATE("date"),
BY_RATING("rating"),
BY_MARK("mark")
}
enum class AwardsSortOption(val value: String) {
BY_NAME("name"),
BY_COUNTRY("country"),
BY_TYPE("type"),
BY_LANG("lang")
}
enum class AwardSortOption(val value: String) {
BY_CONTEST("contest"),
BY_NOMI("nomi")
}
enum class PublishersSortOption(val value: String) {
BY_NAME("name"),
BY_COUNT("editions_count"),
BY_COUNTRY("country"),
BY_CITY("city")
}
enum class PubnewsSortOption(val value: String) {
BY_DATE("date"),
BY_POPULARITY("popularity"),
BY_TYPE("type"),
BY_PUBLISHER("pub"),
BY_AUTHOR("author"),
BY_NAME("title")
}
enum class PubplansSortOption(val value: String) {
BY_CORRECT("correct"),
BY_POPULARITY("popularity"),
BY_DATE("date"),
BY_TYPE("type"),
BY_PUBLISHER("pub"),
BY_AUTHOR("author"),
BY_NAME("title")
}
enum class AutplansSortOption(val value: String) {
BY_CORRECT("correct"),
BY_POPULARITY("popularity"),
BY_AUTHOR("author"),
BY_NAME("title")
}
enum class TopicMessagesSortOption(val value: String) {
BY_NEW("0"),
BY_OLD("1")
}
enum class BlogsSortOption(val value: String) {
BY_UPDATE("update"),
BY_ARTICLES("article"),
BY_SUBSCRIBERS("subscriber")
}
//endregion
//region Urls
fun getAuthorsPath(sort: Int) =
"/autors/$sort".toAbsolutePathWithApiVersion()
fun getAwardsPath(
nonfant: Boolean,
sortOption: AwardsSortOption = AwardsSortOption.BY_NAME
) = "/awards?nonfant=${nonfant.toInt()}&sort=${sortOption.value}".toAbsolutePathWithApiVersion()
fun getForumsPath() = "/forums".toAbsolutePathWithTestApiVersion()
fun getCommunitiesPath() = "/communities".toAbsolutePathWithTestApiVersion()
fun getBlogsPath(
page: Int,
limit: Int,
sortOption: BlogsSortOption
) = "/blogs?page=$page&limit=$limit&sort=${sortOption.value}".toAbsolutePathWithTestApiVersion()
fun getBlogArticlesPath(
id: Int,
page: Int,
limit: Int
) = "/blogs/$id?page=$page&limit=$limit".toAbsolutePathWithTestApiVersion()
fun getBlogArticlePath(
id: Int
) = "/blog_articles/$id".toAbsolutePathWithTestApiVersion()
fun getTopicsPath(
id: Int,
page: Int,
perPage: Int
) = "/forums/$id?page=$page&limit=$perPage".toAbsolutePathWithTestApiVersion()
fun getTopicMessagesPath(
id: Int,
page: Int,
order: TopicMessagesSortOption,
perPage: Int
) = "/topics/$id?page=$page&sortAsc=${order.value}&limit=$perPage".toAbsolutePathWithTestApiVersion()
fun getAuthorPath(
id: Int,
showBiography: Boolean = false,
showAwards: Boolean = false,
showLinguaProfile: Boolean = false,
showBiblioBlocks: Boolean = false,
showClassificatory : Boolean = false,
sortOption: BiblioSortOption = BiblioSortOption.BY_YEAR
) = ("/autor/$id?biography=${showBiography.toInt()}&awards=${showAwards.toInt()}" +
"&la_resume=${showLinguaProfile.toInt()}&biblio_blocks=${showBiblioBlocks.toInt()}&classificatory=${showClassificatory.toInt()}" +
"&sort=${sortOption.value}").toAbsolutePathWithApiVersion()
fun getAuthorEditionsPath(
authorId: Int,
showEditionsBlocks: Boolean = false
) = "/autor/$authorId/alleditions?editions_blocks=${showEditionsBlocks.toInt()}"
.toAbsolutePathWithApiVersion()
fun getAuthorResponsesPath(
authorId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
) = "/autor/$authorId/responses?page=$page&sort=${sortOption.value}".toAbsolutePathWithApiVersion()
fun getPersonAwardsPath(
personId: Int,
personType: String
) = "/$personType/$personId/awards".toAbsolutePathWithApiVersion()
fun getAwardPath(
id: Int,
showNomi: Boolean,
showContests: Boolean,
sortOption: AwardSortOption = AwardSortOption.BY_CONTEST
) = ("/award/$id?include_nomi=${showNomi.toInt()}&include_contests=${showContests.toInt()}" +
"&sort=${sortOption.value}").toAbsolutePathWithApiVersion()
fun getWorkPath(
id: Int,
showAwards: Boolean = false,
showChildren: Boolean = false,
showClassificatory: Boolean = false,
showEditionsBlocks: Boolean = false,
showEditionsInfo: Boolean = false,
showFilms: Boolean = false,
showLinguaProfile: Boolean = false,
showParents: Boolean = false,
showTranslations: Boolean = false
) = ("/work/$id?awards=${showAwards.toInt()}&children=${showChildren.toInt()}" +
"&classificatory=${showClassificatory.toInt()}&editions_blocks=${showEditionsBlocks.toInt()}" +
"&editions_info=${showEditionsInfo.toInt()}&films=${showFilms.toInt()}" +
"&la_resume=${showLinguaProfile.toInt()}&parents=${showParents.toInt()}" +
"&translations=${showTranslations.toInt()}").toAbsolutePathWithApiVersion()
fun getWorkResponsesPath(
workId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
) = "/work/$workId/responses?page=$page&sort=${sortOption.value}".toAbsolutePathWithApiVersion()
fun getWorkAnalogsPath(
workId: Int
) = "/work/$workId/similars".toAbsolutePathWithApiVersion()
fun getEditionPath(
id: Int,
showContent: Boolean = false,
showAdditionalImages: Boolean = false
) = "/edition/$id?content=${showContent.toInt()}&images_plus=${showAdditionalImages.toInt()}"
.toAbsolutePathWithApiVersion()
fun getUserPath(
id: Int
) = "/user/$id".toAbsolutePathWithApiVersion()
fun getTranslatorInformationPath(
id: Int,
showBio: Boolean = false,
showAwards: Boolean = false,
showTranslated: Boolean = false
) = "/translator/$id?awards=${showAwards.toInt()}&biography=${showBio.toInt()}&translated=${showTranslated.toInt()}".toAbsolutePathWithApiVersion()
fun getUserMarksPath(
userId: Int,
page: Int = 1,
typeOption: MarksTypeOption = MarksTypeOption.ALL,
sortOption: MarksSortOption = MarksSortOption.BY_DATE
) = "/user/$userId/marks/extended?page=$page&type=${typeOption.value}&sort=${sortOption.value}"
.toAbsolutePathWithApiVersion()
fun getUserMarksMiniPath(
userId: Int,
workIds: String
) = "/user/$userId/marks?w=$workIds&mini=1".toAbsolutePathWithApiVersion()
fun getUserResponsesPath(
userId: Int,
page: Int = 1,
sortOption: ResponsesSortOption = ResponsesSortOption.BY_DATE
) = "/user/$userId/responses?page=$page&sort=${sortOption.value}".toAbsolutePathWithApiVersion()
fun getPersonalBookcasesPath(
) = "/my/bookcases".toAbsolutePathWithApiVersion()
fun getUserBookcasesPath(
userId: Int
) = "/user/$userId/bookcases".toAbsolutePathWithApiVersion()
fun getPersonalBookcaseInformationPath(
bookcaseId: Int
) = "/my/bookcases/$bookcaseId/description".toAbsolutePathWithApiVersion()
fun getUserBookcasePath(
userId: Int,
bookcaseId: Int,
offset: Int = 0
) = "/user/$userId/bookcase/$bookcaseId?offset=$offset".toAbsolutePathWithApiVersion()
fun getPersonalBookcasePath(
bookcaseId: Int,
offset: Int = 0
) = "/my/bookcases/$bookcaseId/items?offset=$offset".toAbsolutePathWithApiVersion()
fun createBookcasePath(
) = "/my/bookcases/add".toAbsolutePathWithApiVersion()
fun updateBookcasePath(
bookcaseId: Int
) = "/my/bookcases/$bookcaseId/edit".toAbsolutePathWithApiVersion()
fun deletePersonalBookcasePath(
bookcaseId: Int
) = "/my/bookcases/$bookcaseId/delete".toAbsolutePathWithApiVersion()
fun includeItemToBookcasePath(
bookcaseId: Int,
entityId: Int,
include: String
) = "/my/bookcases/$bookcaseId/items/$entityId/$include".toAbsolutePathWithApiVersion()
fun updateBookcaseItemCommentPath(
bookcaseId: Int,
entityId: Int
) = "/my/bookcases/$bookcaseId/items/$entityId/editcomm".toAbsolutePathWithApiVersion()
fun getBookcaseInclusionsPath(
bookcaseType: String,
entityId: Int
) = "/my/bookcases/type/$bookcaseType/$entityId".toAbsolutePathWithApiVersion()
fun sendUserMarkPath(
workId: Int,
toWorkId: Int,
mark: Int
) = "/work$workId/ajaxsetmark${mark}towork$toWorkId".toAbsolutePath()
fun sendResponseVotePath(
responseId: Int,
voteType: String
) = "/vote$responseId$voteType".toAbsolutePath()
fun sendArticleLikePath(
articleId: Int
) = "/blog_articles/$articleId/like".toAbsolutePathWithTestApiVersion()
fun sendMessagePath(
userId: Int
) = "/user$userId/sendprivatemessage"
.toAbsolutePath()
fun sendTopicMessagePath(
topicId: Int
) = "/topics/$topicId/message"
.toAbsolutePathWithTestApiVersion()
fun sendTopicMessageDraftPath(
topicId: Int
) = "/topics/$topicId/message_draft"
.toAbsolutePathWithTestApiVersion()
fun topicMessagePath(
messageId: Int
) = "/forum_messages/$messageId"
.toAbsolutePathWithTestApiVersion()
fun topicDraftPath(
topicId: Int
) = "/topics/$topicId/message_draft"
.toAbsolutePathWithTestApiVersion()
fun attachTopicUrlPath(
messageId: String
) = "/forum_messages/$messageId/file_upload_url"
.toAbsolutePathWithTestApiVersion()
fun attachTopicDraftUrlPath(
topicId: Int
) = "/topics/$topicId/message_draft/file_upload_url"
.toAbsolutePathWithTestApiVersion()
fun sendResponsePath(
workId: Int
) = "/work$workId/addresponse".toAbsolutePath()
fun editResponsePath(
workId: Int,
commentId: Int
) = "/work$workId/editresponse$commentId/editresponse${commentId}ok".toAbsolutePath()
fun sendClassificationPath(
workId: Int,
query: String
) = "/genrevote$workId?$query".toAbsolutePath()
fun loginPath() = "/auth/login".toAbsolutePathWithTestApiVersion()
fun refreshTokenPath() = "/auth/refresh".toAbsolutePathWithTestApiVersion()
fun searchAuthorsPath(
query: String,
page: Int = 1
) = "/search-autors?q=$query&page=$page".toAbsolutePathWithApiVersion()
fun searchWorksPath(
query: String,
page: Int = 1
) = "/search-works?q=$query&page=$page".toAbsolutePathWithApiVersion()
fun searchEditionsPath(
query: String,
page: Int = 1
) = "/search-editions?q=$query&page=$page".toAbsolutePathWithApiVersion()
fun searchAwardsPath(
query: String,
page: Int = 1
) = "/search-awards?q=$query&page=$page".toAbsolutePathWithApiVersion()
fun getLastResponsesPath(
page: Int = 1
) = "/responses?page=$page".toAbsolutePathWithApiVersion()
fun getPublishersPath(
page: Int,
sort: String,
countryId: Int,
type: Int
) = "/publishers?page=$page&sort=$sort&country_id=$countryId&type=$type".toAbsolutePathWithApiVersion()
fun getPubnewsPath(
page: Int,
sort: String,
lang: Int,
pubId: Int
) = "/pubnews?page=$page&lang=$lang&sort=$sort&pub_id=$pubId".toAbsolutePathWithApiVersion()
fun getPubplansPath(
page: Int,
sort: String,
lang: Int,
pubId: Int
) = "/pubplans?page=$page&lang=$lang&sort=$sort&pub_id=$pubId".toAbsolutePathWithApiVersion()
fun getAutplansPath(
page: Int,
sort: String,
lang: Int
) = "/autplans?page=$page&sort=$sort&lang=$lang".toAbsolutePathWithApiVersion()
fun getNewsPath(
page: Int,
perPage: Int
) = "/news?page=$page&mpp=$perPage".toAbsolutePathWithApiVersion()
fun getContestPath(
contestId: Int,
includeWorks: Boolean
) = "/contest/$contestId?include_works=${includeWorks.toInt()}".toAbsolutePathWithApiVersion()
fun getWorkTypesPath(
) = "/conf/worktypes.json".toAbsolutePathWithApiVersion()
//endregion
//region Utils
fun String.toAbsolutePath() = "https://fantlab.ru$this"
fun String.toAbsolutePathWithApiVersion() = "https://api.fantlab.ru$this"
fun String.toAbsolutePathWithTestApiVersion() = "https://api.test.dev3.fantlab.org/v${BuildConfig.API_REVISION}$this"
//endregion
fun Boolean.toInt(): Int = if (this) 1 else 0
fun JsonElement?.isNullable(): Boolean {
return when {
this == null -> true
this.isJsonNull -> true
this.toString() == "null" -> true
else -> false
}
} | gpl-3.0 | 12596b2f92626f86aa88699fbcd630df | 25.288091 | 147 | 0.697435 | 3.333333 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/leermangasxyz/src/eu/kanade/tachiyomi/extension/es/leermangasxyz/LeerMangasXYZ.kt | 1 | 4753 | package eu.kanade.tachiyomi.extension.es.leermangasxyz
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.lang.RuntimeException
import java.net.URLEncoder
open class LeerMangasXYZ : ParsedHttpSource() {
override val baseUrl: String = "https://r1.leermanga.xyz"
override val lang: String = "es"
override val name: String = "LeerManga.xyz"
override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used")
override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException("Not used")
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesSelector(): String = throw UnsupportedOperationException("Not used")
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
override val supportsLatest: Boolean = false
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
val row = element.select("td")
with(row[0]) {
chapter_number = text().toFloat()
date_upload = 0
}
with(row[1]) {
name = text()
url = selectFirst("a").attr("href")
}
}
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = super.fetchChapterList(manga).map {
it.reversed()
}
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
setUrlWithoutDomain(document.baseUri())
val rawStatus = document.selectFirst("td:contains(Status)").text()
println(" Status: $rawStatus")
status = getStatus(rawStatus.substringAfter("Status: "))
author = document.select("li[itemprop=author]")?.joinToString(separator = ", ") { it.text() }
thumbnail_url = document.selectFirst("img.img-thumbnail").attr("abs:src")
description = document.selectFirst("p[itemprop=description]").text()
genre = document.select("span[itemprop=genre]")?.joinToString(", ") { it.text() }
}
override fun pageListParse(document: Document): List<Page> {
val pages = document.select(pageListSelector()).map {
Page(
imageUrl = it.attr("href"),
index = it.attr("data-ngdesc").substringAfter("Page ").toInt()
)
}
if (pages.isNullOrEmpty())
throw RuntimeException("Cannot fetch images from source")
return pages
}
override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply {
thumbnail_url = element.selectFirst("img.card-img-top").attr("abs:src")
element.selectFirst("div.card-body").let {
val dc = it.selectFirst("h5.card-title a")
url = dc.attr("href")
title = dc.text()
}
}
override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply {
with(element) {
thumbnail_url = selectFirst("img").attr("abs:src")
title = selectFirst("span[itemprop=name]").text()
url = selectFirst("div.col-4 a").attr("href")
}
}
fun encodeString(str: String): String = URLEncoder.encode(str, "utf-8")
private fun getStatus(str: String): Int = when (str) {
"Emitiéndose", "Ongoing", "En emisión" -> SManga.ONGOING
"Finalizado" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// ========------- [[< Request >]]] =========--------
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/search?query=${encodeString(query)}&page=$page")
override fun popularMangaRequest(page: Int): Request = GET(baseUrl, headers)
// ------ ======== [[[ SELECTORS ]]] ======== -------
private fun pageListSelector() = "div[data-nanogallery2] a"
override fun searchMangaSelector(): String = "div[itemtype*=ComicSeries]"
override fun searchMangaNextPageSelector(): String = "CHANGE THIS"
override fun popularMangaSelector(): String = "div.card-group div.card"
override fun popularMangaNextPageSelector(): String = "CHANGE THIS"
override fun chapterListSelector(): String = "table#chaptersTable tbody tr"
}
fun Element.selectFirst(cssSelector: String) = this.select(cssSelector).first()
| apache-2.0 | e7c50db1f250835a5605f93055c2bf7f | 37.626016 | 156 | 0.66386 | 4.524762 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/common/DaoExtensions.kt | 1 | 904 | package y2k.joyreactor.common
import com.j256.ormlite.dao.BaseDaoImpl
import com.j256.ormlite.dao.CloseableIterator
import com.j256.ormlite.dao.Dao
import java.util.*
/**
* Created by y2k on 4/11/16.
*/
fun <T, TD> Dao<T, TD>.queryRawList(sql: String): List<T> {
val baseDao = this as BaseDaoImpl<T, TD>
val tableName = baseDao.tableInfo.tableName
val preparedSql = sql.replace("{table-name}", tableName)
return queryRaw(preparedSql, rawRowMapper).results
}
inline fun <T, TD, R> Dao<T, TD>.autoClose(f: Iterable<T>.() -> R): R {
val needToClose = ArrayList<CloseableIterator<T>>()
try {
return object : Iterable<T> {
override fun iterator(): Iterator<T> {
val i = closeableIterator()
needToClose += i
return i
}
}.f()
} finally {
needToClose.forEach { it.close() }
}
} | gpl-2.0 | f4ef0575ecc641243ca0af941c5b8cb6 | 26.424242 | 71 | 0.615044 | 3.53125 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/mine/activity/ShowPushMessageActivity.kt | 1 | 4769 | package com.intfocus.template.dashboard.mine.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.google.gson.Gson
import com.intfocus.template.R
import com.intfocus.template.dashboard.mine.adapter.ShowPushMessageAdapter
import com.intfocus.template.dashboard.mine.presenter.PushMessagePresenter
import com.intfocus.template.dashboard.mine.view.PushMessageView
import com.intfocus.template.model.entity.PushMsgBean
import com.intfocus.template.model.entity.User
import com.intfocus.template.util.FileUtil
import com.intfocus.template.util.K
import com.intfocus.template.util.PageLinkManage
import com.intfocus.template.util.ToastUtils
import kotlinx.android.synthetic.main.activity_show_push_message.*
import java.io.File
/**
* ****************************************************
* author: JamesWong
* created on: 17/08/01 下午4:56
* e-mail: [email protected]
* name: 推送消息显示 Activity
* desc: 根据 用户Id 显示推送消息的 activity
* ****************************************************
*/
class ShowPushMessageActivity : AppCompatActivity(), PushMessageView, ShowPushMessageAdapter.OnPushMessageListener {
/**
* 当前用户id
*/
private var mUserID = 0
/**
* 显示消息的 mAdapter
*/
val adapter = ShowPushMessageAdapter(this, this)
// /**
// * RxBus 接收推送消息的类,需要手动取消注册释放资源
// */
// lateinit var subscribe: Subscription
/**
* mPresenter 类
*/
lateinit var presenter: PushMessagePresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_push_message)
// 初始化数据
initData()
// 初始化适配器
initAdapter()
}
private fun initData() {
// 获取 User 信息
val userConfigPath = String.format("%s/%s", FileUtil.basePath(this), K.K_USER_CONFIG_FILE_NAME)
if (File(userConfigPath).exists()) {
val user = Gson().fromJson(FileUtil.readConfigFile(userConfigPath).toString(), User::class.java)
if (user!!.isIs_login) {
mUserID = user.user_id
}
}
// 请求数据
presenter = PushMessagePresenter(applicationContext, this, mUserID)
presenter.loadData()
// RxBus接收到推送信息,处理数据列表更新
// subscribe = RxBusUtil.getInstance().toObservable(String::class.java)
// .subscribe {
// if ("UpDatePushMessage" == it) presenter.loadData()
// }
}
private fun initAdapter() {
val mLayoutManager = LinearLayoutManager(this)
mLayoutManager.orientation = LinearLayoutManager.VERTICAL
rv_show_push_message.layoutManager = mLayoutManager
rv_show_push_message.adapter = adapter
}
/**
* 请求数据失败的回调方法
*/
override fun onResultFailure() {
ToastUtils.show(this, "没有找到数据")
}
/**
* 请求数据成功的回调方法
*/
override fun onResultSuccess(data: MutableList<PushMsgBean>?) {
adapter.setData(data!!)
}
/**
* 消息 item 的点击回调处理方法
*/
override fun onItemClick(position: Int) {
// 更新点击状态
val pushMsg = adapter.mData[position]
PageLinkManage.pageLink(this, pushMsg)
// // 重新获取数据
// presenter.loadData()
//
// // 通知 mAdapter 刷新数据
// adapter.notifyDataSetChanged()
// val paramsMappingBean = com.alibaba.fastjson.JSONObject.parseObject(pushMsg.params_mapping, object : TypeReference<HashMap<String, String>>() {
// })
// var templateId = ""
// if (pushMsg.template_id == null || "" == pushMsg.template_id) {
// val temp = pushMsg.url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
// for (i in temp.indices) {
// if ("template" == temp[i] && i + 1 < temp.size) {
// templateId = temp[i + 1]
// break
// }
// }
// } else {
// templateId = pushMsg.template_id
// }
// PageLinkManage.pageLink(this, pushMsg.title, pushMsg.url, pushMsg.obj_id, templateId, "4", paramsMappingBean, false)
}
fun back(v: View?) {
finish()
}
//
// /**
// * 释放资源
// */
// override fun onDestroy() {
// super.onDestroy()
// if (subscribe.isUnsubscribed)
// subscribe.unsubscribe()
// }
}
| gpl-3.0 | d688a14dfe40122ba77a26024c0b3aba | 29.875862 | 153 | 0.610453 | 4.022462 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2058.kt | 1 | 1533 | package leetcode
import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/
*/
class Problem2058 {
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun nodesBetweenCriticalPoints(head: ListNode?): IntArray {
var previous: ListNode? = head
var current: ListNode? = previous?.next ?: return intArrayOf(-1, -1)
var next: ListNode? = current?.next ?: return intArrayOf(-1, -1)
var min = -1
var max = -1
var position = 2
val positions = mutableListOf<Int>()
while (next != null) {
var found = false
if (previous!!.`val` < current!!.`val` && current!!.`val` > next!!.`val`) {
positions += position
found = true
} else if (previous!!.`val` > current!!.`val` && current!!.`val` < next!!.`val`) {
positions += position
found = true
}
if (found && positions.size >= 2) {
min = if (min == -1) position - positions[positions.size - 2]
else min(min, position - positions[positions.size - 2])
max = if (max == -1) position - positions[0]
else max(max, position - positions[0])
}
previous = current
current = next
next = next.next
position++
}
return intArrayOf(min, max)
}
}
| mit | 4d1731863bdaa217201a0b8a5cce22a0 | 33.840909 | 102 | 0.519896 | 4.31831 | false | false | false | false |
skuznets0v/metro | src/main/kotlin/com/github/skuznets0v/metro/extensions/comparasion.kt | 1 | 549 | package com.github.skuznets0v.metro.extensions
import com.github.skuznets0v.metro.model.entities.LineEntity
import com.github.skuznets0v.metro.model.entities.PointEntity
import java.time.LocalTime
fun LocalTime.equalsIgnoreNano(other: LocalTime) =
this == other || (hour == other.hour && minute == other.minute && second == other.second)
fun PointEntity.equalsIgnoreId(other: PointEntity) = this === other || (x == other.x && other.y == other.y)
fun LineEntity.eqalsIgnoreId(other: LineEntity) = this === other || points == other.points
| mit | 7cd9a8554671fb5849a1985f18390636 | 44.75 | 107 | 0.743169 | 3.496815 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/step_quiz_review/dispatcher/StepQuizReviewActionDispatcher.kt | 2 | 5590 | package org.stepik.android.presentation.step_quiz_review.dispatcher
import com.jakewharton.rxrelay2.BehaviorRelay
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.persistence.model.StepPersistentWrapper
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.step_quiz.interactor.StepQuizInteractor
import org.stepik.android.domain.step_quiz_review.interactor.StepQuizReviewInteractor
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.dispatcher.StepQuizActionDispatcher
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewFeature
import ru.nobird.android.presentation.redux.dispatcher.RxActionDispatcher
import javax.inject.Inject
class StepQuizReviewActionDispatcher
@Inject
constructor(
stepWrapperRxRelay: BehaviorRelay<StepPersistentWrapper>,
lessonData: LessonData,
private val stepQuizActionDispatcher: StepQuizActionDispatcher, // todo remove
private val stepQuizInteractor: StepQuizInteractor,
private val stepQuizReviewInteractor: StepQuizReviewInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : RxActionDispatcher<StepQuizReviewFeature.Action, StepQuizReviewFeature.Message>() {
init {
compositeDisposable += stepWrapperRxRelay
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(onNext = { onNewMessage(StepQuizReviewFeature.Message.InitWithStep(it, lessonData)) })
}
override fun handleAction(action: StepQuizReviewFeature.Action) {
when (action) {
is StepQuizReviewFeature.Action.FetchStepQuizState -> {
compositeDisposable += Singles
.zip(
getAttemptState(action.stepWrapper, action.lessonData),
stepQuizReviewInteractor.getStepProgress(action.stepWrapper.step.id, action.lessonData.unit?.id)
)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { (quizState, progress) ->
onNewMessage(StepQuizReviewFeature.Message.FetchStepQuizStateSuccess(quizState, progress.firstOrNull()))
},
onError = { onNewMessage(StepQuizReviewFeature.Message.InitialFetchError) }
)
}
is StepQuizReviewFeature.Action.FetchReviewSession -> {
compositeDisposable += stepQuizReviewInteractor
.getReviewSession(action.stepId, action.unitId, action.instructionId, action.sessionId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { (instruction, sessionData, progress) ->
onNewMessage(StepQuizReviewFeature.Message.FetchReviewSessionSuccess(sessionData, instruction.reviewInstruction, progress.firstOrNull()))
},
onError = { onNewMessage(StepQuizReviewFeature.Message.InitialFetchError) }
)
}
is StepQuizReviewFeature.Action.CreateSessionWithSubmission -> {
compositeDisposable += stepQuizReviewInteractor
.createSession(action.submissionId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { (session, instruction) ->
onNewMessage(StepQuizReviewFeature.Message.SessionCreated(session, instruction))
},
onError = { onNewMessage(StepQuizReviewFeature.Message.CreateSessionError) }
)
}
is StepQuizReviewFeature.Action.CreateReviewWithSession -> {
compositeDisposable += stepQuizReviewInteractor
.createReview(action.sessionId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { review ->
onNewMessage(StepQuizReviewFeature.Message.ReviewCreated(review.id))
},
onError = { onNewMessage(StepQuizReviewFeature.Message.StartReviewError) }
)
}
}
}
private fun getAttemptState(stepWrapper: StepPersistentWrapper, lessonData: LessonData): Single<StepQuizFeature.State.AttemptLoaded> =
stepQuizInteractor
.getAttempt(stepWrapper.id)
.flatMap { attempt ->
Singles
.zip(
stepQuizActionDispatcher.getSubmissionState(attempt.id),
stepQuizInteractor.getStepRestrictions(stepWrapper, lessonData)
)
.map { (submissionState, stepRestrictions) ->
StepQuizFeature.State.AttemptLoaded(attempt, submissionState, stepRestrictions)
}
}
} | apache-2.0 | ab260aa12a0020ed99f0bf8c953d6b80 | 47.617391 | 165 | 0.64025 | 6.211111 | false | false | false | false |
huy-vuong/streamr | app/src/main/java/com/huyvuong/streamr/model/mapper/LocationMapper.kt | 1 | 630 | package com.huyvuong.streamr.model.mapper
object LocationMapper {
fun toViewModel(
location: com.huyvuong.streamr.model.transport.photos.geo.Location?
): com.huyvuong.streamr.model.view.Location? =
location?.run {
com.huyvuong.streamr.model.view.Location(
latitude = latitude,
longitude = longitude,
neighborhood = neighborhood?.name,
locality = locality?.name,
region = region.name,
country = country?.name) // FIXME NULL POINTER EXCEPTION! country == null
}
} | gpl-3.0 | 0c221a2af8e82a461d37e71dfda04a75 | 38.4375 | 93 | 0.571429 | 5 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/injection/network/NetworkModule.kt | 2 | 2394 | package org.stepik.android.view.injection.network
import dagger.Module
import dagger.Provides
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.di.AppSingleton
import org.stepic.droid.util.DebugToolsHelper
import org.stepik.android.view.injection.achievement.AchievementDataModule
import org.stepik.android.view.injection.auth.AuthDataModule
import org.stepik.android.view.injection.base.Authorized
import org.stepik.android.view.injection.qualifiers.DebugInterceptors
import org.stepik.android.view.injection.serialization.SerializationModule
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit
@Module(includes = [AuthDataModule::class, SerializationModule::class, AchievementDataModule::class])
abstract class NetworkModule {
@Module
companion object {
const val TIMEOUT_IN_SECONDS = 60L
@Provides
@AppSingleton
@JvmStatic
@DebugInterceptors
fun provideDebugInterceptors(): List<Interceptor> =
DebugToolsHelper.getDebugInterceptors()
@Provides
@JvmStatic
@AppSingleton
internal fun provideOkHttpClient(
@DebugInterceptors debugInterceptors: List<@JvmSuppressWildcards Interceptor>,
interceptors: Set<@JvmSuppressWildcards Interceptor>
): OkHttpClient {
val okHttpBuilder = OkHttpClient.Builder()
.connectTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
interceptors.forEach { okHttpBuilder.addNetworkInterceptor(it) }
debugInterceptors.forEach { okHttpBuilder.addNetworkInterceptor(it) }
return okHttpBuilder.build()
}
@Provides
@JvmStatic
@AppSingleton
@Authorized
internal fun provideRetrofit(endpointResolver: EndpointResolver, okHttpClient: OkHttpClient, converterFactory: Converter.Factory): Retrofit =
Retrofit.Builder()
.baseUrl(endpointResolver.getBaseUrl())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(converterFactory)
.client(okHttpClient)
.build()
}
} | apache-2.0 | de85f95e56f30b6cf56ee996636a2278 | 37.629032 | 149 | 0.723058 | 5.367713 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsNhController.kt | 1 | 593 | package eu.kanade.tachiyomi.ui.setting
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.data.preference.PreferenceKeys
/**
* nhentai Settings fragment
*/
class SettingsNhController : SettingsController() {
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
title = "nhentai"
switchPreference {
title = "Use high-quality thumbnails"
summary = "May slow down search results"
key = PreferenceKeys.eh_nh_useHighQualityThumbs
defaultValue = false
}
}
}
| apache-2.0 | 039180530216cf8a20eb247228062fb4 | 27.238095 | 81 | 0.688027 | 4.706349 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/test/kotlin/com/msc/serverbrowser/LocalizationTest.kt | 1 | 4308 | package com.msc.serverbrowser
import com.msc.serverbrowser.util.Language
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
import java.io.IOException
import java.net.URISyntaxException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
/**
* Checks all localization files for completion. There is a separate test for every language in
* order to assure that every file gets tested.
*
* @author Marcel
* @since 21.09.2017
*/
class LocalizationTest {
@Test
fun testLanguageGermanForCompletion() {
testLanguageForCompletion(Language.DE)
}
@Test
fun testLanguageSpanishForCompletion() {
testLanguageForCompletion(Language.ES)
}
@Test
fun testLanguageGeorgianForCompletion() {
testLanguageForCompletion(Language.GE)
}
@Test
fun testLanguageGreeceForCompletion() {
testLanguageForCompletion(Language.GR)
}
@Test
fun testLanguageDutchForCompletion() {
testLanguageForCompletion(Language.NL)
}
@Test
fun testLanguagePolishForCompletion() {
testLanguageForCompletion(Language.PL)
}
@Test
fun testLanguageRussianForCompletion() {
testLanguageForCompletion(Language.RU)
}
@Test
fun testLanguageRomanianForCompletion() {
testLanguageForCompletion(Language.RO)
}
@Test
fun testLanguageTurkishForCompletion() {
testLanguageForCompletion(Language.TR)
}
@Test
fun testLanguageBosnianForCompletion() {
testLanguageForCompletion(Language.BA)
}
private fun testLanguageForCompletion(lang: Language) {
val englishLanguage = ResourceBundle.getBundle("com.msc.serverbrowser.localization.Lang", Locale(Language.EN.shortcut))
val langProperties = ResourceBundle.getBundle("com.msc.serverbrowser.localization.Lang", Locale(lang.shortcut))
assertEquals(langProperties.keySet().size, englishLanguage.keySet().size, "Language ${lang.name} doesn't inherit all necessary keys.")
}
@Test
fun testLanguageEnglishForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.EN)
}
@Test
fun testLanguageGermanForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.DE)
}
@Test
fun testLanguageSpanishForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.ES)
}
@Test
fun testLanguageGeorgianForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.GE)
}
@Test
fun testLanguageGreeceForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.GR)
}
@Test
fun testLanguageDutchForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.NL)
}
@Test
fun testLanguagePolishForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.PL)
}
@Test
fun testLanguageRussianForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.RU)
}
@Test
fun testLanguageRomanianForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.RO)
}
@Test
fun testLanguageTurkishForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.TR)
}
@Test
fun testLanguageBosnianForDuplicatedKeys() {
testLanguageForDuplicatedKeys(Language.BA)
}
private fun testLanguageForDuplicatedKeys(lang: Language) {
try {
val lines = Files.readAllLines(Paths.get(this.javaClass.getResource("/com/msc/serverbrowser/localization/Lang_" + lang.shortcut + ".properties").toURI()))
val numberOfKeysInFile = lines.stream().filter { line -> line.matches("\\w+=.+".toRegex()) }.count()
val langProperties = ResourceBundle.getBundle("com.msc.serverbrowser.localization.Lang", Locale(lang.shortcut))
val keysInResourceBundle = langProperties.keySet().size.toLong()
assertEquals(numberOfKeysInFile, keysInResourceBundle, "The file contains $numberOfKeysInFile keys, but the ResourceBundle contains only $keysInResourceBundle.")
} catch (exception: IOException) {
fail<Nothing>(exception)
} catch (exception: URISyntaxException) {
fail<Nothing>(exception)
}
}
} | mpl-2.0 | 6f220d3d161ead547992995b9773af32 | 28.513699 | 173 | 0.707753 | 4.47352 | false | true | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsAppearanceScreen.kt | 1 | 7382 | package eu.kanade.presentation.more.settings.screen
import android.app.Activity
import android.content.Context
import android.os.Build
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.app.ActivityCompat
import eu.kanade.domain.ui.UiPreferences
import eu.kanade.domain.ui.model.TabletUiMode
import eu.kanade.domain.ui.model.ThemeMode
import eu.kanade.domain.ui.model.setAppCompatDelegateThemeMode
import eu.kanade.presentation.more.settings.Preference
import eu.kanade.presentation.util.collectAsState
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.isAutoTabletUiAvailable
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.merge
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Date
class SettingsAppearanceScreen : SearchableSettings {
@ReadOnlyComposable
@Composable
@StringRes
override fun getTitleRes() = R.string.pref_category_appearance
@Composable
override fun getPreferences(): List<Preference> {
val context = LocalContext.current
val uiPreferences = remember { Injekt.get<UiPreferences>() }
return listOf(
getThemeGroup(context = context, uiPreferences = uiPreferences),
getDisplayGroup(context = context, uiPreferences = uiPreferences),
getTimestampGroup(uiPreferences = uiPreferences),
)
}
@Composable
private fun getThemeGroup(
context: Context,
uiPreferences: UiPreferences,
): Preference.PreferenceGroup {
val themeModePref = uiPreferences.themeMode()
val themeMode by themeModePref.collectAsState()
val appThemePref = uiPreferences.appTheme()
val amoledPref = uiPreferences.themeDarkAmoled()
LaunchedEffect(themeMode) {
setAppCompatDelegateThemeMode(themeMode)
}
LaunchedEffect(Unit) {
merge(appThemePref.changes(), amoledPref.changes())
.drop(2)
.collectLatest { (context as? Activity)?.let { ActivityCompat.recreate(it) } }
}
return Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_theme),
preferenceItems = listOf(
Preference.PreferenceItem.ListPreference(
pref = themeModePref,
title = stringResource(R.string.pref_theme_mode),
subtitle = "%s",
entries = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mapOf(
ThemeMode.SYSTEM to stringResource(R.string.theme_system),
ThemeMode.LIGHT to stringResource(R.string.theme_light),
ThemeMode.DARK to stringResource(R.string.theme_dark),
)
} else {
mapOf(
ThemeMode.LIGHT to stringResource(R.string.theme_light),
ThemeMode.DARK to stringResource(R.string.theme_dark),
)
},
),
Preference.PreferenceItem.AppThemePreference(
title = stringResource(R.string.pref_app_theme),
pref = appThemePref,
),
Preference.PreferenceItem.SwitchPreference(
pref = amoledPref,
title = stringResource(R.string.pref_dark_theme_pure_black),
enabled = themeMode != ThemeMode.LIGHT,
),
),
)
}
@Composable
private fun getDisplayGroup(
context: Context,
uiPreferences: UiPreferences,
): Preference.PreferenceGroup {
val tabletUiModePref = uiPreferences.tabletUiMode()
val tabletUiMode by tabletUiModePref.collectAsState()
val isTabletUiAvailable = remember(tabletUiMode) { // won't survive config change
when (tabletUiMode) {
TabletUiMode.AUTOMATIC -> context.resources.configuration.isAutoTabletUiAvailable()
TabletUiMode.NEVER -> false
else -> true
}
}
return Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_display),
preferenceItems = listOf(
Preference.PreferenceItem.ListPreference(
pref = tabletUiModePref,
title = stringResource(R.string.pref_tablet_ui_mode),
entries = TabletUiMode.values().associateWith { stringResource(it.titleResId) },
onValueChanged = {
context.toast(R.string.requires_app_restart)
true
},
),
Preference.PreferenceItem.ListPreference(
pref = uiPreferences.sideNavIconAlignment(),
title = stringResource(R.string.pref_side_nav_icon_alignment),
subtitle = "%s",
enabled = isTabletUiAvailable,
entries = mapOf(
0 to stringResource(R.string.alignment_top),
1 to stringResource(R.string.alignment_center),
2 to stringResource(R.string.alignment_bottom),
),
),
),
)
}
@Composable
private fun getTimestampGroup(uiPreferences: UiPreferences): Preference.PreferenceGroup {
val now = remember { Date().time }
return Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_timestamps),
preferenceItems = listOf(
Preference.PreferenceItem.ListPreference(
pref = uiPreferences.relativeTime(),
title = stringResource(R.string.pref_relative_format),
subtitle = "%s",
entries = mapOf(
0 to stringResource(R.string.off),
2 to stringResource(R.string.pref_relative_time_short),
7 to stringResource(R.string.pref_relative_time_long),
),
),
Preference.PreferenceItem.ListPreference(
pref = uiPreferences.dateFormat(),
title = stringResource(R.string.pref_date_format),
subtitle = "%s",
entries = DateFormats
.associateWith {
val formattedDate = UiPreferences.dateFormat(it).format(now)
"${it.ifEmpty { stringResource(R.string.label_default) }} ($formattedDate)"
},
),
),
)
}
}
private val DateFormats = listOf(
"", // Default
"MM/dd/yy",
"dd/MM/yy",
"yyyy-MM-dd",
"dd MMM yyyy",
"MMM dd, yyyy",
)
| apache-2.0 | 10e61ccd83a95aa44fea1f5deef078a1 | 39.119565 | 103 | 0.589407 | 5.314615 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/imagepicker/exporters/CropImageExporter.kt | 2 | 1625 | package abi43_0_0.expo.modules.imagepicker.exporters
import android.graphics.Rect
import android.net.Uri
import abi43_0_0.expo.modules.imagepicker.exporters.ImageExporter.Listener
import org.apache.commons.io.IOUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
class CropImageExporter(
private val mRotation: Int,
private val mCropRect: Rect,
private val mBase64: Boolean
) : ImageExporter {
// Note: Crop activity saves the result to the output file. So, we don't need to do it.
override fun export(source: Uri, output: File, exporterListener: Listener) {
val width: Int
val height: Int
var rot = mRotation % 360
if (rot < 0) {
rot += 360
}
if (rot == 0 || rot == 180) { // Rotation is right-angled only
width = mCropRect.width()
height = mCropRect.height()
} else {
width = mCropRect.height()
height = mCropRect.width()
}
if (mBase64) {
ByteArrayOutputStream().use { base64Stream ->
try {
FileInputStream(source.path!!).use { input ->
// `CropImage` nullifies the `result.getBitmap()` after it writes out to a file, so
// we have to read back.
IOUtils.copy(input, base64Stream)
exporterListener.onResult(base64Stream, width, height)
}
} catch (e: NullPointerException) {
exporterListener.onFailure(e)
} catch (e: IOException) {
exporterListener.onFailure(e)
}
}
return
}
exporterListener.onResult(null, width, height)
}
}
| bsd-3-clause | 13287624767363fca41cd974580a7dd4 | 28.545455 | 95 | 0.651077 | 4.032258 | false | false | false | false |
livefront/bridge | bridgesample/src/main/java/com/livefront/bridgesample/scenario/fragment/NonBridgeLargeDataFragment.kt | 1 | 3260 | package com.livefront.bridgesample.scenario.fragment
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.evernote.android.state.State
import com.livefront.bridgesample.R
import com.livefront.bridgesample.base.NonBridgeBaseFragment
import com.livefront.bridgesample.scenario.activity.FragmentData
import com.livefront.bridgesample.util.FragmentNavigationManager
import kotlinx.android.parcel.Parcelize
import kotlinx.android.synthetic.main.activity_large_data.bitmapGeneratorView
class NonBridgeLargeDataFragment : NonBridgeBaseFragment() {
@State
var savedBitmap: Bitmap? = null
private lateinit var fragmentNavigationManager: FragmentNavigationManager
override fun onAttach(context: Context) {
super.onAttach(context)
fragmentNavigationManager = context as FragmentNavigationManager
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_large_data, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bitmapGeneratorView.apply {
setHeaderText(R.string.non_bridge_large_data_header)
generatedBitmap = savedBitmap
onBitmapGeneratedListener = { savedBitmap = it }
if (getArguments(this@NonBridgeLargeDataFragment).infiniteBackstack) {
onNavigateButtonClickListener = {
fragmentNavigationManager.navigateTo(
newInstance(
NonBridgeLargeDataArguments(infiniteBackstack = true)
),
addToBackstack = true
)
}
}
}
}
companion object {
private const val ARGUMENTS_KEY = "arguments"
fun getArguments(
fragment: NonBridgeLargeDataFragment
): NonBridgeLargeDataArguments = fragment
.requireArguments()
.getParcelable(ARGUMENTS_KEY)!!
fun getFragmentData(
nonBridgeLargeDataArguments: NonBridgeLargeDataArguments = NonBridgeLargeDataArguments()
) = FragmentData(
R.string.non_bridge_large_data_screen_title,
NonBridgeLargeDataFragment::class.java,
getInitialArguments(nonBridgeLargeDataArguments)
)
fun getInitialArguments(
nonBridgeLargeDataArguments: NonBridgeLargeDataArguments = NonBridgeLargeDataArguments()
) = Bundle().apply {
putParcelable(ARGUMENTS_KEY, nonBridgeLargeDataArguments)
}
fun newInstance(
nonBridgeLargeDataArguments: NonBridgeLargeDataArguments = NonBridgeLargeDataArguments()
) = NonBridgeLargeDataFragment().apply {
arguments = getInitialArguments(nonBridgeLargeDataArguments)
}
}
}
@Parcelize
data class NonBridgeLargeDataArguments(
val infiniteBackstack: Boolean = false
) : Parcelable
| apache-2.0 | 36ade806b22dfb586bdb75349dab6201 | 36.471264 | 100 | 0.68681 | 5.258065 | false | false | false | false |
abigpotostew/easypolitics | ui/src/main/kotlin/bz/stew/bracken/ui/pages/browse/view/BrowseBillsView.kt | 1 | 7913 | package bz.stew.bracken.ui.pages.browse.view
import bz.stew.bracken.ui.pages.browse.controller.BillFilters
import bz.stew.bracken.ui.extension.html.elementFixedOffset
import bz.stew.bracken.ui.extension.html.removeAllChildrenNodes
import bz.stew.bracken.ui.extension.jquery.actual
import bz.stew.bracken.ui.extension.jquery.ext.JQuery
import bz.stew.bracken.ui.extension.jquery.ext.jQuery
import bz.stew.bracken.ui.common.bill.BillData
import bz.stew.bracken.ui.common.view.BillViewItem
import bz.stew.bracken.ui.util.animation.Animation
import bz.stew.bracken.ui.util.log.Log
import bz.stew.bracken.ui.common.view.Form
import bz.stew.bracken.ui.common.view.Identifier
import bz.stew.bracken.ui.common.view.Templates
import bz.stew.bracken.view.HtmlSelector
import bz.stew.bracken.view.View
import bz.stewart.bracken.shared.data.FixedStatus
import bz.stewart.bracken.shared.data.MajorStatus
import org.w3c.dom.HTMLElement
import org.w3c.dom.events.Event
import kotlin.browser.document
/**
* Created by stew on 1/25/17.
*/
class BrowseBillsView(private val templater: Templates) : View() {
private val countBillsTextHtmlSelector = HtmlSelector(Identifier.ID, "nav-bar-billCount")
private val openSpeed: Int = 250
private val hideSpeed: Int = 200
private var activeCell: HTMLElement? = null
private val billViews = mutableMapOf<String, BillViewItem>()
private var visibleBills = mutableSetOf<BillViewItem>()
fun appendModelData(bills: List<BillData>) {
for (b: BillData in bills) {
val existing = billViews.get(b.billId)
if (existing == null) {
billViews.put(b.billId, BillViewItem(b))
}
}
}
/**
* Each call replaces the html values in the filter with those passed in. Repeatable.
* TODO define these filters in another place
*/
fun loadStatusFilter(filterEntry: BillFilters,
allStatus: Set<FixedStatus>) {
val parent = getElementBySelector(filterEntry.htmlSelector())
parent.removeAllChildrenNodes()
parent.appendChild(Form.Option.generateHtml("All", mapOf(Pair("value", FixedStatus.NONE.ordinal.toString()))))
//TODO sort these
for (fs: FixedStatus in allStatus) {
val eco = mapOf(Pair("value", fs.ordinal.toString()))
//TODO make this display the nicer string
parent.appendChild(Form.Option.generateHtml(fs.name, eco))
}
}
fun loadMajorStatusFilter(filterEntry: BillFilters,
allMajorStatus: Set<MajorStatus>) {
val parent = getElementBySelector(filterEntry.htmlSelector())
parent.removeAllChildrenNodes()
parent.appendChild(Form.Option.generateHtml("All", mapOf(Pair("value", MajorStatus.NONE.ordinal.toString()))))
//TODO sort these
for (fs: MajorStatus in allMajorStatus) {
val eco = mapOf(Pair("value", fs.ordinal.toString()))
parent.appendChild(Form.Option.generateHtml(fs.niceFormat(), eco))
}
}
private fun updateBillCountText(billCount: Int) {
jQuery(countBillsTextHtmlSelector.text()).get(0).innerHTML = "Showing $billCount bills"
}
fun showSelectedBills(bills: Collection<BillData>) {
this.visibleBills.clear()
bills
.map { this.billViews[it.billId] }
.forEach { it?.let { this.visibleBills.add(it) } }
Log.debug { "Showing #${bills.size} bills" }
updateBillCountText(bills.size)
val remainingBills = this.billViews.toMutableMap()
for (bv: BillViewItem in this.visibleBills) {
getJq(bv.selector()).addClass("billVisible").removeClass("billHidden")
remainingBills.remove(bv.billData.billId)
}
remainingBills.forEach {
getJq(it.value.selector()).addClass("billHidden").removeClass("billVisible")
}
//TODO need to also animate the width and height.
jQuery(".billHidden")
.hide("slow")
jQuery(".billVisible")
.show("slow")
}
//Only call this once. generates
fun generateAndDisplayAllBills(parent:HTMLElement, resetVisible: Boolean = true) {
val sortedList = this.billViews.values.sorted()
if (resetVisible) {
this.visibleBills.clear()
}
Log.debug { "Showing #${sortedList.size} bills" }
updateBillCountText(sortedList.size)
sortedList
.filterNot { this.visibleBills.contains(it) }
.forEach {
try {
this.generateFromTemplate(it, parent)
this.initiateBill(it)
this.visibleBills.add(it)
} catch (e: Throwable) {
console.log(e.message)
console.log(e.cause)
console.log(e)
}
}
}
private fun makeAnimation(position: Int,
units: String,
backwards: Boolean = false): Animation {
val ani: Animation = object : Animation() {
override fun onUpdate(progress: Double) {
element!!.style.marginBottom = (progress * position).toString() + units
}
}
ani.setDuration(openSpeed)
ani.setPlayBackwards(backwards)
return ani
}
private fun makeHtmlCellActive(bill: HTMLElement) {
val active = this.activeCell
val additionalExpandHeight = 30
if (active != null) {
//close prior one
val child = jQuery(active).children(".billExpanded")
val openHeight =
jQuery(child).actual("height").toInt() + additionalExpandHeight
val aniOpen: Animation = makeAnimation(openHeight,
"px",
true
)
aniOpen.run(openSpeed,
active)
child.hide(hideSpeed)
if (this.activeCell == bill) {
this.activeCell = null
return
}
}
this.activeCell = bill
val child: JQuery = jQuery(bill).children(".billExpanded")
//TODO made this centered, and the width of the number of bills across the screen
child.css("transform",
"translateX(-" + expandedBillXOffset(bill) + "px)")
val openHeight = child.actual("height").toInt() + additionalExpandHeight /// MUST be before .show
val aniOpen: Animation = makeAnimation(openHeight, "px")
aniOpen.run(openSpeed,
bill)
child.show(openSpeed)
}
private fun expandedBillXOffset(bill:HTMLElement):Double{
return document.elementFixedOffset(bill).x?.minus(20) ?: 20.0
}
private fun makeCellActive(billSelector: HtmlSelector) {
val jqd = jQuery(billSelector.text())
makeHtmlCellActive(jqd.get(0))
}
private fun generateFromTemplate(billView: BillViewItem,
parent: HTMLElement): HTMLElement {
val billNode = templater.renderBill(billView).getHtml()
parent.appendChild(billNode)
return billNode
}
/**
* Starts events and fades in bill
* assumes a fixed HTML structure
*/
private fun initiateBill(bill: BillViewItem) {
val billSelector = bill.selector()
val billJq = jQuery(billSelector.text())
val view = this
// Make active on click
val clickHeader = billJq.children(".billGridContent")
clickHeader.get(0).onclick = fun(e: Event) {
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
view.makeCellActive(billSelector)
}
//finally, make it display something
billJq.fadeIn("slow")
}
}
| apache-2.0 | 9e9c387a299d751c131287e31aca34ec | 35.465438 | 118 | 0.617591 | 4.265768 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/edit/EANHelper.kt | 1 | 841 | package org.ligi.passandroid.ui.edit
import com.google.zxing.oned.EAN13Writer
import com.google.zxing.oned.EAN8Writer
import com.google.zxing.oned.UPCEANWriter
fun getRandomEAN13(): String {
val randomString = (0..11).map { (Math.random() * 9).toInt() }.joinToString(separator = "")
return (0..9).map { randomString + it }.first(::isValidEAN13)
}
fun isValidEAN13(payload: String) = isValidEAN(payload, EAN13Writer())
fun getRandomEAN8(): String {
val randomString = (0..6).map { (Math.random() * 9).toInt() }.joinToString(separator = "")
return (0..9).map { randomString + it }.first(::isValidEAN8)
}
fun isValidEAN8(payload: String) = isValidEAN(payload, EAN8Writer())
fun isValidEAN(payload: String, writer: UPCEANWriter) = try {
writer.encode(payload)
true
} catch(e: IllegalArgumentException) {
false
} | gpl-3.0 | d9ea9d8dcadecfbf5487f3db41a3b3a3 | 31.384615 | 95 | 0.706302 | 3.209924 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/input/WhichButton.kt | 1 | 823 | /*
* Copyright 2019 Poly Forest, 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.acornui.input
object WhichButton {
const val UNKNOWN: Short = -1
const val LEFT: Short = 0
const val MIDDLE: Short = 1
const val RIGHT: Short = 2
const val BACK: Short = 3
const val FORWARD: Short = 4
} | apache-2.0 | 1451d56f6975fc739a79550c2bc3ae5a | 29.518519 | 75 | 0.72661 | 3.86385 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/qrcodeauth/compose/components/SecondaryButton.kt | 1 | 1159 | package org.wordpress.android.ui.qrcodeauth.compose.components
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.wordpress.android.ui.compose.unit.Margin
@Composable
fun SecondaryButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true
) {
Button(
onClick = onClick,
enabled = enabled,
elevation = ButtonDefaults.elevation(0.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.background,
disabledBackgroundColor = MaterialTheme.colors.background,
),
modifier = modifier.padding(
vertical = Margin.Small.value,
horizontal = Margin.ExtraExtraMediumLarge.value,
)
) {
Text(text = text)
}
}
| gpl-2.0 | 82126e0d713789e40fd16824040ad7fa | 32.114286 | 78 | 0.675582 | 4.75 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/feedforward/highway/HighwayLayerStructureUtils.kt | 1 | 2256 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.feedforward.highway
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.feedforward.highway.HighwayLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.feedforward.highway.HighwayLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
*
*/
internal object HighwayLayerStructureUtils {
/**
*
*/
fun buildLayer(): HighwayLayer<DenseNDArray> = HighwayLayer(
inputArray = AugmentedArray(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.9, -0.9, 1.0))),
inputType = LayerType.Input.Dense,
outputArray = AugmentedArray.zeros(4),
params = buildParams(),
activationFunction = Tanh,
dropout = 0.0
)
/**
*
*/
fun buildParams() = HighwayLayerParameters(inputSize = 4).apply {
input.weights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.6, -0.8, -0.6),
doubleArrayOf(0.7, -0.4, 0.1, -0.8),
doubleArrayOf(0.7, -0.7, 0.3, 0.5),
doubleArrayOf(0.8, -0.9, 0.0, -0.1)
)))
transformGate.weights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.4, -1.0, 0.4),
doubleArrayOf(0.7, -0.2, 0.1, 0.0),
doubleArrayOf(0.7, 0.8, -0.5, -0.3),
doubleArrayOf(-0.9, 0.9, -0.3, -0.3)
)))
input.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.0, -0.3, 0.8)))
transformGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.9, 0.2, -0.9, 0.2)))
}
/**
*
*/
fun getOutputErrors() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.57, 0.75, -0.15, 1.64))
}
| mpl-2.0 | 42b9513e04c87c7b91ee233ca30332ab | 34.25 | 109 | 0.676418 | 3.586645 | false | false | false | false |
mdaniel/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleDefaultVcsRootPolicy.kt | 1 | 1958 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
open class ModuleDefaultVcsRootPolicy(project: Project) : DefaultVcsRootPolicy(project) {
init {
val busConnection = project.messageBus.connect()
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(busConnection, MyModulesListener())
}
override fun getDefaultVcsRoots(): Collection<VirtualFile> {
val result = mutableSetOf<VirtualFile>()
val baseDir = myProject.baseDir
if (baseDir != null) {
result.add(baseDir)
val directoryStorePath = myProject.stateStore.directoryStorePath
if (directoryStorePath != null) {
val ideaDir = LocalFileSystem.getInstance().findFileByNioFile(directoryStorePath)
if (ideaDir != null) {
result.add(ideaDir)
}
}
}
// assertion for read access inside
val modules = runReadAction { ModuleManager.getInstance(myProject).modules }
for (module in modules) {
val moduleRootManager = ModuleRootManager.getInstance(module)
val files = moduleRootManager.contentRoots
for (file in files) {
if (file.isDirectory) {
result.add(file)
}
}
}
return result
}
private inner class MyModulesListener : ContentRootChangeListener(skipFileChanges = true) {
override fun contentRootsChanged(removed: List<VirtualFile>, added: List<VirtualFile>) {
scheduleMappedRootsUpdate()
}
}
} | apache-2.0 | 6bc2d5c1254ad30d6dfa12cc8da164a4 | 35.277778 | 140 | 0.73953 | 4.76399 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToForEachFunctionCallIntention.kt | 1 | 3650 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contentRange
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
class ConvertToForEachFunctionCallIntention : SelfTargetingIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("replace.with.a.foreach.function.call")
) {
override fun isApplicableTo(element: KtForExpression, caretOffset: Int): Boolean {
val rParen = element.rightParenthesis ?: return false
if (caretOffset > rParen.endOffset) return false // available only on the loop header, not in the body
return element.loopRange != null && element.loopParameter != null && element.body != null
}
override fun applyTo(element: KtForExpression, editor: Editor?) {
val commentSaver = CommentSaver(element, saveLineBreaks = true)
val labelName = element.getLabelName()
val body = element.body ?: return
val loopParameter = element.loopParameter ?: return
val loopRange = element.loopRange ?: return
val functionBodyArgument: Any = (body as? KtBlockExpression)?.contentRange() ?: body
val psiFactory = KtPsiFactory(element)
val foreachExpression = psiFactory.createExpressionByPattern(
"$0.forEach{$1->\n$2}", loopRange, loopParameter, functionBodyArgument
)
val result = element.replace(foreachExpression) as KtElement
result.findDescendantOfType<KtFunctionLiteral>()?.getContinuesWithLabel(labelName)?.forEach {
it.replace(psiFactory.createExpression("return@forEach"))
}
commentSaver.restore(result)
}
private fun KtElement.getContinuesWithLabel(labelName: String?): List<KtContinueExpression> {
val continueElements = ArrayList<KtContinueExpression>()
forEachDescendantOfType<KtContinueExpression>({ it.shouldEnterForUnqualified(this) }) {
if (it.getLabelName() == null) {
continueElements += it
}
}
if (labelName != null) {
forEachDescendantOfType<KtContinueExpression>({ it.shouldEnterForQualified(this, labelName) }) {
if (it.getLabelName() == labelName) {
continueElements += it
}
}
}
return continueElements
}
private fun PsiElement.shouldEnterForUnqualified(allow: PsiElement): Boolean {
if (this == allow) return true
if (shouldNeverEnter()) return false
return this !is KtLoopExpression
}
private fun PsiElement.shouldEnterForQualified(allow: PsiElement, labelName: String): Boolean {
if (this == allow) return true
if (shouldNeverEnter()) return false
return this !is KtLoopExpression || getLabelName() != labelName
}
private fun PsiElement.shouldNeverEnter() = this is KtLambdaExpression || this is KtClassOrObject || this is KtFunction
private fun KtLoopExpression.getLabelName() = (parent as? KtExpressionWithLabel)?.getLabelName()
}
| apache-2.0 | c90a5a4ae50f39b9a4a36037f9e9c682 | 41.941176 | 158 | 0.709315 | 5.069444 | false | false | false | false |
eneim/android-UniversalMusicPlayer | media/src/androidTest/java/com/example/android/uamp/media/library/MusicSourceTest.kt | 1 | 5450 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.os.Bundle
import android.provider.MediaStore
import androidx.test.runner.AndroidJUnit4
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.genre
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.title
import junit.framework.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* A small set of Android integration tests for (primarily) [AbstractMusicSource].
*
* The tests all use an extension of [AbstractMusicSource] which is defined at the
* bottom of this file: [TestMusicSource].
*/
@RunWith(AndroidJUnit4::class)
class MusicSourceTest {
private val musicList = listOf<MediaMetadataCompat>(
MediaMetadataCompat.Builder().apply {
id = "ich_hasse_dich"
title = "Ich hasse dich"
album = "Speechless"
artist = "Jemand"
genre = "Folk"
}.build(),
MediaMetadataCompat.Builder().apply {
id = "about_a_guy"
title = "About a Guy"
album = "Tales from the Render Farm"
artist = "7 Developers and a Pastry Chef"
genre = "Rock"
}.build()
)
/** Variables for testing [MusicSource.whenReady] */
var waiting = true
@Test
fun whenReady_waits() {
val testSource = TestMusicSource(musicList)
waiting = true
testSource.whenReady { success ->
Assert.assertEquals(success, true)
waiting = false
}
Assert.assertEquals(waiting, true)
testSource.prepare()
Assert.assertEquals(waiting, false)
}
@Test
fun whenReady_errorContinues() {
val testSource = TestMusicSource(musicList)
waiting = true
testSource.whenReady { success ->
Assert.assertEquals(success, false)
waiting = false
}
Assert.assertEquals(waiting, true)
testSource.error()
Assert.assertEquals(waiting, false)
}
@Test
fun searchByGenre_matches() {
val testSource = TestMusicSource(musicList)
testSource.prepare()
val searchQuery = "Rock"
val searchExtras = Bundle().apply {
putString(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE)
putString(MediaStore.EXTRA_MEDIA_GENRE, searchQuery)
}
val result = testSource.search(searchQuery, searchExtras)
Assert.assertEquals(result.size, 1)
Assert.assertEquals(result[0].id, "about_a_guy")
}
@Test
fun searchByMedia_matches() {
val testSource = TestMusicSource(musicList)
testSource.prepare()
val searchQuery = "About a Guy"
val searchExtras = Bundle().apply {
putString(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Media.ENTRY_CONTENT_TYPE)
putString(MediaStore.EXTRA_MEDIA_TITLE, searchQuery)
putString(MediaStore.EXTRA_MEDIA_ALBUM, "Tales from the Render Farm")
putString(MediaStore.EXTRA_MEDIA_ARTIST, "7 Developers and a Pastry Chef")
}
val result = testSource.search(searchQuery, searchExtras)
Assert.assertEquals(result.size, 1)
Assert.assertEquals(result[0].id, "about_a_guy")
}
@Test
fun searchByMedia_nomatches() {
val testSource = TestMusicSource(musicList)
testSource.prepare()
val searchQuery = "Kotlin in 31 Days"
val searchExtras = Bundle().apply {
putString(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Media.ENTRY_CONTENT_TYPE)
putString(MediaStore.EXTRA_MEDIA_TITLE, searchQuery)
putString(MediaStore.EXTRA_MEDIA_ALBUM, "Delegated by Lazy")
putString(MediaStore.EXTRA_MEDIA_ARTIST, "Brainiest Jet")
}
val result = testSource.search(searchQuery, searchExtras)
Assert.assertEquals(result.size, 0)
}
@Test
fun searchByKeyword_fallback() {
val testSource = TestMusicSource(musicList)
testSource.prepare()
val searchQuery = "hasse"
val searchExtras = Bundle.EMPTY
val result = testSource.search(searchQuery, searchExtras)
Assert.assertEquals(result.size, 1)
Assert.assertEquals(result[0].id, "ich_hasse_dich")
}
}
class TestMusicSource(private val music: List<MediaMetadataCompat>
) : AbstractMusicSource(), Iterable<MediaMetadataCompat> by music {
fun prepare() {
state = STATE_INITIALIZED
}
fun error() {
state = STATE_ERROR
}
} | apache-2.0 | 3dd5e80b63fcd962fad7502657deaa36 | 32.857143 | 95 | 0.657431 | 4.339172 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ricaricami/RicaricaMiTransaction.kt | 1 | 8640 | /*
* RicaricaMiTransaction.kt
*
* Copyright 2018 Google
*
* 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 au.id.micolous.metrodroid.transit.ricaricami
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Transaction
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
data class RicaricaMiTransaction(override val parsed: En1545Parsed) : En1545Transaction() {
private val transactionType: Int
get() = parsed.getIntOrZero(TRANSACTION_TYPE)
override val transport get() = parsed.getIntOrZero(TRANSPORT_TYPE_B)
override val isTapOff get() = transactionType == TRANSACTION_TAP_OFF
override val isTapOn get() = (transactionType == TRANSACTION_TAP_ON
|| transactionType == TRANSACTION_TAP_ON_TRANSFER)
override val mode get(): Trip.Mode {
if (parsed.getIntOrZero(TRANSPORT_TYPE_A) != 0 && transport != RicaricaMiLookup.TRANSPORT_BUS)
return Trip.Mode.OTHER
when (transport) {
RicaricaMiLookup.TRANSPORT_BUS -> {
if (parsed.getIntOrZero(TRANSPORT_TYPE_A) == 0)
return Trip.Mode.TRAM
if (routeNumber in 90..93)
return Trip.Mode.TROLLEYBUS
return Trip.Mode.BUS
}
RicaricaMiLookup.TRANSPORT_METRO -> return Trip.Mode.METRO
RicaricaMiLookup.TRANSPORT_TRAM -> return Trip.Mode.TRAM
RicaricaMiLookup.TRANSPORT_TRENORD1, RicaricaMiLookup.TRANSPORT_TRENORD2 -> return Trip.Mode.TRAIN
else -> return Trip.Mode.OTHER
}
}
override fun getAgencyName(isShort: Boolean) = FormattedString.language(when (transport) {
RicaricaMiLookup.TRANSPORT_METRO, RicaricaMiLookup.TRANSPORT_TRAM, RicaricaMiLookup.TRANSPORT_BUS -> if (isShort) "ATM" else "Azienda Trasporti Milanesi"
RicaricaMiLookup.TRANSPORT_TRENORD1 -> "Trenord (1)"
RicaricaMiLookup.TRANSPORT_TRENORD2 -> "Trenord (2)"
else -> "$transport"
}, "it-IT")
override val stationId get(): Int? {
val id = super.stationId
if (transport == RicaricaMiLookup.TRANSPORT_BUS && id == 999)
return null
return super.stationId
}
override val lookup get() = RicaricaMiLookup
override fun isSameTrip(other: Transaction) =
((transport == RicaricaMiLookup.TRANSPORT_METRO || transport == RicaricaMiLookup.TRANSPORT_TRENORD1
|| transport == RicaricaMiLookup.TRANSPORT_TRENORD2)
&& other is RicaricaMiTransaction
&& other.transport == transport)
override val timestamp get(): Timestamp? {
val firstDate = parsed.getIntOrZero(En1545FixedInteger.dateName(EVENT_FIRST_STAMP))
val firstTime = parsed.getIntOrZero(En1545FixedInteger.timeLocalName(EVENT_FIRST_STAMP))
val time = parsed.getIntOrZero(En1545FixedInteger.timeLocalName(EVENT))
val date = if (time < firstTime) firstDate + 1 else firstDate
return En1545FixedInteger.parseTimeLocal(date, time, RicaricaMiLookup.TZ)
}
companion object {
private const val TRANSPORT_TYPE_A = "TransportTypeA"
private const val TRANSPORT_TYPE_B = "TransportTypeB"
private const val TRANSACTION_TYPE = "TransactionType"
private const val TRANSACTION_COUNTER = "TransactionCounter"
private const val TRAIN_USED_FLAG = "TrainUsed"
private const val TRAM_USED_FLAG = "TramUsed"
private val TRIP_FIELDS = En1545Container(
En1545FixedInteger.date(EVENT_FIRST_STAMP),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger(EVENT_UNKNOWN_A, 2),
En1545Bitmap( // 186bd128
// 8
En1545FixedInteger("NeverSeen0", 0),
En1545FixedInteger("NeverSeen1", 0),
En1545FixedInteger("NeverSeen2", 0),
En1545FixedInteger(TRANSACTION_TYPE, 3),
// 2
En1545FixedInteger("NeverSeen4", 0),
En1545FixedInteger(EVENT_RESULT, 6), // 0 = ok
// 0xb = outside of urban area
En1545FixedInteger("NeverSeen6", 0),
En1545FixedInteger("NeverSeen7", 0),
// 1
En1545FixedInteger(EVENT_LOCATION_ID, 11),
En1545FixedInteger("NeverSeen9", 0),
En1545FixedInteger("NeverSeen10", 0),
En1545FixedInteger("NeverSeen11", 0),
// d
En1545FixedInteger(EVENT_UNKNOWN_C, 2), // Possibly gate
En1545FixedInteger("NeverSeen13", 0),
En1545FixedInteger(EVENT_ROUTE_NUMBER, 10),
En1545FixedInteger(EVENT_UNKNOWN_D, 12),
// b
En1545FixedInteger(TRANSPORT_TYPE_A, 1),
En1545FixedInteger(EVENT_VEHICLE_ID, 13),
En1545FixedInteger("NeverSeen18", 0),
En1545FixedInteger(TRANSPORT_TYPE_B, 4),
// 6
En1545FixedInteger("NeverSeen20", 0),
// Following split is unclear
En1545FixedInteger(EVENT_UNKNOWN_E + "1", 5),
En1545FixedInteger(EVENT_UNKNOWN_E + "2", 16),
En1545FixedInteger("NeverSeen23", 0),
// 8
En1545FixedInteger("NeverSeen24", 0),
En1545FixedInteger("NeverSeen25", 0),
En1545FixedInteger("NeverSeen26", 0),
En1545FixedInteger(EVENT_CONTRACT_POINTER, 4),
// 1
En1545Bitmap( // afc0 or abc0
En1545FixedInteger("NeverSeenExtra0", 0),
En1545FixedInteger("NeverSeenExtra1", 0),
En1545FixedInteger("NeverSeenExtra2", 0),
En1545FixedInteger("NeverSeenExtra3", 0),
// c
En1545FixedInteger("NeverSeenExtra4", 0),
En1545FixedInteger("NeverSeenExtra5", 0),
En1545FixedInteger.timeLocal(EVENT_FIRST_STAMP),
En1545FixedInteger(EVENT_UNKNOWN_G, 1),
// f or b
En1545FixedInteger(EVENT_FIRST_LOCATION_ID, 11),
En1545FixedInteger(EVENT_UNKNOWN_H + "1", 1),
En1545FixedInteger(EVENT_UNKNOWN_H + "2", 2),
En1545FixedInteger(TRANSACTION_COUNTER, 4),
// a
En1545FixedInteger("NeverSeenExtra12", 0),
En1545Container (
En1545FixedInteger(TRAIN_USED_FLAG, 1),
En1545FixedInteger(TRAM_USED_FLAG, 1)
),
En1545FixedInteger("NeverSeenExtra14", 0),
En1545FixedInteger(EVENT_UNKNOWN_I, 1)
)
)
// Rest: 64 bits of 0
)
private const val TRANSACTION_TAP_ON = 1
private const val TRANSACTION_TAP_ON_TRANSFER = 2
private const val TRANSACTION_TAP_OFF = 3
fun parse(tripData: ImmutableByteArray) = RicaricaMiTransaction(En1545Parser.parse(tripData, TRIP_FIELDS))
}
}
| gpl-3.0 | e83c567bdbd9100af12a3a6a0bc366b7 | 45.702703 | 161 | 0.57037 | 4.590861 | false | false | false | false |
ManojMadanmohan/dlt | app/src/main/java/com/manoj/dlt/Constants.kt | 1 | 1472 | package com.manoj.dlt
import android.content.Context
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
object Constants{
enum class CONFIG {
SANDBOX, PRODUCTION
}
const val DEEP_LINK_HISTORY_KEY = "deep_link_history_key_v1"
const val GLOBAL_PREF_KEY = "one_time_key"
const val APP_TUTORIAL_SEEN = "app_tut_seen"
const val SHORTCUT_HINT_SEEN = "shortcut_hint_seen"
const val USER_ID_KEY = "user_id"
const val GOOGLE_PLAY_URI = "https://play.google.com/store/apps/details?id=com.manoj.dlt"
const val WEB_APP_LINK = "https://sweltering-fire-2158.firebaseapp.com/"
const val PRIVACY_POLICY_URL = "https://manojmadanmohan.github.io/dlt/privacy_policy"
var ENVIRONMENT:CONFIG = BuildConfig.CONFIG
@JvmStatic
fun getFirebaseUserRef() : DatabaseReference
{
return FirebaseDatabase.getInstance()
.getReference(ENVIRONMENT.name.toLowerCase())
.child(DbConstants.USERS);
}
@JvmStatic
fun isFirebaseAvailable(context: Context) : Boolean
{
val playServicesAvl = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
return if (playServicesAvl == ConnectionResult.SUCCESS) {
true
} else {
false
}
}
} | mit | 1f4ea6f46e5c82bbb0095e77f1bab1c5 | 34.071429 | 104 | 0.694973 | 3.967655 | false | true | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 2 | 2886 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic
import com.intellij.CommonBundle
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.RememberCheckBoxState
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import com.intellij.util.text.nullize
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun showJetBrainsAccountDialog(parent: Component, project: Project? = null): DialogWrapper {
val credentials = ErrorReportConfigurable.getCredentials()
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.password?.toString())
val passwordSafe = PasswordSafe.instance
val isSelected = if (credentials?.userName == null) {
// if no user name - never stored and so, defaults
passwordSafe.isRememberPasswordByDefault
}
else {
// if user name set, but no password, so, previously was stored without password
!credentials.password.isNullOrEmpty()
}
credentials?.userName == null || !credentials.password.isNullOrEmpty()
val rememberCheckBox = CheckBox(CommonBundle.message("checkbox.remember.password"), isSelected)
val panel = panel {
noteRow("Login to JetBrains Account to get notified\nwhen the submitted exceptions are fixed.")
row("Username:") { userField(growPolicy = GrowPolicy.SHORT_TEXT) }
row("Password:") { passwordField() }
row {
rememberCheckBox()
right {
link("Forgot password?") {
val userName = userField.text.trim().encodeUrlQueryParameter()
BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=$userName")
}
}
}
noteRow("""Do not have an account? <a href="https://account.jetbrains.com/login?signup">Sign Up</a>""")
}
return dialog(
title = DiagnosticBundle.message("error.report.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null) {
val userName = userField.text.nullize(true)
val password = if (rememberCheckBox.isSelected) passwordField.password else null
RememberCheckBoxState.update(rememberCheckBox)
passwordSafe.set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, password))
return@dialog null
}
} | apache-2.0 | d541213dd980b30385877b60fe67304e | 41.455882 | 140 | 0.757103 | 4.509375 | false | false | false | false |
santaevpavel/ClipboardTranslator | app/src/main/java/ru/santaev/clipboardtranslator/ui/SettingsActivity.kt | 1 | 7048 | package ru.santaev.clipboardtranslator.ui
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import androidx.databinding.DataBindingUtil
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.MenuItem
import android.widget.Toast
import ru.santaev.clipboardtranslator.R
import ru.santaev.clipboardtranslator.databinding.ActivitySettingsBinding
import ru.santaev.clipboardtranslator.ui.settings.ListSettingsItem
import ru.santaev.clipboardtranslator.ui.settings.SettingsItem
import ru.santaev.clipboardtranslator.util.Analytics
import ru.santaev.clipboardtranslator.util.AnalyticsConstants.EVENT_ID_NAME_CLICK_SETTINGS_COPY_BUTTON
import ru.santaev.clipboardtranslator.util.AnalyticsConstants.EVENT_ID_NAME_CLICK_SETTINGS_FEEDBACK
import ru.santaev.clipboardtranslator.util.AnalyticsConstants.EVENT_ID_NAME_CLICK_SETTINGS_NOTIFICATION_CLEAR_DELAY
import ru.santaev.clipboardtranslator.util.AnalyticsConstants.EVENT_ID_NAME_CLICK_SETTINGS_NOTIFICATION_TYPE
import ru.santaev.clipboardtranslator.util.AnalyticsConstants.EVENT_ID_NAME_CLICK_SETTINGS_RATE
import ru.santaev.clipboardtranslator.util.settings.AppPreference
import ru.santaev.clipboardtranslator.util.settings.ISettings
import java.util.*
class SettingsActivity : AppCompatActivity() {
private lateinit var settings: ISettings
private lateinit var binding: ActivitySettingsBinding
private lateinit var settingsItemNotificationType: ListSettingsItem
private lateinit var settingsItemNotificationClearDelay: ListSettingsItem
private lateinit var settingsItemNotificationCopyButton: ListSettingsItem
private lateinit var settingsItemFeedback: SettingsItem
private lateinit var settingsItemRate: SettingsItem
private lateinit var settingsItemBuildVersion: SettingsItem
private lateinit var analytics: Analytics
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
analytics = Analytics(this)
settings = AppPreference.getInstance()
binding = DataBindingUtil.setContentView(this, R.layout.activity_settings)
setSupportActionBar(binding.toolbar)
supportActionBar?.setTitle(R.string.settings_activity_title)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
initSettings()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
private fun initSettings() {
// Notification type
settingsItemNotificationType = ListSettingsItem(
R.string.settings_item_notif_title,
R.array.settings_item_notification_type_value,
this,
R.array.settings_item_notification_type_text,
{ settings.notificationType = it },
{ settings.notificationType }
)
binding.itemNotif?.item = settingsItemNotificationType
binding.itemNotif?.root?.setOnClickListener { v ->
analytics.logClickEvent(EVENT_ID_NAME_CLICK_SETTINGS_NOTIFICATION_TYPE)
settingsItemNotificationType.onClick()
}
// Notification clear delay
settingsItemNotificationClearDelay = ListSettingsItem(
R.string.settings_item_notif_delay_title,
R.array.settings_item_notification_clear_delay_value,
this,
R.array.settings_item_notification_clear_delay_text,
{ settings.notificationClearDelay = it },
{ settings.notificationClearDelay }
)
binding.itemNotifDelayButton?.item = settingsItemNotificationClearDelay
binding.itemNotifDelayButton?.root?.setOnClickListener { v ->
analytics.logClickEvent(EVENT_ID_NAME_CLICK_SETTINGS_NOTIFICATION_CLEAR_DELAY)
settingsItemNotificationClearDelay.onClick()
}
// Copy button
settingsItemNotificationCopyButton = ListSettingsItem(
R.string.settings_item_notif_btn_title,
R.array.settings_item_notification_btn_value,
this,
R.array.settings_item_notification_btn_text,
{ value -> settings.isNotificationButtonEnabled = value != 0 }
) { if (settings.isNotificationButtonEnabled) 1 else 0 }
binding.itemNotifCopyButton?.item = settingsItemNotificationCopyButton
binding.itemNotifCopyButton?.root?.setOnClickListener {
analytics.logClickEvent(EVENT_ID_NAME_CLICK_SETTINGS_COPY_BUTTON)
settingsItemNotificationCopyButton.onClick()
}
// Feedback
settingsItemFeedback = SettingsItem(getString(R.string.settings_item_feedback_title),
getString(R.string.settings_item_feedback_subtitle))
binding.itemFeedback?.item = settingsItemFeedback
binding.itemFeedback?.root?.setOnClickListener {
analytics.logClickEvent(EVENT_ID_NAME_CLICK_SETTINGS_FEEDBACK)
email()
}
// Rate
settingsItemRate = SettingsItem(getString(R.string.settings_item_rate_title),
getString(R.string.settings_item_rate_subtitle))
binding.itemRate?.item = settingsItemRate
binding.itemRate?.root?.setOnClickListener { v ->
analytics.logClickEvent(EVENT_ID_NAME_CLICK_SETTINGS_RATE)
launchGooglePLay()
}
// App version
settingsItemBuildVersion = SettingsItem(getString(R.string.settings_item_build_title),
getBuildVersion())
binding.itemBuildVersion?.item = settingsItemBuildVersion
}
private fun launchGooglePLay() {
val uri = Uri.parse("market://details?id=" + packageName)
val myAppLinkToMarket = Intent(Intent.ACTION_VIEW, uri)
try {
startActivity(myAppLinkToMarket)
} catch (e: ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageName)))
}
}
private fun email() {
val mailTo = "mailto:[email protected]"
val emailIntent = Intent(Intent.ACTION_SENDTO)
emailIntent.data = Uri.parse(mailTo)
try {
startActivity(emailIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "Unable to find mail app!", Toast.LENGTH_LONG).show()
}
}
private fun getBuildVersion(): String {
try {
val pInfo = packageManager.getPackageInfo(packageName, 0)
val versionName = pInfo.versionName
return String.format(Locale.ENGLISH, "%s (%d)", versionName, pInfo.versionCode)
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return "-"
}
}
| apache-2.0 | 6ab78265f005620fb24b40614a0bc232 | 40.704142 | 127 | 0.700908 | 4.877509 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadController.kt | 2 | 13564 | package eu.kanade.tachiyomi.ui.download
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.databinding.DownloadControllerBinding
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.base.controller.FabController
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.util.view.shrinkOnScroll
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit
/**
* Controller that shows the currently active downloads.
* Uses R.layout.fragment_download_queue.
*/
class DownloadController :
NucleusController<DownloadControllerBinding, DownloadPresenter>(),
FabController,
DownloadAdapter.DownloadItemListener {
/**
* Adapter containing the active downloads.
*/
private var adapter: DownloadAdapter? = null
private var actionFab: ExtendedFloatingActionButton? = null
private var actionFabScrollListener: RecyclerView.OnScrollListener? = null
/**
* Map of subscriptions for active downloads.
*/
private val progressSubscriptions by lazy { mutableMapOf<Download, Subscription>() }
/**
* Whether the download queue is running or not.
*/
private var isRunning: Boolean = false
init {
setHasOptionsMenu(true)
}
override fun createBinding(inflater: LayoutInflater) = DownloadControllerBinding.inflate(inflater)
override fun createPresenter(): DownloadPresenter {
return DownloadPresenter()
}
override fun getTitle(): String? {
return resources?.getString(R.string.label_download_queue)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
// Check if download queue is empty and update information accordingly.
setInformationView()
// Initialize adapter.
adapter = DownloadAdapter(this@DownloadController)
binding.recycler.adapter = adapter
adapter?.isHandleDragEnabled = true
adapter?.fastScroller = binding.fastScroller
// Set the layout manager for the recycler and fixed size.
binding.recycler.layoutManager = LinearLayoutManager(view.context)
binding.recycler.setHasFixedSize(true)
actionFabScrollListener = actionFab?.shrinkOnScroll(binding.recycler)
// Subscribe to changes
DownloadService.runningRelay
.observeOn(AndroidSchedulers.mainThread())
.subscribeUntilDestroy { onQueueStatusChange(it) }
presenter.getDownloadStatusObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribeUntilDestroy { onStatusChange(it) }
presenter.getDownloadProgressObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribeUntilDestroy { onUpdateDownloadedPages(it) }
presenter.downloadQueue.getUpdatedObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribeUntilDestroy {
updateTitle(it.size)
}
}
override fun configureFab(fab: ExtendedFloatingActionButton) {
actionFab = fab
fab.setOnClickListener {
val context = applicationContext ?: return@setOnClickListener
if (isRunning) {
DownloadService.stop(context)
presenter.pauseDownloads()
} else {
DownloadService.start(context)
}
setInformationView()
}
}
override fun cleanupFab(fab: ExtendedFloatingActionButton) {
fab.setOnClickListener(null)
actionFabScrollListener?.let { binding.recycler.removeOnScrollListener(it) }
actionFab = null
}
override fun onDestroyView(view: View) {
for (subscription in progressSubscriptions.values) {
subscription.unsubscribe()
}
progressSubscriptions.clear()
adapter = null
super.onDestroyView(view)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.download_queue, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.clear_queue).isVisible = !presenter.downloadQueue.isEmpty()
menu.findItem(R.id.reorder).isVisible = !presenter.downloadQueue.isEmpty()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val context = applicationContext ?: return false
when (item.itemId) {
R.id.clear_queue -> {
DownloadService.stop(context)
presenter.clearQueue()
}
R.id.newest, R.id.oldest -> {
reorderQueue({ it.download.chapter.date_upload }, item.itemId == R.id.newest)
}
R.id.asc, R.id.desc -> {
reorderQueue({ it.download.chapter.chapter_number }, item.itemId == R.id.desc)
}
}
return super.onOptionsItemSelected(item)
}
private fun <R : Comparable<R>> reorderQueue(selector: (DownloadItem) -> R, reverse: Boolean = false) {
val adapter = adapter ?: return
val newDownloads = mutableListOf<Download>()
adapter.headerItems.forEach { headerItem ->
headerItem as DownloadHeaderItem
headerItem.subItems = headerItem.subItems.sortedBy(selector).toMutableList().apply {
if (reverse) {
reverse()
}
}
newDownloads.addAll(headerItem.subItems.map { it.download })
}
presenter.reorder(newDownloads)
}
/**
* Called when the status of a download changes.
*
* @param download the download whose status has changed.
*/
private fun onStatusChange(download: Download) {
when (download.status) {
Download.State.DOWNLOADING -> {
observeProgress(download)
// Initial update of the downloaded pages
onUpdateDownloadedPages(download)
}
Download.State.DOWNLOADED -> {
unsubscribeProgress(download)
onUpdateProgress(download)
onUpdateDownloadedPages(download)
}
Download.State.ERROR -> unsubscribeProgress(download)
else -> { /* unused */ }
}
}
/**
* Observe the progress of a download and notify the view.
*
* @param download the download to observe its progress.
*/
private fun observeProgress(download: Download) {
val subscription = Observable.interval(50, TimeUnit.MILLISECONDS)
// Get the sum of percentages for all the pages.
.flatMap {
Observable.from(download.pages)
.map(Page::progress)
.reduce { x, y -> x + y }
}
// Keep only the latest emission to avoid backpressure.
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { progress ->
// Update the view only if the progress has changed.
if (download.totalProgress != progress) {
download.totalProgress = progress
onUpdateProgress(download)
}
}
// Avoid leaking subscriptions
progressSubscriptions.remove(download)?.unsubscribe()
progressSubscriptions[download] = subscription
}
/**
* Unsubscribes the given download from the progress subscriptions.
*
* @param download the download to unsubscribe.
*/
private fun unsubscribeProgress(download: Download) {
progressSubscriptions.remove(download)?.unsubscribe()
}
/**
* Called when the queue's status has changed. Updates the visibility of the buttons.
*
* @param running whether the queue is now running or not.
*/
private fun onQueueStatusChange(running: Boolean) {
isRunning = running
activity?.invalidateOptionsMenu()
// Check if download queue is empty and update information accordingly.
setInformationView()
}
/**
* Called from the presenter to assign the downloads for the adapter.
*
* @param downloads the downloads from the queue.
*/
fun onNextDownloads(downloads: List<DownloadHeaderItem>) {
activity?.invalidateOptionsMenu()
setInformationView()
adapter?.updateDataSet(downloads)
}
/**
* Called when the progress of a download changes.
*
* @param download the download whose progress has changed.
*/
private fun onUpdateProgress(download: Download) {
getHolder(download)?.notifyProgress()
}
/**
* Called when a page of a download is downloaded.
*
* @param download the download whose page has been downloaded.
*/
private fun onUpdateDownloadedPages(download: Download) {
getHolder(download)?.notifyDownloadedPages()
}
/**
* Returns the holder for the given download.
*
* @param download the download to find.
* @return the holder of the download or null if it's not bound.
*/
private fun getHolder(download: Download): DownloadHolder? {
return binding.recycler.findViewHolderForItemId(download.chapter.id!!) as? DownloadHolder
}
/**
* Set information view when queue is empty
*/
private fun setInformationView() {
if (presenter.downloadQueue.isEmpty()) {
binding.emptyView.show(R.string.information_no_downloads)
actionFab?.isVisible = false
updateTitle()
} else {
binding.emptyView.hide()
actionFab?.apply {
isVisible = true
setText(
if (isRunning) {
R.string.action_pause
} else {
R.string.action_resume
}
)
setIconResource(
if (isRunning) {
R.drawable.ic_pause_24dp
} else {
R.drawable.ic_play_arrow_24dp
}
)
}
}
}
/**
* Called when an item is released from a drag.
*
* @param position The position of the released item.
*/
override fun onItemReleased(position: Int) {
val adapter = adapter ?: return
val downloads = adapter.headerItems.flatMap { header ->
adapter.getSectionItems(header).map { item ->
(item as DownloadItem).download
}
}
presenter.reorder(downloads)
}
/**
* Called when the menu item of a download is pressed
*
* @param position The position of the item
* @param menuItem The menu Item pressed
*/
override fun onMenuItemClick(position: Int, menuItem: MenuItem) {
val item = adapter?.getItem(position) ?: return
if (item is DownloadItem) {
when (menuItem.itemId) {
R.id.move_to_top, R.id.move_to_bottom -> {
val headerItems = adapter?.headerItems ?: return
val newDownloads = mutableListOf<Download>()
headerItems.forEach { headerItem ->
headerItem as DownloadHeaderItem
if (headerItem == item.header) {
headerItem.removeSubItem(item)
if (menuItem.itemId == R.id.move_to_top) {
headerItem.addSubItem(0, item)
} else {
headerItem.addSubItem(item)
}
}
newDownloads.addAll(headerItem.subItems.map { it.download })
}
presenter.reorder(newDownloads)
}
R.id.cancel_download -> {
presenter.cancelDownload(item.download)
}
R.id.cancel_series -> {
val allDownloadsForSeries = adapter?.currentItems
?.filterIsInstance<DownloadItem>()
?.filter { item.download.manga.id == it.download.manga.id }
?.map(DownloadItem::download)
if (!allDownloadsForSeries.isNullOrEmpty()) {
presenter.cancelDownloads(allDownloadsForSeries)
}
}
}
}
}
private fun updateTitle(queueSize: Int = 0) {
val defaultTitle = getTitle()
if (queueSize == 0) {
setTitle(defaultTitle)
} else {
setTitle("$defaultTitle ($queueSize)")
}
}
}
| apache-2.0 | 153cabdfc62f19c652ea5354c94aa1cb | 33.426396 | 107 | 0.601887 | 5.335956 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.