repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
youdonghai/intellij-community
|
platform/projectModel-impl/src/com/intellij/openapi/options/scheme.kt
|
1
|
3278
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.options
import com.intellij.configurationStore.StreamProvider
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import org.jdom.Parent
@Deprecated("Please use SchemeManager")
abstract class SchemesManager<T : Scheme> : SchemeManager<T>()
interface ExternalizableScheme : Scheme {
fun setName(value: String)
}
abstract class SchemeManagerFactory {
companion object {
@JvmStatic
fun getInstance() = ServiceManager.getService(SchemeManagerFactory::class.java)!!
@JvmStatic
fun getInstance(project: Project) = ServiceManager.getService(project, SchemeManagerFactory::class.java)!!
}
/**
* directoryName — like "keymaps".
*/
@JvmOverloads
fun <SCHEME : Scheme, MUTABLE_SCHEME : SCHEME> create(directoryName: String, processor: SchemeProcessor<SCHEME, MUTABLE_SCHEME>, presentableName: String? = null): SchemeManager<SCHEME> {
return create(directoryName, processor, presentableName, RoamingType.DEFAULT)
}
abstract fun <SCHEME : Scheme, MUTABLE_SCHEME : SCHEME> create(directoryName: String,
processor: SchemeProcessor<SCHEME, MUTABLE_SCHEME>,
presentableName: String? = null,
roamingType: RoamingType = RoamingType.DEFAULT,
isUseOldFileNameSanitize: Boolean = false,
streamProvider: StreamProvider? = null): SchemeManager<SCHEME>
}
enum class SchemeState {
UNCHANGED, NON_PERSISTENT, POSSIBLY_CHANGED
}
abstract class SchemeProcessor<SCHEME : Scheme, in MUTABLE_SCHEME: SCHEME> {
open fun isExternalizable(scheme: SCHEME) = scheme is ExternalizableScheme
/**
* Element will not be modified, it is safe to return non-cloned instance.
*/
abstract fun writeScheme(scheme: MUTABLE_SCHEME): Parent
open fun initScheme(scheme: MUTABLE_SCHEME) {
}
open fun onSchemeAdded(scheme: MUTABLE_SCHEME) {
}
open fun onSchemeDeleted(scheme: MUTABLE_SCHEME) {
}
open fun onCurrentSchemeSwitched(oldScheme: SCHEME?, newScheme: SCHEME?) {
}
/**
* If scheme implements [com.intellij.configurationStore.SerializableScheme], this method will be called only if [com.intellij.configurationStore.SerializableScheme.getSchemeState] returns `null`
*/
@Suppress("KDocUnresolvedReference")
open fun getState(scheme: SCHEME) = SchemeState.POSSIBLY_CHANGED
}
|
apache-2.0
|
682681fa7cdc14474e94d0774c6fd96f
| 37.552941 | 197 | 0.688034 | 5.009174 | false | false | false | false |
ttomsu/orca
|
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt
|
1
|
16272
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.BasicTag
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.orca.TaskExecutionInterceptor
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.OverridableTimeoutRetryableTask
import com.netflix.spinnaker.orca.api.pipeline.RetryableTask
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.TaskResult
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.exceptions.TimeoutException
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.ext.isManuallySkipped
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.InvalidTaskType
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper
import com.netflix.spinnaker.orca.time.toDuration
import com.netflix.spinnaker.orca.time.toInstant
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.concurrent.TimeUnit
import kotlin.collections.set
import org.apache.commons.lang3.time.DurationFormatUtils
import org.slf4j.MDC
import org.springframework.stereotype.Component
@Component
class RunTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val stageNavigator: StageNavigator,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory,
override val contextParameterProcessor: ContextParameterProcessor,
private val taskResolver: TaskResolver,
private val clock: Clock,
private val exceptionHandlers: List<ExceptionHandler>,
private val taskExecutionInterceptors: List<TaskExecutionInterceptor>,
private val registry: Registry,
private val dynamicConfigService: DynamicConfigService
) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware {
override fun handle(message: RunTask) {
message.withTask { origStage, taskModel, task ->
var stage = origStage
val thisInvocationStartTimeMs = clock.millis()
val execution = stage.execution
var taskResult: TaskResult? = null
try {
taskExecutionInterceptors.forEach { t -> stage = t.beforeTaskExecution(task, stage) }
if (execution.isCanceled) {
task.onCancel(stage)
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status.isComplete) {
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status == PAUSED) {
queue.push(PauseTask(message))
} else if (stage.isManuallySkipped()) {
queue.push(CompleteTask(message, SKIPPED))
} else {
try {
task.checkForTimeout(stage, taskModel, message)
} catch (e: TimeoutException) {
registry
.timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name)
.increment()
taskResult = task.onTimeout(stage)
if (taskResult == null) {
// This means this task doesn't care to alter the timeout flow, just throw
throw e
}
if (!setOf(TERMINAL, FAILED_CONTINUE).contains(taskResult.status)) {
log.error("Task ${task.javaClass.name} returned invalid status (${taskResult.status}) for onTimeout")
throw e
}
}
stage.withAuth {
stage.withLoggingContext(taskModel) {
if (taskResult == null) {
taskResult = task.execute(stage.withMergedContext())
taskExecutionInterceptors.forEach { t -> taskResult = t.afterTaskExecution(task, stage, taskResult) }
}
taskResult!!.let { result: TaskResult ->
// TODO: rather send this data with CompleteTask message
stage.processTaskOutput(result)
when (result.status) {
RUNNING -> {
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
SUCCEEDED, REDIRECT, SKIPPED, FAILED_CONTINUE, STOPPED -> {
queue.push(CompleteTask(message, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
CANCELED -> {
task.onCancel(stage)
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
TERMINAL -> {
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
else ->
TODO("Unhandled task status ${result.status}")
}
}
}
}
}
} catch (e: Exception) {
val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name)
if (exceptionDetails?.shouldRetry == true) {
log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]")
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING)
} else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) {
queue.push(CompleteTask(message, SUCCEEDED))
} else {
log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e)
val status = stage.failureStatus(default = TERMINAL)
stage.context["exception"] = exceptionDetails
repository.storeStage(stage)
queue.push(CompleteTask(message, status, TERMINAL))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
}
}
}
private fun trackResult(stage: StageExecution, thisInvocationStartTimeMs: Long, taskModel: TaskExecution, status: ExecutionStatus) {
val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status)
val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status)
val elapsedMillis = clock.millis() - thisInvocationStartTimeMs
hashMapOf(
"task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application),
"task.invocations.duration.withType" to commonTags + detailedTags
).forEach {
name, tags ->
registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS)
}
}
override val messageType = RunTask::class.java
private fun RunTask.withTask(block: (StageExecution, TaskExecution, Task) -> Unit) =
withTask { stage, taskModel ->
try {
taskResolver.getTask(taskModel.implementingClass)
} catch (e: TaskResolver.NoSuchTaskException) {
try {
taskResolver.getTask(taskType)
} catch (e: TaskResolver.NoSuchTaskException) {
queue.push(InvalidTaskType(this, taskType.name))
null
}
}?.let {
block.invoke(stage, taskModel, it)
}
}
private fun Task.backoffPeriod(taskModel: TaskExecution, stage: StageExecution): TemporalAmount =
when (this) {
is RetryableTask -> Duration.ofMillis(
retryableBackOffPeriod(taskModel, stage).coerceAtMost(taskExecutionInterceptors.maxBackoff())
)
else -> Duration.ofMillis(1000)
}
/**
* The max back off value always wins. For example, given the following dynamic configs:
* `tasks.global.backOffPeriod = 5000`
* `tasks.aws.backOffPeriod = 80000`
* `tasks.aws.someAccount.backoffPeriod = 60000`
* `tasks.aws.backoffPeriod` will be used (given the criteria matches and unless the default dynamicBackOffPeriod is greater).
*/
private fun RetryableTask.retryableBackOffPeriod(
taskModel: TaskExecution,
stage: StageExecution
): Long {
val dynamicBackOffPeriod = getDynamicBackoffPeriod(
stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime ?: 0))
)
val backOffs: MutableList<Long> = mutableListOf(
dynamicBackOffPeriod,
dynamicConfigService.getConfig(
Long::class.java,
"tasks.global.backOffPeriod",
dynamicBackOffPeriod)
)
if (this is CloudProviderAware && hasCloudProvider(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
if (hasCredentials(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.${getCredentials(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
}
}
return backOffs.max() ?: dynamicBackOffPeriod
}
private fun List<TaskExecutionInterceptor>.maxBackoff(): Long =
this.fold(Long.MAX_VALUE) { backoff, interceptor ->
backoff.coerceAtMost(interceptor.maxTaskBackoff())
}
private fun formatTimeout(timeout: Long): String {
return DurationFormatUtils.formatDurationWords(timeout, true, true)
}
private fun Task.checkForTimeout(stage: StageExecution, taskModel: TaskExecution, message: Message) {
if (stage.type == RestrictExecutionDuringTimeWindow.TYPE) {
return
} else {
checkForStageTimeout(stage)
checkForTaskTimeout(taskModel, stage, message)
}
}
private fun Task.checkForTaskTimeout(taskModel: TaskExecution, stage: StageExecution, message: Message) {
if (this is RetryableTask) {
val startTime = taskModel.startTime.toInstant()
if (startTime != null) {
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val elapsedTime = Duration.between(startTime, clock.instant())
val actualTimeout = (
if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent)
stage.parentWithTimeout.get().timeout.get().toDuration()
else
getDynamicTimeout(stage).toDuration()
)
if (elapsedTime.minus(pausedDuration) > actualTimeout) {
val durationString = formatTimeout(elapsedTime.toMillis())
val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ")
msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ")
msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())}, ")
msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}")
log.warn(msg.toString())
throw TimeoutException(msg.toString())
}
}
}
}
private fun checkForStageTimeout(stage: StageExecution) {
stage.parentWithTimeout.ifPresent {
val startTime = it.startTime.toInstant()
if (startTime != null) {
val elapsedTime = Duration.between(startTime, clock.instant())
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val executionWindowDuration = stage.executionWindow?.duration ?: ZERO
val timeout = Duration.ofMillis(it.timeout.get())
if (elapsedTime.minus(pausedDuration).minus(executionWindowDuration) > timeout) {
throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}")
}
}
}
}
private val StageExecution.executionWindow: StageExecution?
get() = beforeStages()
.firstOrNull { it.type == RestrictExecutionDuringTimeWindow.TYPE }
private val StageExecution.duration: Duration
get() = run {
if (startTime == null || endTime == null) {
throw IllegalStateException("Only valid on completed stages")
}
Duration.between(startTime.toInstant(), endTime.toInstant())
}
private fun Registry.timeoutCounter(
executionType: ExecutionType,
application: String,
stageType: String,
taskType: String
) =
counter(
createId("queue.task.timeouts")
.withTags(mapOf(
"executionType" to executionType.toString(),
"application" to application,
"stageType" to stageType,
"taskType" to taskType
))
)
private fun PipelineExecution.pausedDurationRelativeTo(instant: Instant?): Duration {
val pausedDetails = paused
return if (pausedDetails != null) {
if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) {
Duration.ofMillis(pausedDetails.pausedMs)
} else ZERO
} else ZERO
}
private fun StageExecution.processTaskOutput(result: TaskResult) {
val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" }
if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) {
context.putAll(result.context)
outputs.putAll(filteredOutputs)
repository.storeStage(this)
}
}
private fun StageExecution.withLoggingContext(taskModel: TaskExecution, block: () -> Unit) {
try {
MDC.put("stageType", type)
MDC.put("taskType", taskModel.implementingClass)
if (taskModel.startTime != null) {
MDC.put("taskStartTime", taskModel.startTime.toString())
}
block.invoke()
} finally {
MDC.remove("stageType")
MDC.remove("taskType")
MDC.remove("taskStartTime")
}
}
}
|
apache-2.0
|
b2a4118af999923f65ffb60866cd4f64
| 40.723077 | 134 | 0.695735 | 4.838537 | false | false | false | false |
allotria/intellij-community
|
platform/lang-impl/src/com/intellij/ide/actions/runAnything/RunAnythingChooseContextAction.kt
|
1
|
8838
|
// Copyright 2000-2021 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.ide.actions.runAnything
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.runAnything.RunAnythingContext.*
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ErrorLabel
import com.intellij.ui.popup.ActionPopupStep
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.awt.Dimension
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.JPanel
abstract class RunAnythingChooseContextAction(private val containingPanel: JPanel) : CustomComponentAction, DumbAware, ActionGroup() {
override fun canBePerformed(context: DataContext): Boolean = true
override fun isPopup(): Boolean = true
override fun getChildren(e: AnActionEvent?): Array<AnAction> = EMPTY_ARRAY
abstract var selectedContext: RunAnythingContext?
abstract var availableContexts: List<RunAnythingContext>
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
presentation.description = IdeBundle.message("run.anything.context.tooltip")
return ActionButtonWithText(this, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE)
}
override fun update(e: AnActionEvent) {
if (availableContexts.isEmpty()) {
e.presentation.isEnabledAndVisible = false
return
}
if (selectedContext != null && !availableContexts.contains(selectedContext!!)) {
selectedContext = null
}
selectedContext = selectedContext ?: availableContexts[0]
e.presentation.isEnabledAndVisible = true
e.presentation.text = selectedContext!!.label
e.presentation.icon = selectedContext!!.icon
containingPanel.revalidate()
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
if (project == null) {
return
}
val component = e.presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY)
if (component == null) {
return
}
val updateToolbar = {
ActionToolbar.findToolbarBy(component)!!.updateActionsImmediately()
}
val dataContext = e.dataContext
val actionItems = ActionPopupStep.createActionItems(
DefaultActionGroup(createItems()), dataContext,
false,
false, true,
true, ActionPlaces.POPUP, null)
ChooseContextPopup(ChooseContextPopupStep(actionItems, dataContext, updateToolbar), dataContext)
.also { it.size = Dimension(500, 300) }
.also { it.setRequestFocus(false) }
.showUnderneathOf(component)
}
private fun createItems(): List<ContextItem> {
return availableContexts.map {
when (it) {
is ProjectContext -> ProjectItem(it)
is ModuleContext -> ModuleItem(it)
is BrowseRecentDirectoryContext -> BrowseDirectoryItem(it)
is RecentDirectoryContext -> RecentDirectoryItem(it)
}
}
}
inner class ProjectItem(context: ProjectContext) : ContextItem(context) {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.icon = EmptyIcon.ICON_16
}
}
inner class ModuleItem(context: ModuleContext) : ContextItem(context)
inner class BrowseDirectoryItem(context: BrowseRecentDirectoryContext) : ContextItem(context) {
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().invokeLater {
val project = e.project!!
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor().also { it.isForcedToUseIdeaFileChooser = true }
FileChooserFactory.getInstance().createPathChooser(descriptor, project, e.dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT))
.choose(project.guessProjectDir()) {
val recentDirectories = RunAnythingContextRecentDirectoryCache.getInstance(project).state.paths
val path = it.single().path
if (recentDirectories.size >= Registry.intValue("run.anything.context.recent.directory.number")) {
recentDirectories.removeAt(0)
}
recentDirectories.add(path)
selectedContext = RecentDirectoryContext(path)
}
}
}
}
inner class RecentDirectoryItem(context: RecentDirectoryContext) : ContextItem(context)
abstract inner class ContextItem(val context: RunAnythingContext) : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.text = context.label
e.presentation.description = context.description
e.presentation.icon = context.icon
}
override fun actionPerformed(e: AnActionEvent) {
selectedContext = context
}
}
open inner class ChooseContextPopup(step: ActionPopupStep, dataContext: DataContext)
: PopupFactoryImpl.ActionGroupPopup(null, step, null, dataContext, ActionPlaces.POPUP, -1) {
override fun getListElementRenderer(): PopupListElementRenderer<PopupFactoryImpl.ActionItem> =
object : PopupListElementRenderer<PopupFactoryImpl.ActionItem>(this) {
private lateinit var myInfoLabel: JLabel
override fun createItemComponent(): JComponent {
myTextLabel = ErrorLabel()
myInfoLabel = JLabel()
myTextLabel.border = JBUI.Borders.emptyRight(10)
val textPanel = JPanel(BorderLayout())
textPanel.add(myTextLabel, BorderLayout.WEST)
textPanel.add(myInfoLabel, BorderLayout.CENTER)
return layoutComponent(textPanel)
}
override fun customizeComponent(list: JList<out PopupFactoryImpl.ActionItem>,
actionItem: PopupFactoryImpl.ActionItem,
isSelected: Boolean) {
val event = ActionUtil.createEmptyEvent()
ActionUtil.performDumbAwareUpdate(true, actionItem.action, event, false)
val description = event.presentation.description
if (description != null) {
myInfoLabel.text = description
}
myTextLabel.text = event.presentation.text
myInfoLabel.foreground = if (isSelected) UIUtil.getListSelectionForeground(true) else UIUtil.getInactiveTextColor()
}
}
}
class ChooseContextPopupStep(val actions: List<PopupFactoryImpl.ActionItem>, dataContext: DataContext, val updateToolbar: () -> Unit)
: ActionPopupStep(actions, IdeBundle.message("run.anything.context.title.working.directory"), Supplier { dataContext }, null, true,
Condition { false }, false, true, null) {
override fun getSeparatorAbove(value: PopupFactoryImpl.ActionItem?): ListSeparator? {
val action = value?.action
when {
action is BrowseDirectoryItem -> return ListSeparator(IdeBundle.message("run.anything.context.separator.directories"))
action is ModuleItem && action == actions.filter { it.action is ModuleItem }[0].action ->
return ListSeparator(IdeBundle.message("run.anything.context.separator.modules"))
else -> return super.getSeparatorAbove(value)
}
}
override fun getFinalRunnable(): Runnable? {
return super.getFinalRunnable().also { updateToolbar }
}
}
companion object {
fun allContexts(project: Project): List<RunAnythingContext> {
return projectAndModulesContexts(project)
.plus(BrowseRecentDirectoryContext)
.plus(RunAnythingContextRecentDirectoryCache.getInstance(project).state.paths.map { RecentDirectoryContext(it) })
.toList()
}
fun projectAndModulesContexts(project: Project): List<RunAnythingContext> {
return sequenceOf<RunAnythingContext>()
.plus(ProjectContext(project))
.plus(ModuleManager.getInstance(project).modules.map {
ModuleContext(it)
}.let { if (it.size > 1) it else emptyList() })
.toList()
}
}
}
|
apache-2.0
|
bfc3cf7be6a269fb1a9a3ba230e12e40
| 39.545872 | 140 | 0.726409 | 5.053173 | false | false | false | false |
allotria/intellij-community
|
plugins/devkit/devkit-core/src/inspections/missingApi/resolve/LibrariesWithIntellijClassesState.kt
|
1
|
3619
|
// Copyright 2000-2019 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.idea.devkit.inspections.missingApi.resolve
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import org.jetbrains.idea.devkit.projectRoots.IntelliJPlatformProduct
/**
* This is used to save "groupId:artifactId" pairs for all libraries that may contain IntelliJ classes.
* External annotations `@ApiStatus.AvailableSince` should be attached to such libraries.
*
* Until it is possible to attach external annotations to arbitrary libraries (see https://youtrack.jetbrains.com/issue/IDEA-201991)
* we need this workaround for Kotlin project, which has IDEA classes stored in dependencies like `kotlin.build:ideaIC:<version>`
* and `kotlin.build:java:<version>`. Kotlin project may supplement the storage.xml with coordinates of all
* libraries containing IntelliJ classes.
*/
@State(name = "libraries-with-intellij-classes", storages = [Storage("libraries-with-intellij-classes.xml")])
class LibrariesWithIntellijClassesSetting : SimplePersistentStateComponent<LibrariesWithIntellijClassesState>(defaultState) {
companion object {
val defaultState = LibrariesWithIntellijClassesState().also {
getKnownIntellijLibrariesCoordinates()
.mapTo(it.intellijApiContainingLibraries) { (groupId, artifactId) ->
val state = LibraryCoordinatesState()
state.groupId = groupId
state.artifactId = artifactId
state
}
}
fun getInstance(project: Project): LibrariesWithIntellijClassesSetting =
ServiceManager.getService(project, LibrariesWithIntellijClassesSetting::class.java)
}
}
class LibrariesWithIntellijClassesState : BaseState() {
var intellijApiContainingLibraries by list<LibraryCoordinatesState>()
}
class LibraryCoordinatesState : BaseState() {
var groupId by string()
var artifactId by string()
}
private fun getKnownIntellijLibrariesCoordinates(): List<Pair<String, String>> {
val result = arrayListOf<Pair<String, String>>()
IntelliJPlatformProduct.values().mapNotNull { product ->
getMavenCoordinatesOfProduct(product)
}.forEach { (groupId, artifactId) ->
//Original coordinates of the product.
result += groupId to artifactId
//Coordinates used in the 'gradle-intellij-plugin' to specify IDE dependency
result += "com.jetbrains" to artifactId
}
return result
}
@Suppress("HardCodedStringLiteral")
private fun getMavenCoordinatesOfProduct(product: IntelliJPlatformProduct): Pair<String, String>? = when (product) {
IntelliJPlatformProduct.IDEA -> "com.jetbrains.intellij.idea" to "ideaIU"
IntelliJPlatformProduct.IDEA_IC -> "com.jetbrains.intellij.idea" to "ideaIC"
IntelliJPlatformProduct.CLION -> "com.jetbrains.intellij.clion" to "clion"
IntelliJPlatformProduct.PYCHARM -> "com.jetbrains.intellij.pycharm" to "pycharmPY"
IntelliJPlatformProduct.PYCHARM_PC -> "com.jetbrains.intellij.pycharm" to "pycharmPC"
IntelliJPlatformProduct.RIDER -> "com.jetbrains.intellij.rider" to "riderRD"
IntelliJPlatformProduct.GOIDE -> "com.jetbrains.intellij.goland" to "goland"
IntelliJPlatformProduct.RUBYMINE,
IntelliJPlatformProduct.PYCHARM_DS,
IntelliJPlatformProduct.PYCHARM_EDU,
IntelliJPlatformProduct.PHPSTORM,
IntelliJPlatformProduct.WEBSTORM,
IntelliJPlatformProduct.APPCODE,
IntelliJPlatformProduct.MOBILE_IDE,
IntelliJPlatformProduct.DBE,
IntelliJPlatformProduct.ANDROID_STUDIO,
IntelliJPlatformProduct.CWM_GUEST,
IntelliJPlatformProduct.IDEA_IE -> null
}
|
apache-2.0
|
f3d18bfb04a61462ec1ea987cddf75e0
| 44.25 | 140 | 0.779497 | 4.903794 | false | false | false | false |
allotria/intellij-community
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectRefreshAction.kt
|
3
|
3300
|
// Copyright 2000-2019 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.externalSystem.autoimport
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.ui.DefaultExternalSystemIconProvider
import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.text.NaturalComparator
import javax.swing.Icon
class ProjectRefreshAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val projectNotificationAware = ProjectNotificationAware.getInstance(project)
val systemIds = projectNotificationAware.getSystemIds()
if (ExternalSystemUtil.confirmLoadingUntrustedProject(project, systemIds)) {
val projectTracker = ExternalSystemProjectTracker.getInstance(project)
projectTracker.scheduleProjectRefresh()
}
}
override fun update(e: AnActionEvent) {
val project = e.project ?: return
val notificationAware = ProjectNotificationAware.getInstance(project)
val systemIds = notificationAware.getSystemIds()
if (systemIds.isNotEmpty()) {
e.presentation.text = getNotificationText(systemIds)
e.presentation.description = getNotificationDescription(systemIds)
e.presentation.icon = getNotificationIcon(systemIds)
}
e.presentation.isEnabled = notificationAware.isNotificationVisible()
}
@NlsActions.ActionText
private fun getNotificationText(systemIds: Set<ProjectSystemId>): String {
val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds)
return ExternalSystemBundle.message("external.system.reload.notification.action.reload.text", systemsPresentation)
}
@NlsActions.ActionDescription
private fun getNotificationDescription(systemIds: Set<ProjectSystemId>): String {
val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds)
val productName = ApplicationNamesInfo.getInstance().fullProductName
return ExternalSystemBundle.message("external.system.reload.notification.action.reload.description", systemsPresentation, productName)
}
private fun getNotificationIcon(systemIds: Set<ProjectSystemId>): Icon {
val iconManager = when (systemIds.size) {
1 -> ExternalSystemIconProvider.getExtension(systemIds.first())
else -> DefaultExternalSystemIconProvider
}
return iconManager.reloadIcon
}
init {
val productName = ApplicationNamesInfo.getInstance().fullProductName
templatePresentation.icon = DefaultExternalSystemIconProvider.reloadIcon
templatePresentation.text = ExternalSystemBundle.message("external.system.reload.notification.action.reload.text.empty")
templatePresentation.description = ExternalSystemBundle.message("external.system.reload.notification.action.reload.description.empty", productName)
}
}
|
apache-2.0
|
b06dc1df4f0dc93c394231a59ac71fcb
| 49.015152 | 151 | 0.81 | 5.357143 | false | false | false | false |
allotria/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/viewer/GHPRTwosideDiffViewerReviewThreadsHandler.kt
|
2
|
4298
|
// 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.comment.viewer
import com.intellij.diff.tools.util.side.TwosideTextDiffViewer
import com.intellij.diff.util.LineRange
import com.intellij.diff.util.Range
import com.intellij.diff.util.Side
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.util.ui.codereview.diff.EditorComponentInlaysManager
import org.jetbrains.plugins.github.pullrequest.comment.GHPRCommentsUtil
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewThreadMapping
import org.jetbrains.plugins.github.pullrequest.comment.ui.*
import org.jetbrains.plugins.github.ui.util.SingleValueModel
class GHPRTwosideDiffViewerReviewThreadsHandler(reviewProcessModel: GHPRReviewProcessModel,
commentableRangesModel: SingleValueModel<List<Range>?>,
reviewThreadsModel: SingleValueModel<List<GHPRDiffReviewThreadMapping>?>,
viewer: TwosideTextDiffViewer,
componentsFactory: GHPRDiffEditorReviewComponentsFactory,
cumulative: Boolean)
: GHPRDiffViewerBaseReviewThreadsHandler<TwosideTextDiffViewer>(commentableRangesModel, reviewThreadsModel, viewer) {
private val commentableRangesLeft = SingleValueModel<List<LineRange>>(emptyList())
private val editorThreadsLeft = GHPREditorReviewThreadsModel()
private val commentableRangesRight = SingleValueModel<List<LineRange>>(emptyList())
private val editorThreadsRight = GHPREditorReviewThreadsModel()
override val viewerReady = true
init {
val inlaysManagerLeft = EditorComponentInlaysManager(viewer.editor1 as EditorImpl)
val gutterIconRendererFactoryLeft = GHPRDiffEditorGutterIconRendererFactoryImpl(reviewProcessModel,
inlaysManagerLeft,
componentsFactory,
cumulative) { line ->
val (startLine, endLine) = getCommentLinesRange(viewer.editor1, line)
GHPRCommentLocation(Side.LEFT, endLine, startLine)
}
GHPREditorCommentableRangesController(commentableRangesLeft, gutterIconRendererFactoryLeft, viewer.editor1)
GHPREditorReviewThreadsController(editorThreadsLeft, componentsFactory, inlaysManagerLeft)
val inlaysManagerRight = EditorComponentInlaysManager(viewer.editor2 as EditorImpl)
val gutterIconRendererFactoryRight = GHPRDiffEditorGutterIconRendererFactoryImpl(reviewProcessModel,
inlaysManagerRight,
componentsFactory,
cumulative) { line ->
val (startLine, endLine) = getCommentLinesRange(viewer.editor2, line)
GHPRCommentLocation(Side.RIGHT, endLine, startLine)
}
GHPREditorCommentableRangesController(commentableRangesRight, gutterIconRendererFactoryRight, viewer.editor2)
GHPREditorReviewThreadsController(editorThreadsRight, componentsFactory, inlaysManagerRight)
}
override fun markCommentableRanges(ranges: List<Range>?) {
commentableRangesLeft.value = ranges?.let { GHPRCommentsUtil.getLineRanges(it, Side.LEFT) }.orEmpty()
commentableRangesRight.value = ranges?.let { GHPRCommentsUtil.getLineRanges(it, Side.RIGHT) }.orEmpty()
}
override fun showThreads(threads: List<GHPRDiffReviewThreadMapping>?) {
editorThreadsLeft.update(threads
?.filter { it.diffSide == Side.LEFT }
?.groupBy({ it.fileLineIndex }, { it.thread }).orEmpty())
editorThreadsRight.update(threads
?.filter { it.diffSide == Side.RIGHT }
?.groupBy({ it.fileLineIndex }, { it.thread }).orEmpty())
}
}
|
apache-2.0
|
6a99ff8c10ae93aafd228ee110878173
| 58.694444 | 140 | 0.652396 | 6.002793 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/jvm/src/flow/internal/SafeCollector.kt
|
1
|
6543
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow.internal
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.coroutines.jvm.internal.*
@Suppress("UNCHECKED_CAST")
private val emitFun =
FlowCollector<Any?>::emit as Function3<FlowCollector<Any?>, Any?, Continuation<Unit>, Any?>
/*
* Implementor of ContinuationImpl (that will be preserved as ABI nearly forever)
* in order to properly control 'intercepted()' lifecycle.
*/
@Suppress("CANNOT_OVERRIDE_INVISIBLE_MEMBER", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "UNCHECKED_CAST")
internal actual class SafeCollector<T> actual constructor(
@JvmField internal actual val collector: FlowCollector<T>,
@JvmField internal actual val collectContext: CoroutineContext
) : FlowCollector<T>, ContinuationImpl(NoOpContinuation, EmptyCoroutineContext), CoroutineStackFrame {
override val callerFrame: CoroutineStackFrame? get() = completion as? CoroutineStackFrame
override fun getStackTraceElement(): StackTraceElement? = null
@JvmField // Note, it is non-capturing lambda, so no extra allocation during init of SafeCollector
internal actual val collectContextSize = collectContext.fold(0) { count, _ -> count + 1 }
// Either context of the last emission or wrapper 'DownstreamExceptionContext'
private var lastEmissionContext: CoroutineContext? = null
// Completion if we are currently suspended or within completion body or null otherwise
private var completion: Continuation<Unit>? = null
/*
* This property is accessed in two places:
* * ContinuationImpl invokes this in its `releaseIntercepted` as `context[ContinuationInterceptor]!!`
* * When we are within a callee, it is used to create its continuation object with this collector as completion
*/
override val context: CoroutineContext
get() = lastEmissionContext ?: EmptyCoroutineContext
override fun invokeSuspend(result: Result<Any?>): Any {
result.onFailure { lastEmissionContext = DownstreamExceptionContext(it, context) }
completion?.resumeWith(result as Result<Unit>)
return COROUTINE_SUSPENDED
}
// Escalate visibility to manually release intercepted continuation
public actual override fun releaseIntercepted() {
super.releaseIntercepted()
}
/**
* This is a crafty implementation of state-machine reusing.
* First it checks that it is not used concurrently (which we explicitly prohibit) and
* then just cache an instance of the completion in order to avoid extra allocation on each emit,
* making it effectively garbage-free on its hot-path.
*/
override suspend fun emit(value: T) {
return suspendCoroutineUninterceptedOrReturn sc@{ uCont ->
try {
emit(uCont, value)
} catch (e: Throwable) {
// Save the fact that exception from emit (or even check context) has been thrown
// Note, that this can the first emit and lastEmissionContext may not be saved yet,
// hence we use `uCont.context` here.
lastEmissionContext = DownstreamExceptionContext(e, uCont.context)
throw e
}
}
}
private fun emit(uCont: Continuation<Unit>, value: T): Any? {
val currentContext = uCont.context
currentContext.ensureActive()
// This check is triggered once per flow on happy path.
val previousContext = lastEmissionContext
if (previousContext !== currentContext) {
checkContext(currentContext, previousContext, value)
lastEmissionContext = currentContext
}
completion = uCont
val result = emitFun(collector as FlowCollector<Any?>, value, this as Continuation<Unit>)
/*
* If the callee hasn't suspended, that means that it won't (it's forbidden) call 'resumeWith` (-> `invokeSuspend`)
* and we don't have to retain a strong reference to it to avoid memory leaks.
*/
if (result != COROUTINE_SUSPENDED) {
completion = null
}
return result
}
private fun checkContext(
currentContext: CoroutineContext,
previousContext: CoroutineContext?,
value: T
) {
if (previousContext is DownstreamExceptionContext) {
exceptionTransparencyViolated(previousContext, value)
}
checkContext(currentContext)
}
private fun exceptionTransparencyViolated(exception: DownstreamExceptionContext, value: Any?) {
/*
* Exception transparency ensures that if a `collect` block or any intermediate operator
* throws an exception, then no more values will be received by it.
* For example, the following code:
* ```
* val flow = flow {
* emit(1)
* try {
* emit(2)
* } catch (e: Exception) {
* emit(3)
* }
* }
* // Collector
* flow.collect { value ->
* if (value == 2) {
* throw CancellationException("No more elements required, received enough")
* } else {
* println("Collected $value")
* }
* }
* ```
* is expected to print "Collected 1" and then "No more elements required, received enough" exception,
* but if exception transparency wasn't enforced, "Collected 1" and "Collected 3" would be printed instead.
*/
error("""
Flow exception transparency is violated:
Previous 'emit' call has thrown exception ${exception.e}, but then emission attempt of value '$value' has been detected.
Emissions from 'catch' blocks are prohibited in order to avoid unspecified behaviour, 'Flow.catch' operator can be used instead.
For a more detailed explanation, please refer to Flow documentation.
""".trimIndent())
}
}
internal class DownstreamExceptionContext(
@JvmField val e: Throwable,
originalContext: CoroutineContext
) : CoroutineContext by originalContext
private object NoOpContinuation : Continuation<Any?> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resumeWith(result: Result<Any?>) {
// Nothing
}
}
|
apache-2.0
|
f8abc5cbcfff82ca6f4469dc1ee46d78
| 41.212903 | 144 | 0.661317 | 5.160095 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/ProtobufUtil.kt
|
1
|
4313
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.serialization.deserialization.descriptors.*
import org.jetbrains.kotlin.serialization.KonanIr
import org.jetbrains.kotlin.serialization.KonanLinkData
import org.jetbrains.kotlin.serialization.KonanLinkData.*
import org.jetbrains.kotlin.serialization.ProtoBuf
fun newUniqId(index: Long): KonanIr.UniqId =
KonanIr.UniqId.newBuilder().setIndex(index).build()
// -----------------------------------------------------------
val KonanIr.KotlinDescriptor.index: Long
get() = this.uniqId.index
fun KonanIr.KotlinDescriptor.Builder.setIndex(index: Long)
= this.setUniqId(newUniqId(index))
val KonanIr.KotlinDescriptor.originalIndex: Long
get() = this.originalUniqId.index
fun KonanIr.KotlinDescriptor.Builder.setOriginalIndex(index: Long)
= this.setOriginalUniqId(newUniqId(index))
val KonanIr.KotlinDescriptor.dispatchReceiverIndex: Long
get() = this.dispatchReceiverUniqId.index
fun KonanIr.KotlinDescriptor.Builder.setDispatchReceiverIndex(index: Long)
= this.setDispatchReceiverUniqId(newUniqId(index))
val KonanIr.KotlinDescriptor.extensionReceiverIndex: Long
get() = this.extensionReceiverUniqId.index
fun KonanIr.KotlinDescriptor.Builder.setExtensionReceiverIndex(index: Long)
= this.setExtensionReceiverUniqId(newUniqId(index))
// -----------------------------------------------------------
val ProtoBuf.Property.getterIr: InlineIrBody
get() = this.getExtension(inlineGetterIrBody)
fun ProtoBuf.Property.Builder.setGetterIr(body: InlineIrBody): ProtoBuf.Property.Builder =
this.setExtension(inlineGetterIrBody, body)
val ProtoBuf.Property.setterIr: InlineIrBody
get() = this.getExtension(inlineSetterIrBody)
fun ProtoBuf.Property.Builder.setSetterIr(body: InlineIrBody): ProtoBuf.Property.Builder =
this.setExtension(inlineSetterIrBody, body)
val ProtoBuf.Constructor.constructorIr: InlineIrBody
get() = this.getExtension(inlineConstructorIrBody)
fun ProtoBuf.Constructor.Builder.setConstructorIr(body: InlineIrBody): ProtoBuf.Constructor.Builder =
this.setExtension(inlineConstructorIrBody, body)
val ProtoBuf.Function.inlineIr: InlineIrBody
get() = this.getExtension(inlineIrBody)
fun ProtoBuf.Function.Builder.setInlineIr(body: InlineIrBody): ProtoBuf.Function.Builder =
this.setExtension(inlineIrBody, body)
// -----------------------------------------------------------
fun inlineBody(encodedIR: String)
= KonanLinkData.InlineIrBody
.newBuilder()
.setEncodedIr(encodedIR)
.build()
// -----------------------------------------------------------
internal fun printType(proto: ProtoBuf.Type) {
println("debug text: " + proto.getExtension(KonanLinkData.typeText))
}
internal fun printTypeTable(proto: ProtoBuf.TypeTable) {
proto.getTypeList().forEach {
printType(it)
}
}
// -----------------------------------------------------------
internal val DeclarationDescriptor.typeParameterProtos: List<ProtoBuf.TypeParameter>
get() = when (this) {
// These are different typeParameterLists not
// having a common ancestor.
is DeserializedSimpleFunctionDescriptor
-> this.proto.typeParameterList
is DeserializedPropertyDescriptor
-> this.proto.typeParameterList
is DeserializedClassDescriptor
-> this.classProto.typeParameterList
is DeserializedTypeAliasDescriptor
-> this.proto.typeParameterList
is DeserializedClassConstructorDescriptor
-> listOf()
else -> error("Unexpected descriptor kind: $this")
}
|
apache-2.0
|
1d3f1aa42f6b7e7e8ef779c26ce19a06
| 34.941667 | 103 | 0.706933 | 4.698257 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/annotations/propertyWithPropertyInInitializerAsParameter.kt
|
2
|
518
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Ann(i) class MyClass
fun box(): String {
val ann = MyClass::class.java.getAnnotation(Ann::class.java)
if (ann == null) return "fail: cannot find Ann on MyClass}"
if (ann.i != 1) return "fail: annotation parameter i should be 1, but was ${ann.i}"
return "OK"
}
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(val i: Int)
const val i2: Int = 1
const val i: Int = i2
|
apache-2.0
|
1fef5e675b8e4f74b9ab4f83ba0cac4f
| 26.263158 | 87 | 0.687259 | 3.363636 | false | false | false | false |
redundent/kotlin-xml-builder
|
kotlin-xml-dsl-generator/src/main/kotlin/org/redundent/kotlin/xml/gen/writer/CodeWriter.kt
|
1
|
4322
|
package org.redundent.kotlin.xml.gen.writer
import com.sun.tools.xjc.model.CAttributePropertyInfo
import com.sun.tools.xjc.model.CClassInfo
import com.sun.tools.xjc.model.CElementPropertyInfo
import com.sun.tools.xjc.model.CPropertyInfo
import com.sun.tools.xjc.model.CTypeInfo
import com.sun.tools.xjc.outline.Outline
import com.sun.tools.xjc.reader.xmlschema.bindinfo.BindInfo
import com.sun.xml.xsom.XSComponent
import java.util.Comparator
import java.util.Date
class CodeWriter(private val outline: Outline) {
private var output = StringBuilder()
var currentIndex = 0
private set
fun writePackage(packageName: String) {
writeln("package $packageName\n")
}
fun writeImport(importStatement: String) {
writeln("import $importStatement")
}
fun writeKotlinDoc(doc: String?) {
if (doc == null || doc.isBlank()) {
return
}
writeln("/**")
doc.split("\n").map(String::trim).filter(String::isNotBlank).forEach { writeln(" * $it") }
writeln(" */")
}
fun indent() = currentIndex++
fun dedent() = currentIndex--
fun write(text: String, writeIndex: Boolean = true) {
if (writeIndex) {
output.append((0 until currentIndex).joinToString("") { "\t" })
}
output.append(text)
}
fun writeSuppress(block: MutableList<String>.() -> Unit) {
val list = ArrayList<String>()
list.block()
writeln("@file:Suppress(${list.joinToString(", ") { "\"$it\"" }})")
writeln()
}
fun writeln(text: String = "", writeIndex: Boolean = true) {
if (text.isNotEmpty()) {
write(text, writeIndex)
}
output.append("\n")
}
fun writeBlock(block: () -> String) {
val text = block().trimStart()
text.split("\n").forEach { writeln(it) }
}
fun asText(): String = output.toString().trim()
fun trimLastNewLine() {
if (output.endsWith('\n')) {
output = StringBuilder(output.substring(0, output.lastIndex))
}
}
fun CClassInfo.attributesAsParameters(indentLength: Int): String {
if (allAttributes.isEmpty()) {
return ""
}
val sortedAttributes = allAttributes.sortedWith(Comparator { o1, o2 -> Integer.compare(if (o1.isRequired) 0 else 1, if (o2.isRequired) 0 else 1) })
val numOfTabs = Math.floor(indentLength.toDouble() / 4.0).toInt()
val numOfSpaces = indentLength % 4
val delimiter = ",\n${(0..numOfTabs).joinToString("\t") { "" }}${(0..numOfSpaces).joinToString(" ") { "" }}"
return sortedAttributes.joinToString(delimiter) {
val field = outline.getField(it)
"`${it.xmlName.localPart}`: ${mapType(field.rawType.fullName())}${if (!it.isRequired) "? = null" else ""}"
} + delimiter
}
companion object {
fun mapType(type: String): String {
return when (type) {
"int",
java.lang.Integer::class.java.name,
java.math.BigInteger::class.java.name -> Int::class.qualifiedName
"long",
java.lang.Long::class.java.name -> Long::class.qualifiedName
"boolean",
java.lang.Boolean::class.java.name -> Boolean::class.qualifiedName
"double",
java.lang.Double::class.java.name -> Double::class.qualifiedName
"float",
java.lang.Float::class.java.name -> Float::class.qualifiedName
java.lang.String::class.java.name,
javax.xml.namespace.QName::class.java.name -> String::class.qualifiedName
"byte",
java.lang.Byte::class.java.name -> Byte::class.qualifiedName
"short",
java.lang.Short::class.java.name -> Short::class.qualifiedName
"byte[]" -> ByteArray::class.qualifiedName
javax.xml.datatype.XMLGregorianCalendar::class.java.name -> Date::class.qualifiedName
else -> type
}!!
}
}
}
val CClassInfo.attributes: List<CAttributePropertyInfo>
get() = properties.mapNotNull { it as? CAttributePropertyInfo }
val CClassInfo.allAttributes: List<CAttributePropertyInfo>
get() = generateSequence(this) { it.baseClass }.toList().flatMap { it.properties.mapNotNull { p -> p as? CAttributePropertyInfo } }
val CClassInfo.hasOptionalAttributes: Boolean
get() = allAttributes.any { !it.isRequired }
val CClassInfo.elements: List<CElementPropertyInfo>
get() = properties.mapNotNull { it as? CElementPropertyInfo }
val CPropertyInfo.documentation: String?
get() = schemaComponent?.documentation
val CTypeInfo.documentation: String?
get() = schemaComponent?.documentation
val XSComponent.documentation: String?
get() = annotation?.annotation?.let { it as? BindInfo }?.documentation
|
apache-2.0
|
e88d405fe1337f6e9e9ff0763226a1cc
| 30.779412 | 149 | 0.702221 | 3.452077 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/reflection/properties/kotlinPropertyInheritedInJava.kt
|
1
|
1776
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J extends K {
}
// FILE: K.kt
import kotlin.reflect.*
import kotlin.reflect.full.*
import kotlin.reflect.jvm.*
public open class K {
var prop: String = ":("
val Int.ext: Int get() = this
}
fun box(): String {
val j = J()
val prop = J::prop
if (prop !is KMutableProperty1<*, *>) return "Fail instanceof"
if (prop.name != "prop") return "Fail name: ${prop.name}"
if (prop.get(j) != ":(") return "Fail get before: ${prop.get(j)}"
prop.set(j, ":)")
if (prop.get(j) != ":)") return "Fail get after: ${prop.get(j)}"
if (prop == K::prop) return "Fail J::prop == K::prop (these are different properties)"
val klass = J::class
if (klass.declaredMemberProperties.isNotEmpty()) return "Fail: declaredMemberProperties should be empty"
if (klass.declaredMemberExtensionProperties.isNotEmpty()) return "Fail: declaredMemberExtensionProperties should be empty"
val prop2 = klass.memberProperties.firstOrNull { it.name == "prop" } ?: "Fail: no 'prop' property in memberProperties"
if (prop != prop2) return "Fail: property references from :: and from properties differ: $prop != $prop2"
if (prop2 !is KMutableProperty1<*, *>) return "Fail instanceof 2"
(prop2 as KMutableProperty1<J, String>).set(j, "::)")
if (prop.get(j) != "::)") return "Fail get after 2: ${prop.get(j)}"
val ext = klass.memberExtensionProperties.firstOrNull { it.name == "ext" } ?: "Fail: no 'ext' property in memberExtensionProperties"
ext as KProperty2<J, Int, Int>
val fortyTwo = ext.get(j, 42)
if (fortyTwo != 42) return "Fail ext get: $fortyTwo"
return "OK"
}
|
apache-2.0
|
43297ffea8f825e58c74d46ade6d90ef
| 32.509434 | 136 | 0.65259 | 3.566265 | false | false | false | false |
siosio/intellij-community
|
platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitWorkflow.kt
|
2
|
5522
|
// 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.vcs.commit
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog.DIALOG_TITLE
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.impl.PartialChangesUtil
import com.intellij.util.ui.UIUtil.removeMnemonic
import com.intellij.vcs.commit.SingleChangeListCommitter.Companion.moveToFailedList
import org.jetbrains.annotations.Nls
private val LOG = logger<SingleChangeListCommitWorkflow>()
internal val CommitOptions.changeListSpecificOptions: Sequence<CheckinChangeListSpecificComponent>
get() = allOptions.filterIsInstance<CheckinChangeListSpecificComponent>()
internal fun CommitOptions.changeListChanged(changeList: LocalChangeList) = changeListSpecificOptions.forEach {
it.onChangeListSelected(changeList)
}
internal fun CommitOptions.saveChangeListSpecificOptions() = changeListSpecificOptions.forEach { it.saveState() }
@Nls
internal fun String.removeEllipsisSuffix() = StringUtil.removeEllipsisSuffix(this)
@Nls
internal fun CommitExecutor.getPresentableText() = removeMnemonic(actionText).removeEllipsisSuffix()
open class SingleChangeListCommitWorkflow(
project: Project,
affectedVcses: Set<AbstractVcs>,
val initiallyIncluded: Collection<*>,
val initialChangeList: LocalChangeList? = null,
executors: List<CommitExecutor> = emptyList(),
final override val isDefaultCommitEnabled: Boolean = executors.isEmpty(),
private val isDefaultChangeListFullyIncluded: Boolean = true,
val initialCommitMessage: String? = null,
private val resultHandler: CommitResultHandler? = null
) : AbstractCommitWorkflow(project) {
init {
updateVcses(affectedVcses)
initCommitExecutors(executors)
}
val isPartialCommitEnabled: Boolean =
vcses.any { it.arePartialChangelistsSupported() } && (isDefaultCommitEnabled || commitExecutors.any { it.supportsPartialCommit() })
internal val commitMessagePolicy: SingleChangeListCommitMessagePolicy = SingleChangeListCommitMessagePolicy(project, initialCommitMessage)
internal lateinit var commitState: ChangeListCommitState
override fun processExecuteDefaultChecksResult(result: CheckinHandler.ReturnResult) = when (result) {
CheckinHandler.ReturnResult.COMMIT -> DefaultNameChangeListCleaner(project, commitState).use { doCommit(commitState) }
CheckinHandler.ReturnResult.CLOSE_WINDOW ->
moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name))
CheckinHandler.ReturnResult.CANCEL -> Unit
}
override fun executeCustom(executor: CommitExecutor, session: CommitSession): Boolean =
executeCustom(executor, session, commitState.changes, commitState.commitMessage)
override fun processExecuteCustomChecksResult(executor: CommitExecutor, session: CommitSession, result: CheckinHandler.ReturnResult) =
when (result) {
CheckinHandler.ReturnResult.COMMIT -> doCommitCustom(executor, session)
CheckinHandler.ReturnResult.CLOSE_WINDOW ->
moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name))
CheckinHandler.ReturnResult.CANCEL -> Unit
}
override fun doRunBeforeCommitChecks(checks: Runnable) =
PartialChangesUtil.runUnderChangeList(project, commitState.changeList, checks)
protected open fun doCommit(commitState: ChangeListCommitState) {
LOG.debug("Do actual commit")
with(object : SingleChangeListCommitter(project, commitState, commitContext, DIALOG_TITLE, isDefaultChangeListFullyIncluded) {
override fun afterRefreshChanges() = endExecution { super.afterRefreshChanges() }
}) {
addResultHandler(CommitHandlersNotifier(commitHandlers))
addResultHandler(getCommitEventDispatcher())
addResultHandler(resultHandler ?: ShowNotificationCommitResultHandler(this))
runCommit(DIALOG_TITLE, false)
}
}
private fun doCommitCustom(executor: CommitExecutor, session: CommitSession) {
val cleaner = DefaultNameChangeListCleaner(project, commitState)
with(CustomCommitter(project, session, commitState.changes, commitState.commitMessage)) {
addResultHandler(CommitHandlersNotifier(commitHandlers))
addResultHandler(CommitResultHandler { cleaner.clean() })
addResultHandler(getCommitCustomEventDispatcher())
resultHandler?.let { addResultHandler(it) }
addResultHandler(getEndExecutionHandler())
runCommit(executor.actionText)
}
}
}
private class DefaultNameChangeListCleaner(val project: Project, commitState: ChangeListCommitState) {
private val isChangeListFullyIncluded = commitState.changeList.changes.size == commitState.changes.size
private val isDefaultNameChangeList = commitState.changeList.hasDefaultName()
private val listName = commitState.changeList.name
fun use(block: () -> Unit) {
block()
clean()
}
fun clean() {
if (isDefaultNameChangeList && isChangeListFullyIncluded) {
ChangeListManager.getInstance(project).editComment(listName, "")
}
}
}
|
apache-2.0
|
89e546dd6b4c0882034028bca915f0b6
| 43.540323 | 140 | 0.798624 | 5.219282 | false | false | false | false |
ncoe/rosetta
|
Van_Eck_sequence/Kotlin/src/VanEckSequence.kt
|
1
|
619
|
fun main() {
println("First 10 terms of Van Eck's sequence:")
vanEck(1, 10)
println("")
println("Terms 991 to 1000 of Van Eck's sequence:")
vanEck(991, 1000)
}
private fun vanEck(firstIndex: Int, lastIndex: Int) {
val vanEckMap = mutableMapOf<Int, Int>()
var last = 0
if (firstIndex == 1) {
println("VanEck[1] = 0")
}
for (n in 2..lastIndex) {
val vanEck = if (vanEckMap.containsKey(last)) n - vanEckMap[last]!! else 0
vanEckMap[last] = n
last = vanEck
if (n >= firstIndex) {
println("VanEck[$n] = $vanEck")
}
}
}
|
mit
|
0286ed5b1daee8521461761dcf6acee5
| 25.913043 | 82 | 0.555735 | 3.477528 | false | false | false | false |
idea4bsd/idea4bsd
|
platform/built-in-server/src/org/jetbrains/io/jsonRpc/ClientManager.kt
|
17
|
2419
|
package org.jetbrains.io.jsonRpc
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.SimpleTimer
import gnu.trove.THashSet
import gnu.trove.TObjectProcedure
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.util.AttributeKey
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.webSocket.WebSocketServerOptions
internal val CLIENT = AttributeKey.valueOf<Client>("SocketHandler.client")
class ClientManager(private val listener: ClientListener?, val exceptionHandler: ExceptionHandler, options: WebSocketServerOptions? = null) : Disposable {
private val heartbeatTimer = SimpleTimer.getInstance().setUp({
forEachClient(TObjectProcedure {
if (it.channel.isActive) {
it.sendHeartbeat()
}
true
})
}, (options ?: WebSocketServerOptions()).heartbeatDelay.toLong())
private val clients = THashSet<Client>()
fun addClient(client: Client) {
synchronized (clients) {
clients.add(client)
}
}
val clientCount: Int
get() = synchronized (clients) { clients.size }
fun hasClients() = clientCount > 0
override fun dispose() {
try {
heartbeatTimer.cancel()
}
finally {
synchronized (clients) {
clients.clear()
}
}
}
fun <T> send(messageId: Int, message: ByteBuf, results: MutableList<Promise<Pair<Client, T>>>? = null) {
forEachClient(object : TObjectProcedure<Client> {
private var first: Boolean = false
override fun execute(client: Client): Boolean {
try {
val result = client.send<Pair<Client, T>>(messageId, if (first) message else message.duplicate())
first = false
results?.add(result!!)
}
catch (e: Throwable) {
exceptionHandler.exceptionCaught(e)
}
return true
}
})
}
fun disconnectClient(channel: Channel, client: Client, closeChannel: Boolean): Boolean {
synchronized (clients) {
if (!clients.remove(client)) {
return false
}
}
try {
channel.attr(CLIENT).remove()
if (closeChannel) {
channel.close()
}
client.rejectAsyncResults(exceptionHandler)
}
finally {
listener?.disconnected(client)
}
return true
}
fun forEachClient(procedure: TObjectProcedure<Client>) {
synchronized (clients) {
clients.forEach(procedure)
}
}
}
|
apache-2.0
|
2f0555ddda5a8f8c3dafdfe7632e4cc8
| 24.744681 | 154 | 0.663911 | 4.342908 | false | false | false | false |
mseroczynski/CityBikes
|
app/src/main/kotlin/pl/ches/citybikes/presentation/screen/intro/IntroActivity.kt
|
1
|
1438
|
package pl.ches.citybikes.presentation.screen.intro
import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.maxcruz.reactivePermissions.ReactivePermissions
import com.maxcruz.reactivePermissions.entity.Permission
import pl.ches.citybikes.R
import pl.ches.citybikes.presentation.screen.main.MainActivity
/**
* @author Michał Seroczyński <[email protected]>
*/
class IntroActivity : AppCompatActivity() {
val reactive: ReactivePermissions = ReactivePermissions(this, REQUEST_CODE)
val location = Permission(
Manifest.permission.ACCESS_FINE_LOCATION,
R.string.app_name,
false // If the user deny this permission, block the app
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
reactive.observeResultPermissions().subscribe { event ->
if (event.second) {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
finish()
}
}
reactive.evaluate(listOf(location))
}
override fun onRequestPermissionsResult(code: Int, permissions: Array<String>, results: IntArray) {
if (code == REQUEST_CODE) reactive.receive(permissions, results)
}
companion object {
// Define a code to request the permissions
const val REQUEST_CODE = 10
}
}
|
gpl-3.0
|
b42dacf229e916118d4b6ff71201ffa1
| 28.916667 | 101 | 0.740947 | 4.312312 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/ImportableFqNameClassifier.kt
|
2
|
3157
|
// 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.core
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.load.java.components.JavaAnnotationMapper
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.ImportPath
import java.util.*
class ImportableFqNameClassifier(private val file: KtFile) {
private val preciseImports = HashSet<FqName>()
private val preciseImportPackages = HashSet<FqName>()
private val allUnderImports = HashSet<FqName>()
private val excludedImports = HashSet<FqName>()
init {
for (import in file.importDirectives) {
val importPath = import.importPath ?: continue
val fqName = importPath.fqName
when {
importPath.isAllUnder -> allUnderImports.add(fqName)
!importPath.hasAlias() -> {
preciseImports.add(fqName)
preciseImportPackages.add(fqName.parent())
}
else -> excludedImports.add(fqName)
// TODO: support aliased imports in completion
}
}
}
enum class Classification {
fromCurrentPackage,
topLevelPackage,
preciseImport,
defaultImport,
allUnderImport,
siblingImported,
notImported,
notToBeUsedInKotlin
}
fun classify(fqName: FqName, isPackage: Boolean): Classification {
val importPath = ImportPath(fqName, false)
if (isPackage) {
return when {
isImportedWithPreciseImport(fqName) -> Classification.preciseImport
fqName.parent().isRoot -> Classification.topLevelPackage
else -> Classification.notImported
}
}
return when {
isJavaClassNotToBeUsedInKotlin(fqName) -> Classification.notToBeUsedInKotlin
fqName.parent() == file.packageFqName -> Classification.fromCurrentPackage
ImportInsertHelper.getInstance(file.project).isImportedWithDefault(importPath, file) -> Classification.defaultImport
isImportedWithPreciseImport(fqName) -> Classification.preciseImport
isImportedWithAllUnderImport(fqName) -> Classification.allUnderImport
hasPreciseImportFromPackage(fqName.parent()) -> Classification.siblingImported
else -> Classification.notImported
}
}
private fun isImportedWithPreciseImport(name: FqName) = name in preciseImports
private fun isImportedWithAllUnderImport(name: FqName) = name.parent() in allUnderImports && name !in excludedImports
private fun hasPreciseImportFromPackage(packageName: FqName) = packageName in preciseImportPackages
}
fun isJavaClassNotToBeUsedInKotlin(fqName: FqName): Boolean =
JavaToKotlinClassMap.isJavaPlatformClass(fqName) || JavaAnnotationMapper.javaToKotlinNameMap[fqName] != null
|
apache-2.0
|
be89322964a26fa25b171f4c5b78627d
| 38.4625 | 158 | 0.691479 | 5.341794 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/nullability/NullabilityBoundTypeEnhancer.kt
|
4
|
5471
|
// 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.nj2k.inference.nullability
import javaslang.control.Option
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.nj2k.inference.common.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue
import org.jetbrains.kotlin.resolve.calls.smartcasts.Nullability
import org.jetbrains.kotlin.resolve.jvm.checkers.mustNotBeNull
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
private fun <T> Option<T>.getOrNull(): T? = getOrElse(null as T?)
class NullabilityBoundTypeEnhancer(private val resolutionFacade: ResolutionFacade) : BoundTypeEnhancer() {
override fun enhance(
expression: KtExpression,
boundType: BoundType,
inferenceContext: InferenceContext
): BoundType = when {
expression.isNullExpression() ->
WithForcedStateBoundType(boundType, State.UPPER)
expression is KtCallExpression -> enhanceCallExpression(expression, boundType, inferenceContext)
expression is KtQualifiedExpression && expression.selectorExpression is KtCallExpression ->
enhanceCallExpression(expression.selectorExpression as KtCallExpression, boundType, inferenceContext)
expression is KtNameReferenceExpression ->
boundType.enhanceWith(expression.smartCastEnhancement())
expression is KtLambdaExpression ->
WithForcedStateBoundType(boundType, State.LOWER)
else -> boundType
}
private fun enhanceCallExpression(
expression: KtCallExpression,
boundType: BoundType,
inferenceContext: InferenceContext
): BoundType {
if (expression.resolveToCall(resolutionFacade)?.candidateDescriptor is ConstructorDescriptor) {
return WithForcedStateBoundType(boundType, State.LOWER)
}
val resolved = expression.calleeExpression?.mainReference?.resolve() ?: return boundType
if (inferenceContext.isInConversionScope(resolved)) return boundType
return boundType.enhanceWith(expression.getExternallyAnnotatedForcedState())
}
override fun enhanceKotlinType(
type: KotlinType,
boundType: BoundType,
allowLowerEnhancement: Boolean,
inferenceContext: InferenceContext
): BoundType {
if (type.arguments.size != boundType.typeParameters.size) return boundType
val inner = BoundTypeImpl(
boundType.label,
boundType.typeParameters.zip(type.arguments) { typeParameter, typeArgument ->
TypeParameter(
enhanceKotlinType(
typeArgument.type,
typeParameter.boundType,
allowLowerEnhancement,
inferenceContext
),
typeParameter.variance
)
}
)
val enhancement = when {
type.isMarkedNullable -> State.UPPER
allowLowerEnhancement -> State.LOWER
else -> null
}
return inner.enhanceWith(enhancement)
}
private fun KtReferenceExpression.smartCastEnhancement() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, _ ->
if (dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL) State.LOWER
else null
}
private inline fun KtExpression.analyzeExpressionUponTheTypeInfo(analyzer: (DataFlowValue, DataFlowInfo, KotlinType) -> State?): State? {
val bindingContext = analyze(resolutionFacade)
val type = getType(bindingContext) ?: return null
val dataFlowValue = resolutionFacade.dataFlowValueFactory
.createDataFlowValue(this, type, bindingContext, resolutionFacade.moduleDescriptor)
val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return null
return analyzer(dataFlowValue, dataFlowInfo, type)
}
private fun KtExpression.getExternallyAnnotatedForcedState() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, type ->
if (!type.isNullable()) return@analyzeExpressionUponTheTypeInfo State.LOWER
when {
dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL -> State.LOWER
type.isExternallyAnnotatedNotNull(dataFlowInfo, dataFlowValue) -> State.LOWER
else -> null
}
}
private fun KotlinType.isExternallyAnnotatedNotNull(dataFlowInfo: DataFlowInfo, dataFlowValue: DataFlowValue): Boolean =
mustNotBeNull()?.isFromJava == true && dataFlowInfo.getStableNullability(dataFlowValue).canBeNull()
}
|
apache-2.0
|
acc97a04a79f99376a6a82f09b330e65
| 47.424779 | 158 | 0.724913 | 5.789418 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt
|
1
|
14901
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.imports
import com.intellij.lang.ImportOptimizer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo
import org.jetbrains.kotlin.idea.caches.project.ScriptModuleInfo
import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.references.*
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.*
import org.jetbrains.kotlin.types.error.ErrorFunctionDescriptor
class KotlinImportOptimizer : ImportOptimizer {
override fun supports(file: PsiFile) = file is KtFile
override fun processFile(file: PsiFile): ImportOptimizer.CollectingInfoRunnable {
val ktFile = (file as? KtFile) ?: return DO_NOTHING
val (add, remove, imports) = prepareImports(ktFile) ?: return DO_NOTHING
return object : ImportOptimizer.CollectingInfoRunnable {
override fun getUserNotificationInfo(): String = if (remove == 0)
KotlinBundle.message("import.optimizer.text.zero")
else
KotlinBundle.message(
"import.optimizer.text.non.zero",
remove,
KotlinBundle.message("import.optimizer.text.import", remove),
add,
KotlinBundle.message("import.optimizer.text.import", add)
)
override fun run() = replaceImports(ktFile, imports)
}
}
// The same as com.intellij.pom.core.impl.PomModelImpl.isDocumentUncommitted
// Which is checked in com.intellij.pom.core.impl.PomModelImpl.startTransaction
private val KtFile.isDocumentUncommitted: Boolean
get() {
val documentManager = PsiDocumentManager.getInstance(project)
val cachedDocument = documentManager.getCachedDocument(this)
return cachedDocument != null && documentManager.isUncommited(cachedDocument)
}
private fun prepareImports(file: KtFile): OptimizeInformation? {
ApplicationManager.getApplication().assertReadAccessAllowed()
// Optimize imports may be called after command
// And document can be uncommitted after running that command
// In that case we will get ISE: Attempt to modify PSI for non-committed Document!
if (file.isDocumentUncommitted) return null
val moduleInfo = file.getNullableModuleInfo()
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is ScriptModuleInfo) return null
val oldImports = file.importDirectives
if (oldImports.isEmpty()) return null
//TODO: keep existing imports? at least aliases (comments)
val descriptorsToImport = collectDescriptorsToImport(file, true)
val imports = prepareOptimizedImports(file, descriptorsToImport) ?: return null
val intersect = imports.intersect(oldImports.map { it.importPath })
return OptimizeInformation(
add = imports.size - intersect.size,
remove = oldImports.size - intersect.size,
imports = imports
)
}
private data class OptimizeInformation(val add: Int, val remove: Int, val imports: List<ImportPath>)
private class CollectUsedDescriptorsVisitor(file: KtFile, val progressIndicator: ProgressIndicator? = null) : KtVisitorVoid() {
//private val elementsSize: Int = if (progressIndicator != null) {
// var size = 0
// file.accept(object : KtVisitorVoid() {
// override fun visitElement(element: PsiElement) {
// size += 1
// element.acceptChildren(this)
// }
// })
//
// size
//} else {
// 0
//}
private var elementProgress: Int = 0
private val currentPackageName = file.packageFqName
private val aliases: Map<FqName, List<Name>> = file.importDirectives
.asSequence()
.filter { !it.isAllUnder && it.alias != null }
.mapNotNull { it.importPath }
.groupBy(keySelector = { it.fqName }, valueTransform = { it.importedName as Name })
private val descriptorsToImport = hashSetOf<OptimizedImportsBuilder.ImportableDescriptor>()
private val namesToImport = hashMapOf<FqName, MutableSet<Name>>()
private val abstractRefs = ArrayList<OptimizedImportsBuilder.AbstractReference>()
private val unresolvedNames = hashSetOf<Name>()
val data: OptimizedImportsBuilder.InputData
get() = OptimizedImportsBuilder.InputData(
descriptorsToImport,
namesToImport,
abstractRefs,
unresolvedNames,
)
override fun visitElement(element: PsiElement) {
ProgressIndicatorProvider.checkCanceled()
elementProgress += 1
//progressIndicator?.apply {
// if (elementsSize != 0) {
// fraction = elementProgress / elementsSize.toDouble()
// }
//}
element.acceptChildren(this)
}
override fun visitImportList(importList: KtImportList) {
}
override fun visitPackageDirective(directive: KtPackageDirective) {
}
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
if (element is KtLabelReferenceExpression) return
val references = element.references.ifEmpty { return }
val bindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val isResolved = hasResolvedDescriptor(element, bindingContext)
for (reference in references) {
if (reference !is KtReference) continue
ProgressIndicatorProvider.checkCanceled()
abstractRefs.add(AbstractReferenceImpl(reference))
val names = reference.resolvesByNames
if (!isResolved) {
unresolvedNames += names
}
for (target in reference.targets(bindingContext)) {
val importableDescriptor = target.getImportableDescriptor()
val importableFqName = target.importableFqName ?: continue
val parentFqName = importableFqName.parent()
if (target is PackageViewDescriptor && parentFqName == FqName.ROOT) continue // no need to import top-level packages
if (target !is PackageViewDescriptor && parentFqName == currentPackageName && (importableFqName !in aliases)) continue
if (!reference.canBeResolvedViaImport(target, bindingContext)) continue
if (importableDescriptor.name in names && isAccessibleAsMember(importableDescriptor, element, bindingContext)) {
continue
}
val descriptorNames = (aliases[importableFqName].orEmpty() + importableFqName.shortName()).intersect(names)
namesToImport.getOrPut(importableFqName) { hashSetOf() } += descriptorNames
descriptorsToImport += OptimizedImportsBuilder.ImportableDescriptor(importableDescriptor, importableFqName)
}
}
}
private fun isAccessibleAsMember(target: DeclarationDescriptor, place: KtElement, bindingContext: BindingContext): Boolean {
if (target.containingDeclaration !is ClassDescriptor) return false
fun isInScope(scope: HierarchicalScope): Boolean {
return when (target) {
is FunctionDescriptor ->
scope.findFunction(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
is PropertyDescriptor ->
scope.findVariable(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
is ClassDescriptor ->
scope.findClassifier(target.name, NoLookupLocation.FROM_IDE) == target
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
else -> false
}
}
val resolutionScope = place.getResolutionScope(bindingContext, place.getResolutionFacade())
val noImportsScope = resolutionScope.replaceImportingScopes(null)
if (isInScope(noImportsScope)) return true
// classes not accessible through receivers, only their constructors
return if (target is ClassDescriptor) false
else resolutionScope.getImplicitReceiversHierarchy().any { isInScope(it.type.memberScope.memberScopeAsImportingScope()) }
}
private class AbstractReferenceImpl(private val reference: KtReference) : OptimizedImportsBuilder.AbstractReference {
override val element: KtElement
get() = reference.element
override val dependsOnNames: Collection<Name>
get() {
val resolvesByNames = reference.resolvesByNames
if (reference is KtInvokeFunctionReference) {
val additionalNames =
(reference.element.calleeExpression as? KtNameReferenceExpression)?.mainReference?.resolvesByNames
if (additionalNames != null) {
return resolvesByNames + additionalNames
}
}
return resolvesByNames
}
override fun resolve(bindingContext: BindingContext) = reference.resolveToDescriptors(bindingContext)
override fun toString() = when (reference) {
is SyntheticPropertyAccessorReferenceDescriptorImpl -> {
reference.toString().replace(
"SyntheticPropertyAccessorReferenceDescriptorImpl",
if (reference.getter) "Getter" else "Setter"
)
}
else -> reference.toString().replace("DescriptorsImpl", "")
}
}
}
companion object {
fun collectDescriptorsToImport(file: KtFile, inProgressBar: Boolean = false): OptimizedImportsBuilder.InputData {
val progressIndicator = if (inProgressBar) ProgressIndicatorProvider.getInstance().progressIndicator else null
progressIndicator?.text = KotlinBundle.message("import.optimizer.progress.indicator.text.collect.imports.for", file.name)
progressIndicator?.isIndeterminate = false
val visitor = CollectUsedDescriptorsVisitor(file, progressIndicator)
file.accept(visitor)
return visitor.data
}
fun prepareOptimizedImports(file: KtFile, data: OptimizedImportsBuilder.InputData): List<ImportPath>? {
val settings = file.kotlinCustomSettings
val options = OptimizedImportsBuilder.Options(
settings.NAME_COUNT_TO_USE_STAR_IMPORT,
settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS,
isInPackagesToUseStarImport = { fqName -> fqName.asString() in settings.PACKAGES_TO_USE_STAR_IMPORTS }
)
return OptimizedImportsBuilder(file, data, options, file.languageVersionSettings.apiVersion).buildOptimizedImports()
}
fun replaceImports(file: KtFile, imports: List<ImportPath>) {
val manager = PsiDocumentManager.getInstance(file.project)
manager.getDocument(file)?.let { manager.commitDocument(it) }
val importList = file.importList ?: return
val oldImports = importList.imports
val psiFactory = KtPsiFactory(file.project)
for (importPath in imports) {
importList.addBefore(
psiFactory.createImportDirective(importPath),
oldImports.lastOrNull()
) // insert into the middle to keep collapsed state
}
// remove old imports after adding new ones to keep imports folding state
for (import in oldImports) {
import.delete()
}
}
private fun KtReference.targets(bindingContext: BindingContext): Collection<DeclarationDescriptor> {
//class qualifiers that refer to companion objects should be considered (containing) class references
return bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element as? KtReferenceExpression]?.let { listOf(it) }
?: resolveToDescriptors(bindingContext)
}
private val DO_NOTHING = object : ImportOptimizer.CollectingInfoRunnable {
override fun run() = Unit
override fun getUserNotificationInfo() = KotlinBundle.message("import.optimizer.notification.text.unused.imports.not.found")
}
}
}
private fun hasResolvedDescriptor(element: KtElement, bindingContext: BindingContext): Boolean =
if (element is KtCallElement)
element.getResolvedCall(bindingContext) != null
else
element.mainReference?.resolveToDescriptors(bindingContext)?.let { descriptors ->
descriptors.isNotEmpty() && descriptors.none { it is ErrorFunctionDescriptor }
} == true
|
apache-2.0
|
8d304f4c8f9b04512c1eca7794e2c756
| 46.155063 | 140 | 0.652909 | 5.873473 | false | false | false | false |
androidx/androidx
|
compose/material/material/src/desktopMain/kotlin/androidx/compose/material/DesktopMenu.desktop.kt
|
3
|
10917
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.window.rememberCursorPositionProvider
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
/**
* A Material Design [dropdown menu](https://material.io/components/menus#dropdown-menu).
*
* A [DropdownMenu] behaves similarly to a [Popup], and will use the position of the parent layout
* to position itself on screen. Commonly a [DropdownMenu] will be placed in a [Box] with a sibling
* that will be used as the 'anchor'. Note that a [DropdownMenu] by itself will not take up any
* space in a layout, as the menu is displayed in a separate window, on top of other content.
*
* The [content] of a [DropdownMenu] will typically be [DropdownMenuItem]s, as well as custom
* content. Using [DropdownMenuItem]s will result in a menu that matches the Material
* specification for menus. Also note that the [content] is placed inside a scrollable [Column],
* so using a [LazyColumn] as the root layout inside [content] is unsupported.
*
* [onDismissRequest] will be called when the menu should close - for example when there is a
* tap outside the menu, or when the back key is pressed.
*
* [DropdownMenu] changes its positioning depending on the available space, always trying to be
* fully visible. It will try to expand horizontally, depending on layout direction, to the end of
* its parent, then to the start of its parent, and then screen end-aligned. Vertically, it will
* try to expand to the bottom of its parent, then from the top of its parent, and then screen
* top-aligned. An [offset] can be provided to adjust the positioning of the menu for cases when
* the layout bounds of its parent do not coincide with its visual bounds. Note the offset will
* be applied in the direction in which the menu will decide to expand.
*
* Example usage:
* @sample androidx.compose.material.samples.MenuSample
*
* @param expanded Whether the menu is currently open and visible to the user
* @param onDismissRequest Called when the user requests to dismiss the menu, such as by
* tapping outside the menu's bounds
* @param offset [DpOffset] to be added to the position of the menu
*/
@Suppress("ModifierParameter")
@Composable
fun DropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
focusable: Boolean = true,
modifier: Modifier = Modifier,
offset: DpOffset = DpOffset(0.dp, 0.dp),
content: @Composable ColumnScope.() -> Unit
) {
val expandedStates = remember { MutableTransitionState(false) }
expandedStates.targetState = expanded
if (expandedStates.currentState || expandedStates.targetState) {
val transformOriginState = remember { mutableStateOf(TransformOrigin.Center) }
val density = LocalDensity.current
// The original [DropdownMenuPositionProvider] is not yet suitable for large screen devices,
// so we need to make additional checks and adjust the position of the [DropdownMenu] to
// avoid content being cut off if the [DropdownMenu] contains too many items.
// See: https://github.com/JetBrains/compose-jb/issues/1388
val popupPositionProvider = DesktopDropdownMenuPositionProvider(
offset,
density
) { parentBounds, menuBounds ->
transformOriginState.value = calculateTransformOrigin(parentBounds, menuBounds)
}
Popup(
focusable = focusable,
onDismissRequest = onDismissRequest,
popupPositionProvider = popupPositionProvider
) {
DropdownMenuContent(
expandedStates = expandedStates,
transformOriginState = transformOriginState,
modifier = modifier,
content = content
)
}
}
}
/**
* A dropdown menu item, as defined by the Material Design spec.
*
* Example usage:
* @sample androidx.compose.material.samples.MenuSample
*
* @param onClick Called when the menu item was clicked
* @param modifier The modifier to be applied to the menu item
* @param enabled Controls the enabled state of the menu item - when `false`, the menu item
* will not be clickable and [onClick] will not be invoked
* @param contentPadding the padding applied to the content of this menu item
* @param interactionSource the [MutableInteractionSource] representing the different [Interaction]s
* present on this DropdownMenuItem. You can create and pass in your own remembered
* [MutableInteractionSource] if you want to read the [MutableInteractionSource] and customize
* the appearance / behavior of this DropdownMenuItem in different [Interaction]s.
*/
@Composable
fun DropdownMenuItem(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
contentPadding: PaddingValues = MenuDefaults.DropdownMenuItemContentPadding,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable RowScope.() -> Unit
) {
DropdownMenuItemContent(
onClick = onClick,
modifier = modifier,
enabled = enabled,
contentPadding = contentPadding,
interactionSource = interactionSource,
content = content
)
}
/**
*
* A [CursorDropdownMenu] behaves similarly to [Popup] and will use the current position of the mouse
* cursor to position itself on screen.
*
* The [content] of a [CursorDropdownMenu] will typically be [DropdownMenuItem]s, as well as custom
* content. Using [DropdownMenuItem]s will result in a menu that matches the Material
* specification for menus.
*
* @param expanded Whether the menu is currently open and visible to the user
* @param onDismissRequest Called when the user requests to dismiss the menu, such as by
* tapping outside the menu's bounds
*/
@Suppress("ModifierParameter")
@Composable
fun CursorDropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
focusable: Boolean = true,
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit
) {
val expandedStates = remember { MutableTransitionState(false) }
expandedStates.targetState = expanded
if (expandedStates.currentState || expandedStates.targetState) {
val transformOriginState = remember { mutableStateOf(TransformOrigin.Center) }
Popup(
focusable = focusable,
onDismissRequest = onDismissRequest,
popupPositionProvider = rememberCursorPositionProvider()
) {
DropdownMenuContent(
expandedStates = expandedStates,
transformOriginState = transformOriginState,
modifier = modifier,
content = content
)
}
}
}
@Immutable
internal data class DesktopDropdownMenuPositionProvider(
val contentOffset: DpOffset,
val density: Density,
val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
// The min margin above and below the menu, relative to the screen.
val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() }
// The content offset specified using the dropdown offset parameter.
val contentOffsetX = with(density) { contentOffset.x.roundToPx() }
val contentOffsetY = with(density) { contentOffset.y.roundToPx() }
// Compute horizontal position.
val toRight = anchorBounds.left + contentOffsetX
val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width
val toDisplayRight = windowSize.width - popupContentSize.width
val toDisplayLeft = 0
val x = if (layoutDirection == LayoutDirection.Ltr) {
sequenceOf(toRight, toLeft, toDisplayRight)
} else {
sequenceOf(toLeft, toRight, toDisplayLeft)
}.firstOrNull {
it >= 0 && it + popupContentSize.width <= windowSize.width
} ?: toLeft
// Compute vertical position.
val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin)
val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height
val toCenter = anchorBounds.top - popupContentSize.height / 2
val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin
var y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull {
it >= verticalMargin &&
it + popupContentSize.height <= windowSize.height - verticalMargin
} ?: toTop
// Desktop specific vertical position checking
val aboveAnchor = anchorBounds.top + contentOffsetY
val belowAnchor = windowSize.height - anchorBounds.bottom - contentOffsetY
if (belowAnchor >= aboveAnchor) {
y = anchorBounds.bottom + contentOffsetY
}
if (y + popupContentSize.height > windowSize.height) {
y = windowSize.height - popupContentSize.height
}
y = y.coerceAtLeast(0)
onPositionCalculated(
anchorBounds,
IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height)
)
return IntOffset(x, y)
}
}
|
apache-2.0
|
b886febd4fb8cf13e994026d9a5e8947
| 41.815686 | 101 | 0.713749 | 4.969049 | false | false | false | false |
oldcwj/iPing
|
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/SecurityDialog.kt
|
1
|
4052
|
package com.simplemobiletools.commons.dialogs
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.PasswordTypesAdapter
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.helpers.PROTECTION_PIN
import com.simplemobiletools.commons.helpers.SHOW_ALL_TABS
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.views.MyDialogViewPager
import kotlinx.android.synthetic.main.dialog_security.view.*
class SecurityDialog(val activity: BaseSimpleActivity, val requiredHash: String, val showTabIndex: Int, val callback: (hash: String, type: Int) -> Unit) : HashListener {
var dialog: AlertDialog? = null
val view = LayoutInflater.from(activity).inflate(R.layout.dialog_security, null)
lateinit var tabsAdapter: PasswordTypesAdapter
lateinit var viewPager: MyDialogViewPager
init {
view.apply {
viewPager = findViewById(R.id.dialog_tab_view_pager)
viewPager.offscreenPageLimit = 2
tabsAdapter = PasswordTypesAdapter(context, requiredHash, this@SecurityDialog)
viewPager.adapter = tabsAdapter
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
dialog_tab_layout.getTabAt(position)!!.select()
}
})
viewPager.onGlobalLayout {
updateTabVisibility()
}
if (showTabIndex == SHOW_ALL_TABS) {
val textColor = context.baseConfig.textColor
if (!activity.isFingerPrintSensorAvailable())
dialog_tab_layout.removeTabAt(PROTECTION_FINGERPRINT)
dialog_tab_layout.setTabTextColors(textColor, textColor)
dialog_tab_layout.setSelectedTabIndicatorColor(context.baseConfig.primaryColor)
dialog_tab_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabSelected(tab: TabLayout.Tab) {
when {
tab.text.toString().equals(resources.getString(R.string.pattern), true) -> viewPager.currentItem = PROTECTION_PATTERN
tab.text.toString().equals(resources.getString(R.string.pin), true) -> viewPager.currentItem = PROTECTION_PIN
else -> viewPager.currentItem = PROTECTION_FINGERPRINT
}
updateTabVisibility()
}
})
} else {
dialog_tab_layout.beGone()
viewPager.currentItem = showTabIndex
viewPager.allowSwiping = false
}
}
dialog = AlertDialog.Builder(activity)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
override fun receivedHash(hash: String, type: Int) {
callback(hash, type)
dialog!!.dismiss()
}
private fun updateTabVisibility() {
for (i in 0..2) {
tabsAdapter.isTabVisible(i, viewPager.currentItem == i)
}
}
}
|
gpl-3.0
|
15c7f4f010a8580723a0192d67c60b45
| 41.208333 | 169 | 0.642152 | 5.276042 | false | false | false | false |
GunoH/intellij-community
|
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrSwitchExhaustivenessCheckInspection.kt
|
7
|
9920
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.codeInspection.bugs
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.*
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.GrRangeExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GrRangeExpression.BoundaryType
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrSwitchElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSwitchExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.psi.util.isNullLiteral
import javax.swing.JComponent
import kotlin.math.max
class GrSwitchExhaustivenessCheckInspection : BaseInspection() {
private var shouldReportNulls: Boolean = false
@TestOnly
fun enableNullCheck() {
shouldReportNulls = true
}
override fun createGroovyOptionsPanel(): JComponent = panel {
row {
checkBox(GroovyBundle.message("checkbox.report.unmatched.null")).bindSelected(::shouldReportNulls)
}
}
override fun buildVisitor(): BaseInspectionVisitor = object : BaseInspectionVisitor() {
override fun visitSwitchExpression(switchExpression: GrSwitchExpression) {
visitSwitchElement(switchExpression)
super.visitSwitchExpression(switchExpression)
}
private fun visitSwitchElement(switchElement: GrSwitchElement) {
val cases = switchElement.caseSections
if (cases.any { it.isDefault }) {
return
}
val conditionalType = switchElement.condition?.type ?: PsiType.NULL
val patterns = cases.flatMap { it.expressions?.asList() ?: emptyList() }.filterNotNull()
when (conditionalType) {
is PsiPrimitiveType -> handlePrimitiveType(switchElement, conditionalType, patterns)
is PsiClassType -> {
val unboxed = PsiPrimitiveType.getUnboxedType(conditionalType)
if (unboxed != null) {
handlePrimitiveType(switchElement, unboxed, patterns)
}
else {
handleClassType(switchElement, conditionalType, patterns)
}
}
}
}
private fun handleClassType(switchElement: GrSwitchElement, conditionalType: PsiClassType, patterns: List<GrExpression>) {
val clazz = conditionalType.resolve() ?: return
val resolvedPatterns = patterns.mapNotNull { (it as? GrReferenceExpression)?.resolve() }
val elementsToInsert = if (clazz.isEnum) {
checkEnum(clazz, resolvedPatterns)
}
else {
checkPatternMatchingOnType(clazz, resolvedPatterns.filterIsInstance<PsiClass>())
}
val nullElement = if (shouldReportNulls && !(patterns.any { it is GrLiteral && it.isNullLiteral() })) {
listOf(GroovyPsiElementFactory.getInstance(switchElement.project).createLiteralFromValue(null))
}
else {
emptyList()
}
val allElementsToInsert = (elementsToInsert + nullElement)
insertErrors(switchElement, allElementsToInsert.isNotEmpty(), allElementsToInsert)
}
private fun checkEnum(clazz: PsiClass, existingPatterns: List<PsiElement>): List<PsiElement> {
val constants = clazz.allFields.filterIsInstance<PsiEnumConstant>()
val unwrappedPatterns = existingPatterns.flatMap { if (it is GrRangeExpression) unwrapEnumRange(constants, it) else listOf(it) }
return constants - unwrappedPatterns
}
private fun unwrapEnumRange(allConstants : List<PsiEnumConstant>, range : GrRangeExpression) : List<PsiEnumConstant> {
val leftBound = (range.from as? GrReferenceExpression)?.resolve() as? PsiEnumConstant ?: return emptyList()
val rightBound = (range.to as? GrReferenceExpression)?.resolve() as? PsiEnumConstant ?: return emptyList()
val boundaryType = range.boundaryType ?: return emptyList()
val coveredConstants = mutableListOf<PsiEnumConstant>()
var startCollecting = false
for (constant in allConstants) {
if (constant == rightBound) {
if (boundaryType == BoundaryType.CLOSED || boundaryType == BoundaryType.LEFT_OPEN) {
coveredConstants.add(constant)
}
break
}
if (startCollecting) {
coveredConstants.add(constant)
}
if (constant == leftBound) {
startCollecting = true
if (boundaryType == BoundaryType.CLOSED || boundaryType == BoundaryType.RIGHT_OPEN) {
coveredConstants.add(constant)
}
}
}
return coveredConstants
}
private fun checkPatternMatchingOnType(clazz: PsiClass, resolvedClasses: List<PsiClass>): List<PsiElement> {
if (resolvedClasses.any { clazz === it || clazz.isInheritor(it, true) }) {
return emptyList()
}
if (clazz is GrTypeDefinition) {
val permittedSubclasses = PsiUtil.getAllPermittedClassesJvmAware(clazz)
if (permittedSubclasses.isNotEmpty() && (clazz.isInterface || clazz.hasModifierProperty(PsiModifier.ABSTRACT))) {
return permittedSubclasses.flatMap { checkPatternMatchingOnType(it, resolvedClasses) }
}
}
return listOf(clazz)
}
private fun handlePrimitiveType(switchElement: GrSwitchElement,
conditionalType: PsiPrimitiveType,
patterns: List<GrExpression>) = when (conditionalType) {
PsiType.BOOLEAN -> {
val factory = GroovyPsiElementFactory.getInstance(switchElement.project)
val patternTexts = patterns.map { it.text }
val trueLiteral = if ("true" !in patternTexts) factory.createLiteralFromValue(true) else null
val falseLiteral = if ("false" !in patternTexts) factory.createLiteralFromValue(false) else null
val necessaryPatterns = listOfNotNull(trueLiteral, falseLiteral)
insertErrors(switchElement, necessaryPatterns.isNotEmpty(), necessaryPatterns)
}
PsiType.BYTE, PsiType.SHORT, PsiType.INT, PsiType.LONG -> {
val definedRanges = glueRange(patterns)
insertErrors(switchElement, definedRanges.size > 1, emptyList())
val expectedRange = calculateActualRange(conditionalType)
if (definedRanges.size == 1) {
val definedRange = definedRanges.single()
insertErrors(switchElement, definedRange.first > expectedRange.first || definedRange.second < expectedRange.second, emptyList())
}
Unit
}
else -> {
insertErrors(switchElement, true, emptyList())
}
}
private fun calculateActualRange(conditionalType: PsiPrimitiveType): Pair<Long, Long> = when (conditionalType) {
PsiType.BYTE -> Byte.MIN_VALUE.toLong() to Byte.MAX_VALUE.toLong()
PsiType.SHORT -> Short.MIN_VALUE.toLong() to Short.MAX_VALUE.toLong()
PsiType.INT -> Int.MIN_VALUE.toLong() to Int.MAX_VALUE.toLong()
PsiType.LONG -> Long.MIN_VALUE to Long.MAX_VALUE
else -> error("unreachable")
}
private fun glueRange(patterns: List<GrExpression>): List<Pair<Long, Long>> {
// both-inclusive
data class Range(val left: Long, val right: Long)
val ranges = mutableListOf<Range>()
val evaluator = JavaPsiFacade.getInstance(patterns[0].project).constantEvaluationHelper
for (pattern in patterns) {
if (pattern is GrLiteral) {
val evaluated = evaluator.computeConstantExpression(pattern) as? Number
evaluated?.toLong()?.let { ranges.add(Range(it, it)) }
}
else if (pattern is GrRangeExpression) {
val left = evaluator.computeConstantExpression(pattern.from) as? Number
val right = evaluator.computeConstantExpression(pattern.to) as? Number
if (left != null && right != null) {
val boundaryType = pattern.boundaryType
val leftDelta = if (boundaryType == BoundaryType.LEFT_OPEN || boundaryType == BoundaryType.BOTH_OPEN) 1 else 0
val rightDelta = if (boundaryType == BoundaryType.RIGHT_OPEN || boundaryType == BoundaryType.BOTH_OPEN) 1 else 0
ranges.add(Range(left.toLong() + leftDelta, right.toLong() - rightDelta))
}
}
}
ranges.sortBy { it.left }
val collapsedRanges = mutableListOf<Pair<Long, Long>>()
for (range in ranges) {
if (collapsedRanges.isEmpty() || collapsedRanges.last().second < range.left - 1) {
collapsedRanges.add(range.left to range.right)
}
else {
val lastRange = collapsedRanges.removeLast()
collapsedRanges.add(lastRange.first to max(lastRange.second, range.right))
}
}
return collapsedRanges
}
private fun insertErrors(switchElement: GrSwitchElement, reallyInsert: Boolean, missingExpressions : List<PsiElement>) {
if (reallyInsert) {
registerError(switchElement.firstChild,
GroovyBundle.message("inspection.message.switch.expression.does.not.cover.all.possible.outcomes"),
arrayOf(GrAddMissingCaseSectionsFix(missingExpressions, switchElement)),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
}
}
|
apache-2.0
|
e246c1f3cd249f784a4b679a6ff8a7b9
| 45.79717 | 138 | 0.70121 | 4.867517 | false | false | false | false |
YutaKohashi/FakeLineApp
|
app/src/main/java/jp/yuta/kohashi/fakelineapp/views/adapter/TalkRecyclerAdapter.kt
|
1
|
6661
|
package jp.yuta.kohashi.fakelineapp.views.adapter
import android.content.Context
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import jp.yuta.kohashi.fakelineapp.R
import jp.yuta.kohashi.fakelineapp.models.TalkItem
import jp.yuta.kohashi.fakelineapp.utils.Util
import java.util.*
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 18 / 08 / 2017
*/
class TalkRecyclerAdapter(context: Context, items: MutableList<TalkItem>) : RecyclerView.Adapter<TalkRecyclerAdapter.TalkRecyclerViewHolder>() {
var mItems: MutableList<TalkItem> = items
private val mInflater: LayoutInflater = LayoutInflater.from(context)
private val mContext = context
private var mClickAction:((position:Int, itemView:View) -> Unit)? = null
// private var mDataChangeAction:((itemCount:Int) -> Unit)? = null
private var mRecyclerView: RecyclerView? = null
// private var touchHelper: ItemTouchHelper? = null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TalkRecyclerViewHolder {
return TalkRecyclerViewHolder(
mInflater.inflate(
when (viewType) {
TalkItem.WriterType.ME.num -> R.layout.cell_talk_me
TalkItem.WriterType.YOU.num -> R.layout.cell_talk_you
TalkItem.WriterType.DATE.num -> R.layout.cell_talk_date_week
else -> R.layout.cell_talk_you
},
parent,
false
)
,viewType)
}
override fun onBindViewHolder(holder: TalkRecyclerViewHolder, position: Int) {
when(mItems[position].writerType){
TalkItem.WriterType.DATE -> holder.timeTextView!!.text = mItems[position]?.time ?: ""
TalkItem.WriterType.ME -> {
holder.containsTextView!!.text = mItems[position]?.text ?: ""
holder.timeTextView!!.text = mItems[position]?.time ?: ""
holder.readTextView!!.visibility = if (mItems[position].isRead) View.VISIBLE else View.GONE
}
TalkItem.WriterType.YOU -> {
holder.containsTextView!!.text = mItems[position]?.text ?: ""
holder.timeTextView!!.text = mItems[position]?.time ?: ""
if(TextUtils.isEmpty(mItems[position].imgPath)) Util.setImageByGlide(R.drawable.img_default,holder.imgView!!)
else Util.setImageByGlide(Uri.parse(mItems[position].imgPath),holder.imgView!!)
}
}
if(mItems[position].writerType == TalkItem.WriterType.DATE) {
holder.timeTextView!!.text = mItems[position]?.time ?: ""
} else {
holder.containsTextView!!.text = mItems[position]?.text ?: ""
holder.timeTextView!!.text = mItems[position]?.time ?: ""
}
holder.itemView.setOnClickListener { mClickAction?.invoke(holder.adapterPosition, holder.itemView) }
}
override fun getItemCount(): Int {
return mItems.size
}
override fun getItemViewType(position: Int): Int {
return mItems[position].writerType.num
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
super.onAttachedToRecyclerView(recyclerView)
mRecyclerView = recyclerView
helper.attachToRecyclerView(recyclerView)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView?) {
super.onDetachedFromRecyclerView(recyclerView)
helper.attachToRecyclerView(null)
mRecyclerView = null
}
fun setOnClickListener(action:(position:Int,itemView:View) -> Unit){
mClickAction = action
}
// fun setOnDataChangeListener(action:(itemCount:Int) -> Unit){
// mDataChangeAction = action
// }
fun remove(position:Int, animation:Boolean = true){
mItems.removeAt(position)
if(animation)notifyItemRemoved(position)
// mDataChangeAction?.invoke(itemCount)
}
fun add(item:TalkItem, scrollToBottom:Boolean = false){
mItems.add(item)
notifyDataSetChanged()
if(scrollToBottom) mRecyclerView?.scrollToPosition(itemCount - 1)
// mDataChangeAction?.invoke(itemCount)
}
fun move(from:Int, to:Int){
Collections.swap(mItems, from, to)
notifyItemMoved(from, to)
}
private val helper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int {
return makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0)
}
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val fromPos: Int = viewHolder.adapterPosition
val toPos: Int = target.adapterPosition
// Collections.swap(mTalkData.items, fromPos, toPos)
// mAdapter.notifyItemMoved(fromPos, toPos)
move(fromPos, toPos)
return true
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
// 半透明
when (actionState) {
ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.ACTION_STATE_SWIPE -> {
(viewHolder as? TalkRecyclerAdapter.TalkRecyclerViewHolder)?.let {
it.itemView.alpha = 0.6f
}
}
}
}
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) {
super.clearView(recyclerView, viewHolder)
(viewHolder as TalkRecyclerAdapter.TalkRecyclerViewHolder).itemView.alpha = 1.0f
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
}
})
class TalkRecyclerViewHolder(itemView: View, viewType: Int) : RecyclerView.ViewHolder(itemView) {
var containsTextView: TextView? = itemView.findViewById(R.id.cellTextView)
var timeTextView:TextView? = itemView.findViewById(R.id.timeTextView)
var imgView:ImageView? = itemView.findViewById(R.id.circleImageView)
var readTextView:TextView? = itemView.findViewById(R.id.readStateTextView)
}
}
|
mit
|
1ddb8317208c277a519fe45a33977d9b
| 38.856287 | 144 | 0.653043 | 4.879032 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/WrapWithSafeLetCallFix.kt
|
1
|
6563
|
// 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.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.intentions.canBeReplacedWithInvokeCall
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.isNullabilityMismatch
class WrapWithSafeLetCallFix(
expression: KtExpression,
nullableExpression: KtExpression
) : KotlinQuickFixAction<KtExpression>(expression), HighPriorityAction {
private val nullableExpressionPointer = nullableExpression.createSmartPointer()
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("wrap.with.let.call")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val nullableExpression = nullableExpressionPointer.element ?: return
val qualifiedExpression = element.getQualifiedExpressionForSelector()
val receiverExpression = qualifiedExpression?.receiverExpression
val canBeReplacedWithInvokeCall = (nullableExpression.parent as? KtCallExpression)?.canBeReplacedWithInvokeCall() == true
val factory = KtPsiFactory(element)
val nullableText = if (receiverExpression != null && canBeReplacedWithInvokeCall) {
"${receiverExpression.text}${qualifiedExpression.operationSign.value}${nullableExpression.text}"
} else {
nullableExpression.text
}
val validator = NewDeclarationNameValidator(element, nullableExpression, NewDeclarationNameValidator.Target.VARIABLES)
val name = KotlinNameSuggester.suggestNameByName("it", validator)
nullableExpression.replace(factory.createExpression(name))
val underLetExpression = when {
receiverExpression != null && !canBeReplacedWithInvokeCall ->
factory.createExpressionByPattern("$0.$1", receiverExpression, element)
else -> element
}
val wrapped = when (name) {
"it" -> factory.createExpressionByPattern("($0)?.let { $1 }", nullableText, underLetExpression)
else -> factory.createExpressionByPattern("($0)?.let { $1 -> $2 }", nullableText, name, underLetExpression)
}
val replaced = (qualifiedExpression ?: element).replace(wrapped) as KtSafeQualifiedExpression
val receiver = replaced.receiverExpression
if (receiver is KtParenthesizedExpression && KtPsiUtil.areParenthesesUseless(receiver)) {
receiver.replace(KtPsiUtil.safeDeparenthesize(receiver))
}
}
object UnsafeFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement
if (element is KtNameReferenceExpression) {
val resolvedCall = element.resolveToCall()
if (resolvedCall?.call?.callType != Call.CallType.INVOKE) return null
}
val expression = element.getStrictParentOfType<KtExpression>() ?: return null
val (targetExpression, nullableExpression) = if (expression is KtQualifiedExpression) {
val argument = expression.parent as? KtValueArgument ?: return null
val call = argument.getStrictParentOfType<KtCallExpression>() ?: return null
val parameter = call.resolveToCall()?.getParameterForArgument(argument) ?: return null
if (parameter.type.isNullable()) return null
val targetExpression = call.getLastParentOfTypeInRow<KtQualifiedExpression>() ?: call
targetExpression to expression.receiverExpression
} else {
val nullableExpression = (element.parent as? KtCallExpression)?.calleeExpression ?: return null
expression to nullableExpression
}
return WrapWithSafeLetCallFix(targetExpression, nullableExpression)
}
}
object TypeMismatchFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtExpression ?: return null
val argument = element.parent as? KtValueArgument ?: return null
val call = argument.getParentOfType<KtCallExpression>(true) ?: return null
val expectedType: KotlinType
val actualType: KotlinType
when (diagnostic.factory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
Errors.TYPE_MISMATCH_WARNING -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS -> {
val diagnosticWithParameters = ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
else -> return null
}
if (element.isNull() || !isNullabilityMismatch(expected = expectedType, actual = actualType)) return null
return WrapWithSafeLetCallFix(call.getLastParentOfTypeInRow<KtQualifiedExpression>() ?: call, element)
}
}
}
|
apache-2.0
|
a7e7eb7537af3ddde0c03044520274ce
| 53.247934 | 158 | 0.699832 | 6.02663 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/compiler-plugins/noarg/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/noarg/gradleJava/NoArgGradleProjectImportHandler.kt
|
1
|
1897
|
// 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.compilerPlugin.noarg.gradleJava
import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler
import org.jetbrains.kotlin.noarg.NoArgCommandLineProcessor
import org.jetbrains.kotlin.idea.gradleTooling.model.noarg.NoArgModel
class NoArgGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<NoArgModel>() {
override val compilerPluginId = NoArgCommandLineProcessor.PLUGIN_ID
override val pluginName = "noarg"
override val annotationOptionName = NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = KotlinArtifacts.instance.noargCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override val modelKey = NoArgProjectResolverExtension.KEY
override fun getOptions(model: NoArgModel): List<PluginOption> {
val additionalOptions = listOf(
PluginOption(
NoArgCommandLineProcessor.INVOKE_INITIALIZERS_OPTION.optionName,
model.invokeInitializers.toString()
)
)
return super.getOptions(model) + additionalOptions
}
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in NoArgCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
|
apache-2.0
|
182085c7d3f2a56100efb474f3462e1d
| 47.641026 | 158 | 0.773853 | 5.546784 | false | false | false | false |
GunoH/intellij-community
|
xml/xml-psi-impl/src/com/intellij/documentation/mdn/XmlMdnDocumentationProvider.kt
|
2
|
3398
|
// 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 com.intellij.documentation.mdn
import com.intellij.lang.documentation.DocumentationProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.html.dtd.HtmlSymbolDeclaration
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.findParentInFile
import com.intellij.psi.util.findParentOfType
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlElement
import com.intellij.psi.xml.XmlTag
import com.intellij.util.asSafely
import com.intellij.xml.util.HtmlUtil
import com.intellij.xml.util.XmlUtil
import org.jetbrains.annotations.Nls
class XmlMdnDocumentationProvider : DocumentationProvider {
override fun getUrlFor(element: PsiElement, originalElement: PsiElement?): List<String>? =
getMdnDocumentation(element, originalElement)?.let { listOf(it.url) }
override fun generateDoc(element: PsiElement, originalElement: PsiElement?): @Nls String? =
getMdnDocumentation(element, originalElement)?.getDocumentation(true)
override fun getDocumentationElementForLookupItem(psiManager: PsiManager, `object`: Any, element: PsiElement?): PsiElement? {
return null
}
companion object {
private val supportedNamespaces = setOf(HtmlUtil.SVG_NAMESPACE, HtmlUtil.MATH_ML_NAMESPACE, XmlUtil.HTML_URI, XmlUtil.XHTML_URI)
private fun getMdnDocumentation(element: PsiElement, originalElement: PsiElement?): MdnSymbolDocumentation? =
originalElement.takeIf { it is XmlElement }
?.let { PsiTreeUtil.getNonStrictParentOfType<XmlElement>(it, XmlTag::class.java, XmlAttribute::class.java) }
?.let {
when {
it is XmlAttribute && supportedNamespaces.contains(it.parent.getNamespaceByPrefix(it.namespacePrefix)) ->
getHtmlMdnDocumentation(element, it.parent)
it is XmlTag && supportedNamespaces.contains(it.namespace) -> getHtmlMdnDocumentation(element, it)
else -> null
}
}
?: (element as? HtmlSymbolDeclaration)?.let {
getHtmlMdnDocumentation(element, PsiTreeUtil.getNonStrictParentOfType(originalElement, XmlTag::class.java))
}
?: (element as? XmlTag)
?.takeIf { it.namespace == XmlUtil.XML_SCHEMA_URI }
?.let { schemaElement ->
val targetNamespace =
schemaElement
.findParentInFile { it is XmlTag && it.localName == "schema" }
?.asSafely<XmlTag>()
?.getAttributeValue("targetNamespace")
?.let {
when (it) {
HtmlUtil.SVG_NAMESPACE -> MdnApiNamespace.Svg
HtmlUtil.MATH_ML_NAMESPACE -> MdnApiNamespace.MathML
XmlUtil.HTML_URI, XmlUtil.XHTML_URI -> MdnApiNamespace.Html
else -> null
}
} ?: return@let null
val name = schemaElement.getAttributeValue("name") ?: return@let null
when (element.localName) {
"element" -> getHtmlMdnTagDocumentation(targetNamespace, name)
"attribute" -> getHtmlMdnAttributeDocumentation(targetNamespace, originalElement?.findParentOfType<XmlTag>()?.localName, name)
else -> null
}
}
}
}
|
apache-2.0
|
369b76e299a4c1d534ad3e4ba26584b8
| 44.306667 | 158 | 0.695703 | 4.889209 | false | false | false | false |
smmribeiro/intellij-community
|
java/java-impl/src/com/intellij/lang/java/actions/propertyTemplates.kt
|
20
|
2133
|
// 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.lang.java.actions
import com.intellij.psi.*
internal const val FIELD_VARIABLE = "FIELD_NAME_VARIABLE"
internal const val SETTER_PARAM_NAME = "SETTER_PARAM_NAME"
internal interface AccessorTemplateData {
val fieldRef: PsiElement
val typeElement: PsiTypeElement
val endElement: PsiElement?
}
internal class GetterTemplateData(
override val fieldRef: PsiElement,
override val typeElement: PsiTypeElement,
override val endElement: PsiElement?
) : AccessorTemplateData
internal class SetterTemplateData(
override val fieldRef: PsiElement,
override val typeElement: PsiTypeElement,
val parameterName: PsiElement,
val parameterRef: PsiElement,
override val endElement: PsiElement?
) : AccessorTemplateData
internal fun PsiMethod.extractGetterTemplateData(): GetterTemplateData {
val body = requireNotNull(body) { text }
val returnStatement = body.statements.single() as PsiReturnStatement
val fieldReference = returnStatement.returnValue as PsiReferenceExpression
return GetterTemplateData(
fieldRef = requireNotNull(fieldReference.referenceNameElement) { text },
typeElement = requireNotNull(returnTypeElement) { text },
endElement = body.lBrace
)
}
internal fun PsiMethod.extractSetterTemplateData(): SetterTemplateData {
val body = requireNotNull(body) { text }
val assignmentStatement = body.statements.singleOrNull() as? PsiExpressionStatement
val assignment = requireNotNull(assignmentStatement?.expression as? PsiAssignmentExpression) { text }
val fieldReference = assignment.lExpression as PsiReferenceExpression
val parameter = parameterList.parameters.single()
return SetterTemplateData(
fieldRef = requireNotNull(fieldReference.referenceNameElement) { text },
typeElement = requireNotNull(parameter.typeElement) { text },
parameterName = requireNotNull(parameter.nameIdentifier) { text },
parameterRef = requireNotNull(assignment.rExpression) { text },
endElement = body.lBrace
)
}
|
apache-2.0
|
0598fb57d3f15a9db32f68156ff739da
| 39.245283 | 140 | 0.789498 | 5.115108 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/formatter/trailingComma/valueParameters/ParameterListDoNotWrap.kt
|
13
|
5812
|
class A1 {
val x: String
val y: String
constructor(
x: String,
y: String,
) {
this.x = x
this.y = y
}
}
class B1 {
val x: String
val y: String
constructor(
x: String,
y: String
) {
this.x = x
this.y = y
}
}
class C1 {
val x: String
val y: String
constructor(
x: String,
y: String,) {
this.x = x
this.y = y
}
}
class D1 {
val x: String
val y: String
constructor(
x: String,
y: String
,) {
this.x = x
this.y = y
}
}
class A2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String,
) {
this.x = x
this.y = y
this.z = z
}
}
class B2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String
) {
this.x = x
this.y = y
this.z = z
}
}
class C2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String,) {
this.x = x
this.y = y
this.z = z
}
}
class D2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String
,) {
this.x = x
this.y = y
this.z = z
}
}
class A3 {
val x: String
constructor(x: String,) {
this.x = x
}
}
class B3 {
val x: String
constructor(x: String) {
this.x = x
}
}
class C3 {
val x: String
constructor(
x: String,) {
this.x = x
}
}
class D3 {
val x: String
constructor(
x: String
,) {
this.x = x
}
}
class E1 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String, z: String,) {
this.x = x
this.y = y
this.z = z
}
}
class E2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String, z: String) {
this.x = x
this.y = y
this.z = z
}
}
class A1(
val x: String,
y: String,
)
class B1(
val x: String,
val y: String
)
class C1(
val x: String,
val y: String,)
class D1(
val x: String,
val y: String
,)
class A2(
val x: String,
val y: String,
val z: String,
)
class B2(
val x: String,
val y: String,
val z: String
)
class C2(
val x: String,
val y: String,
val z: String,)
class D2(
val x: String,
val y: String,
val z: String
,)
class A3(
val x: String,
)
class B3(
val x: String
)
class C3(
val x: String,)
class D3(
val x: String
,)
class A4(
val x: String ,
val y: String,
val z: String ,
)
class B4(
val x: String,
val y: String,
val z: String
)
class C4(
val x: String,
val y: String,
val z: String ,)
class D4(
val x: String,
val y: String,
val z: String
, )
class E1(
val x: String, val y: String,
val z: String
, )
class E2(
val x: String, val y: String, val z: String
)
class C(
z: String, val v: Int, val x: Int =
42, val y: Int =
42
)
val foo1: (Int, Int) -> Int = fun(
x,
y,
): Int = 42
val foo2: (Int, Int) -> Int = fun(
x,
y
): Int {
return x + y
}
val foo3: (Int, Int) -> Int = fun(
x, y,
): Int {
return x + y
}
val foo4: (Int) -> Int = fun(
x,
): Int = 42
val foo5: (Int) -> Int = fun(
x
): Int = 42
val foo6: (Int) -> Int = fun(x,): Int = 42
val foo7: (Int) -> Int = fun(x): Int = 42
val foo8: (Int, Int, Int) -> Int = fun (x, y: Int, z,): Int {
return x + y
}
val foo9: (Int, Int, Int) -> Int = fun (
x,
y: Int,
z,
): Int = 42
val foo10: (Int, Int, Int) -> Int = fun (
x,
y: Int,
z: Int
): Int = 43
val foo10 = fun (
x: Int,
y: Int,
z: Int
): Int = 43
val foo11 = fun (
x: Int,
y: Int,
z: Int,
): Int = 43
val foo12 = fun (
x: Int, y: Int, z: Int,
): Int = 43
val foo13 = fun (x: Int, y: Int, z: Int,
): Int = 43
val foo14 = fun (x: Int, y: Int, z: Int
,): Int = 43
fun a1(
x: String,
y: String,
) = Unit
fun b1(
x: String,
y: String
) = Unit
fun c1(
x: String,
y: String,) = Unit
fun d1(
x: String,
y: String
,) = Unit
fun a2(
x: String,
y: String,
z: String,
) = Unit
fun b2(
x: String,
y: String,
z: String
) = Unit
fun c2(
x: String,
y: String,
z: String,) = Unit
fun d2(
x: String,
y: String,
z: String
,) = Unit
fun a3(
x: String,
) = Unit
fun b3(
x: String
) = Unit
fun c3(
x: String,) = Unit
fun d3(
x: String
,) = Unit
fun a4(
x: String
,
y: String,
z: String ,
) = Unit
fun b4(
x: String,
y: String,
z: String
) = Unit
fun c4(x: String,
y: String,
z: String ,) = Unit
fun d4(
x: String,
y: String,
z: String
, ) = Unit
fun foo(
x: Int =
42
) {
}
class C(
val x: Int =
42
)
class G(
val x: String, val y: String
= "", /* */ val z: String
)
class G(
val x: String, val y: String
= "" /* */, /* */ val z: String
)
class H(
val x: String, /*
*/ val y: String,
val z: String ,)
class J(
val x: String, val y: String , val z: String /*
*/
, )
class K(
val x: String, val y: String,
val z: String
, )
class L(
val x: String, val y: String, val z: String // adwd
)
// SET_TRUE: ALLOW_TRAILING_COMMA
// SET_INT: METHOD_PARAMETERS_WRAP = 0
|
apache-2.0
|
ee4102ac504e642568263009dab47835
| 11.607375 | 61 | 0.455093 | 2.844836 | false | false | false | false |
smmribeiro/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/daemon/problems/Member.kt
|
4
|
7596
|
// 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.codeInsight.daemon.problems
import com.intellij.psi.*
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.SearchScope
internal class ScopedMember(val member: Member, val scope: SearchScope) {
val name = member.name
internal fun hasChanged(other: ScopedMember) = member.hasChanged(other.member)
override fun equals(other: Any?) = other is ScopedMember && member == other.member
override fun hashCode(): Int = member.hashCode()
override fun toString(): String {
return "ScopedMember(member=$member, scope=$scope)"
}
companion object {
internal fun create(psiMember: PsiMember,
scope: SearchScope = PsiSearchHelper.getInstance(psiMember.project).getUseScope(psiMember)): ScopedMember? {
val member = Member.create(psiMember) ?: return null
return ScopedMember(member, scope)
}
}
}
internal sealed class Member(open val name: String, open val modifiers: Set<String>) {
internal open fun hasChanged(other: Member): Boolean {
return name != other.name || modifiers != other.modifiers
}
protected abstract fun copy(modifiers: MutableSet<String>): Member
companion object {
internal fun create(psiMember: PsiMember) = when (psiMember) {
is PsiMethod -> Method.create(psiMember)
is PsiField -> Field.create(psiMember)
is PsiClass -> Class.create(psiMember)
is PsiEnumConstant -> EnumConstant.create(psiMember)
else -> null
}
private fun extractModifiers(psiModifierList: PsiModifierList?): Set<String> {
if (psiModifierList == null) return mutableSetOf()
return PsiModifier.MODIFIERS.filterTo(mutableSetOf()) { psiModifierList.hasModifierProperty(it) }
}
private fun getReferencedClassesNames(referenceList: PsiReferenceList?): Set<String> {
if (referenceList == null) return emptySet()
return referenceList.referenceElements.mapTo(mutableSetOf()) { it.qualifiedName }
}
private fun getTypeParameters(typeParametersList: PsiTypeParameterList?): List<String> {
if (typeParametersList == null) return emptyList()
return typeParametersList.typeParameters.map { it.text }
}
}
internal data class EnumConstant(override val name: String, override val modifiers: Set<String>) : Member(name, modifiers) {
override fun copy(modifiers: MutableSet<String>): Member = copy(name = this.name, modifiers = modifiers)
companion object {
internal fun create(psiEnumConstant: PsiEnumConstant): EnumConstant {
val name = psiEnumConstant.name
val modifiers = extractModifiers(psiEnumConstant.modifierList)
return EnumConstant(name, modifiers)
}
}
}
internal data class Field(override val name: String,
override val modifiers: Set<String>,
val type: String) : Member(name, modifiers) {
override fun hasChanged(other: Member): Boolean {
return other !is Field || super.hasChanged(other) || type != other.type
}
override fun copy(modifiers: MutableSet<String>): Member = copy(name = name, modifiers = modifiers, type = type)
companion object {
internal fun create(psiField: PsiField): Field? {
val name = psiField.name
val modifiers = extractModifiers(psiField.modifierList)
val type = psiField.type.canonicalText
return Field(name, modifiers, type)
}
}
}
internal data class Method(override val name: String,
override val modifiers: Set<String>,
val returnType: String?,
val paramTypes: List<String>,
val throwsTypes: List<String>,
val typeParametersList: List<String>) : Member(name, modifiers) {
override fun hasChanged(other: Member): Boolean {
return other !is Method || super.hasChanged(other) || returnType != other.returnType ||
paramTypes != other.paramTypes || throwsTypes != other.throwsTypes ||
typeParametersList != other.typeParametersList
}
override fun copy(modifiers: MutableSet<String>): Member = copy(name = name, modifiers = modifiers, returnType = returnType,
paramTypes = paramTypes, throwsTypes = throwsTypes,
typeParametersList = typeParametersList)
companion object {
internal fun create(psiMethod: PsiMethod): Method? {
val returnType = psiMethod.returnType?.canonicalText
if (returnType == null && !psiMethod.isConstructor) return null
val name = psiMethod.name
val modifiers = extractModifiers(psiMethod.modifierList)
val paramTypes = psiMethod.parameterList.parameters.map { it.type.canonicalText }
val throwsTypes = psiMethod.throwsList.referencedTypes.map { it.canonicalText }
val typeParameterList = getTypeParameters(psiMethod.typeParameterList)
return Method(name, modifiers, returnType, paramTypes, throwsTypes, typeParameterList)
}
}
}
internal data class Class(override val name: String,
override val modifiers: Set<String>,
val isEnum: Boolean,
val isInterface: Boolean,
val isAnnotationType: Boolean,
val extendsList: Set<String>,
val implementsList: Set<String>,
val permitsList: Set<String>,
val typeParametersList: List<String>) : Member(name, modifiers) {
override fun hasChanged(other: Member): Boolean {
return other !is Class || super.hasChanged(other) ||
isEnum != other.isEnum || isInterface != other.isInterface || isAnnotationType != other.isAnnotationType ||
extendsList != other.extendsList || implementsList != other.implementsList || permitsList != other.permitsList ||
typeParametersList != other.typeParametersList
}
override fun copy(modifiers: MutableSet<String>): Member = copy(name = name, modifiers = modifiers, isEnum = isEnum,
isInterface = isInterface, isAnnotationType = isAnnotationType,
extendsList = extendsList, implementsList = implementsList,
typeParametersList = typeParametersList)
companion object {
internal fun create(psiClass: PsiClass): Class? {
val name = psiClass.name ?: return null
val modifiers = extractModifiers(psiClass.modifierList)
val isEnum = psiClass.isEnum
val isInterface = psiClass.isInterface
val isAnnotationType = psiClass.isAnnotationType
val extendsList = getReferencedClassesNames(psiClass.extendsList)
val implementsList = getReferencedClassesNames(psiClass.implementsList)
val permitsList = getReferencedClassesNames(psiClass.permitsList)
val typeParametersList = getTypeParameters(psiClass.typeParameterList)
return Class(name, modifiers, isEnum, isInterface, isAnnotationType, extendsList, implementsList, permitsList, typeParametersList)
}
}
}
}
|
apache-2.0
|
ee19661d03d94232b199f5a5cd7abda2
| 45.042424 | 140 | 0.647446 | 5.58119 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/curl_command/src/main/kotlin/ch/rmy/curlcommand/CurlParser.kt
|
1
|
5235
|
package ch.rmy.curlcommand
import java.net.URLEncoder
class CurlParser private constructor(arguments: List<String>) {
private val builder = CurlCommand.Builder()
init {
val args = arguments.toMutableList()
val iterator = args.listIterator()
var urlFound = false
loop@ while (iterator.hasNext()) {
val index = iterator.nextIndex()
var argument = iterator.next()
if (argument.equals("curl", ignoreCase = true) && index == 0) {
continue
}
if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 2) {
val argumentParameter = argument.substring(2)
argument = argument.substring(0, 2)
iterator.add(argumentParameter)
iterator.previous()
}
// arguments with 1 parameter
if (iterator.hasNext()) {
when (argument) {
"-X", "--request" -> {
builder.method(iterator.next())
continue@loop
}
"-x", "--proxy" -> {
val parts = iterator.next().split(":")
builder.proxy(parts[0], parts.getOrNull(1)?.toIntOrNull() ?: 3128)
continue@loop
}
"-H", "--header" -> {
val header = iterator.next().split(":", limit = 2)
if (header.size == 2) {
builder.header(header[0], header[1].removePrefix(" "))
}
continue@loop
}
"-d", "--data", "--data-binary", "--data-urlencode" -> {
builder.methodIfNotYetSet("POST")
var dataItems = iterator.next().split("&")
if (argument == "--data-urlencode") {
dataItems = dataItems.map { data ->
if (data.contains("=")) {
val parts = data.split("=", limit = 2)
parts[0] + "=" + URLEncoder.encode(parts[1], "utf-8")
} else {
URLEncoder.encode(data, "utf-8")
}
}
}
if (argument == "--data-binary" && dataItems.any { it.startsWith("@") }) {
builder.usesBinaryData()
} else {
dataItems.forEach { data ->
builder.data(data)
}
}
continue@loop
}
"-F", "--form" -> {
val data = iterator.next()
builder.isFormData()
builder.data(data)
builder.methodIfNotYetSet("POST")
continue@loop
}
"-m", "--max-time", "--connect-timeout" -> {
iterator.next()
.toIntOrNull()
?.let {
builder.timeout(it)
}
continue@loop
}
"-u", "--user" -> {
val credentials = iterator.next().split(":", limit = 2)
builder.username(credentials[0])
if (credentials.size > 1) {
builder.password(credentials[1])
}
continue@loop
}
"-A", "--user-agent" -> {
builder.header("User-Agent", iterator.next())
continue@loop
}
"--url" -> {
builder.url(iterator.next())
continue@loop
}
"-e", "--referer" -> {
builder.header("Referer", iterator.next())
continue@loop
}
}
}
// arguments with 0 parameters
when (argument) {
"-G", "--get" -> {
builder.forceGet()
continue@loop
}
}
if (argument.startsWith("http:", ignoreCase = true) || argument.startsWith("https:", ignoreCase = true)) {
urlFound = true
builder.url(argument)
} else if (!argument.startsWith("-") && !urlFound) {
urlFound = true
builder.url(argument)
}
}
}
companion object {
fun parse(commandString: String): CurlCommand {
val arguments = CommandParser.parseCommand(commandString)
val curlParser = CurlParser(arguments)
return curlParser.builder.build()
}
}
}
|
mit
|
c2d23989469cd4aafa2c6f19c9f416eb
| 38.360902 | 118 | 0.375931 | 5.908578 | false | false | false | false |
aosp-mirror/platform_frameworks_support
|
room/compiler/src/main/kotlin/androidx/room/processor/QueryParameterProcessor.kt
|
1
|
1803
|
/*
* 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.processor
import androidx.room.vo.QueryParameter
import com.google.auto.common.MoreTypes
import javax.lang.model.element.VariableElement
import javax.lang.model.type.DeclaredType
class QueryParameterProcessor(
baseContext: Context,
val containing: DeclaredType,
val element: VariableElement,
private val sqlName: String? = null) {
val context = baseContext.fork(element)
fun process(): QueryParameter {
val asMember = MoreTypes.asMemberOf(context.processingEnv.typeUtils, containing, element)
val parameterAdapter = context.typeAdapterStore.findQueryParameterAdapter(asMember)
context.checker.check(parameterAdapter != null, element,
ProcessorErrors.CANNOT_BIND_QUERY_PARAMETER_INTO_STMT)
val name = element.simpleName.toString()
context.checker.check(!name.startsWith("_"), element,
ProcessorErrors.QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE)
return QueryParameter(
name = name,
sqlName = sqlName ?: name,
type = asMember,
queryParamAdapter = parameterAdapter)
}
}
|
apache-2.0
|
03c5ba450a7cb142e8bd1448da4b5415
| 39.066667 | 97 | 0.705491 | 4.683117 | false | false | false | false |
Dissem/Jabit-Server
|
src/main/kotlin/ch/dissem/bitmessage/server/JabitServerConfig.kt
|
1
|
6434
|
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.bitmessage.server
import ch.dissem.bitmessage.BitmessageContext
import ch.dissem.bitmessage.cryptography.bc.BouncyCryptography
import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.payload.Pubkey
import ch.dissem.bitmessage.networking.nio.NioNetworkHandler
import ch.dissem.bitmessage.repository.*
import ch.dissem.bitmessage.server.Constants.ADMIN_LIST
import ch.dissem.bitmessage.server.Constants.BLACKLIST
import ch.dissem.bitmessage.server.Constants.CLIENT_LIST
import ch.dissem.bitmessage.server.Constants.SHORTLIST
import ch.dissem.bitmessage.server.Constants.WHITELIST
import ch.dissem.bitmessage.server.repository.ServerProofOfWorkRepository
import ch.dissem.bitmessage.utils.Singleton
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
@Configuration
class JabitServerConfig {
@Value("\${bitmessage.port}")
private val port: Int = 0
@Value("\${bitmessage.connection.ttl.hours}")
private val connectionTTL: Long = 0
@Value("\${bitmessage.connection.limit}")
private val connectionLimit: Int = 0
@Value("\${database.url}")
private lateinit var dbUrl: String
@Value("\${database.user}")
private lateinit var dbUser: String
@Value("\${database.password}")
private var dbPassword: String? = null
@Bean
fun jdbcConfig() = JdbcConfig(dbUrl, dbUser, dbPassword)
@Bean
fun addressRepo() = JdbcAddressRepository(jdbcConfig())
@Bean
fun inventory() = JdbcInventory(jdbcConfig())
@Bean
fun labelRepo() = JdbcLabelRepository(jdbcConfig())
@Bean
fun messageRepo() = JdbcMessageRepository(jdbcConfig())
@Bean
fun proofOfWorkRepo() = JdbcProofOfWorkRepository(jdbcConfig())
@Bean
fun nodeRegistry() = JdbcNodeRegistry(jdbcConfig())
@Bean
fun networkHandler() = NioNetworkHandler()
@Bean
fun cryptography() = BouncyCryptography().also {
Singleton.initialize(it) // needed for admins and clients
}
@Bean
fun serverListener(): BitmessageContext.Listener =
ServerListener(
admins(), clients(),
whitelist(), shortlist(), blacklist()
)
@Bean
fun serverProofOfWorkRepository() = ServerProofOfWorkRepository(jdbcConfig())
@Bean
fun commandHandler() = ProofOfWorkRequestHandler(serverProofOfWorkRepository(), clients())
@Bean
fun bitmessageContext() = BitmessageContext.build {
addressRepo = addressRepo()
inventory = inventory()
labelRepo = labelRepo()
messageRepo = messageRepo()
nodeRegistry = nodeRegistry()
proofOfWorkRepo = proofOfWorkRepo()
networkHandler = networkHandler()
listener = serverListener()
customCommandHandler = commandHandler()
cryptography = cryptography()
preferences.port = port
preferences.connectionLimit = connectionLimit
preferences.connectionTTL = connectionTTL
}
@Bean
@DependsOn("cryptography")
fun admins() = Utils.readOrCreateList(
ADMIN_LIST,
"""# Admins can send commands to the server.
|
""".trimMargin()
).map { BitmessageAddress(it) }.toMutableSet()
@Bean
@DependsOn("cryptography")
fun clients() = Utils.readOrCreateList(
CLIENT_LIST,
"# Clients may send incomplete objects for proof of work.\n"
).map { BitmessageAddress(it) }.toMutableSet()
@Bean
fun whitelist() = Utils.readOrCreateList(
WHITELIST,
"""# If there are any Bitmessage addresses in the whitelist, only those will be shown.
|# blacklist.conf will be ignored, but shortlist.conf will be applied to whitelisted addresses.
|
""".trimMargin()
)
@Bean
fun shortlist() = Utils.readOrCreateList(
SHORTLIST,
""""# Broadcasts of these addresses will be restricted to the last $SHORTLIST_SIZE entries.
|
|# Time Service:
|BM-BcbRqcFFSQUUmXFKsPJgVQPSiFA3Xash
|
|# Q's Aktivlist:
|BM-GtT7NLCCAu3HrT7dNTUTY9iDns92Z2ND
|
""".trimMargin()
)
@Bean
fun blacklist() = Utils.readOrCreateList(
BLACKLIST,
"""# Bitmessage addresses in this file are being ignored and their broadcasts won't be returned.
|
""".trimMargin()
)
@Bean
fun api(): Docket = Docket(DocumentationType.SWAGGER_2)
.select()
.build()
@Bean
fun identity(): BitmessageAddress {
val identities = bitmessageContext().addresses.getIdentities()
val identity: BitmessageAddress
if (identities.isEmpty()) {
LOG.info("Creating new identity...")
identity = bitmessageContext().createIdentity(false, Pubkey.Feature.DOES_ACK)
LOG.info("Identity " + identity.address + " created.")
} else {
LOG.info("Identities:")
identities.forEach { LOG.info(it.address) }
identity = identities[0]
if (identities.size > 1) {
LOG.info("Using " + identity)
}
}
LOG.info("QR Code:\n" + Utils.qrCode(identity))
return identity
}
companion object {
private val LOG = LoggerFactory.getLogger(JabitServerConfig::class.java)
val SHORTLIST_SIZE = 5
}
}
|
apache-2.0
|
aafc59c3ac1c6dd2df0997aa87f308fa
| 32.336788 | 111 | 0.660398 | 4.717009 | false | true | false | false |
Dissem/Jabit-Server
|
src/main/kotlin/ch/dissem/bitmessage/server/ServerListener.kt
|
1
|
7070
|
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.bitmessage.server
import ch.dissem.bitmessage.BitmessageContext
import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.Plaintext
import ch.dissem.bitmessage.entity.Plaintext.Encoding.EXTENDED
import ch.dissem.bitmessage.entity.Plaintext.Type.MSG
import ch.dissem.bitmessage.entity.valueobject.extended.Message
import ch.dissem.bitmessage.server.Constants.ADMIN_LIST
import ch.dissem.bitmessage.server.Constants.BLACKLIST
import ch.dissem.bitmessage.server.Constants.CLIENT_LIST
import ch.dissem.bitmessage.server.Constants.SHORTLIST
import ch.dissem.bitmessage.server.Constants.WHITELIST
import org.slf4j.LoggerFactory
import java.util.*
/**
* @author Christian Basler
*/
class ServerListener(private val admins: MutableCollection<BitmessageAddress>,
private val clients: MutableCollection<BitmessageAddress>,
private val whitelist: MutableCollection<String>,
private val shortlist: MutableCollection<String>,
private val blacklist: MutableCollection<String>) : BitmessageContext.Listener.WithContext {
private lateinit var ctx: BitmessageContext
private val identity: BitmessageAddress by lazy {
val identities = ctx.addresses.getIdentities()
if (identities.isEmpty()) {
ctx.createIdentity(false)
} else {
identities[0]
}
}
override fun setContext(ctx: BitmessageContext) {
this.ctx = ctx
}
override fun receive(plaintext: Plaintext) {
if (admins.contains(plaintext.from)) {
val command = plaintext.subject!!.trim { it <= ' ' }.toLowerCase().split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val data = plaintext.text
if (command.size == 1) {
when (command[0].toLowerCase()) {
"status" -> {
val response = Plaintext.Builder(MSG)
response.from(identity)
response.to(plaintext.from)
if (plaintext.encoding == EXTENDED) {
response.message(
Message.Builder()
.subject("RE: status")
.body(ctx.status().toString())
.addParent(plaintext)
.build()
)
} else {
response.message("RE: status", ctx.status().toString())
}
ctx.send(response.build())
}
else -> LOG.info("ignoring unknown command " + plaintext.subject!!)
}
} else if (command.size == 2) {
when (command[1].toLowerCase()) {
"client", "clients" -> updateUserList(CLIENT_LIST, clients, command[0], data)
"admin", "admins", "administrator", "administrators" -> updateUserList(ADMIN_LIST, admins, command[0], data)
"whitelist" -> updateList(WHITELIST, whitelist, command[0], data)
"shortlist" -> updateList(SHORTLIST, shortlist, command[0], data)
"blacklist" -> updateList(BLACKLIST, blacklist, command[0], data)
else -> LOG.info("ignoring unknown command " + plaintext.subject!!)
}
}
}
}
private fun updateUserList(file: String, list: MutableCollection<BitmessageAddress>, command: String, data: String?) {
when (command.toLowerCase()) {
"set" -> {
list.clear()
val scanner = Scanner(data!!)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
try {
list.add(BitmessageAddress(line))
} catch (e: Exception) {
LOG.info("$command $file: ignoring line: $line")
}
}
Utils.saveList(file, list.map { it.address })
}
"add" -> {
val scanner = Scanner(data!!)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
try {
list.add(BitmessageAddress(line))
} catch (e: Exception) {
LOG.info("$command $file: ignoring line: $line")
}
}
Utils.saveList(file, list.map { it.address })
}
"remove" -> {
list.removeIf { address -> data!!.contains(address.address) }
Utils.saveList(file, list.map { it.address })
}
else -> LOG.info("unknown command $command on list $file")
}
}
private fun updateList(file: String, list: MutableCollection<String>, command: String, data: String?) {
when (command.toLowerCase()) {
"set" -> {
list.clear()
val scanner = Scanner(data!!)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
try {
list.add(BitmessageAddress(line).address)
} catch (e: Exception) {
LOG.info("$command $file: ignoring line: $line")
}
}
Utils.saveList(file, list)
}
"add" -> {
val scanner = Scanner(data!!)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
try {
list.add(BitmessageAddress(line).address)
} catch (e: Exception) {
LOG.info("$command $file: ignoring line: $line")
}
}
Utils.saveList(file, list)
}
"remove" -> {
list.removeAll { data!!.contains(it) }
Utils.saveList(file, list)
}
else -> LOG.info("unknown command $command on list $file")
}
}
companion object {
private val LOG = LoggerFactory.getLogger(ServerListener::class.java)
}
}
|
apache-2.0
|
87b4253148ca85b8136dc6f7a63cad54
| 40.345029 | 148 | 0.524611 | 5.153061 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/problem/rest/resource/dependency/CreationChain.kt
|
1
|
1605
|
package org.evomaster.core.problem.rest.resource.dependency
import org.evomaster.core.database.DbAction
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.search.service.Randomness
/**
* to present a chain of actions to create a resource with its dependent resource(s)
* @property isComplete indicates whether the chain is complete.
* If isComplete is FALSE, it means that actions for creating the resource or dependent resources cannot be found.
* @property additionalInfo carries info about first resource that cannot be created if isComplete is FALSE, otherwise it is Blank.
*/
abstract class CreationChain(
private var isComplete : Boolean = false,
var additionalInfo : String = ""
){
fun confirmComplete(){
isComplete = true
}
fun confirmIncomplete(){
isComplete = false
}
fun confirmIncomplete(info : String){
isComplete = false
additionalInfo = info
}
fun isComplete() :Boolean = isComplete
}
class PostCreationChain(val actions: MutableList<RestCallAction>, private var failToCreate : Boolean = false) : CreationChain(){
fun confirmFailure(){
failToCreate = true
}
fun createPostChain(randomness: Randomness) : List<RestCallAction>{
return actions.map {
val a = (it.copy() as RestCallAction)
a.randomize(randomness, false)
a
}
}
}
class DBCreationChain(val actions: MutableList<DbAction>) : CreationChain()
class CompositeCreationChain(val actions: MutableList<Any>) : CreationChain()
|
lgpl-3.0
|
82904789271d4e725ead52f552f076e4
| 31.12 | 131 | 0.702181 | 4.908257 | false | false | false | false |
BraisGabin/hanabi-kotlin
|
hanabi/src/test/kotlin/com/braisgabin/hanabi/GameTest.kt
|
1
|
12008
|
package com.braisgabin.hanabi
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Assert.assertThat
import org.junit.Test
class GameTest {
@Test
fun ended_for_too_much_fails() {
build {
with_fails(3)
} assert {
then_is_ended()
}
}
@Test
fun not_ended_because_few_fails() {
build {
with_fails(2)
} assert {
then_is_not_ended()
}
}
@Test
fun ended_because_win() {
build {
with_table(listOf(5, 5, 5, 5, 5))
} assert {
then_is_ended()
}
}
@Test
fun not_ended_because_no_win() {
build {
with_table(listOf(4, 5, 5, 5, 5))
} assert {
then_is_not_ended()
}
}
@Test
fun ended_because_no_more_turn() {
build {
with_remaining_turn(0)
} assert {
then_is_ended()
}
}
@Test
fun not_ended_because_more_turn() {
build {
with_remaining_turn(2)
} assert {
then_is_not_ended()
}
}
@Test
fun apply_unknown_action_throws_an_illegal_argument_exception() {
test {
when_apply(object : Hanabi.Action {})
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun apply_an_action_with_ended_game_throws_an_illegal_state_exception() {
build {
with_remaining_turn(0)
} test {
when_discard_card(0)
} assert {
then_throw_an_illegal_state_exception()
}
}
@Test
fun discard_with_less_than_8_hints_gives_a_hint() {
build {
with_hints(4)
} test {
when_discard_card(0)
} assert {
then_there_are_hints(5)
}
}
@Test
fun discard_with_8_hints_gives_no_hint() {
build {
with_hints(8)
} test {
when_discard_card(0)
} assert {
then_there_are_hints(8)
}
}
@Test
fun discard_end_your_turn() {
test {
when_discard_card(0)
} assert {
then_play_the_next_player()
}
}
@Test
fun discard_removes_your_card() {
test {
when_discard_card(0)
} assert {
then_you_dont_have_that_card()
}
}
@Test
fun discard_gives_you_the_next_from_the_deck() {
test {
when_discard_card(0)
} assert {
then_you_have_the_next_deck_card()
}
}
@Test
fun discard_when_there_are_not_more_cards_in_deck_lefts_you_with_a_smaller_hand() {
build {
with_empty_deck()
} test {
when_discard_card(0)
} assert {
then_you_have_a_hand_smaller_by_one()
}
}
@Test
fun play_with_an_incorrect_card_increase_the_fails_by_1() {
build {
with_table(listOf(3, 0, 0))
with_hints(4)
with_fails(0)
with_playable_hand(listOf(Card(0, 3), Card(1, 5), Card(2, 5), Card(3, 5)))
} test {
when_play_card(0)
} assert {
then_there_are_fails(1)
then_there_are_hints(4)
then_there_are_table(listOf(3, 0, 0))
}
}
@Test
fun play_with_a_correct_card_increase_the_table_value_at_that_color_and_not_changes_hints() {
build {
with_table(listOf(3, 0, 0))
with_hints(4)
with_playable_hand(listOf(Card(0, 4), Card(1, 5), Card(2, 5), Card(3, 5)))
} test {
when_play_card(0)
} assert {
then_there_are_fails(0)
then_there_are_hints(4)
then_there_are_table(listOf(4, 0, 0))
}
}
@Test
fun play_with_a_correct_5card_increases_hints_by_1_if_less_than_8() {
build {
with_table(listOf(4, 0, 0))
with_hints(4)
with_playable_hand(listOf(Card(0, 5), Card(1, 5), Card(2, 5), Card(3, 5)))
} test {
when_play_card(0)
} assert {
then_there_are_hints(5)
then_there_are_table(listOf(5, 0, 0))
}
}
@Test
fun play_with_a_correct_5card_not_increases_hints_by_1_if_there_are_8() {
build {
with_table(listOf(4, 0, 0))
with_hints(8)
with_playable_hand(listOf(Card(0, 5), Card(1, 5), Card(2, 5), Card(3, 5)))
} test {
when_play_card(0)
} assert {
then_there_are_hints(8)
then_there_are_table(listOf(5, 0, 0))
}
}
@Test
fun play_end_your_turn() {
test {
when_play_card(0)
} assert {
then_play_the_next_player()
}
}
@Test
fun play_removes_your_card() {
test {
when_play_card(0)
} assert {
then_you_dont_have_that_card()
}
}
@Test
fun play_gives_you_the_next_from_the_deck() {
test {
when_play_card(0)
} assert {
then_you_have_the_next_deck_card()
}
}
@Test
fun play_when_there_are_not_more_cards_in_deck_lefts_you_with_a_smaller_hand() {
build {
with_empty_deck()
} test {
when_play_card(0)
} assert {
then_you_have_a_hand_smaller_by_one()
}
}
@Test
fun color_hint_to_yourself() {
build {
} test {
when_give_a_color_hint(0, 1)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun color_hint_to_unknown_player() {
build {
} test {
when_give_a_color_hint(6, 1)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun color_hint_to_player_that_doesnt_have() {
build {
} test {
when_give_a_color_hint(1, 2)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun color_hint_without_hints() {
build {
with_hints(0)
} test {
when_give_a_color_hint(1, 1)
} assert {
then_throw_an_illegal_state_exception()
}
}
@Test
fun color_hint_reduce_hints() {
build {
with_hints(4)
} test {
when_give_a_color_hint(1, 1)
} assert {
then_there_are_hints(3)
}
}
@Test
fun number_hint_to_yourself() {
build {
} test {
when_give_a_number_hint(0, 1)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun number_hint_to_unknown_player() {
build {
} test {
when_give_a_number_hint(6, 1)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun number_hint_to_player_that_doesnt_have() {
build {
} test {
when_give_a_number_hint(1, 8)
} assert {
then_throw_an_illegal_argument_exception()
}
}
@Test
fun number_hint_without_hints() {
build {
with_hints(0)
} test {
when_give_a_number_hint(1, 1)
} assert {
then_throw_an_illegal_state_exception()
}
}
@Test
fun number_hint_reduce_hints() {
build {
with_hints(4)
} test {
when_give_a_number_hint(1, 1)
} assert {
then_there_are_hints(3)
}
}
private fun build(func: GameBuilder.() -> Unit) = GameBuilder().apply(func)
private fun test(func: Tester.() -> Unit) = GameBuilder().test(func)
class GameBuilder {
private var deck: Deck? = null
private var hands: List<Hand>? = null
private var players: Int = 4
private var handSize: Int = 4
private var playableHand: Hand? = null
private var table: Table = Table(listOf(0, 0, 0, 0, 0))
private var hints: Int = 8
private var fails: Int = 0
private var remainingTurns: Int? = null
fun with_fails(fails: Int) {
this.fails = fails
}
fun with_playable_hand(cards: List<Card>) {
playableHand = Hand(cards)
}
fun with_table(table: List<Int>) {
this.table = Table(table)
}
fun with_remaining_turn(remainingTurns: Int?) {
this.remainingTurns = remainingTurns
}
fun with_hints(hints: Int): GameBuilder {
this.hints = hints
return this
}
fun with_empty_deck(): GameBuilder {
this.deck = Deck(emptyList())
return this
}
infix fun test(func: Tester.() -> Unit): Tester {
return Tester(buildGame()).apply(func)
}
infix fun assert(func: Assertions.() -> Unit): Assertions {
return Assertions(listOf(buildGame()), null, null).apply(func)
}
private fun buildGame(): Game {
var deck = deck
if (deck == null) {
deck = Deck(List(20, { Card(0, 20 - it) }))
}
var hands = hands
if (hands == null) {
hands = mutableListOf()
val playableHand = playableHand
if (playableHand != null) {
hands.add(playableHand)
}
for (player in hands.size until players) {
val handCards = mutableListOf<Card>()
(0 until handSize).mapTo(handCards) { Card(1, it + 1) }
hands.add(Hand(handCards))
}
}
return Game(deck, hands, table, hints, fails, remainingTurns)
}
}
class Tester(game: Hanabi) {
private var currentTurn: Hanabi? = game
private var exception: RuntimeException? = null
private val turns: MutableList<Hanabi> = mutableListOf(game)
private var previousPlayedCard: Card? = null
private fun getGame(): Hanabi {
val exception = exception
if (exception != null) {
throw exception
}
return currentTurn!!
}
fun when_play_card(i: Int) {
previousPlayedCard = getGame().hands[0][i]
apply(ActionPlay(i))
}
fun when_discard_card(i: Int) {
previousPlayedCard = getGame().hands[0][i]
apply(ActionDiscard(i))
}
fun when_give_a_color_hint(player: Int, color: Int) {
previousPlayedCard = null
apply(ActionHintColor(player, color))
}
fun when_give_a_number_hint(player: Int, number: Int) {
previousPlayedCard = null
apply(ActionHintNumber(player, number))
}
fun when_apply(action: Hanabi.Action) {
apply(action)
}
private fun apply(action: Hanabi.Action) {
try {
val game = getGame().apply(action)
turns.add(game)
this.currentTurn = game
} catch (ex: RuntimeException) {
currentTurn = null
exception = ex
}
}
infix fun assert(func: Assertions.() -> Unit): Assertions {
return Assertions(turns, exception, previousPlayedCard).apply(func)
}
}
class Assertions(private val turns: List<Hanabi>,
private val exception: Throwable?,
private val previousPlayedCard: Card?) {
private val currentTurn: Hanabi by lazy {
if (exception != null) {
throw exception
} else {
turns.last()
}
}
fun then_is_ended() {
assertThat(currentTurn.ended, `is`(true))
}
fun then_is_not_ended() {
assertThat(currentTurn.ended, `is`(false))
}
fun then_throw_an_illegal_argument_exception() {
return exception(IllegalArgumentException::class.java)
}
fun then_throw_an_illegal_state_exception() {
return exception(IllegalStateException::class.java)
}
private fun exception(clazz: Class<out Throwable>) {
assertThat(exception, `is`(instanceOf(clazz)))
}
fun then_there_are_hints(hints: Int) {
assertThat(currentTurn.hints, `is`(hints))
}
fun then_there_are_fails(fails: Int) {
assertThat(currentTurn.fails, `is`(fails))
}
fun then_play_the_next_player() {
val lastTurn = previousTurn()
assertThat(lastTurn.hands[1], `is`(currentTurn.hands[0]))
}
fun then_you_dont_have_that_card() {
assertThat(currentTurn.hands.last().contains(previousPlayedCard!!), `is`(false))
}
fun then_you_have_the_next_deck_card() {
val lastTurnDeck = previousTurn().deck
val card = lastTurnDeck.last()
assertThat(currentTurn.hands.last().contains(card), `is`(true))
}
fun then_you_have_a_hand_smaller_by_one() {
val previousHandSize = previousTurn().hands[0].size
val currentHandSize = currentTurn.hands.last().size
assertThat(previousHandSize, `is`(currentHandSize + 1))
}
fun then_there_are_table(table: List<Int>) {
assertThat(currentTurn.table as Table, `is`(Table(table)))
}
private fun previousTurn() = turns[turns.size - 2]
private fun Hand.contains(card: Card) = (0 until size).any { this[it] == card }
private fun Hanabi.Deck.last() = this[size - 1]
}
}
|
apache-2.0
|
ff43fd5c0f753b707d425764146bf962
| 21.154982 | 95 | 0.580613 | 3.322634 | false | true | false | false |
savoirfairelinux/ring-client-android
|
ring-android/libjamiclient/src/main/kotlin/net/jami/services/NotificationService.kt
|
1
|
2576
|
/*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Aline Bonnet <[email protected]>
* Author: Adrien Béraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.jami.services
import net.jami.model.*
interface NotificationService {
fun showCallNotification(notifId: Int): Any?
fun cancelCallNotification()
fun removeCallNotification(notifId: Int)
fun handleCallNotification(conference: Conference, remove: Boolean)
fun showMissedCallNotification(call: Call)
fun showTextNotification(accountId: String, conversation: Conversation)
fun cancelTextNotification(accountId: String, contact: Uri)
fun cancelAll()
fun showIncomingTrustRequestNotification(account: Account)
fun cancelTrustRequestNotification(accountID: String)
fun showFileTransferNotification(conversation: Conversation, info: DataTransfer)
fun handleDataTransferNotification(transfer: DataTransfer, conversation: Conversation, remove: Boolean)
fun removeTransferNotification(accountId: String, conversationUri: Uri, fileId: String)
fun getDataTransferNotification(notificationId: Int): Any?
fun cancelFileNotification(notificationId: Int)
//void updateNotification(Object notification, int notificationId);
val serviceNotification: Any
fun onConnectionUpdate(b: Boolean)
fun showLocationNotification(first: Account, contact: Contact)
fun cancelLocationNotification(first: Account, contact: Contact)
companion object {
const val TRUST_REQUEST_NOTIFICATION_ACCOUNT_ID = "trustRequestNotificationAccountId"
const val TRUST_REQUEST_NOTIFICATION_FROM = "trustRequestNotificationFrom"
const val KEY_CALL_ID = "callId"
const val KEY_HOLD_ID = "holdId"
const val KEY_END_ID = "endId"
const val KEY_NOTIFICATION_ID = "notificationId"
}
}
|
gpl-3.0
|
d77d68bb048153ae065b4c967836102e
| 45 | 107 | 0.756505 | 4.517544 | false | false | false | false |
BlueBoxWare/LibGDXPlugin
|
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/inspections/LibGDXJsonInvalidEscapeInspection.kt
|
1
|
3511
|
package com.gmail.blueboxware.libgdxplugin.filetypes.json.inspections
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonElementVisitor
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonString
import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.SuppressForFileFix
import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.SuppressForObjectFix
import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.SuppressForPropertyFix
import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.SuppressForStringFix
import com.gmail.blueboxware.libgdxplugin.message
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import kotlin.math.min
/*
* Copyright 2019 Blue Box Ware
*
* 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.
*/
class LibGDXJsonInvalidEscapeInspection : GdxJsonBaseInspection() {
override fun getStaticDescription() = message("json.inspection.invalid.escape.description")
override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> =
arrayOf(
SuppressForFileFix(getShortID()),
SuppressForObjectFix(getShortID()),
SuppressForPropertyFix(getShortID()),
SuppressForStringFix(getShortID())
)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
object : GdxJsonElementVisitor() {
override fun visitString(o: GdxJsonString) {
var i = 0
while (i < o.text.length - 1) {
if (o.text[i] != '\\') {
i++
continue
}
val c = o.text[i + 1]
if (c == 'u') {
try {
Character.toChars(Integer.parseInt(o.text.substring(i + 2, i + 6), 16))
} catch (e: Exception) {
val maxlen = if (o.isQuoted) o.text.length - 1 else o.text.length
holder.registerProblem(
o, TextRange(i, min(i + 6, maxlen)), message("json.inspection.invalid.escape.message")
)
}
i += 4
continue
} else {
i++
}
if (c !in ESCAPABLE_CHARS) {
holder.registerProblem(
o, TextRange(i - 1, min(i + 1, o.text.length)),
message("json.inspection.invalid.escape.message")
)
}
}
}
}
companion object {
val ESCAPABLE_CHARS = setOf('"', '\\', '/', 'b', 'f', 'n', 'r', 't')
}
}
|
apache-2.0
|
175f787047d99a570e76b97b7d313f17
| 36.351064 | 118 | 0.596981 | 4.917367 | false | false | false | false |
Doist/TodoistPojos
|
src/main/java/com/todoist/pojo/LiveNotification.kt
|
1
|
2742
|
package com.todoist.pojo
open class LiveNotification<C : Collaborator>(
id: String,
var notificationType: String,
open var createdAt: Long,
open var isUnread: Boolean,
// Optional fields, not set in all types.
open var fromUid: String?,
open var projectId: String?,
open var projectName: String?,
open var invitationId: String?,
open var invitationSecret: String?,
open var state: String?,
open var itemId: String?,
open var itemContent: String?,
open var responsibleUid: String?,
open var noteId: String?,
open var noteContent: String?,
open var removedUid: String?,
open var fromUser: C?,
open var accountName: String?,
// Optional fields used in Karma notifications (which are set depends on the karma level).
open var karmaLevel: Int?,
open var completedTasks: Int?,
open var completedInDays: Int?,
open var completedLastMonth: Int?,
open var topProcent: Double?,
open var dateReached: Long?,
open var promoImg: String?,
isDeleted: Boolean
) : Model(id, isDeleted) {
open val isInvitation
get() = notificationType == TYPE_SHARE_INVITATION_SENT ||
notificationType == TYPE_BIZ_INVITATION_CREATED
open val isStatePending get() = state != STATE_ACCEPTED && state != STATE_REJECTED
companion object {
const val TYPE_SHARE_INVITATION_SENT = "share_invitation_sent"
const val TYPE_SHARE_INVITATION_ACCEPTED = "share_invitation_accepted"
const val TYPE_SHARE_INVITATION_REJECTED = "share_invitation_rejected"
const val TYPE_USER_LEFT_PROJECT = "user_left_project"
const val TYPE_USER_REMOVED_FROM_PROJECT = "user_removed_from_project"
const val TYPE_NOTE_ADDED = "note_added"
const val TYPE_ITEM_ASSIGNED = "item_assigned"
const val TYPE_ITEM_COMPLETED = "item_completed"
const val TYPE_ITEM_UNCOMPLETED = "item_uncompleted"
const val TYPE_KARMA_LEVEL = "karma_level"
const val TYPE_BIZ_POLICY_DISALLOWED_INVITATION = "biz_policy_disallowed_invitation"
const val TYPE_BIZ_POLICY_REJECTED_INVITATION = "biz_policy_rejected_invitation"
const val TYPE_BIZ_TRIAL_WILL_END = "biz_trial_will_end"
const val TYPE_BIZ_PAYMENT_FAILED = "biz_payment_failed"
const val TYPE_BIZ_ACCOUNT_DISABLED = "biz_account_disabled"
const val TYPE_BIZ_INVITATION_CREATED = "biz_invitation_created"
const val TYPE_BIZ_INVITATION_ACCEPTED = "biz_invitation_accepted"
const val TYPE_BIZ_INVITATION_REJECTED = "biz_invitation_rejected"
const val STATE_INVITED = "invited"
const val STATE_ACCEPTED = "accepted"
const val STATE_REJECTED = "rejected"
}
}
|
mit
|
ffa116d1af33ebb815b23499679fbfb6
| 41.84375 | 94 | 0.684537 | 4.154545 | false | false | false | false |
davinkevin/Podcast-Server
|
backend/src/test/kotlin/com/github/davinkevin/podcastserver/download/ItemDownloadManagerTest.kt
|
1
|
26702
|
package com.github.davinkevin.podcastserver.download
import com.github.davinkevin.podcastserver.entity.Status
import com.github.davinkevin.podcastserver.manager.downloader.Downloader
import com.github.davinkevin.podcastserver.manager.downloader.DownloadingInformation
import com.github.davinkevin.podcastserver.manager.downloader.DownloadingItem
import com.github.davinkevin.podcastserver.manager.selector.DownloaderSelector
import com.github.davinkevin.podcastserver.messaging.MessagingTemplate
import com.github.davinkevin.podcastserver.service.properties.PodcastServerParameters
import org.apache.commons.io.FilenameUtils
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.Awaitility.await
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mockito
import org.mockito.kotlin.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Import
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import org.springframework.test.context.junit.jupiter.SpringExtension
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.test.StepVerifier
import java.net.URI
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.io.path.Path
/**
* Created by kevin on 06/05/15
*/
@ExtendWith(SpringExtension::class)
class ItemDownloadManagerTest(
@Autowired val downloadExecutor: ThreadPoolTaskExecutor,
@Autowired val idm: ItemDownloadManager
) {
@MockBean private lateinit var messaging: MessagingTemplate
@MockBean private lateinit var repository: DownloadRepository
@MockBean private lateinit var parameters: PodcastServerParameters
@MockBean private lateinit var downloaders: DownloaderSelector
private val date = OffsetDateTime.of(2012, 3, 4, 5, 6, 7, 0, ZoneOffset.UTC)
@AfterEach
fun afterEach() {
Mockito.reset(messaging, repository, downloadExecutor)
downloadExecutor.corePoolSize = 1
}
@Nested
@DisplayName("should use limitParallelDownload")
inner class ShouldUseLimitParallelDownload {
@Test
fun `and change its value`() {
/* Given */
whenever(repository.initQueue(date, 1))
.thenReturn(Mono.empty())
whenever(repository.findAllToDownload(3)).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
idm.limitParallelDownload = 3
/* Then */
await().atMost(1, SECONDS).untilAsserted {
verify(messaging).sendWaitingQueue(emptyList())
}
assertThat(downloadExecutor.corePoolSize).isEqualTo(3)
}
@Test
fun `and reflects value from internal executor`() {
/* Given */
/* When */
/* Then */
assertThat(idm.limitParallelDownload).isEqualTo(1)
}
}
@Nested
@DisplayName("should expose waiting queue")
inner class ShouldExposeWaitingQueue {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
private val item2 = DownloadingItem(
id = UUID.fromString("27455c79-3349-4359-aca9-d4ea2cedc538"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("493b2fa5-8dc3-4d66-8bce-556e60c9a173"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("5be6d50d-8288-47e3-84fe-7eb9e2184466"),
title = "bar"
)
)
@Test
fun `with no item`() {
/* Given */
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.queue)
/* Then */
.expectSubscription()
.verifyComplete()
}
@Test
fun `with items`() {
/* Given */
whenever(repository.findAllWaiting()).thenReturn(Flux.just(item1, item2))
/* When */
StepVerifier.create(idm.queue)
/* Then */
.expectSubscription()
.expectNext(item1)
.expectNext(item2)
.verifyComplete()
}
}
@Nested
@DisplayName("should expose downloading queue")
inner class ShouldExposeDownloadingQueue {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
private val item2 = DownloadingItem(
id = UUID.fromString("27455c79-3349-4359-aca9-d4ea2cedc538"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("493b2fa5-8dc3-4d66-8bce-556e60c9a173"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("5be6d50d-8288-47e3-84fe-7eb9e2184466"),
title = "bar"
)
)
@Test
fun `with no item`() {
/* Given */
whenever(repository.findAllDownloading()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.downloading)
/* Then */
.expectSubscription()
.verifyComplete()
}
@Test
fun `with items`() {
/* Given */
whenever(repository.findAllDownloading()).thenReturn(Flux.just(item1, item2))
/* When */
StepVerifier.create(idm.downloading)
/* Then */
.expectSubscription()
.expectNext(item1)
.expectNext(item2)
.verifyComplete()
}
}
@Nested
@DisplayName("should launch download")
inner class ShouldLaunchDownload {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
private val item2 = DownloadingItem(
id = UUID.fromString("27455c79-3349-4359-aca9-d4ea2cedc538"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("493b2fa5-8dc3-4d66-8bce-556e60c9a173"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("5be6d50d-8288-47e3-84fe-7eb9e2184466"),
title = "bar"
)
)
@Test
fun `with no item to download`() {
/* Given */
whenever(parameters.limitDownloadDate()).thenReturn(date)
whenever(parameters.numberOfTry).thenReturn(10)
whenever(repository.initQueue(date, 10)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(any())).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.launchDownload())
/* Then */
.expectSubscription()
.verifyComplete()
verify(repository, times(1)).initQueue(date, 10)
verify(repository, times(1)).findAllToDownload(1)
verify(messaging, times(1)).sendWaitingQueue(emptyList())
verify(repository, never()).startItem(any())
verify(downloadExecutor, never()).execute(any())
}
@Test
fun `with one item`() {
/* Given */
val downloader = SimpleDownloader()
val information = item1.toInformation()
whenever(parameters.limitDownloadDate()).thenReturn(date)
whenever(parameters.numberOfTry).thenReturn(10)
whenever(repository.initQueue(date, 10)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(any())).thenReturn(Flux.just(item1))
whenever(repository.findAllWaiting()).thenReturn(Flux.just(item1))
whenever(downloaders.of(information)).thenReturn(downloader)
whenever(repository.startItem(item1.id)).thenReturn(Mono.empty())
/* When */
StepVerifier.create(idm.launchDownload())
/* Then */
.expectSubscription()
.verifyComplete()
verify(repository, times(1)).initQueue(date, 10)
verify(repository, times(1)).findAllToDownload(1)
verify(messaging, atLeast(1)).sendWaitingQueue(listOf(item1))
assertThat(downloader.itemDownloadManager).isEqualTo(idm)
assertThat(downloader.downloadingInformation).isEqualTo(information)
verify(downloadExecutor, times(1)).execute(downloader)
}
@Test
fun `with multiple items`() {
/* Given */
val downloader1 = SimpleDownloader()
val information1 = item1.toInformation()
val downloader2 = SimpleDownloader()
val information2 = item2.toInformation()
whenever(parameters.limitDownloadDate()).thenReturn(date)
whenever(parameters.numberOfTry).thenReturn(10)
whenever(repository.initQueue(date, 10)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(any())).thenReturn(Flux.just(item1, item2))
whenever(repository.findAllWaiting()).thenReturn(Flux.just(item1, item2))
whenever(downloaders.of(information1)).thenReturn(downloader1)
whenever(downloaders.of(information2)).thenReturn(downloader2)
whenever(repository.startItem(item1.id)).thenReturn(Mono.empty())
whenever(repository.startItem(item2.id)).thenReturn(Mono.empty())
/* When */
StepVerifier.create(idm.launchDownload())
/* Then */
.expectSubscription()
.verifyComplete()
verify(repository, times(1)).initQueue(date, 10)
verify(repository, times(1)).findAllToDownload(1)
verify(messaging, atLeast(1)).sendWaitingQueue(listOf(item1, item2))
assertThat(downloader1.itemDownloadManager).isEqualTo(idm)
assertThat(downloader1.downloadingInformation).isEqualTo(information1)
assertThat(downloader2.itemDownloadManager).isEqualTo(idm)
assertThat(downloader2.downloadingInformation).isEqualTo(information2)
verify(downloadExecutor, times(1)).execute(downloader1)
verify(downloadExecutor, times(1)).execute(downloader2)
}
}
@Nested
@DisplayName("should stop all download")
inner class ShouldStopAllDownload {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
private val item2 = DownloadingItem(
id = UUID.fromString("27455c79-3349-4359-aca9-d4ea2cedc538"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("493b2fa5-8dc3-4d66-8bce-556e60c9a173"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("5be6d50d-8288-47e3-84fe-7eb9e2184466"),
title = "bar"
)
)
@Test
fun `with no items`() {
/* Given */
/* When */
idm.stopAllDownload()
/* Then */
// ? nothing to test, because nothing was executed…
}
@Test
fun `with multiple items`() {
/* Given */
val downloader1: SimpleDownloader = mock(spiedInstance = SimpleDownloader())
val information1 = item1.toInformation()
val downloader2: SimpleDownloader = mock(spiedInstance = SimpleDownloader())
val information2 = item2.toInformation()
whenever(parameters.limitDownloadDate()).thenReturn(date)
whenever(parameters.numberOfTry).thenReturn(10)
whenever(repository.initQueue(date, 10)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(any())).thenReturn(Flux.just(item1, item2))
whenever(repository.findAllWaiting()).thenReturn(Flux.just(item1, item2))
whenever(downloaders.of(information1)).thenReturn(downloader1)
whenever(downloaders.of(information2)).thenReturn(downloader2)
whenever(repository.startItem(item1.id)).thenReturn(Mono.empty())
whenever(repository.startItem(item2.id)).thenReturn(Mono.empty())
whenever(downloader1.with(any(), any())).thenCallRealMethod()
whenever(downloader2.with(any(), any())).thenCallRealMethod()
idm.launchDownload().block()
/* When */
idm.stopAllDownload()
/* Then */
verify(downloader1, times(1)).stopDownload()
verify(downloader2, times(1)).stopDownload()
}
}
@Nested
@DisplayName("should add item to queue")
inner class ShouldAddItemToQueue {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
@Test
fun `with success`() {
/* Given */
whenever(repository.addItemToQueue(item1.id)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.addItemToQueue(item1.id))
/* Then */
.expectSubscription()
.verifyComplete()
verify(repository, times(1)).addItemToQueue(item1.id)
}
}
@Nested
@DisplayName("should remove item from queue")
inner class ShouldRemoveItemFromQueue {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
@Test
fun `with success`() {
/* Given */
whenever(repository.remove(item1.id, true)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
idm.removeItemFromQueue(item1.id, true)
/* Then */
verify(repository, times(1)).remove(item1.id, true)
}
}
@Nested
@DisplayName("should remove item from downloading")
inner class ShouldRemoveItemFromDownloading {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
@Test
fun `with success`() {
/* Given */
whenever(repository.remove(item1.id, false)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
idm.removeACurrentDownload(item1.id)
/* Then */
verify(repository, times(1)).remove(item1.id, false)
}
}
@Nested
@DisplayName("should remove item from queue and downloading")
inner class ShouldRemoveItemFromQueueAndDownloading {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
@Test
fun `with item only in waiting list`() {
/* Given */
whenever(repository.remove(item1.id, false)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.removeItemFromQueueAndDownload(item1.id))
/* Then */
.expectSubscription()
.verifyComplete()
verify(repository, times(1)).remove(item1.id, false)
}
@Test
fun `with item only in downloading list`() {
/* Given */
val downloader = SimpleDownloader()
whenever(downloaders.of(any())).thenReturn(downloader)
whenever(repository.addItemToQueue(item1.id)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.just(item1))
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
whenever(repository.startItem(item1.id)).thenReturn(Mono.empty())
idm.addItemToQueue(item1.id).block()
/* When */
StepVerifier.create(idm.removeItemFromQueueAndDownload(item1.id))
/* Then */
.expectSubscription()
.verifyComplete()
}
}
@Nested
@DisplayName("should provide if is in downloading queue")
inner class ShouldProvideIfIsInDownloadingQueue {
private val item1 = DownloadingItem(
id = UUID.fromString("1f8d2177-357e-4db3-82ff-65012b5ffc23"),
title = "first",
url = URI("https://foo.bar.com/1/url/com.mp3"),
status = Status.NOT_DOWNLOADED,
numberOfFail = 0,
progression = 0,
cover = DownloadingItem.Cover(
id = UUID.fromString("6663237f-d940-4a9f-8aa7-30c43b07e7e3"),
url = URI("https://foo.bar.com/url.jpg")
),
podcast = DownloadingItem.Podcast(
id = UUID.fromString("fb6cf955-c3da-4bfc-b3a7-275d86d266b5"),
title = "bar"
)
)
@Test
fun `with element in downloading queue`() {
/* Given */
val downloader = SimpleDownloader()
whenever(downloaders.of(any())).thenReturn(downloader)
whenever(repository.addItemToQueue(item1.id)).thenReturn(Mono.empty())
whenever(repository.findAllToDownload(1)).thenReturn(Flux.just(item1))
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
whenever(repository.startItem(item1.id)).thenReturn(Mono.empty())
idm.addItemToQueue(item1.id).block()
/* When */
StepVerifier.create(idm.isInDownloadingQueueById(item1.id))
/* Then */
.expectSubscription()
.expectNext(true)
.verifyComplete()
}
@Test
fun `with element not in downloading queue`() {
/* Given */
/* When */
StepVerifier.create(idm.isInDownloadingQueueById(UUID.fromString("3372d87e-30a0-4517-ba1f-bfd31e3555cb")))
/* Then */
.expectSubscription()
.expectNext(false)
.verifyComplete()
}
}
@Nested
@DisplayName("should move into queue")
inner class ShouldMoveIntoQueue {
@Test
@Timeout(5)
fun `with success`() {
/* Given */
whenever(repository.moveItemInQueue(UUID.fromString("b768eb50-64d2-4707-8da6-6672cc69a4ca"), 3)).thenReturn(Mono.empty())
whenever(repository.findAllWaiting()).thenReturn(Flux.empty())
/* When */
StepVerifier.create(idm.moveItemInQueue(UUID.fromString("b768eb50-64d2-4707-8da6-6672cc69a4ca"), 3))
/* Then */
.expectSubscription()
.verifyComplete()
}
}
@TestConfiguration
@Import(ItemDownloadManager::class)
class LocalTestConfiguration {
@Bean @Qualifier("DownloadExecutor")
fun downloadExecutor(): ThreadPoolTaskExecutor = Mockito.spy(
ThreadPoolTaskExecutor().apply {
corePoolSize = 1
setThreadNamePrefix("Downloader-")
initialize()
}
)
}
}
private fun DownloadingItem.toInformation(): DownloadingInformation {
val fileName = Path(url.path).fileName
return DownloadingInformation(this, listOf(url), fileName, null)
}
internal class SimpleDownloader: Downloader {
override lateinit var downloadingInformation: DownloadingInformation
internal lateinit var itemDownloadManager: ItemDownloadManager
override fun with(information: DownloadingInformation, itemDownloadManager: ItemDownloadManager): Downloader {
this.downloadingInformation = information
this.itemDownloadManager = itemDownloadManager
return this
}
override fun download(): DownloadingItem = TODO("Not yet implemented")
override fun startDownload(){}
override fun stopDownload(){}
override fun failDownload(){}
override fun finishDownload(){}
override fun run(){}
override fun compatibility(downloadingInformation: DownloadingInformation) = 1
}
|
apache-2.0
|
1ed269bad75b566cb46ed287869f0e42
| 37.142857 | 133 | 0.588502 | 4.458173 | false | false | false | false |
ajalt/clikt
|
clikt/src/jsMain/kotlin/com/github/ajalt/clikt/output/EditorJS.kt
|
1
|
3769
|
package com.github.ajalt.clikt.output
import com.github.ajalt.clikt.core.CliktError
import com.github.ajalt.clikt.mpp.nodeRequire
import com.github.ajalt.clikt.mpp.readEnvvar
internal actual fun createEditor(
editorPath: String?,
env: Map<String, String>,
requireSave: Boolean,
extension: String,
): Editor {
try {
val fs = nodeRequire("fs")
val crypto = nodeRequire("crypto")
val childProcess = nodeRequire("child_process")
return NodeJsEditor(fs, crypto, childProcess, editorPath, env, requireSave, extension)
} catch (e: Exception) {
throw IllegalStateException("Cannot edit files on this platform", e)
}
}
private class NodeJsEditor(
private val fs: dynamic,
private val crypto: dynamic,
private val childProcess: dynamic,
private val editorPath: String?,
private val env: Map<String, String>,
private val requireSave: Boolean,
private val extension: String,
) : Editor {
private fun getEditorPath(): String {
return editorPath ?: inferEditorPath { editor ->
val options = jsObject(
"timeout" to 100,
"windowsHide" to true,
"stdio" to "ignore"
)
childProcess.execSync("${getWhichCommand()} $editor", options) == 0
}
}
private fun getEditorCommand(): Array<String> {
return getEditorPath().trim().split(" ").toTypedArray()
}
private fun editFileWithEditor(editorCmd: Array<String>, filename: String) {
val cmd = editorCmd[0]
val args = (editorCmd.drop(1) + filename).toTypedArray()
val options = jsObject("stdio" to "inherit", "env" to env.toJsObject())
try {
val exitCode = childProcess.spawnSync(cmd, args, options)
if (exitCode.status != 0) throw CliktError("$cmd: Editing failed!")
} catch (err: CliktError) {
throw err
} catch (err: Throwable) {
throw CliktError("Error staring editor")
}
}
override fun editFile(filename: String) {
editFileWithEditor(getEditorCommand(), filename)
}
private fun getTmpFileName(extension: String): String {
val rand = crypto.randomBytes(8).toString("hex")
val dir = readEnvvar("TMP") ?: "."
return "$dir/clikt_tmp_$rand.${extension.trimStart { it == '.' }}"
}
private fun getLastModified(path: String): Int {
return (fs.statSync(path).mtimeMs as Number).toInt()
}
override fun edit(text: String): String? {
val editorCmd = getEditorCommand()
val textToEdit = normalizeEditorText(editorCmd[0], text)
val tmpFilename = getTmpFileName(extension)
try {
fs.writeFileSync(tmpFilename, textToEdit)
try {
val lastModified = getLastModified(tmpFilename)
editFileWithEditor(editorCmd, tmpFilename)
if (requireSave && getLastModified(tmpFilename) == lastModified) {
return null
}
val readFileSync = fs.readFileSync(tmpFilename, "utf8")
return (readFileSync as String?)?.replace("\r\n", "\n")
} finally {
try {
fs.unlinkSync(tmpFilename)
} catch (ignored: Throwable) {
}
}
} catch (e: Throwable) {
throw CliktError("Error staring editing text: ${e.message}")
}
}
}
private fun <K, V> Map<K, V>.toJsObject(): dynamic {
val result = js("{}")
for ((key, value) in this) {
result[key] = value
}
return result
}
private fun jsObject(vararg pairs: Pair<Any, Any>): dynamic {
return pairs.toMap().toJsObject()
}
|
apache-2.0
|
18e5e275a8d23da9de01082b3f60581c
| 32.954955 | 94 | 0.597506 | 4.444575 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy
|
src/main/kotlin/com/zj/example/kotlin/advancefunction/21.函数复合.kt
|
1
|
2965
|
package com.zj.example.kotlin.advancefunction
/**
* Created by zhengjiong
* date: 2017/9/24 21:19
*/
fun main(args: Array<String>) {
/**
* 1.普通调用的方式:
*/
println(add5(multiplyBy2(1)))
/**
* 2.使用复合函数的形式, add5和multiplyBy2必须是匿名函数不能是普通函数,不然会报错
*/
val add5AndMultiplyBy2 = add5.andThen(multiplyBy2)
println(add5AndMultiplyBy2(1))
//val add5AndMultiplyBy2 = add5 andThen multiplyBy2
//add5AndMultiplyBy2(1)
val and5ThenToString = add5 andThenToString toString
println(and5ThenToString(1))//输出"6"
}
//fun add5(x: Int) = x + 5
val add5 = { x: Int -> x + 5 }
//fun multiplyBy2(x: Int) = x * 2
val multiplyBy2 = { x: Int -> x * 2 }
val toString = { x: Int -> "\"" + x.toString() + "\"" }
/**
* 1.只实用于Int型的符合函数
*
* Function1<Int, Int>.andThen相当于是给Function1扩展一个andThen函数,传入一个函数也就是multiplyBy2
*
* val add5AndMultiplyBy2 = add5.andThen(multiplyBy2)
* add5AndMultiplyBy2(1)
* 下面的this代表add5, action就是multiplyBy2, 传入的1就是x
*
*/
fun Function1<Int, Int>.andThen(action: Function1<Int, Int>): Function1<Int, Int> {
return fun(x: Int): Int {
return action.invoke(this.invoke(x))
}
}
/**
* 2.适用于传入Int返回一个String的类型
* Function1<Int, Int>代表要给这种类型的函数扩展函数, 也就是给add5扩展函数, toString是不会有扩展函数的因为类型不一样
*/
infix fun Function1<Int, Int>.andThenToString(action: Function1<Int, String>): Function1<Int, String> {
return fun(x: Int): String {
return action.invoke(this.invoke(x))
}
}
/**
* 3.各种类型都支持
* action:Function1<P2, R>,这里用P2是因为要实用前面Function1<P1, P2>的返回值, 前面返回值是P2,
* 所以这里传入给action的参数也就是P2,
*/
infix fun <P1, P2, R> Function1<P1, P2>.andThenToStringX(action: Function1<P2, R>): Function1<P1, R> {
/**
* 因为返回类型是: Function1<P1, R>, 所以这里也是P1和R
*/
return fun(x: P1): R {
return action.invoke(this.invoke(x))
}
}
/**
* 4.把3.用lambda表达式来写,后面用=等号和lambda相连接
*/
infix fun <P1, P2, R> Function1<P1, P2>.simpleAddAndThen(action: (P2) -> R): (P1) -> R = { x: P1 ->
action.invoke(this.invoke(x))
}
/**
* 5.还可以把4.再简写
* 去掉simpleAddAndThen2函数的返回值类型,lambda表达式作为返回的类型, lambda表达式就告诉了传入参数和返回类型
*/
infix fun <P1, P2, R> Function1<P1, P2>.simpleAddAndThen2(action: (P2) -> R) = { x: P1 ->
println("x" + x)
action.invoke(this.invoke(x))
}
/**
* compose和andThen执行顺序刚好相仿:
* andThen是:g(f(x))
* compose是:f(g(x))
*/
infix fun <P1, P2, R> Function1<P2, R>.composeAddAndThen(action: (P1) -> P2) = { x: P1 ->
this.invoke(action.invoke(x))
}
|
mit
|
60522b48e4cfffa9f06d3cc79888e4bf
| 23.29703 | 103 | 0.649817 | 2.547248 | false | false | false | false |
luhaoaimama1/AndroidZone
|
JavaTest_Zone/src/adapter/Test.kt
|
1
|
12027
|
package adapter
/**
* Created by fuzhipeng on 2018/9/5.
*/
fun main(args: Array<String>) {
ADD_OR_CHANGE(args)
// ADD(args)
// removeContent(args)
// removePos()
}
private fun removePos() {
val adapter = HFListHistory<String>()
adapter.styleExtra = styleExtra
arrayList(adapter)
val list = ArrayList<String>()
for (i in 0..4) {
val content = "insert one item!+${i}"
list.add(content)
}
list.add("header1_1")
adapter.add(list)
adapter.remove(1,1)
print("")
}
var styleExtra = object : ViewStyleDefault<String>() {
override fun generateViewStyleOBJ( item: String): ViewStyleOBJ? {
val viewStyle = when (item) {
"header1_1" -> 3
"header1_2" -> 3
"header2" -> 4
"header3_1" -> 5
"header3_2" -> 5
"footer1_1" -> 6
"footer1_2" -> 6
"footer2" -> 7
"footer3_1" -> 8
"footer3_2" -> 8
else -> -1
}
return ViewStyleOBJ().viewStyle(viewStyle)
}
override fun getItemViewType(position: Int, itemConfig: ViewStyleOBJ) {
}
}
fun removeContent(args: Array<String>) {
val adapter = HFListHistory<String>()
adapter.styleExtra = styleExtra
val list = arrayList(adapter)
adapter.add(list)
adapter.clearFooterDatas()
adapter.clearHeaderDatas()
adapter.clearContentDatas()
val notifyHistoryAdapter = ArrayList<HFListHistory.Operate>()
notifyHistoryAdapter.add(adapter.notifyHistory.get(adapter.notifyHistory.size - 3))
notifyHistoryAdapter.add(adapter.notifyHistory.get(adapter.notifyHistory.size - 2))
notifyHistoryAdapter.add(adapter.notifyHistory.get(adapter.notifyHistory.size - 1))
val notifyHistory = ArrayList<HFListHistory.Operate>()
val operateClearFooter = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 8
size = 3
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operateClearFooter)
val operateClearHeader = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 0
size = 3
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operateClearHeader)
val operateClearContent = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 0
size = 5
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operateClearContent)
if (equalsContent(notifyHistory, notifyHistoryAdapter)) println("clear 操作正确")
else throw IllegalStateException("clear 操作错误")
}
fun ADD_OR_CHANGE(args: Array<String>) {
val adapter = HFListHistory<String>()
adapter.styleExtra = styleExtra
val list = arrayList(adapter)
adapter.add(list)
// 判定是否一直
var notifyHistory = ArrayList<HFListHistory.Operate>()
val operate = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 0
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate)
val operate2 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 1
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate2)
val operate3 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 1
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate3)
val operate4 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 2
mode = HFListHistory.Operate.MMOde.CHANGE
}
}
notifyHistory.add(operate4)
val operate5 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 0
mode = HFListHistory.Operate.MMOde.CHANGE
}
}
notifyHistory.add(operate5)
//底部操作
val operate6 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 3
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate6)
val operate7 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 3
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate7)
val operate8 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 4
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate8)
val operate9 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 3
mode = HFListHistory.Operate.MMOde.CHANGE
}
}
notifyHistory.add(operate9)
val operate10 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 5
mode = HFListHistory.Operate.MMOde.CHANGE
}
}
notifyHistory.add(operate10)
val operate11 = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 3
size = 5
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate11)
if (equalsContent(notifyHistory, adapter.notifyHistory)) println("ADD_OR_CHANGE 添加 操作正确")
else throw IllegalStateException("ADD_OR_CHANGE 添加 操作错误")
//删除操作
adapter.remove(1, 9)
val operate12 = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 8
size = 2
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operate12)
val operate13 = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 3
size = 5
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operate13)
val operate14 = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 1
size = 2
mode = HFListHistory.Operate.MMOde.REMOVE
}
}
notifyHistory.add(operate14)
if (equalsContent(notifyHistory, adapter.notifyHistory)) println("ADD_OR_CHANGE 删除 操作正确")
else throw IllegalStateException("ADD_OR_CHANGE 删除 操作错误")//这里仅省 header1和footer1就是对的了
}
private fun arrayList(adapter: HFListHistory<String>): ArrayList<String> {
adapter.headerViewStyleOrder.add(3)
adapter.headerViewStyleOrder.add(4)
adapter.headerViewStyleOrder.add(5)
adapter.footerViewStyleOrder.add(6)
adapter.footerViewStyleOrder.add(7)
adapter.footerViewStyleOrder.add(8)
val list = ArrayList<String>()
for (i in 0..4) {
val content = "insert one item!+${i}"
list.add(content)
}
list.add("header1_1")
list.add("header3_1")
list.add("header2")
list.add("header3_2")
list.add("header1_2")
list.add("footer1_1")
list.add("footer3_1")
list.add("footer2")
list.add("footer3_2")
list.add("footer1_2")
return list
}
fun equalsContent(notifyHistory: ArrayList<HFListHistory.Operate>, otherNotifyHistory: ArrayList<HFListHistory.Operate>): Boolean {
if (notifyHistory.size != otherNotifyHistory.size) return false
notifyHistory.forEachIndexed { index, operate ->
val otherOperate = otherNotifyHistory.get(index)
if (operate.move != null && otherOperate.move != null) {
if (operate.move!!.pos == otherOperate.move!!.pos && operate.move!!.toPos == otherOperate.move!!.toPos) {
} else {
return false;
}
}
if (operate.range != null && otherOperate.range != null) {
if (operate.range!!.pos == otherOperate.range!!.pos
&& operate.range!!.size == otherOperate.range!!.size
&& operate.range!!.mode.name == otherOperate.range!!.mode.name
) {
} else {
return false;
}
}
if (operate.single != null && otherOperate.single != null) {
if (operate.single!!.index_ == otherOperate.single!!.index_
&& operate.single!!.mode.name == otherOperate.single!!.mode.name
) {
} else {
return false;
}
}
}
return true;
}
fun ADD(args: Array<String>) {
println("----------------------------")
val adapter = HFListHistory<String>()
adapter.footerMode = HFMode.ADD
adapter.headerMode = HFMode.ADD
adapter.styleExtra = styleExtra
val list = arrayList(adapter)
adapter.add(list)
// 头部操作
var notifyHistory = ArrayList<HFListHistory.Operate>()
val operate = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 0
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate)
val operate2 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 1
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate2)
val operate3 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 1
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate3)
val operate4 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 3
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate4)
val operate5 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 1
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate5)
//底部操作
val operate6 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 5
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate6)
val operate7 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 5
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate7)
val operate8 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 6
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate8)
val operate9 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 6
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate9)
val operate10 = HFListHistory.Operate().apply {
single = HFListHistory.Operate.Single().apply {
index_ = 9
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate10)
val operate11 = HFListHistory.Operate().apply {
range = HFListHistory.Operate.Range().apply {
[email protected] = 5
size = 5
mode = HFListHistory.Operate.MMOde.ADD
}
}
notifyHistory.add(operate11)
if (equalsContent(notifyHistory, adapter.notifyHistory)) println("ADD 添加 操作正确")
else throw IllegalStateException("ADD 添加 操作错误")
}
|
epl-1.0
|
3d26cdd37223fe2652142b1d7d6651a9
| 27.965854 | 131 | 0.601684 | 4.394893 | false | false | false | false |
android/user-interface-samples
|
CanonicalLayouts/feed-compose/app/src/main/java/com/example/feedcompose/ui/FeedSampleApp.kt
|
1
|
2601
|
/*
* 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 com.example.feedcompose.ui
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.feedcompose.data.DataProvider
import com.example.feedcompose.data.Sweets
import com.example.feedcompose.ui.screen.SweetsDetails
import com.example.feedcompose.ui.screen.SweetsFeed
@Composable
fun FeedSampleApp(windowSizeClass: WindowSizeClass) {
val navController = rememberNavController()
val router = Router(navController)
NavHost(navController = navController, startDestination = "/") {
composable(Destination.Feed.path) {
SweetsFeed(windowSizeClass = windowSizeClass) {
router.showSweets(it)
}
}
composable(
Destination.Details.path,
arguments = listOf(navArgument("sweetsId") { type = NavType.IntType })
) {
val selectedSweetsId = it.arguments?.getInt("sweetsId") ?: 0
SweetsDetails(
sweets = DataProvider.getSweetsById(selectedSweetsId),
windowSizeClass = windowSizeClass
) {
navController.popBackStack()
}
}
}
}
private sealed interface Destination {
val base: String
val path: String
object Feed : Destination {
override val base: String = "/"
override val path: String = base
}
object Details : Destination {
override val base: String = "/show"
override val path: String = "$base/{sweetsId}"
}
}
private class Router(val navController: NavController) {
fun showSweets(sweets: Sweets) {
navController.navigate("${Destination.Details.base}/${sweets.id}")
}
}
|
apache-2.0
|
fa0c0554da44313190192d7c8b8622c0
| 33.223684 | 82 | 0.700884 | 4.711957 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/colorinfo/RgbColorInfoExecutor.kt
|
1
|
2005
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.colorinfo
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.ColorInfoCommand
import java.awt.Color
class RgbColorInfoExecutor(loritta: LorittaBot) : ColorInfoExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val red = integer(
"red",
ColorInfoCommand.I18N_PREFIX.RgbColorInfo.Options.Red.Text
)
val green = integer(
"green",
ColorInfoCommand.I18N_PREFIX.RgbColorInfo.Options.Green.Text
)
val blue = integer(
"blue",
ColorInfoCommand.I18N_PREFIX.RgbColorInfo.Options.Blue.Text
)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val red = args[options.red].toInt()
val green = args[options.green].toInt()
val blue = args[options.blue].toInt()
if (red !in 0..255 || green !in 0..255 || blue !in 0..255)
context.failEphemerally {
styled(
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.RgbColorInfo.InvalidColor),
Emotes.Error
)
}
val color = Color(red, green, blue)
executeWithColor(context, color)
}
}
|
agpl-3.0
|
ba37f25aad40643749d5c8a12dfe39f2
| 39.938776 | 114 | 0.712219 | 4.77381 | false | false | false | false |
angcyo/RLibrary
|
uiview/src/main/java/com/angcyo/uiview/dialog/UIGuideDialogImpl.kt
|
1
|
2388
|
package com.angcyo.uiview.dialog
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import com.angcyo.uiview.R
import com.angcyo.uiview.base.UIIDialogImpl
import com.angcyo.uiview.widget.group.GuideFrameLayout
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:用来显示引导图的对话框
* 创建人员:Robi
* 创建时间:2018/01/11 10:01
* 修改人员:Robi
* 修改时间:2018/01/11 10:01
* 修改备注:
* Version: 1.0.0
*/
open abstract class UIGuideDialogImpl : UIIDialogImpl() {
/**锚点矩形列表*/
protected val anchorRectList = mutableListOf<Rect>()
var onFinishButtonClick: (() -> Unit)? = null
init {
layoutAnim = true
}
// init {
// anchorView.getGlobalVisibleRect(anchorRect)
// L.e("call: GuideLayoutUIView init -> $anchorRect")
// }
// override fun inflateDialogView(dialogRootLayout: FrameLayout, inflater: LayoutInflater): View {
// return inflate(R.layout.dialog_guide_layout)
// }
override fun initDialogContentView() {
super.initDialogContentView()
val rootLayout: GuideFrameLayout? = getGuideFrameLayout()
rootLayout?.addAnchorList(anchorRectList)
getFinishButton()?.let {
click(it) {
finishDialog {
onFinishButtonClick?.invoke()
}
}
}
}
open fun getGuideFrameLayout(): GuideFrameLayout? = v(R.id.base_guide_layout)
open fun getFinishButton(): View? = v(R.id.base_finish_view)
override fun onViewShow(bundle: Bundle?) {
super.onViewShow(bundle)
interceptTouchEvent(false)
}
override fun loadLayoutAnimation(): Animation {
return super.loadLayoutAnimation()
}
override fun isDimBehind(): Boolean {
return true
}
override fun loadStartAnimation(): Animation? {
return null
}
override fun loadFinishAnimation(): Animation? {
return null
}
override fun loadOtherEnterAnimation(): Animation? {
return null
}
override fun loadOtherExitAnimation(): Animation? {
return null
}
}
|
apache-2.0
|
14b6ccba57713317c2eca28019433d54
| 23.066667 | 101 | 0.62378 | 4.174074 | false | false | false | false |
carlphilipp/chicago-commutes
|
android-app/src/main/kotlin/fr/cph/chicago/redux/State.kt
|
1
|
3099
|
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.redux
import fr.cph.chicago.R
import fr.cph.chicago.core.model.BikeStation
import fr.cph.chicago.core.model.BusRoute
import fr.cph.chicago.core.model.TrainArrival
import fr.cph.chicago.core.model.dto.BusArrivalDTO
import fr.cph.chicago.core.model.dto.BusArrivalStopDTO
import fr.cph.chicago.core.model.dto.RoutesAlertsDTO
import fr.cph.chicago.core.model.dto.TrainArrivalDTO
import java.util.Date
import org.apache.commons.lang3.StringUtils
import org.rekotlin.StateType
data class State(
// Can be useful to force an update
val random: String = StringUtils.EMPTY,
// Api keys
val ctaTrainKey: String = StringUtils.EMPTY,
val ctaBusKey: String = StringUtils.EMPTY,
val googleStreetKey: String = StringUtils.EMPTY,
val status: Status = Status.UNKNOWN,
val lastFavoritesUpdate: Date = Date(), // Field displayed in favorites
// Favorites
val trainFavorites: List<String> = listOf(),
val busFavorites: List<String> = listOf(),
val busRouteFavorites: List<String> = listOf(),
val bikeFavorites: List<String> = listOf(),
// Trains and Buses arrivals
val trainArrivalsDTO: TrainArrivalDTO = TrainArrivalDTO(mutableMapOf(), false),
val busArrivalsDTO: BusArrivalDTO = BusArrivalDTO(listOf(), false),
// Bus routes
val busRoutesStatus: Status = Status.UNKNOWN,
val busRoutesErrorMessage: Int = R.string.message_something_went_wrong,
val busRoutes: List<BusRoute> = listOf(),
// Bikes
val bikeStationsStatus: Status = Status.UNKNOWN,
val bikeStationsErrorMessage: Int = R.string.message_something_went_wrong,
val bikeStations: List<BikeStation> = listOf(),
// Train Station activity state
val trainStationStatus: Status = Status.UNKNOWN,
val trainStationErrorMessage: Int = R.string.message_something_went_wrong,
val trainStationArrival: TrainArrival = TrainArrival.buildEmptyTrainArrival(),
// Bus stop activity state
val busStopStatus: Status = Status.UNKNOWN,
val busStopErrorMessage: Int = R.string.message_something_went_wrong,
val busArrivalStopDTO: BusArrivalStopDTO = BusArrivalStopDTO(),
// Alerts
val alertStatus: Status = Status.UNKNOWN,
val alertErrorMessage: Int = R.string.message_something_went_wrong,
val alertsDTO: List<RoutesAlertsDTO> = listOf()
) : StateType
enum class Status {
UNKNOWN,
SUCCESS,
FAILURE,
FAILURE_NO_SHOW,
FULL_FAILURE,
ADD_FAVORITES,
REMOVE_FAVORITES
}
|
apache-2.0
|
bf055fac2db704a94124fce590e16107
| 33.820225 | 83 | 0.737012 | 4.121011 | false | false | false | false |
jitsi/jitsi-videobridge
|
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/outgoing/AbsSendTime.kt
|
1
|
2050
|
/*
* Copyright @ 2018 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node.outgoing
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.rtp.RtpExtensionType.ABS_SEND_TIME
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.node.ModifierNode
import org.jitsi.nlj.util.ReadOnlyStreamInformationStore
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.rtp.rtp.header_extensions.AbsSendTimeHeaderExtension
class AbsSendTime(
val streamInformationStore: ReadOnlyStreamInformationStore
) : ModifierNode("Absolute send time") {
private var extensionId: Int? = null
init {
streamInformationStore.onRtpExtensionMapping(ABS_SEND_TIME) {
extensionId = it
}
}
override fun modify(packetInfo: PacketInfo): PacketInfo {
if (streamInformationStore.supportsTcc) return packetInfo
extensionId?.let { absSendTimeExtId ->
val rtpPacket = packetInfo.packetAs<RtpPacket>()
val ext = rtpPacket.getHeaderExtension(absSendTimeExtId)
?: rtpPacket.addHeaderExtension(absSendTimeExtId, AbsSendTimeHeaderExtension.DATA_SIZE_BYTES)
AbsSendTimeHeaderExtension.setTime(ext, System.nanoTime())
}
return packetInfo
}
override fun getNodeStats(): NodeStatsBlock {
return super.getNodeStats().apply {
addString("abs_send_time_ext_id", extensionId.toString())
}
}
override fun trace(f: () -> Unit) = f.invoke()
}
|
apache-2.0
|
3ce2fc99a21b92ff7e5344efd76c146a
| 34.964912 | 109 | 0.719024 | 4.399142 | false | false | false | false |
Phakx/my_movie_db
|
movie-db-service/src/main/java/de/bke/actor/ActorController.kt
|
1
|
1145
|
package de.bke.actor
import com.google.inject.Inject
import ninja.Context
import ninja.Result
import ninja.Results
import ninja.params.PathParam
/**
* Created by bkeucher on 04.07.16.
*/
class ActorController{
@Inject
val actorEntityManager: ActorEntityManager = ActorEntityManager()
fun getActor(@PathParam("id") actor_id: String): Result {
val longId = try {
actor_id.toLong()
} catch (e: NumberFormatException) {
return Results.forbidden()
}
val fetchedActor = actorEntityManager.getById(Actor::class.java,longId)
return Results.json().render(fetchedActor)
}
fun getAllActors(): Result {
val actor_list = actorEntityManager.getAllActors()
return Results.json().render(actor_list)
}
fun addActor(context: Context, actor: Actor): Result {
actorEntityManager.persist(actor)
return Results.json().render(actor)
}
fun findActorsByName(@PathParam("name") name: String): Result {
val actor_list = actorEntityManager.getActorsByName(name)
return Results.json().render(actor_list)
}
}
|
mit
|
686cf7296e0e143a8b10ebda1dccad43
| 23.382979 | 79 | 0.667249 | 4.304511 | false | false | false | false |
JayNewstrom/ScreenSwitcher
|
screen-switcher/src/main/java/com/jaynewstrom/screenswitcher/ScreenSwitcherState.kt
|
1
|
6163
|
package com.jaynewstrom.screenswitcher
import android.os.Parcelable
import android.util.SparseArray
import android.view.View
/**
* This object is designed to persist in memory when an [android.app.Activity] configuration change occurs.
*/
class ScreenSwitcherState
/**
* @param lifecycleListener The [ScreenLifecycleListener] to be notified of what's happening on the internals.
* @param screens The initial screens that the [ScreenSwitcher] should show.
* @throws IllegalArgumentException if screens is empty
* @throws IllegalArgumentException if the same screen is passed
*/
(internal val lifecycleListener: ScreenLifecycleListener, screens: List<Screen>) {
internal val screens: MutableList<Screen>
private val transitionMap: MutableMap<Screen, (ScreenSwitcherData) -> Unit> = mutableMapOf()
private val popListenerMap: MutableMap<Screen, ScreenPopListener> = mutableMapOf()
private val screenViewStateMap: MutableMap<Screen, SparseArray<Parcelable>> = mutableMapOf()
private val screenSwitcherCreatedListenerMap: MutableMap<Screen, MutableList<ScreenSwitcherCreatedListener>> =
mutableMapOf()
init {
checkArgument(screens.isNotEmpty()) { "screens must contain at least one screen" }
this.screens = ArrayList(15)
for (screen in screens) {
addScreen(screen)
}
}
/**
* The pop listener will be automatically unregistered when the [Screen] is popped.
* See documentation for [ScreenPopListener] for what objects should be registered.
*
* @param screen The [Screen] to be notified of before it gets popped.
* @param popListener The [ScreenPopListener] to call when the [Screen] is trying to be popped.
*
* @return true if the pop listener was added.
*/
fun setPopListener(screen: Screen, popListener: ScreenPopListener): Boolean {
if (screens.contains(screen)) {
popListenerMap[screen] = popListener
return true
}
return false
}
/**
* @return the index of the screen if it exists, or -1 if it doesn't.
*/
fun indexOf(screen: Screen): Int {
return screens.indexOf(screen)
}
/**
* @return number of screens that will be used in any associated [ScreenSwitcher].
*/
fun screenCount(): Int {
return screens.size
}
/**
* Enqueues a transition to be executed when [Screen] is the active screen and a transition is not occurring.
* Enqueued transitions are only executed when another transition is complete.
* If there are no transitions occurring, this will not be executed immediately.
*/
fun enqueueTransition(fromScreen: Screen, transitionFunction: (data: ScreenSwitcherData) -> Unit) {
if (screens.contains(fromScreen)) {
transitionMap[fromScreen] = transitionFunction
}
}
/**
* Create a nested [ScreenSwitcherState] object, reusing the [ScreenLifecycleListener], for use with a new [ScreenSwitcher].
*/
fun createNestedState(screens: List<Screen>): ScreenSwitcherState {
return ScreenSwitcherState(lifecycleListener, screens)
}
internal fun removeActiveScreenTransition(): ((ScreenSwitcherData) -> Unit)? {
if (screens.isEmpty()) return null
return transitionMap.remove(screens.last())
}
internal fun addScreen(screen: Screen) {
checkArgument(!screens.contains(screen)) { "screen already exists" }
screens.add(screen)
lifecycleListener.onScreenAdded(screen)
}
internal fun removeScreen(screen: Screen) {
screens.remove(screen)
transitionMap.remove(screen)
popListenerMap.remove(screen)
screenViewStateMap.remove(screen)
lifecycleListener.onScreenRemoved(screen)
screenSwitcherCreatedListenerMap.remove(screen)
}
internal fun handlesPop(view: View, screen: Screen, popContext: Any?): Boolean {
val popListener = popListenerMap[screen]
return popListener != null && popListener.onScreenPop(view, popContext)
}
internal fun saveViewHierarchyState(screen: Screen, viewState: SparseArray<Parcelable>) {
screenViewStateMap[screen] = viewState
}
internal fun removeViewHierarchyState(screen: Screen): SparseArray<Parcelable>? {
return screenViewStateMap.remove(screen)
}
/**
* Listen to all subsequent screen switchers that get created within the context of the attached [ScreenSwitcherState].
*/
interface ScreenSwitcherCreatedListener {
fun screenSwitcherCreated(screenSwitcher: ScreenSwitcher)
}
/**
* Add a [ScreenSwitcherCreatedListener] for any new screen switcher that's created with this [ScreenSwitcherState].
* The [Screen] is passed as context, so the listener can be automatically removed when the screen is removed.
*
* See [ScreenSwitcherState#unregisterScreenSwitcherCreatedListener].
*
* @return true if the listener was added.
*/
fun registerScreenSwitcherCreatedListener(screen: Screen, listener: ScreenSwitcherCreatedListener): Boolean {
if (screens.contains(screen)) {
return screenSwitcherCreatedListenerMap.getOrPut(screen) { mutableListOf() }.add(listener)
}
return false
}
/**
* Remove the [ScreenSwitcherCreatedListener] for the given [Screen].
* The listener will only be removed for the given screen. If the listener is reused for other screens, they will remain.
*
* See [ScreenSwitcherState#registerScreenSwitcherCreatedListener].
*
* @return true if the listener was removed.
*/
fun unregisterScreenSwitcherCreatedListener(screen: Screen, listener: ScreenSwitcherCreatedListener): Boolean {
return screenSwitcherCreatedListenerMap[screen]?.remove(listener) == true
}
internal fun screenSwitcherCreated(screenSwitcher: ScreenSwitcher) {
for (listenerList in screenSwitcherCreatedListenerMap.values) {
for (listener in listenerList) {
listener.screenSwitcherCreated(screenSwitcher)
}
}
}
}
|
apache-2.0
|
56adc9b548ca11509f7998597b4d4300
| 38.50641 | 128 | 0.699659 | 5.15301 | false | false | false | false |
mrebollob/m2p
|
app/src/main/java/com/mrebollob/m2p/data/datasources/network/interceptor/CookiesInterceptor.kt
|
2
|
1744
|
/*
* Copyright (c) 2016. Manuel Rebollo Báez
*
* 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.mrebollob.m2p.data.datasources.network.interceptor
import com.mrebollob.m2p.utils.NonPersistentCookieJar
import okhttp3.Cookie
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import javax.inject.Inject
class CookiesInterceptor @Inject
constructor(private val mNonPersistentCookieJar: NonPersistentCookieJar) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
val cookies = mNonPersistentCookieJar.loadForRequest(chain.request().url())
var cookieString = ""
for (cookie in cookies) {
cookieString += cookie.name() + "=" + cookie.value() + "; "
}
builder.header("Cookie", cookieString)
val response = chain.proceed(builder.build())
if (!response.headers("Set-Cookie").isEmpty()) {
val newCookies = Cookie.parseAll(response.request().url(), response.headers())
mNonPersistentCookieJar.saveFromResponse(response.request().url(), newCookies)
}
return response
}
}
|
apache-2.0
|
f324ba978b7e79f842fa8c5dc4222e0e
| 32.538462 | 90 | 0.709696 | 4.401515 | false | false | false | false |
epabst/kotlin-showcase
|
src/jsMain/kotlin/bootstrap/SplitButton.kt
|
1
|
1081
|
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused")
@file:JsModule("react-bootstrap")
package bootstrap
import react.Component
import react.RState
external interface SplitButtonProps : PropsFromToggle {
var id: dynamic /* String | Number */
var toggleLabel: String? get() = definedExternally; set(value) = definedExternally
override var href: String? get() = definedExternally; set(value) = definedExternally
var target: String? get() = definedExternally; set(value) = definedExternally
var onClick: React.MouseEventHandler<SplitButtonProps /* this */>? get() = definedExternally; set(value) = definedExternally
var title: React.ReactNode
var menuRole: String? get() = definedExternally; set(value) = definedExternally
var rootCloseEvent: String /* 'click' | 'mousedown' */
var bsPrefix: String? get() = definedExternally; set(value) = definedExternally
}
abstract external class SplitButton : Component<SplitButtonProps, RState>
|
apache-2.0
|
3b710313ea2802c4bda05db65c596c61
| 55.894737 | 164 | 0.752081 | 4.430328 | false | false | false | false |
Zhuinden/simple-stack
|
samples/advanced-samples/extensions-example/src/main/java/com/zhuinden/simplestackextensionsample/features/login/LoginViewModel.kt
|
1
|
2222
|
package com.zhuinden.simplestackextensionsample.features.login
import com.jakewharton.rxrelay2.BehaviorRelay
import com.zhuinden.rxvalidatebykt.validateBy
import com.zhuinden.simplestack.*
import com.zhuinden.simplestackextensionsample.app.AuthenticationManager
import com.zhuinden.simplestackextensionsample.features.profile.ProfileKey
import com.zhuinden.simplestackextensionsample.features.registration.EnterProfileDataKey
import com.zhuinden.simplestackextensionsample.utils.get
import com.zhuinden.simplestackextensionsample.utils.observe
import com.zhuinden.simplestackextensionsample.utils.set
import com.zhuinden.statebundle.StateBundle
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
class LoginViewModel(
private val authenticationManager: AuthenticationManager,
private val backstack: Backstack
) : Bundleable, ScopedServices.Registered {
private val compositeDisposable = CompositeDisposable()
val username = BehaviorRelay.createDefault("")
val password = BehaviorRelay.createDefault("")
private val isLoginEnabledRelay = BehaviorRelay.createDefault(false)
val isLoginEnabled: Observable<Boolean> = isLoginEnabledRelay
override fun onServiceRegistered() {
validateBy(
username.map { it.isNotBlank() },
password.map { it.isNotBlank() },
).observe(compositeDisposable) {
isLoginEnabledRelay.set(it)
}
}
override fun onServiceUnregistered() {
compositeDisposable.clear()
}
fun onLoginClicked() {
if (isLoginEnabledRelay.get()) {
authenticationManager.saveRegistration(username.get())
backstack.setHistory(History.of(ProfileKey(username.get())), StateChange.FORWARD)
}
}
fun onRegisterClicked() {
backstack.goTo(EnterProfileDataKey)
}
override fun toBundle(): StateBundle = StateBundle().apply {
putString("username", username.get())
putString("password", password.get())
}
override fun fromBundle(bundle: StateBundle?) {
bundle?.run {
username.set(getString("username", ""))
password.set(getString("password", ""))
}
}
}
|
apache-2.0
|
abab617f94618ace074b07dae789d796
| 34.285714 | 93 | 0.732223 | 5.341346 | false | false | false | false |
OurFriendIrony/MediaNotifier
|
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/tvshow/get/TVShowGetCreatedBy.kt
|
1
|
921
|
package uk.co.ourfriendirony.medianotifier.clients.tmdb.tvshow.get
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("id", "credit_id", "name", "gender", "profile_path")
class TVShowGetCreatedBy {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("credit_id")
@set:JsonProperty("credit_id")
@JsonProperty("credit_id")
var creditId: String? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("gender")
@set:JsonProperty("gender")
@JsonProperty("gender")
var gender: Int? = null
@get:JsonProperty("profile_path")
@set:JsonProperty("profile_path")
@JsonProperty("profile_path")
var profilePath: String? = null
}
|
apache-2.0
|
844b9634803347de7f33394eac867552
| 26.939394 | 71 | 0.684039 | 3.790123 | false | false | false | false |
dirkraft/cartograph
|
cartograph/src/main/kotlin/com/github/dirkraft/cartograph/annotations.kt
|
1
|
3087
|
package com.github.dirkraft.cartograph
import kotlin.reflect.*
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
object Annotations {
fun resolveTableName(tableName: String, obj: Any): String {
if (tableName != "") {
return tableName
} else {
return resolveTableName(obj.javaClass.kotlin)
}
}
inline fun <reified T : Any> resolveTableName(): String {
return resolveTableName(T::class)
}
fun <T : Any> resolveTableName(dataClass: KClass<T>): String {
val tableAnnot = dataClass.annotations.filterIsInstance<CartTable>().firstOrNull()
return tableAnnot?.value ?: throw CartographException("No @Table annotation found on " + dataClass)
}
fun resolvePrimaryKeyValue(obj: Any): Pair<String, Any> {
val (colName, prop) = resolvePrimaryKey(obj.javaClass.kotlin)
// Technically a PK can be nullable, but that can cause some other subtle complications when
// dealing with PKs. Just don't allow nullable PKs.
val value = prop.get(obj) ?: throw CartographException("Cartograph does not support null @PrimaryKey")
return Pair(colName, value)
}
fun <T : Any> resolvePrimaryKey(klass: KClass<T>): Pair<String, KProperty1<T, *>> {
val prop = klass.memberProperties
.firstOrNull { it.annotations.filterIsInstance<CartPrimaryKey>().firstOrNull() != null }
?: throw CartographException("No @CartPrimaryKey annotated property found on " + klass)
val colName = camelCaseTo_snake_case(prop.name)
return Pair(colName, prop)
}
/**
* Returns suitable SQL placeholder string, '?' by default.
* [CartPlaceholder] may annotate the property with a custom placeholder.
*/
fun resolvePlaceholder(prop: KProperty1<Any, *>): String {
val token = prop.findAnnotation<CartPlaceholder>()
return token?.value ?: "?"
}
}
/**
* Annotates a class with the table name which records such entities.
*
* @param value name of the table
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class CartTable(val value: String)
/**
* Annotates a property as the primary key. Optionally takes an explicit column name.
* Otherwise uses the name of the property.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CartPrimaryKey
/**
* Annotates a String property with a custom placeholder besides the default
* (usually '?'). An example use case is with JSON columns which must be
* passed as strings with casts: `CAST(? as JSON)` or `?::JSON` (PostgreSQL)
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CartPlaceholder(val value: String)
/**
* Annotates a property to be ignored by automatic entity-sql mapping.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CartIgnore
|
mit
|
3e726f91e1d53cfda64f776db53876de
| 35.216867 | 110 | 0.683511 | 4.539706 | false | false | false | false |
charlesmadere/smash-ranks-android
|
smash-ranks-android/app/src/androidTest/java/com/garpr/android/features/rankings/RankingsAndFavoritesViewModelTest.kt
|
1
|
43746
|
package com.garpr.android.features.rankings
import com.garpr.android.data.models.Endpoint
import com.garpr.android.data.models.LitePlayer
import com.garpr.android.data.models.PreviousRank
import com.garpr.android.data.models.RankedPlayer
import com.garpr.android.data.models.RankingsBundle
import com.garpr.android.data.models.Region
import com.garpr.android.data.models.SimpleDate
import com.garpr.android.features.common.viewModels.BaseViewModelTest
import com.garpr.android.features.player.SmashRosterAvatarUrlHelper
import com.garpr.android.features.rankings.RankingsAndFavoritesViewModel.ListItem
import com.garpr.android.misc.Schedulers
import com.garpr.android.misc.ThreadUtils
import com.garpr.android.misc.Timber
import com.garpr.android.repositories.FavoritePlayersRepository
import com.garpr.android.repositories.IdentityRepository
import com.garpr.android.repositories.RankingsRepository
import com.garpr.android.sync.roster.SmashRosterStorage
import com.garpr.android.sync.roster.SmashRosterSyncManager
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.koin.core.inject
import java.util.Calendar
class RankingsAndFavoritesViewModelTest : BaseViewModelTest() {
private lateinit var viewModel: RankingsAndFavoritesViewModel
protected val favoritePlayersRepository: FavoritePlayersRepository by inject()
protected val identityRepository: IdentityRepository by inject()
protected val schedulers: Schedulers by inject()
protected val smashRosterAvatarUrlHelper: SmashRosterAvatarUrlHelper by inject()
protected val smashRosterStorage: SmashRosterStorage by inject()
protected val smashRosterSyncManager: SmashRosterSyncManager by inject()
protected val threadUtils: ThreadUtils by inject()
protected val timber: Timber by inject()
@Before
override fun setUp() {
super.setUp()
viewModel = RankingsAndFavoritesViewModel(favoritePlayersRepository, identityRepository,
RankingsRepositoryOverride(), schedulers, smashRosterAvatarUrlHelper,
smashRosterStorage, smashRosterSyncManager, threadUtils, timber)
}
@Test
fun testAddAndRemoveFavoritePlayersCausesUpdates() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
assertEquals(4, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
assertEquals(ListItem.Header.Rankings, state?.list?.get(2))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(3))
favoritePlayersRepository.addPlayer(IMYT, NORCAL)
assertEquals(4, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
var player = state?.list?.get(1) as ListItem.Player
assertFalse(player.isIdentity)
assertEquals(IMYT, player.player)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(2))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(3))
favoritePlayersRepository.addPlayer(SNAP, NORCAL)
assertEquals(5, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
player = state?.list?.get(1) as ListItem.Player
assertFalse(player.isIdentity)
assertEquals(IMYT, player.player)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = state?.list?.get(2) as ListItem.Player
assertFalse(player.isIdentity)
assertEquals(SNAP, player.player)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(4))
favoritePlayersRepository.removePlayer(IMYT, NORCAL)
assertEquals(4, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
player = state?.list?.get(1) as ListItem.Player
assertFalse(player.isIdentity)
assertEquals(SNAP, player.player)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(2))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(3))
}
@Test
fun testAddFavoritePlayerCausesUpdate() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
assertEquals(4, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
assertEquals(ListItem.Header.Rankings, state?.list?.get(2))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(3))
favoritePlayersRepository.addPlayer(IBDW, NYC)
favoritePlayersRepository.addPlayer(MIKKUZ, NORCAL)
assertEquals(5, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
var player = state?.list?.get(1) as ListItem.Player
assertEquals(MIKKUZ, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = state?.list?.get(2) as ListItem.Player
assertEquals(IBDW, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NYC.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(4))
identityRepository.setIdentity(CHARLEZARD, NORCAL)
assertEquals(6, state?.list?.size)
val identity = state?.list?.get(0) as ListItem.Identity
assertEquals(CHARLEZARD, identity.player)
assertEquals(PreviousRank.GONE, identity.previousRank)
assertNull(identity.avatar)
assertNull(identity.rank)
assertNull(identity.rating)
assertEquals(CHARLEZARD.name, identity.tag)
assertEquals(ListItem.Header.Favorites, state?.list?.get(1))
player = state?.list?.get(2) as ListItem.Player
assertEquals(MIKKUZ, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = state?.list?.get(3) as ListItem.Player
assertEquals(IBDW, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NYC.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(4))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(5))
}
@Test
fun testFetchRankingsWithNorcal() {
val states = mutableListOf<RankingsAndFavoritesViewModel.State>()
viewModel.stateLiveData.observeForever {
states.add(it)
}
assertEquals(1, states.size)
assertEquals(false, states[0].hasContent)
assertEquals(false, states[0].isRefreshing)
assertEquals(4, states[0].list.size)
assertEquals(ListItem.Header.Favorites, states[0].list[0])
assertEquals(ListItem.Empty.Favorites, states[0].list[1])
assertEquals(ListItem.Header.Rankings, states[0].list[2])
assertEquals(ListItem.Fetching.Rankings, states[0].list[3])
assertNull(states[0].searchResults)
assertNull(states[0].rankingsBundle)
viewModel.fetchRankings(NORCAL)
assertEquals(3, states.size)
assertEquals(false, states[1].hasContent)
assertEquals(true, states[1].isRefreshing)
assertEquals(4, states[1].list.size)
assertEquals(ListItem.Header.Favorites, states[1].list[0])
assertEquals(ListItem.Empty.Favorites, states[1].list[1])
assertEquals(ListItem.Header.Rankings, states[1].list[2])
assertEquals(ListItem.Fetching.Rankings, states[1].list[3])
assertNull(states[1].searchResults)
assertNull(states[1].rankingsBundle)
assertEquals(true, states[2].hasContent)
assertEquals(false, states[2].isRefreshing)
assertEquals(9, states[2].list.size)
assertEquals(ListItem.Header.Favorites, states[2].list[0])
assertEquals(ListItem.Empty.Favorites, states[2].list[1])
val activityRequirements = states[2].list[2] as ListItem.ActivityRequirements
assertEquals(NORCAL.rankingActivityDayLimit, activityRequirements.rankingActivityDayLimit)
assertEquals(NORCAL.rankingNumTourneysAttended, activityRequirements.rankingNumTourneysAttended)
assertEquals(ListItem.Header.Rankings, states[2].list[3])
var player = states[2].list[4] as ListItem.Player
assertEquals(NMW, player.player)
assertFalse(player.isIdentity)
assertEquals(NMW.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = states[2].list[5] as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = states[2].list[6] as ListItem.Player
assertEquals(UMARTH, player.player)
assertFalse(player.isIdentity)
assertEquals(UMARTH.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = states[2].list[7] as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = states[2].list[8] as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertEquals(SNAP.rank, player.rawRank)
assertEquals(PreviousRank.INCREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertNull(states[2].searchResults)
assertEquals(NORCAL_RANKINGS_BUNDLE, states[2].rankingsBundle)
}
@Test
fun testFetchRankingsWithGoogleMtvAndCharlezardAsIdentityAndSomeFavorites() {
favoritePlayersRepository.addPlayer(CHARLEZARD, NORCAL)
favoritePlayersRepository.addPlayer(IMYT, NORCAL)
favoritePlayersRepository.addPlayer(SNAP, NORCAL)
identityRepository.setIdentity(CHARLEZARD, NORCAL)
val states = mutableListOf<RankingsAndFavoritesViewModel.State>()
viewModel.stateLiveData.observeForever {
states.add(it)
}
assertEquals(1, states.size)
assertFalse(states[0].hasContent)
assertFalse(states[0].isRefreshing)
assertEquals(7, states[0].list.size)
var identity = states[0].list[0] as ListItem.Identity
assertEquals(CHARLEZARD, identity.player)
assertEquals(PreviousRank.GONE, identity.previousRank)
assertNull(identity.avatar)
assertNull(identity.rank)
assertNull(identity.rating)
assertEquals(CHARLEZARD.name, identity.tag)
assertEquals(ListItem.Header.Favorites, states[0].list[1])
var player = states[0].list[2] as ListItem.Player
assertEquals(CHARLEZARD, player.player)
assertTrue(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[0].list[3] as ListItem.Player
assertEquals(IMYT, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[0].list[4] as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, states[0].list[5])
assertEquals(ListItem.Fetching.Rankings, states[0].list[6])
assertNull(states[0].searchResults)
assertNull(states[0].rankingsBundle)
viewModel.fetchRankings(GOOGLE_MTV)
assertEquals(3, states.size)
assertFalse(states[1].hasContent)
assertTrue(states[1].isRefreshing)
assertEquals(7, states[1].list.size)
identity = states[1].list[0] as ListItem.Identity
assertEquals(CHARLEZARD, identity.player)
assertEquals(PreviousRank.GONE, identity.previousRank)
assertNull(identity.avatar)
assertNull(identity.rank)
assertNull(identity.rating)
assertEquals(CHARLEZARD.name, identity.tag)
assertEquals(ListItem.Header.Favorites, states[1].list[1])
player = states[1].list[2] as ListItem.Player
assertEquals(CHARLEZARD, player.player)
assertTrue(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[1].list[3] as ListItem.Player
assertEquals(IMYT, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[1].list[4] as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, states[1].list[5])
assertEquals(ListItem.Fetching.Rankings, states[1].list[6])
assertNull(states[1].searchResults)
assertNull(states[1].rankingsBundle)
assertTrue(states[2].hasContent)
assertFalse(states[2].isRefreshing)
assertEquals(7, states[2].list.size)
identity = states[2].list[0] as ListItem.Identity
assertEquals(CHARLEZARD, identity.player)
assertEquals(PreviousRank.GONE, identity.previousRank)
assertNull(identity.avatar)
assertNull(identity.rank)
assertNull(identity.rating)
assertEquals(CHARLEZARD.name, identity.tag)
assertEquals(ListItem.Header.Favorites, states[2].list[1])
player = states[2].list[2] as ListItem.Player
assertEquals(CHARLEZARD, player.player)
assertTrue(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[2].list[3] as ListItem.Player
assertEquals(IMYT, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = states[2].list[4] as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, states[2].list[5])
assertEquals(ListItem.Empty.Rankings, states[2].list[6])
assertNull(states[2].searchResults)
assertEquals(GOOGLE_MTV_RANKINGS_BUNDLE, states[2].rankingsBundle)
}
@Test
fun testFetchRankingsWithNycAndHaxAsIdentity() {
identityRepository.setIdentity(HAX, NYC)
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NYC)
assertEquals(false, state?.isRefreshing)
assertEquals(true, state?.hasContent)
assertEquals(7, state?.list?.size)
val identity = state?.list?.get(0) as ListItem.Identity
assertEquals(HAX, identity.player)
assertEquals(PreviousRank.GONE, identity.previousRank)
assertNull(identity.avatar)
assertFalse(identity.rank.isNullOrBlank())
assertFalse(identity.rating.isNullOrBlank())
assertEquals(HAX.name, identity.tag)
assertEquals(ListItem.Header.Favorites, state?.list?.get(1))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(2))
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
var player = state?.list?.get(4) as ListItem.Player
assertEquals(HAX, player.player)
assertTrue(player.isIdentity)
assertEquals(HAX.rank, player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(5) as ListItem.Player
assertEquals(IBDW, player.player)
assertFalse(player.isIdentity)
assertEquals(IBDW.rank, player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(6) as ListItem.Player
assertEquals(RISHI, player.player)
assertFalse(player.isIdentity)
assertEquals(RISHI.rank, player.rawRank)
assertEquals(PreviousRank.GONE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertNull(state?.searchResults)
assertEquals(NYC_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testInitialState() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
assertEquals(false, state?.isRefreshing)
assertEquals(false, state?.hasContent)
assertEquals(4, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
assertEquals(ListItem.Header.Rankings, state?.list?.get(2))
assertEquals(ListItem.Fetching.Rankings, state?.list?.get(3))
assertNull(state?.searchResults)
assertNull(state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithA() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = "a"
assertEquals(9, state?.list?.size)
assertEquals(6, state?.searchResults?.size)
assertEquals(ListItem.Header.Favorites, state?.searchResults?.get(0))
val noResults = state?.searchResults?.get(1) as ListItem.NoResults
assertEquals("a", noResults.query)
assertEquals(ListItem.Header.Rankings, state?.searchResults?.get(2))
var player = state?.searchResults?.get(3) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(4) as ListItem.Player
assertEquals(UMARTH, player.player)
assertFalse(player.isIdentity)
assertEquals(UMARTH.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(5) as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertEquals(SNAP.rank, player.rawRank)
assertEquals(PreviousRank.INCREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithBlankString() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = " "
assertEquals(9, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
val activityRequirements = state?.list?.get(2) as ListItem.ActivityRequirements
assertEquals(NORCAL.rankingActivityDayLimit, activityRequirements.rankingActivityDayLimit)
assertEquals(NORCAL.rankingNumTourneysAttended, activityRequirements.rankingNumTourneysAttended)
assertEquals(NORCAL.displayName, activityRequirements.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
var player = state?.list?.get(4) as ListItem.Player
assertEquals(NMW, player.player)
assertFalse(player.isIdentity)
assertEquals(NMW.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(5) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(6) as ListItem.Player
assertEquals(UMARTH, player.player)
assertFalse(player.isIdentity)
assertEquals(UMARTH.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(7) as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(8) as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertEquals(SNAP.rank, player.rawRank)
assertEquals(PreviousRank.INCREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertNull(state?.searchResults)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithEmptyString() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = ""
assertEquals(true, state?.hasContent)
assertEquals(false, state?.isRefreshing)
assertEquals(9, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
val activityRequirements = state?.list?.get(2) as ListItem.ActivityRequirements
assertEquals(NORCAL.rankingActivityDayLimit, activityRequirements.rankingActivityDayLimit)
assertEquals(NORCAL.rankingNumTourneysAttended, activityRequirements.rankingNumTourneysAttended)
assertEquals(NORCAL.displayName, activityRequirements.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
var player = state?.list?.get(4) as ListItem.Player
assertEquals(NMW, player.player)
assertFalse(player.isIdentity)
assertEquals(NMW.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(5) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(6) as ListItem.Player
assertEquals(UMARTH, player.player)
assertFalse(player.isIdentity)
assertEquals(UMARTH.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(7) as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(8) as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertEquals(SNAP.rank, player.rawRank)
assertEquals(PreviousRank.INCREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertNull(state?.searchResults)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithZAndCharlezardAsIdentityAndSomeFavoritesAndThenRemoveIdentity() {
favoritePlayersRepository.addPlayer(AZEL, NORCAL)
favoritePlayersRepository.addPlayer(CHARLEZARD, NORCAL)
favoritePlayersRepository.addPlayer(HAX, NYC)
favoritePlayersRepository.addPlayer(MIKKUZ, NORCAL)
favoritePlayersRepository.addPlayer(UMARTH, NORCAL)
identityRepository.setIdentity(CHARLEZARD, NORCAL)
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = "z"
assertEquals(14, state?.list?.size)
assertEquals(7, state?.searchResults?.size)
assertEquals(ListItem.Header.Favorites, state?.searchResults?.get(0))
var player = state?.searchResults?.get(1) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(2) as ListItem.Player
assertEquals(CHARLEZARD, player.player)
assertTrue(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = state?.searchResults?.get(3) as ListItem.Player
assertEquals(MIKKUZ, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.searchResults?.get(4))
player = state?.searchResults?.get(5) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(6) as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
identityRepository.removeIdentity()
assertEquals(13, state?.list?.size)
assertEquals(7, state?.searchResults?.size)
assertEquals(ListItem.Header.Favorites, state?.searchResults?.get(0))
player = state?.searchResults?.get(1) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(2) as ListItem.Player
assertEquals(CHARLEZARD, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
player = state?.searchResults?.get(3) as ListItem.Player
assertEquals(MIKKUZ, player.player)
assertFalse(player.isIdentity)
assertNull(player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertNull(player.rank)
assertNull(player.rating)
assertEquals(NORCAL.displayName, player.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.searchResults?.get(4))
player = state?.searchResults?.get(5) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.searchResults?.get(6) as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithNullString() {
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = null
assertEquals(true, state?.hasContent)
assertEquals(false, state?.isRefreshing)
assertEquals(9, state?.list?.size)
assertEquals(ListItem.Header.Favorites, state?.list?.get(0))
assertEquals(ListItem.Empty.Favorites, state?.list?.get(1))
val activityRequirements = state?.list?.get(2) as ListItem.ActivityRequirements
assertEquals(NORCAL.rankingActivityDayLimit, activityRequirements.rankingActivityDayLimit)
assertEquals(NORCAL.rankingNumTourneysAttended, activityRequirements.rankingNumTourneysAttended)
assertEquals(NORCAL.displayName, activityRequirements.regionDisplayName)
assertEquals(ListItem.Header.Rankings, state?.list?.get(3))
var player = state?.list?.get(4) as ListItem.Player
assertEquals(NMW, player.player)
assertFalse(player.isIdentity)
assertEquals(NMW.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(5) as ListItem.Player
assertEquals(AZEL, player.player)
assertFalse(player.isIdentity)
assertEquals(AZEL.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(6) as ListItem.Player
assertEquals(UMARTH, player.player)
assertFalse(player.isIdentity)
assertEquals(UMARTH.rank, player.rawRank)
assertEquals(PreviousRank.INVISIBLE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(7) as ListItem.Player
assertEquals(YCZ6, player.player)
assertFalse(player.isIdentity)
assertEquals(YCZ6.rank, player.rawRank)
assertEquals(PreviousRank.DECREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
player = state?.list?.get(8) as ListItem.Player
assertEquals(SNAP, player.player)
assertFalse(player.isIdentity)
assertEquals(SNAP.rank, player.rawRank)
assertEquals(PreviousRank.INCREASE, player.previousRank)
assertFalse(player.rank.isNullOrBlank())
assertFalse(player.rating.isNullOrBlank())
assertNull(player.regionDisplayName)
assertNull(state?.searchResults)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
@Test
fun testSearchNorcalWithWaduAndImytAsIdentity() {
identityRepository.setIdentity(IMYT, NORCAL)
var state: RankingsAndFavoritesViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
viewModel.fetchRankings(NORCAL)
viewModel.searchQuery = "wadu"
assertEquals(10, state?.list?.size)
assertEquals(4, state?.searchResults?.size)
assertEquals(ListItem.Header.Favorites, state?.searchResults?.get(0))
var noResults = state?.searchResults?.get(1) as ListItem.NoResults
assertEquals("wadu", noResults.query)
assertEquals(ListItem.Header.Rankings, state?.searchResults?.get(2))
noResults = state?.searchResults?.get(3) as ListItem.NoResults
assertEquals("wadu", noResults.query)
assertEquals(NORCAL_RANKINGS_BUNDLE, state?.rankingsBundle)
}
companion object {
private val AZEL = RankedPlayer(
id = "588852e8d2994e3bbfa52d9f",
name = "Azel",
rating = 42.30158803535407f,
rank = 2,
previousRank = 2
)
private val CHARLEZARD = LitePlayer(
id = "587a951dd2994e15c7dea9fe",
name = "Charlezard"
)
private val IMYT = LitePlayer(
id = "5877eb55d2994e15c7dea98b",
name = "Imyt"
)
private val IBDW = RankedPlayer(
id = "57470593e59257583a0756db",
name = "iBDW",
rating = 41.98998559382721f,
rank = 2
)
private val HAX = RankedPlayer(
id = "53c64dba8ab65f6e6651f7bc",
name = "Hax",
rating = 42.71520580698563f,
rank = 1
)
private val NMW = RankedPlayer(
id = "5e2427d5d2994e6bf4d676eb",
name = "NMW",
rating = 42.556818424504314f,
rank = 1,
previousRank = 1
)
private val RISHI = RankedPlayer(
id = "5778339fe592575dfd89bd0e",
name = "Rishi",
rating = 41.55162805506685f,
rank = 3
)
private val MIKKUZ = LitePlayer(
id = "583a4a15d2994e0577b05c74",
name = "mikkuz"
)
private val SNAP = RankedPlayer(
id = "59213f1ad2994e1d79144956",
name = "Snap",
rating = 33.59832158713955f,
rank = 18,
previousRank = 20
)
private val UMARTH = RankedPlayer(
id = "5877eb55d2994e15c7dea977",
name = "Umarth",
rating = 40.90797800656901f,
rank = 3,
previousRank = 3
)
private val YCZ6 = RankedPlayer(
id = "5888542ad2994e3bbfa52de4",
name = "ycz6",
rating = 35.02962221777487f,
rank = 12,
previousRank = 11
)
private val GOOGLE_MTV = Region(
displayName = "Google MTV",
id = "googlemtv",
endpoint = Endpoint.GAR_PR
)
private val NORCAL = Region(
rankingActivityDayLimit = 60,
rankingNumTourneysAttended = 2,
displayName = "Norcal",
id = "norcal",
endpoint = Endpoint.GAR_PR
)
private val NYC = Region(
displayName = "New York City",
id = "nyc",
endpoint = Endpoint.NOT_GAR_PR
)
private val GOOGLE_MTV_RANKINGS_BUNDLE = RankingsBundle(
rankingCriteria = GOOGLE_MTV,
time = with(Calendar.getInstance()) {
clear()
set(Calendar.YEAR, 2017)
set(Calendar.MONTH, Calendar.MAY)
set(Calendar.DAY_OF_MONTH, 20)
SimpleDate(time)
},
id = "E6CF8660",
region = GOOGLE_MTV.id
)
private val NORCAL_RANKINGS_BUNDLE = RankingsBundle(
rankingCriteria = NORCAL,
rankings = listOf(NMW, AZEL, UMARTH, YCZ6, SNAP),
time = with(Calendar.getInstance()) {
clear()
set(Calendar.YEAR, 2018)
set(Calendar.MONTH, Calendar.APRIL)
set(Calendar.DAY_OF_MONTH, 28)
SimpleDate(time)
},
id = "1A9C9DD4",
region = NORCAL.id
)
private val NYC_RANKINGS_BUNDLE = RankingsBundle(
rankingCriteria = NYC,
rankings = listOf(HAX, IBDW, RISHI),
time = with(Calendar.getInstance()) {
clear()
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, Calendar.OCTOBER)
set(Calendar.DAY_OF_MONTH, 17)
SimpleDate(time)
},
id = "7F053ECF",
region = NYC.id
)
}
private class RankingsRepositoryOverride : RankingsRepository {
override fun getRankings(region: Region): Single<RankingsBundle> {
return when (region) {
GOOGLE_MTV -> Single.just(GOOGLE_MTV_RANKINGS_BUNDLE)
NORCAL -> Single.just(NORCAL_RANKINGS_BUNDLE)
NYC -> Single.just(NYC_RANKINGS_BUNDLE)
else -> Single.error(NoSuchElementException())
}
}
}
}
|
unlicense
|
055b4caa84a0601e66af47a3ee561072
| 39.097159 | 104 | 0.675467 | 4.918597 | false | false | false | false |
wuseal/JsonToKotlinClass
|
gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/GetChangelogTask.kt
|
1
|
1569
|
package org.jetbrains.changelog.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.jetbrains.changelog.Changelog
import org.jetbrains.changelog.ChangelogPluginExtension
import java.io.File
open class GetChangelogTask : DefaultTask() {
private val extension = project.extensions.getByType(ChangelogPluginExtension::class.java)
private var noHeader = false
@Suppress("UnstableApiUsage")
@Option(option = "no-header", description = "Omits header version line")
fun setNoHeader(noHeader: Boolean) {
this.noHeader = noHeader
}
@Input
fun getNoHeader() = noHeader
private var unreleased = false
@Suppress("UnstableApiUsage")
@Option(option = "unreleased", description = "Returns Unreleased change notes")
fun setUnreleased(unreleased: Boolean) {
this.unreleased = unreleased
}
@Input
fun getUnreleased() = unreleased
@InputFile
fun getInputFile() = File(extension.path)
@OutputFile
fun getOutputFile() = getInputFile()
@TaskAction
fun run() = logger.quiet(
Changelog(extension).run {
val version = when (unreleased) {
true -> extension.unreleasedTerm
false -> extension.version
}
get(version).run {
withHeader(!noHeader)
toText()
}
}
)
}
|
gpl-3.0
|
e58c3a055e70501bd085fba206b084ca
| 26.051724 | 94 | 0.669853 | 4.444759 | false | false | false | false |
MyDogTom/detekt
|
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/ComplexMethod.kt
|
1
|
1201
|
package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdRule
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.api.internal.McCabeVisitor
import org.jetbrains.kotlin.psi.KtNamedFunction
/**
* @author Artur Bosch
*/
class ComplexMethod(config: Config = Config.empty,
threshold: Int = DEFAULT_ACCEPTED_METHOD_COMPLEXITY) : ThresholdRule(config, threshold) {
override val issue = Issue("ComplexMethod",
Severity.Maintainability,
"Prefer splitting up complex methods into smaller, " +
"easier to understand methods.")
override fun visitNamedFunction(function: KtNamedFunction) {
val visitor = McCabeVisitor()
visitor.visitNamedFunction(function)
val mcc = visitor.mcc
if (mcc > threshold) {
report(ThresholdedCodeSmell(issue, Entity.from(function), Metric("MCC", mcc, threshold)))
}
}
}
private const val DEFAULT_ACCEPTED_METHOD_COMPLEXITY = 10
|
apache-2.0
|
548510dd75cbdc5bceafd0401b64dead
| 34.323529 | 94 | 0.786844 | 3.861736 | false | true | false | false |
dataloom/conductor-client
|
src/test/kotlin/com/openlattice/hazelcast/serializers/CollectionTemplatesStreamSerializerTest.kt
|
1
|
1085
|
package com.openlattice.hazelcast.serializers
import com.google.common.collect.Maps
import com.kryptnostic.rhizome.hazelcast.serializers.AbstractStreamSerializerTest
import com.openlattice.collections.CollectionTemplates
import org.apache.commons.lang3.RandomUtils
import java.util.*
import java.util.concurrent.ConcurrentMap
class CollectionTemplatesStreamSerializerTest : AbstractStreamSerializerTest<CollectionTemplatesStreamSerializer, CollectionTemplates>() {
override fun createSerializer(): CollectionTemplatesStreamSerializer {
return CollectionTemplatesStreamSerializer()
}
override fun createInput(): CollectionTemplates {
val templates = mutableMapOf<UUID, MutableMap<UUID, UUID>>()
for (i in 0..4) {
val size = RandomUtils.nextInt(1, 5)
val map = Maps.newConcurrentMap<UUID, UUID>()
for (j in 0 until size) {
map[UUID.randomUUID()] = UUID.randomUUID()
}
templates[UUID.randomUUID()] = map
}
return CollectionTemplates(templates)
}
}
|
gpl-3.0
|
3225f385fea7bb0bd2b2cbfe0fd660b8
| 31.909091 | 138 | 0.717972 | 5.344828 | false | true | false | false |
Jire/POMade
|
src/main/kotlin/org/jire/pomade/pom/XMLElement.kt
|
1
|
272
|
package org.jire.pomade.pom
const val INDENT_SPACING = " "
interface XMLElement {
fun generate(indent: Int = 0): String
operator fun Int.invoke(extra: Int = 0): String {
var spaces = ""
for (i in 0..this + extra) spaces += INDENT_SPACING
return spaces
}
}
|
mit
|
e4a8405193f8124b43e4e72a0d9d4222
| 17.2 | 53 | 0.665441 | 3.126437 | false | false | false | false |
b3er/idea-archive-browser
|
src/main/kotlin/com/github/b3er/idea/plugins/arc/browser/util/Psi.kt
|
1
|
2384
|
package com.github.b3er.idea.plugins.arc.browser.util
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.BasePsiNode
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode
import com.intellij.ide.projectView.impl.nodes.PsiFileNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleFileIndex
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileSystemItem
import com.intellij.util.containers.ContainerUtil
fun processPsiDirectoryChildren(
children: Array<PsiElement>,
container: MutableList<AbstractTreeNode<*>>, moduleFileIndex: ModuleFileIndex?,
viewSettings: ViewSettings
) {
for (child in children) {
if (child !is PsiFileSystemItem) {
continue
}
val vFile = child.virtualFile ?: continue
if (moduleFileIndex != null && !moduleFileIndex.isInContent(vFile)) {
continue
}
if (child is PsiFile) {
container.add(PsiFileNode(child.getProject(), child, viewSettings))
} else if (child is PsiDirectory) {
container.add(PsiGenericDirectoryNode(child.getProject(), child, viewSettings))
}
}
}
@Suppress("NOTHING_TO_INLINE")
inline fun BasePsiNode<*>.processChildren(
dir: PsiDirectory
): MutableCollection<AbstractTreeNode<*>> {
val children = ArrayList<AbstractTreeNode<*>>()
val project = dir.project
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
val module = fileIndex.getModuleForFile(dir.virtualFile)
val moduleFileIndex = if (module == null) null else ModuleRootManager.getInstance(module).fileIndex
processPsiDirectoryChildren(dir.children, children, moduleFileIndex, settings)
return children
}
class PsiGenericDirectoryNode(
project: Project?, value: PsiDirectory,
viewSettings: ViewSettings?
) : PsiDirectoryNode(project, value, viewSettings) {
override fun getChildrenImpl(): MutableCollection<AbstractTreeNode<*>> {
val project = project
if (project != null) {
val psiDirectory = value
if (psiDirectory != null) {
return processChildren(psiDirectory)
}
}
return ContainerUtil.emptyList()
}
}
|
apache-2.0
|
4889b4f2b558390c29eb27223543f8ec
| 34.597015 | 101 | 0.768037 | 4.489642 | false | false | false | false |
timbotetsu/kotlin-koans
|
src/iv_properties/_33_LazyProperty.kt
|
1
|
693
|
package iv_properties
import util.TODO
class LazyProperty(val initializer: () -> Int) {
private val lazyValue: Int? = null
get() {
if (field == null) field = initializer()
return field
}
val lazy: Int
get() = lazyValue!!
}
fun todoTask33(): Nothing = TODO(
"""
Task 33.
Add a custom getter to make the 'lazy' val really lazy.
It should be initialized by the invocation of 'initializer()'
at the moment of the first access.
You can add as many additional properties as you need.
Do not use delegated properties!
""",
references = { LazyProperty({ 42 }).lazy }
)
|
mit
|
e83e7d9b949976be3983bdc75aa6613b
| 25.653846 | 69 | 0.58153 | 4.589404 | false | false | false | false |
wleroux/fracturedskies
|
src/main/kotlin/com/fracturedskies/task/TaskManagementSystem.kt
|
1
|
1756
|
package com.fracturedskies.task
import com.fracturedskies.api.World
import com.fracturedskies.api.entity.Colonist
import com.fracturedskies.api.task.*
import com.fracturedskies.engine.api.Update
import javax.enterprise.event.*
import javax.inject.Inject
/**
* This system is responsible for assigning the colonist to the desired task every tick
*/
class TaskManagementSystem {
@Inject
lateinit var events: Event<Any>
@Inject
lateinit var world: World
fun onUpdate(@Observes message: Update) {
world.colonists.values
.map { colonist -> colonist to getDesiredTask(world, colonist, world.tasks.values) }
.groupBy({ (_, desiredTask) -> desiredTask }, { (colonist, _) -> colonist })
.mapValues { entry ->
when {
entry.key != null && entry.value.size > 1 ->
listOf(entry.value.minBy { colonist -> entry.key?.details?.behavior?.cost(world, colonist) ?: 0 }!!)
else -> entry.value
}
}
.forEach { task, colonists ->
colonists.forEach { colonist ->
if (colonist.assignedTask != task?.id) {
world.selectTask(colonist.id, task?.id, message.cause)
}
}
}
}
private fun getDesiredTask(world: World, colonist: Colonist, tasks: Collection<Task>): Task? {
val comparator = colonistPriorityComparator(world)
var desiredTask: Task? = null
for (task in tasks.shuffled()) {
if (!task.details.condition.matches(world, colonist, task)) continue
if (desiredTask != null && comparator.compare(colonist, desiredTask, task) >= 0) continue
if (!task.details.behavior.isPossible(world, colonist)) continue
desiredTask = task
}
return desiredTask
}
}
|
unlicense
|
cfcbe6f23e0e43b623c5136d3c979af6
| 32.150943 | 114 | 0.649203 | 4.272506 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/order/OrderShipmentTrackingApiResponse.kt
|
2
|
409
|
package org.wordpress.android.fluxc.network.rest.wpcom.wc.order
import org.wordpress.android.fluxc.network.Response
@Suppress("PropertyName", "VariableNaming")
class OrderShipmentTrackingApiResponse : Response {
val tracking_id: String? = null
val tracking_provider: String? = null
val tracking_link: String? = null
val tracking_number: String? = null
val date_shipped: String? = null
}
|
gpl-2.0
|
31f47d8e88841f26867454b31ce32be7
| 33.083333 | 63 | 0.748166 | 3.895238 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/api/world/chunk/ChunkPosition.kt
|
1
|
2590
|
/*
* 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>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.world.chunk
import org.lanternpowered.server.world.chunk.ChunkPositionHelper
import org.spongepowered.math.vector.Vector3i
/**
* Represents a position of a chunk.
*/
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
inline class ChunkPosition @PublishedApi internal constructor(
internal val packed: Long
) {
/**
* Constructs a new [ChunkPosition] from the given x, y and z values.
*/
constructor(x: Int, y: Int, z: Int) : this(ChunkPositionHelper.pack(x, y, z))
/**
* The x coordinate.
*/
val x: Int
get() = ChunkPositionHelper.unpackX(this.packed)
/**
* The y coordinate.
*/
val y: Int
get() = ChunkPositionHelper.unpackY(this.packed)
/**
* The z coordinate.
*/
val z: Int
get() = ChunkPositionHelper.unpackZ(this.packed)
inline operator fun component1(): Int = this.x
inline operator fun component2(): Int = this.y
inline operator fun component3(): Int = this.z
/**
* The column this position belongs to.
*/
val column: ChunkColumnPosition
get() = ChunkColumnPosition(this.x, this.z)
fun offset(xOffset: Int, yOffset: Int, zOffset: Int): ChunkPosition =
ChunkPosition(this.x + xOffset, this.y + yOffset, this.z + zOffset)
fun west(): ChunkPosition = this.west(1)
fun west(offset: Int): ChunkPosition = this.offset(-offset, 0, 0)
fun east(): ChunkPosition = this.east(1)
fun east(offset: Int): ChunkPosition = this.offset(offset, 0, 0)
fun north(): ChunkPosition = this.north(1)
fun north(offset: Int): ChunkPosition = this.offset(0, 0, -offset)
fun south(): ChunkPosition = this.south(1)
fun south(offset: Int): ChunkPosition = this.offset(0, 0, offset)
fun up(): ChunkPosition = this.up(1)
fun up(offset: Int): ChunkPosition = this.offset(0, offset, 0)
fun down(): ChunkPosition = this.down(1)
fun down(offset: Int): ChunkPosition = this.offset(0, -offset, 0)
fun toVector(): Vector3i = Vector3i(this.x, this.y, this.z)
override fun toString(): String = "($x, $y, $z)"
companion object {
val None = ChunkPosition(Long.MAX_VALUE)
}
}
|
mit
|
cdc913de0472f3e8d07447b074e24beb
| 28.431818 | 81 | 0.653282 | 3.721264 | false | false | false | false |
andersonlucasg3/SpriteKit-Android
|
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKActionRotateBy.kt
|
1
|
1414
|
package br.com.insanitech.spritekit.actions
import br.com.insanitech.spritekit.SKEaseCalculations
import br.com.insanitech.spritekit.SKNode
/**
* Created by anderson on 06/01/17.
*/
internal class SKActionRotateBy(private val radians: Float) : SKAction() {
private var startRadians: Float = 0.0f
override fun computeStart(node: SKNode) {
this.startRadians = node.zRotation
}
override fun computeAction(node: SKNode, elapsed: Long) {
when (this.timingMode) {
SKActionTimingMode.EaseIn -> {
node.zRotation = SKEaseCalculations.easeIn(elapsed.toFloat(), this.startRadians, this.radians, this.duration.toFloat())
}
SKActionTimingMode.EaseOut -> {
node.zRotation = SKEaseCalculations.easeOut(elapsed.toFloat(), this.startRadians, this.radians, this.duration.toFloat())
}
SKActionTimingMode.EaseInEaseOut -> {
node.zRotation = SKEaseCalculations.easeInOut(elapsed.toFloat(), this.startRadians, this.radians, this.duration.toFloat())
}
SKActionTimingMode.Linear -> {
node.zRotation = SKEaseCalculations.linear(elapsed.toFloat(), this.startRadians, this.radians, this.duration.toFloat())
}
}
}
override fun computeFinish(node: SKNode) {
node.zRotation = this.startRadians + this.radians
}
}
|
bsd-3-clause
|
39ef10d053b7c591a632db53c0f59342
| 34.35 | 138 | 0.658416 | 4.56129 | false | false | false | false |
importre/ready-for-production
|
app/src/main/kotlin/io/github/importre/rfp/main/MainActivity.kt
|
1
|
3194
|
package io.github.importre.rfp.main
import android.os.Bundle
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.Menu
import android.view.MenuItem
import io.github.importre.rfp.BuildConfig
import io.github.importre.rfp.R
import io.github.importre.rfp.api.repo.Repository
import io.github.importre.rfp.app.App
import io.github.importre.rfp.ext.toast
import io.github.importre.rfp.presenter.MainPresenter
import io.github.importre.rfp.util.UiUtils
import io.github.importre.rfp.view.MainView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import java.util.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), MainView {
@Inject
lateinit var presenter: MainPresenter
private val user = BuildConfig.GITHUB_USER
private val adapter by lazy { RepoAdapter(this) }
private val handler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
inject()
initUi()
presenter.setView(this)
presenter.loadRepos(user, savedInstanceState == null)
}
override fun onDestroy() {
presenter.stop()
super.onDestroy()
}
private fun inject() {
(application as App).appComp.inject(this)
}
private fun initUi() {
setSupportActionBar(toolbar)
initRecyclerView()
initSwipeRefreshView()
}
private fun initRecyclerView() {
val span = if (UiUtils.isLandscape(this)) 2 else 1
val layoutManager = StaggeredGridLayoutManager(span, StaggeredGridLayoutManager.VERTICAL)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
}
private fun initSwipeRefreshView() {
swipeView.setOnRefreshListener { presenter.loadRepos(user, true) }
swipeView.setColorSchemeColors(
ContextCompat.getColor(this, R.color.color01),
ContextCompat.getColor(this, R.color.color02),
ContextCompat.getColor(this, R.color.color03),
ContextCompat.getColor(this, R.color.color04))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun showLoading(loading: Boolean) {
handler.postDelayed({
swipeView.isRefreshing = loading
}, 100)
}
override fun showError(error: Throwable) {
error.message?.let { toast(it) }
error.printStackTrace()
}
override fun showRepos(repositories: ArrayList<Repository>) {
adapter.run {
repos.clear()
repos.addAll(repositories)
notifyDataSetChanged()
}
}
}
|
apache-2.0
|
f6eea29fac5435174b0b95fac3820b7a
| 29.711538 | 97 | 0.683782 | 4.608947 | false | false | false | false |
zaviyalov/dialog
|
backend/src/main/kotlin/com/github/zaviyalov/dialog/common/Paths.kt
|
1
|
347
|
package com.github.zaviyalov.dialog.common
object Paths {
const val API_PREFIX = "/api"
const val LOGOUT_CONTROLLER = API_PREFIX + "/logout"
const val DIARY_ENTRY_CONTROLLER = API_PREFIX + "/diaryEntries"
const val BASAL_RATE_CONTROLLER = API_PREFIX + "/basalRates"
const val USER_INFO_CONTROLLER = API_PREFIX + "/userInfo"
}
|
bsd-3-clause
|
77c8e65e15a9ae1ef41df03f1f966402
| 37.555556 | 67 | 0.706052 | 3.540816 | false | false | false | false |
computerlove/Fiskeoversikt
|
plugins/repository/src/main/java/no/lillehaug/landingsopplysninger/repository/JdbcRepository.kt
|
1
|
5516
|
package no.lillehaug.landingsopplysninger.repository
import no.lillehaug.landingsopplysninger.api.LandingsdataFraTilQuery
import no.lillehaug.landingsopplysninger.api.LandingsopplysningerRepository
import no.lillehaug.landingsopplysninger.api.Leveringslinje
import no.lillehaug.landingsopplysninger.api.LeveringslinjeWithId
import no.lillehaug.landingsopplysninger.library.TryWR.Companion.trywr
import no.lillehaug.landingsopplysninger.repository.database.Database
import org.slf4j.LoggerFactory
import java.sql.Date
import java.time.LocalDate
import java.util.*
class JdbcRepository(val database: Database) : LandingsopplysningerRepository {
val log = LoggerFactory.getLogger(JdbcRepository::class.java)
override fun alleLeveranselinjer(): List<LeveringslinjeWithId> {
return this.alleLeveranselinjer(no.lillehaug.landingsopplysninger.api.LandingsdataFraTilQuery(null, null))
}
private fun getParams(landingsdataQuery: LandingsdataFraTilQuery): List<Any> {
val params = mutableListOf<Any>()
if(landingsdataQuery.fraDato != null){
params.add(Date.valueOf(landingsdataQuery.fraDato))
}
if(landingsdataQuery.tilDato != null){
params.add(Date.valueOf(landingsdataQuery.tilDato))
}
return params.toList()
}
private fun getWhere(landingsdataQuery: LandingsdataFraTilQuery) : String {
if(landingsdataQuery.tilDato == null && landingsdataQuery.fraDato == null) {
return ""
}
val parts = mutableListOf<String>()
if(landingsdataQuery.fraDato != null) {
parts.add(" landingsdato >= ?")
}
if(landingsdataQuery.tilDato != null) {
parts.add(" landingsdato <= ?")
}
return parts.joinToString(" AND ", "WHERE ")
}
override fun alleLeveranselinjer(landingsdataQuery: LandingsdataFraTilQuery): List<LeveringslinjeWithId> {
val where = getWhere(landingsdataQuery)
val params = getParams(landingsdataQuery)
return doQuery(params, where)
}
override fun alleLeveranselinjerByDates(num: Int, start: Int): List<LeveringslinjeWithId> {
val where = "where landingsdato in (select distinct landingsdato from leveringslinje order by landingsdato desc limit ? offset ?)"
return doQuery(listOf(num, start), where)
}
private fun doQuery(params: List<Any>, where: String): List<LeveringslinjeWithId> {
val sql = "select * from leveringslinje ${where} order by landingsdato desc,fiskeslag,kvalitet"
return database.readOnly {
val ps = it.prepareStatement(sql)
trywr(ps) {
var i = 1
for (param in params) {
ps.setObject(i++, param)
}
val rs = ps.executeQuery()
trywr(rs) {
val results = mutableListOf<LeveringslinjeWithId>()
while (rs.next()) {
results.add(
LeveringslinjeWithId(
rs.getObject("id", UUID::class.java),
rs.getString("fartøy"),
rs.getDate("landingsdato").toLocalDate(),
rs.getString("mottak"),
rs.getString("fiskeslag"),
rs.getString("tilstand"),
rs.getString("størrelse"),
rs.getString("kvalitet"),
rs.getDouble("nettovekt")))
}
results.toList()
}
}
}
}
override fun lagreLeveranselinjer(leveranselinjer: Collection<Leveringslinje>) {
if (leveranselinjer.isNotEmpty()) {
database.transactional {
val ps = it.prepareStatement("insert into leveringslinje(fartøy, landingsdato, mottak, fiskeslag, tilstand, størrelse, kvalitet, nettovekt) values (?,?,?,?,?,?,?,?)")
trywr(ps){
leveranselinjer.forEach {
ps.setString(1, it.fartøy)
ps.setDate(2, Date.valueOf(it.landingsdato))
ps.setString(3, it.mottak)
ps.setString(4, it.fiskeslag)
ps.setString(5, it.tilstand)
ps.setString(6, it.størrelse)
ps.setString(7, it.kvalitet)
ps.setDouble(8, it.nettovekt)
ps.addBatch()
}
val numInserted = ps.executeBatch()
log.info("Inserted {} rows", numInserted.size)
}
}
}
}
override fun forrigeLandingFor(registration: String): LocalDate {
return database.readOnly {
val ps = it.prepareStatement("select max(landingsdato) as landingsdato from leveringslinje where fartøy = ?")
trywr(ps){
ps.setString(1, registration)
val rs = ps.executeQuery()
trywr(rs){
if(rs.next()) {
rs.getDate("landingsdato")?.toLocalDate() ?: LocalDate.MIN
} else {
LocalDate.MIN
}
}
}
}
}
}
|
apache-2.0
|
d1ddf4c968a390f8304bce4712186e6c
| 41.376923 | 182 | 0.557633 | 5.143791 | false | false | false | false |
SimonVT/cathode
|
cathode/src/main/java/net/simonvt/cathode/ui/HomeViewModel.kt
|
1
|
1683
|
/*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.Movie
import net.simonvt.cathode.entity.ShowWithEpisode
import net.simonvt.cathode.entitymapper.MovieMapper
import net.simonvt.cathode.entitymapper.ShowWithEpisodeMapper
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.ProviderSchematic.Shows
class HomeViewModel(application: Application) : AndroidViewModel(application) {
val watchingShow: LiveData<ShowWithEpisode>
val watchingMovie: LiveData<Movie>
init {
watchingShow = MappedCursorLiveData(
application,
Shows.SHOW_WATCHING,
ShowWithEpisodeMapper.projection,
mapper = ShowWithEpisodeMapper,
allowNulls = true
)
watchingMovie = MappedCursorLiveData(
application,
Movies.WATCHING,
MovieMapper.projection,
mapper = MovieMapper,
allowNulls = true
)
}
}
|
apache-2.0
|
475ef25f9217ee7689254db9ab6f227b
| 32 | 79 | 0.767677 | 4.5 | false | false | false | false |
if710/if710.github.io
|
2019-09-04/DataManagement/app/src/main/java/br/ufpe/cin/android/datamanagement/SqlEstadosHelperAnko.kt
|
1
|
1862
|
package br.ufpe.cin.android.datamanagement
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*
//TODO restringir o construtor
class SqlEstadosHelperAnko(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "if710", null, 1) {
internal val estadosBrasil: Array<String> = ctx.resources.getStringArray(R.array.estadosBrasil)
//public static String DATABASE_TABLE = "estados";
companion object {
//Nome da tabela do Banco a ser usada
val DATABASE_TABLE = "estados"
//Versão atual do banco
private val DB_VERSION = 1
//colunas
val STATE_CODE = "uf"
val STATE_NAME = "name"
val _ID = "_id"
val columns = arrayOf(_ID, STATE_CODE, STATE_NAME)
private var instance: SqlEstadosHelperAnko? = null
@Synchronized
fun getInstance(ctx: Context): SqlEstadosHelperAnko {
if (instance == null) {
instance = SqlEstadosHelperAnko(ctx.applicationContext)
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
db.createTable(DATABASE_TABLE, true,
_ID to INTEGER + PRIMARY_KEY,
STATE_CODE to TEXT,
STATE_NAME to TEXT)
var i = 1
val nomeEstado = "indefinido"
for (siglaEstado in estadosBrasil) {
db.insert(DATABASE_TABLE,
_ID to i,
STATE_CODE to siglaEstado,
STATE_NAME to nomeEstado)
i++
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
//nao estamos usando
}
}
// Access property for Context
val Context.database: SqlEstadosHelperAnko
get() = SqlEstadosHelperAnko.getInstance(getApplicationContext())
|
mit
|
5eb3ff9d06d4083b551485fca54a3d2f
| 30.542373 | 103 | 0.613111 | 4.430952 | false | false | false | false |
hartwigmedical/hmftools
|
cider/src/main/java/com/hartwig/hmftools/cider/VJReadLayoutFile.kt
|
1
|
3882
|
package com.hartwig.hmftools.cider
import com.hartwig.hmftools.cider.layout.ReadLayout
import com.hartwig.hmftools.common.codon.Codons
import com.hartwig.hmftools.common.utils.FileWriterUtils.createGzipBufferedWriter
import htsjdk.samtools.SAMUtils
import java.io.BufferedWriter
import java.io.File
object VJReadLayoutFile
{
private const val FILE_EXTENSION = ".cider.layout.gz"
private fun generateFilename(basePath: String, sample: String): String
{
return basePath + File.separator + sample + FILE_EXTENSION
}
@JvmStatic
fun writeLayouts(outputDir: String, sampleId: String, overlayMap: Map<VJGeneType, List<ReadLayout>>, minSoftClipBases: Int)
{
val filePath = generateFilename(outputDir, sampleId)
createGzipBufferedWriter(filePath).use { writer ->
for ((geneType, overlayList) in overlayMap)
{
writeLayouts(writer, geneType, overlayList)
}
}
}
private fun writeLayouts(writer: BufferedWriter, geneType: VJGeneType, overlayList: List<ReadLayout>)
{
val vjReadLayoutAdaptor = VJReadLayoutAdaptor(0)
// sort the overlays by number of reads
val sortedOverlayList = overlayList.sortedByDescending({ o -> o.reads.size })
for (layout in sortedOverlayList)
{
writeLayout(layout, geneType, vjReadLayoutAdaptor, writer)
}
}
private fun writeLayout(
overlay: ReadLayout,
geneType: VJGeneType,
vjReadLayoutAdaptor: VJReadLayoutAdaptor,
writer: BufferedWriter)
{
// count how many split reads
val numSplitReads5Bases = overlay.reads.map { o -> vjReadLayoutAdaptor.toReadCandidate(o) }
.count { o -> Math.max(o.leftSoftClip, o.rightSoftClip) >= 5 }
val numSplitReads10Bases = overlay.reads.map { o -> vjReadLayoutAdaptor.toReadCandidate(o) }
.count { o -> Math.max(o.leftSoftClip, o.rightSoftClip) >= 10 }
val anchorRange = vjReadLayoutAdaptor.getAnchorRange(geneType, overlay)
// if there is no anchor within this layout then don't write it
if (anchorRange == null)
return
var sequence = overlay.consensusSequence()
var support = overlay.highQualSupportString()
// make sure aligned to codon
val codonAlignedSeq = sequence.drop(anchorRange.first % 3)
val aa = insertDashes(Codons.aminoAcidFromBases(codonAlignedSeq), IntRange(anchorRange.first / 3, (anchorRange.last + 1) / 3 - 1))
// insert - into the sequence and support
sequence = insertDashes(sequence, anchorRange)
support = insertDashes(support, anchorRange)
writer.write("${overlay.id} type: ${geneType}, read count: ${overlay.reads.size}, split(5) read count: ${numSplitReads5Bases}, ")
writer.write("split(10) read count: ${numSplitReads10Bases}, ")
writer.write("AA: ${aa}, ")
writer.write("aligned: ${overlay.alignedPosition}\n")
writer.write(" ${sequence}\n")
writer.write(" ${support}\n")
for (r in overlay.reads)
{
val read: VJReadCandidate = vjReadLayoutAdaptor.toReadCandidate(r)
val readPadding = Math.max(overlay.alignedPosition - r.alignedPosition, 0)
val paddedSeq = " ".repeat(readPadding) + r.sequence
val paddedQual = " ".repeat(readPadding) + SAMUtils.phredToFastq(r.baseQualities)
writer.write(" read: ${read.read}, aligned: ${r.alignedPosition}\n")
writer.write(" ${insertDashes(paddedSeq, anchorRange)}\n")
writer.write(" ${insertDashes(paddedQual, anchorRange)}\n")
}
}
private fun insertDashes(str: String, anchorRange: IntRange): String
{
return CiderUtils.insertDashes(str, anchorRange.first, anchorRange.last + 1)
}
}
|
gpl-3.0
|
a960b7c940821445273d2c4c8740f5c4
| 38.622449 | 138 | 0.659196 | 4.38149 | false | false | false | false |
d3xter/bo-android
|
app/src/main/java/org/blitzortung/android/app/controller/ButtonColumnHandler.kt
|
1
|
2930
|
/*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.app.controller
import android.view.View
import android.widget.RelativeLayout
import org.blitzortung.android.app.helper.ViewHelper
class ButtonColumnHandler<V : View, G : Enum<G>>(private val buttonSize: Float) {
data class GroupedView<V, G>(val view: V, val groups: Set<G>) {
constructor(view: V, vararg groups: G) : this(view, groups.toSet()) {}
}
private val elements: MutableList<GroupedView<V, G>>
init {
elements = arrayListOf()
}
fun addElement(element: V, vararg groups: G) {
elements.add(GroupedView(element, *groups))
}
fun addAllElements(elements: Collection<V>, vararg groups: G) {
this.elements.addAll(elements.map { GroupedView(it, *groups) })
}
fun lockButtonColumn(vararg groups: G) {
enableButtonElements(false, *groups)
}
fun unlockButtonColumn(vararg groups: G) {
enableButtonElements(true, *groups)
}
private fun enableButtonElements(enabled: Boolean, vararg groups: G) {
val filter: (GroupedView<V, G>) -> Boolean = if (groups.isEmpty()) {
element -> true
} else {
element -> element.groups.intersect(groups.toSet()).isNotEmpty()
}
elements.filter { filter.invoke(it) }.forEach {
it.view.isEnabled = enabled
}
}
fun updateButtonColumn() {
var previousIndex = -1
for (currentIndex in elements.indices) {
val element = elements[currentIndex]
val view = element.view
if (view.visibility == View.VISIBLE) {
val lp = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
lp.width = ViewHelper.pxFromSp(view, buttonSize).toInt()
lp.height = ViewHelper.pxFromSp(view, buttonSize).toInt()
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1)
if (previousIndex < 0) {
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1)
} else {
lp.addRule(RelativeLayout.BELOW, elements[previousIndex].view.id)
}
view.layoutParams = lp
previousIndex = currentIndex
}
}
}
}
|
apache-2.0
|
2eff00fd87a64136f2ebf99e944c72f9
| 31.910112 | 107 | 0.630932 | 4.520062 | false | false | false | false |
nickthecoder/paratask
|
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ProjectWindow.kt
|
1
|
6330
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.project
import javafx.beans.binding.Bindings
import javafx.geometry.Side
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.ToolBar
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import javafx.scene.layout.Pane
import javafx.scene.layout.VBox
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.ParaTask
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.ToolBarTool
import uk.co.nickthecoder.paratask.gui.ShortcutHelper
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.paratask.tools.CustomTaskListTool
import uk.co.nickthecoder.paratask.tools.ExceptionTool
import uk.co.nickthecoder.paratask.tools.HomeTool
import uk.co.nickthecoder.paratask.tools.WebTool
import uk.co.nickthecoder.paratask.tools.places.DirectoryTool
import uk.co.nickthecoder.paratask.tools.places.TrashTool
import uk.co.nickthecoder.paratask.util.AutoExit
import uk.co.nickthecoder.tedi.TediArea
class ProjectWindow(width: Double = 800.0, height: Double = 600.0) {
val project = Project(this)
private val borderPane = BorderPane()
val scene = Scene(borderPane, width, height)
private var stage: Stage? = null
val tabs: ProjectTabs = ProjectTabs_Impl(this)
private val topToolBars = HBox()
private val rightToolBars = VBox()
private val bottomToolBars = HBox()
private val leftToolBars = VBox()
private val mainToolBar = ToolBar()
private val shortcuts = ShortcutHelper("ProjectWindow", borderPane)
init {
scene.userData = this
TediArea.style(scene)
topToolBars.styleClass.add("toolbar-container")
bottomToolBars.styleClass.addAll("toolbar-container", "bottom")
leftToolBars.styleClass.addAll("toolbar-container", "left")
rightToolBars.styleClass.addAll("toolbar-container", "right")
topToolBars.children.add(mainToolBar)
with(borderPane) {
center = tabs as Node
top = topToolBars
bottom = bottomToolBars
left = leftToolBars
right = rightToolBars
setPrefSize(800.0, 600.0)
}
with(mainToolBar.items) {
add(ParataskActions.PROJECT_OPEN.createButton(shortcuts) { onOpenProject() })
add(ParataskActions.PROJECT_SAVE.createButton(shortcuts) { onSaveProject() })
add(ParataskActions.QUIT.createButton(shortcuts) { onQuit() })
add(ParataskActions.WINDOW_NEW.createButton(shortcuts) { onNewWindow() })
add(ParataskActions.APPLICATION_ABOUT.createButton(shortcuts) { onAbout() })
}
}
fun onQuit() {
System.exit(0)
}
fun onNewWindow() {
val newWindow = ProjectWindow()
newWindow.placeOnStage(Stage())
newWindow.addDefaultTools()
}
fun addDefaultTools() {
addTool(HomeTool())
val customTasks = CustomTaskListTool()
customTasks.toolBarSideP.value = Side.TOP
val home = customTasks.toolsP.newValue()
home.taskP.value = DirectoryTool()
val trash = customTasks.toolsP.newValue()
trash.taskP.value = TrashTool()
addTool(customTasks)
}
fun placeOnStage(stage: Stage) {
GlobalShortcuts(scene, this)
ParaTask.style(scene)
stage.title = "ParaTask"
stage.scene = scene
AutoExit.show(stage)
this.stage = stage
}
fun addToolBar(toolBar: ToolBar, side: Side = Side.TOP) {
toolBar.styleClass.removeAll("bottom", "left", "right")
when (side) {
Side.TOP -> topToolBars.children.add(toolBar)
Side.RIGHT -> {
rightToolBars.children.add(toolBar)
toolBar.styleClass.add("right")
}
Side.BOTTOM -> {
bottomToolBars.children.add(toolBar)
toolBar.styleClass.add("bottom")
}
Side.LEFT -> {
leftToolBars.children.add(toolBar)
toolBar.styleClass.add("left")
}
}
}
fun removeToolBar(toolBar: ToolBar) {
topToolBars.children.remove(toolBar)
rightToolBars.children.remove(toolBar)
bottomToolBars.children.remove(toolBar)
leftToolBars.children.remove(toolBar)
}
fun toolBarTools(): List<ToolBarTool> {
val list = mutableListOf<ToolBarTool>()
fun add(toolBars: Pane) {
toolBars.children.forEach { child ->
if (child is ToolBarToolConnector.ConnectedToolBar) {
list.add(child.connector.tool)
}
}
}
add(topToolBars)
add(rightToolBars)
add(bottomToolBars)
add(leftToolBars)
return list
}
fun addTool(tool: Tool, select: Boolean = true): ProjectTab {
return tabs.addTool(tool, select = select)
}
fun onAbout() {
val about = WebTool("http://nickthecoder.co.uk/wiki/view/software/ParaTask")
tabs.addTool(about)
}
fun onOpenProject() {
TaskPrompter(NewProjectWindowTask()).placeOnStage(Stage())
}
fun onSaveProject() {
project.save()
}
fun handleException(e: Exception) {
try {
val tool = ExceptionTool(e)
addTool(tool)
} catch(e: Exception) {
}
}
fun toolChanged(currentTool: Tool) {
val prefix = project.projectFile?.nameWithoutExtension?.capitalize()?.plus(": ") ?: ""
stage?.titleProperty()?.bind(Bindings.concat(prefix, currentTool.longTitleProperty))
}
}
|
gpl-3.0
|
60f0b3b1cae9a030ad4914650a7bb02a
| 30.029412 | 94 | 0.659874 | 4.386694 | false | false | false | false |
jereksel/LibreSubstratum
|
app/src/test/kotlin/com/jereksel/libresubstratum/adapters/Type1SpinnerArrayAdapterTest.kt
|
1
|
2584
|
package com.jereksel.libresubstratum.adapters
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.support.v7.graphics.Palette
import android.widget.ListView
import android.widget.TextView
import com.jereksel.libresubstratum.BaseRobolectricTest
import com.jereksel.libresubstratum.R
import com.jereksel.libresubstratum.data.Type1ExtensionToString
import com.jereksel.libresubstratumlib.Type1Extension
import org.assertj.android.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.anko.find
import org.junit.Before
import org.junit.Test
import org.robolectric.RuntimeEnvironment
@Suppress("IllegalIdentifier")
class Type1SpinnerArrayAdapterTest: BaseRobolectricTest() {
lateinit var adapter: Type1SpinnerArrayAdapter
@Before
fun setUp() {
val objects = listOf(Type1Extension("a", true, "#ABCDEF"), Type1Extension("b", false, "")).map { Type1ExtensionToString(it) }
adapter = Type1SpinnerArrayAdapter(RuntimeEnvironment.application, objects)
}
@Test
fun `Type1 extension with color should have background and colored text`() {
val parent = ListView(RuntimeEnvironment.application)
val view = adapter.getView(0, null, parent)
val textView = view.find<TextView>(R.id.textView)
val swatch = Palette.Swatch(Color.parseColor("#ABCDEF"), 1)
assertThat(textView).hasText("a")
assertThat(textView).hasCurrentTextColor(swatch.titleTextColor)
assertThat((view.background as ColorDrawable).color).isEqualTo(Color.parseColor("#ABCDEF"))
}
@Test
fun `Type1 extension without color has white background and black text`() {
val parent = ListView(RuntimeEnvironment.application)
val view = adapter.getView(1, null, parent)
val textView = view.find<TextView>(R.id.textView)
assertThat(textView).hasText("b")
assertThat(textView).hasCurrentTextColor(Color.BLACK)
assertThat((view.background as ColorDrawable).color).isEqualTo(Color.WHITE)
}
@Test
fun `Translucent colors doesn't throw exceptions`() {
val objects = listOf(Type1Extension("a", true, "#33ABCDEF")).map { Type1ExtensionToString(it) }
adapter = Type1SpinnerArrayAdapter(RuntimeEnvironment.application, objects)
val parent = ListView(RuntimeEnvironment.application)
val view = adapter.getView(0, null, parent)
val view2 = adapter.getDropDownView(0, null, parent)
assertThat(view).isNotNull
assertThat(view2).isNotNull
}
}
|
mit
|
91f66e8fd9bd6b38c9dde21c2b2c285f
| 39.390625 | 133 | 0.740712 | 4.517483 | false | true | false | false |
rsiebert/TVHClient
|
app/src/main/java/org/tvheadend/tvhclient/service/htsp/HtspUtils.kt
|
1
|
29406
|
package org.tvheadend.tvhclient.service.htsp
import android.content.Intent
import org.tvheadend.data.entity.*
import org.tvheadend.htsp.HtspMessage
import timber.log.Timber
import java.util.*
fun convertMessageToChannelTagModel(tag: ChannelTag, msg: HtspMessage, channels: List<Channel>): ChannelTag {
if (msg.containsKey("tagId")) {
tag.tagId = msg.getInteger("tagId")
}
if (msg.containsKey("tagName")) {
tag.tagName = msg.getString("tagName")
}
if (msg.containsKey("tagIndex")) {
if (msg.getInteger("tagIndex") > 0) {
tag.tagIndex = msg.getInteger("tagIndex")
}
}
if (msg.containsKey("tagIcon")) {
if (!msg.getString("tagIcon").isNullOrEmpty()) {
tag.tagIcon = msg.getString("tagIcon")
}
}
if (msg.containsKey("tagTitledIcon")) {
if (msg.getInteger("tagTitledIcon") > 0) {
tag.tagTitledIcon = msg.getInteger("tagTitledIcon")
}
}
if (msg.containsKey("members")) {
val members = msg.getIntegerList("members")
tag.members = members
var channelCount = 0
for (channelId in members) {
for ((id) in channels) {
if (id == channelId) {
channelCount++
break
}
}
}
tag.channelCount = channelCount
}
return tag
}
fun convertMessageToChannelModel(channel: Channel, msg: HtspMessage): Channel {
if (msg.containsKey("channelId")) {
channel.id = msg.getInteger("channelId")
}
if (msg.containsKey("channelNumber") && msg.containsKey("channelNumberMinor")) {
val channelNumber = msg.getInteger("channelNumber")
val channelNumberMinor = msg.getInteger("channelNumberMinor")
channel.number = channelNumber
channel.numberMinor = channelNumberMinor
channel.displayNumber = "$channelNumber.$channelNumberMinor"
} else if (msg.containsKey("channelNumber")) {
val channelNumber = msg.getInteger("channelNumber")
channel.number = channelNumber
channel.displayNumber = "$channelNumber.0"
}
if (msg.containsKey("channelName")) {
channel.name = msg.getString("channelName")
}
if (msg.containsKey("channelIcon")) {
if (!msg.getString("channelIcon").isNullOrEmpty()) {
channel.icon = msg.getString("channelIcon")
}
}
if (msg.containsKey("eventId")) {
if (msg.getInteger("eventId") > 0) {
channel.eventId = msg.getInteger("eventId")
}
}
if (msg.containsKey("nextEventId")) {
if (msg.getInteger("nextEventId") > 0) {
channel.nextEventId = msg.getInteger("nextEventId")
}
}
if (msg.containsKey("tags")) {
val tags = msg.getIntegerList("tags")
channel.tags = tags
}
return channel
}
fun convertMessageToRecordingModel(recording: Recording, msg: HtspMessage): Recording {
if (msg.containsKey("id")) {
recording.id = msg.getInteger("id")
}
if (msg.containsKey("channel")) {
if (msg.getInteger("channel") > 0) {
recording.channelId = msg.getInteger("channel")
}
}
if (msg.containsKey("start")) {
// The message value is in seconds, convert to milliseconds
recording.start = msg.getLong("start") * 1000
}
if (msg.containsKey("stop")) {
// The message value is in seconds, convert to milliseconds
recording.stop = msg.getLong("stop") * 1000
}
if (msg.containsKey("startExtra")) {
recording.startExtra = msg.getLong("startExtra")
}
if (msg.containsKey("stopExtra")) {
recording.stopExtra = msg.getLong("stopExtra")
}
if (msg.containsKey("retention")) {
recording.retention = msg.getLong("retention")
}
if (msg.containsKey("priority")) {
recording.priority = msg.getInteger("priority")
}
if (msg.containsKey("eventId")) {
if (msg.getInteger("eventId") > 0) {
recording.eventId = msg.getInteger("eventId")
}
}
if (msg.containsKey("autorecId")) {
if (!msg.getString("autorecId").isNullOrEmpty()) {
recording.autorecId = msg.getString("autorecId")
}
}
if (msg.containsKey("timerecId")) {
if (!msg.getString("timerecId").isNullOrEmpty()) {
recording.timerecId = msg.getString("timerecId")
}
}
if (msg.containsKey("contentType")) {
if (msg.getInteger("contentType") > 0) {
recording.contentType = msg.getInteger("contentType")
}
}
if (msg.containsKey("title")) {
if (!msg.getString("title").isNullOrEmpty()) {
recording.title = msg.getString("title")
}
}
if (msg.containsKey("subtitle")) {
if (!msg.getString("subtitle").isNullOrEmpty()) {
recording.subtitle = msg.getString("subtitle")
}
}
if (msg.containsKey("summary")) {
if (!msg.getString("summary").isNullOrEmpty()) {
recording.summary = msg.getString("summary")
}
}
if (msg.containsKey("description")) {
if (!msg.getString("description").isNullOrEmpty()) {
recording.description = msg.getString("description")
}
}
if (msg.containsKey("state")) {
recording.state = msg.getString("state")
}
if (msg.containsKey("error")) {
if (!msg.getString("error").isNullOrEmpty()) {
recording.error = msg.getString("error")
}
}
if (msg.containsKey("owner")) {
if (!msg.getString("owner").isNullOrEmpty()) {
recording.owner = msg.getString("owner")
}
}
if (msg.containsKey("creator")) {
if (!msg.getString("creator").isNullOrEmpty()) {
recording.creator = msg.getString("creator")
}
}
if (msg.containsKey("subscriptionError")) {
if (!msg.getString("subscriptionError").isNullOrEmpty()) {
recording.subscriptionError = msg.getString("subscriptionError")
}
}
if (msg.containsKey("streamErrors")) {
if (!msg.getString("streamErrors").isNullOrEmpty()) {
recording.streamErrors = msg.getString("streamErrors")
}
}
if (msg.containsKey("dataErrors")) {
if (!msg.getString("dataErrors").isNullOrEmpty()) {
recording.dataErrors = msg.getString("dataErrors")
}
}
if (msg.containsKey("path")) {
if (!msg.getString("path").isNullOrEmpty()) {
recording.path = msg.getString("path")
}
}
if (msg.containsKey("dataSize")) {
if (msg.getLong("dataSize") > 0) {
recording.dataSize = msg.getLong("dataSize")
}
}
if (msg.containsKey("enabled")) {
recording.isEnabled = msg.getInteger("enabled") == 1
}
if (msg.containsKey("duplicate")) {
recording.duplicate = msg.getInteger("duplicate")
}
if (msg.containsKey("image")) {
if (!msg.getString("image").isNullOrEmpty()) {
recording.image = msg.getString("image")
}
}
if (msg.containsKey("fanart_image")) {
if (!msg.getString("fanart_image").isNullOrEmpty()) {
recording.fanartImage = msg.getString("fanart_image")
}
}
if (msg.containsKey("copyright_year")) {
if (msg.getInteger("copyright_year") > 0) {
recording.copyrightYear = msg.getInteger("copyright_year")
}
}
if (msg.containsKey("removal")) {
if (msg.getInteger("removal") > 0) {
recording.removal = msg.getInteger("removal")
}
}
if (msg.containsKey("start") && msg.containsKey("stop")) {
val start = msg.getLong("start")
val stop = msg.getLong("stop")
recording.duration = ((stop - start) / 60).toInt()
}
return recording
}
fun convertMessageToProgramModel(program: Program, msg: HtspMessage): Program {
if (msg.containsKey("eventId")) {
program.eventId = msg.getInteger("eventId")
}
if (msg.containsKey("channelId")) {
program.channelId = msg.getInteger("channelId")
}
if (msg.containsKey("start")) {
// The message value is in seconds, convert to milliseconds
program.start = msg.getLong("start") * 1000
}
if (msg.containsKey("stop")) {
// The message value is in seconds, convert to milliseconds
program.stop = msg.getLong("stop") * 1000
}
if (msg.containsKey("title")) {
if (!msg.getString("title").isNullOrEmpty()) {
program.title = msg.getString("title")
}
}
if (msg.containsKey("subtitle")) {
if (!msg.getString("subtitle").isNullOrEmpty()) {
program.subtitle = msg.getString("subtitle")
}
}
if (msg.containsKey("summary")) {
if (!msg.getString("summary").isNullOrEmpty()) {
program.summary = msg.getString("summary")
}
}
if (msg.containsKey("description")) {
if (!msg.getString("description").isNullOrEmpty()) {
program.description = msg.getString("description")
}
}
if (msg.containsKey("serieslinkId")) {
if (msg.getInteger("serieslinkId") > 0) {
program.serieslinkId = msg.getInteger("serieslinkId")
}
}
if (msg.containsKey("episodeId")) {
if (msg.getInteger("episodeId") > 0) {
program.episodeId = msg.getInteger("episodeId")
}
}
if (msg.containsKey("seasonId")) {
if (msg.getInteger("seasonId") > 0) {
program.seasonId = msg.getInteger("seasonId")
}
}
if (msg.containsKey("brandId")) {
if (msg.getInteger("brandId") > 0) {
program.brandId = msg.getInteger("brandId")
}
}
if (msg.containsKey("contentType")) {
if (msg.getInteger("contentType") > 0) {
program.contentType = msg.getInteger("contentType")
}
}
if (msg.containsKey("ageRating")) {
if (msg.getInteger("ageRating") > 0) {
program.ageRating = msg.getInteger("ageRating")
}
}
if (msg.containsKey("starRating")) {
if (msg.getInteger("starRating") > 0) {
program.starRating = msg.getInteger("starRating")
}
}
if (msg.containsKey("firstAired")) {
if (msg.getInteger("firstAired") > 0) {
program.firstAired = msg.getLong("firstAired")
}
}
if (msg.containsKey("seasonNumber")) {
if (msg.getInteger("seasonNumber") > 0) {
program.seasonNumber = msg.getInteger("seasonNumber")
}
}
if (msg.containsKey("seasonCount")) {
if (msg.getInteger("seasonCount") > 0) {
program.seasonCount = msg.getInteger("seasonCount")
}
}
if (msg.containsKey("episodeNumber")) {
if (msg.getInteger("episodeNumber") > 0) {
program.episodeNumber = msg.getInteger("episodeNumber")
}
}
if (msg.containsKey("episodeCount")) {
if (msg.getInteger("episodeCount") > 0) {
program.episodeCount = msg.getInteger("episodeCount")
}
}
if (msg.containsKey("partNumber")) {
if (msg.getInteger("partNumber") > 0) {
program.partNumber = msg.getInteger("partNumber")
}
}
if (msg.containsKey("partCount")) {
if (msg.getInteger("partCount") > 0) {
program.partCount = msg.getInteger("partCount")
}
}
if (msg.containsKey("episodeOnscreen")) {
if (!msg.getString("episodeOnscreen").isNullOrEmpty()) {
program.episodeOnscreen = msg.getString("episodeOnscreen")
}
}
if (msg.containsKey("image")) {
if (!msg.getString("image").isNullOrEmpty()) {
program.image = msg.getString("image")
}
}
if (msg.containsKey("dvrId")) {
if (msg.getInteger("dvrId") > 0) {
program.dvrId = msg.getInteger("dvrId")
}
}
if (msg.containsKey("nextEventId")) {
if (msg.getInteger("nextEventId") > 0) {
program.nextEventId = msg.getInteger("nextEventId")
}
}
if (msg.containsKey("episodeOnscreen")) {
if (!msg.getString("episodeOnscreen").isNullOrEmpty()) {
program.episodeOnscreen = msg.getString("episodeOnscreen")
}
}
if (msg.containsKey("serieslinkUri")) {
if (!msg.getString("serieslinkUri").isNullOrEmpty()) {
program.serieslinkUri = msg.getString("serieslinkUri")
}
}
if (msg.containsKey("episodeUri")) {
if (!msg.getString("episodeUri").isNullOrEmpty()) {
program.episodeUri = msg.getString("episodeUri")
}
}
if (msg.containsKey("copyright_year")) {
if (msg.getInteger("copyright_year") > 0) {
program.copyrightYear = msg.getInteger("copyright_year")
}
}
program.modifiedTime = System.currentTimeMillis()
/*
if (msg.containsKey("credits")) {
StringBuilder sb = new StringBuilder();
for (String credit : msg.getStringArray("credits")) {
sb.append(credit).append(",");
}
// Remove the last separator character
program.setCredits(sb.substring(0, sb.lastIndexOf(",")));
}
if (msg.containsKey("category")) {
StringBuilder sb = new StringBuilder();
for (String s : msg.getStringArray("category")) {
sb.append(s).append(",");
}
// Remove the last separator character
program.setCredits(sb.substring(0, sb.lastIndexOf(",")));
}
if (msg.containsKey("keyword")) {
StringBuilder sb = new StringBuilder();
for (String s : msg.getStringArray("keyword")) {
sb.append(s).append(",");
}
// Remove the last separator character
program.setKeyword(sb.substring(0, sb.lastIndexOf(",")));
}
*/
return program
}
fun convertMessageToSeriesRecordingModel(seriesRecording: SeriesRecording, msg: HtspMessage): SeriesRecording {
if (msg.containsKey("id")) {
seriesRecording.id = msg.getString("id")
}
if (msg.containsKey("enabled")) {
seriesRecording.isEnabled = msg.getInteger("enabled") == 1
}
if (msg.containsKey("name")) {
seriesRecording.name = msg.getString("name")
}
if (msg.containsKey("minDuration")) {
seriesRecording.minDuration = msg.getInteger("minDuration")
}
if (msg.containsKey("maxDuration")) {
seriesRecording.maxDuration = msg.getInteger("maxDuration")
}
if (msg.containsKey("retention")) {
seriesRecording.retention = msg.getInteger("retention")
}
if (msg.containsKey("daysOfWeek")) {
seriesRecording.daysOfWeek = msg.getInteger("daysOfWeek")
}
if (msg.containsKey("priority")) {
seriesRecording.priority = msg.getInteger("priority")
}
if (msg.containsKey("approxTime")) {
seriesRecording.approxTime = msg.getInteger("approxTime")
}
if (msg.containsKey("start")) {
// The message value is in minutes
seriesRecording.start = msg.getLong("start")
}
if (msg.containsKey("startWindow")) {
// The message value is in minutes
seriesRecording.startWindow = msg.getLong("startWindow")
}
if (msg.containsKey("startExtra")) {
seriesRecording.startExtra = msg.getLong("startExtra")
}
if (msg.containsKey("stopExtra")) {
seriesRecording.stopExtra = msg.getLong("stopExtra")
}
if (msg.containsKey("title")) {
if (!msg.getString("title").isNullOrEmpty()) {
seriesRecording.title = msg.getString("title")
}
}
if (msg.containsKey("fulltext")) {
if (!msg.getString("fulltext").isNullOrEmpty()) {
seriesRecording.fulltext = msg.getInteger("fulltext")
}
}
if (msg.containsKey("directory")) {
if (!msg.getString("directory").isNullOrEmpty()) {
seriesRecording.directory = msg.getString("directory")
}
}
if (msg.containsKey("channel")) {
if (msg.getInteger("channel") > 0) {
seriesRecording.channelId = msg.getInteger("channel")
}
}
if (msg.containsKey("owner")) {
if (!msg.getString("owner").isNullOrEmpty()) {
seriesRecording.owner = msg.getString("owner")
}
}
if (msg.containsKey("creator")) {
if (!msg.getString("creator").isNullOrEmpty()) {
seriesRecording.creator = msg.getString("creator")
}
}
if (msg.containsKey("dupDetect")) {
if (msg.getInteger("dupDetect") > 0) {
seriesRecording.dupDetect = msg.getInteger("dupDetect")
}
}
if (msg.containsKey("maxCount")) {
if (msg.getInteger("maxCount") > 0) {
seriesRecording.maxCount = msg.getInteger("maxCount")
}
}
if (msg.containsKey("removal")) {
if (msg.getInteger("removal") > 0) {
seriesRecording.removal = msg.getInteger("removal")
}
}
return seriesRecording
}
fun convertMessageToTimerRecordingModel(timerRecording: TimerRecording, msg: HtspMessage): TimerRecording {
if (msg.containsKey("id")) {
timerRecording.id = msg.getString("id")
}
if (msg.containsKey("title")) {
timerRecording.title = msg.getString("title")
}
if (msg.containsKey("directory")) {
if (!msg.getString("directory").isNullOrEmpty()) {
timerRecording.directory = msg.getString("directory")
}
}
if (msg.containsKey("enabled")) {
timerRecording.isEnabled = msg.getInteger("enabled") == 1
}
if (msg.containsKey("name")) {
timerRecording.name = msg.getString("name")
}
if (msg.containsKey("configName")) {
timerRecording.configName = msg.getString("configName")
}
if (msg.containsKey("channel")) {
timerRecording.channelId = msg.getInteger("channel")
}
if (msg.containsKey("daysOfWeek")) {
if (msg.getInteger("daysOfWeek") > 0) {
timerRecording.daysOfWeek = msg.getInteger("daysOfWeek")
}
}
if (msg.containsKey("priority")) {
if (msg.getInteger("priority") > 0) {
timerRecording.priority = msg.getInteger("priority")
}
}
if (msg.containsKey("start")) {
// The message value is in minutes
timerRecording.start = msg.getLong("start")
}
if (msg.containsKey("stop")) {
// The message value is in minutes
timerRecording.stop = msg.getLong("stop")
}
if (msg.containsKey("retention")) {
if (msg.getInteger("retention") > 0) {
timerRecording.retention = msg.getInteger("retention")
}
}
if (msg.containsKey("owner")) {
if (!msg.getString("owner").isNullOrEmpty()) {
timerRecording.owner = msg.getString("owner")
}
}
if (msg.containsKey("creator")) {
if (!msg.getString("creator").isNullOrEmpty()) {
timerRecording.creator = msg.getString("creator")
}
}
if (msg.containsKey("removal")) {
if (msg.getInteger("removal") > 0) {
timerRecording.removal = msg.getInteger("removal")
}
}
return timerRecording
}
fun convertMessageToServerStatusModel(serverStatus: ServerStatus, msg: HtspMessage): ServerStatus {
if (msg.containsKey("htspversion")) {
serverStatus.htspVersion = msg.getInteger("htspversion", 13)
}
if (msg.containsKey("servername")) {
serverStatus.serverName = msg.getString("servername")
}
if (msg.containsKey("serverversion")) {
serverStatus.serverVersion = msg.getString("serverversion")
}
if (msg.containsKey("webroot")) {
val webroot = msg.getString("webroot")
serverStatus.webroot = webroot ?: ""
}
if (msg.containsKey("servercapability")) {
for (capabilitiy in msg.getArrayList("servercapability")) {
Timber.d("Server supports $capabilitiy")
}
}
return serverStatus
}
fun convertIntentToAutorecMessage(intent: Intent, htspVersion: Int): HtspMessage {
val enabled = intent.getIntExtra("enabled", 1).toLong()
val title = intent.getStringExtra("title")
val fulltext = intent.getStringExtra("fulltext")
val directory = intent.getStringExtra("directory")
val name = intent.getStringExtra("name")
val configName = intent.getStringExtra("configName")
val channelId = intent.getIntExtra("channelId", 0).toLong()
val minDuration = intent.getIntExtra("minDuration", 0).toLong()
val maxDuration = intent.getIntExtra("maxDuration", 0).toLong()
val daysOfWeek = intent.getIntExtra("daysOfWeek", 127).toLong()
val priority = intent.getIntExtra("priority", 2).toLong()
val start = intent.getLongExtra("start", -1)
val startWindow = intent.getLongExtra("startWindow", -1)
val startExtra = intent.getLongExtra("startExtra", 0)
val stopExtra = intent.getLongExtra("stopExtra", 0)
val dupDetect = intent.getIntExtra("dupDetect", 0).toLong()
val comment = intent.getStringExtra("comment")
val request = HtspMessage()
if (htspVersion >= 19) {
request["enabled"] = enabled
}
request["title"] = title
if (fulltext != null && htspVersion >= 20) {
request["fulltext"] = fulltext
}
if (directory != null) {
request["directory"] = directory
}
if (name != null) {
request["name"] = name
}
if (configName != null) {
request["configName"] = configName
}
// Don't add the channel id if none was given.
// Assume the user wants to record on all channels
if (channelId > 0) {
request["channelId"] = channelId
}
// Minimal duration in seconds (0 = Any)
request["minDuration"] = minDuration
// Maximal duration in seconds (0 = Any)
request["maxDuration"] = maxDuration
request["daysOfWeek"] = daysOfWeek
request["priority"] = priority
// Minutes from midnight (up to 24*60) (window +- 15 minutes) (Obsoleted from version 18)
// Do not send the value if the default of -1 (no time specified) was set
if (start >= 0 && htspVersion < 18) {
request["approxTime"] = start
}
// Minutes from midnight (up to 24*60) for the start of the time window.
// Do not send the value if the default of -1 (no time specified) was set
if (start >= 0 && htspVersion >= 18) {
request["start"] = start
}
// Minutes from midnight (up to 24*60) for the end of the time window (including, cross-noon allowed).
// Do not send the value if the default of -1 (no time specified) was set
if (startWindow >= 0 && htspVersion >= 18) {
request["startWindow"] = startWindow
}
request["startExtra"] = startExtra
request["stopExtra"] = stopExtra
if (htspVersion >= 20) {
request["dupDetect"] = dupDetect
}
if (comment != null) {
request["comment"] = comment
}
return request
}
fun convertIntentToDvrMessage(intent: Intent, htspVersion: Int): HtspMessage {
val eventId = intent.getIntExtra("eventId", 0).toLong()
val channelId = intent.getIntExtra("channelId", 0).toLong()
val start = intent.getLongExtra("start", 0)
val stop = intent.getLongExtra("stop", 0)
val retention = intent.getLongExtra("retention", 0)
val priority = intent.getIntExtra("priority", 2).toLong()
val startExtra = intent.getLongExtra("startExtra", 0)
val stopExtra = intent.getLongExtra("stopExtra", 0)
val title = intent.getStringExtra("title")
val subtitle = intent.getStringExtra("subtitle")
val description = intent.getStringExtra("description")
val configName = intent.getStringExtra("configName")
val enabled = intent.getIntExtra("enabled", 1).toLong()
// Controls that certain fields will only be added when the recording
// is only scheduled and not being recorded
val isRecording = intent.getBooleanExtra("isRecording", false)
val request = HtspMessage()
// If the eventId is set then an existing program from the program guide
// shall be recorded. The server will then ignore the other fields
// automatically.
if (eventId > 0) {
request["eventId"] = eventId
}
if (channelId > 0 && htspVersion >= 22) {
request["channelId"] = channelId
}
if (!isRecording && start > 0) {
request["start"] = start
}
if (stop > 0) {
request["stop"] = stop
}
if (!isRecording && retention > 0) {
request["retention"] = retention
}
if (!isRecording && priority > 0) {
request["priority"] = priority
}
if (!isRecording && startExtra > 0) {
request["startExtra"] = startExtra
}
if (stopExtra > 0) {
request["stopExtra"] = stopExtra
}
// Only add the text fields if no event id was given
if (eventId == 0L) {
if (title != null) {
request["title"] = title
}
if (subtitle != null && htspVersion >= 21) {
request["subtitle"] = subtitle
}
if (description != null) {
request["description"] = description
}
}
if (configName != null) {
request["configName"] = configName
}
if (htspVersion >= 23) {
request["enabled"] = enabled
}
return request
}
fun convertIntentToTimerecMessage(intent: Intent, htspVersion: Int): HtspMessage {
val enabled = intent.getIntExtra("enabled", 1).toLong()
val title = intent.getStringExtra("title")
val directory = intent.getStringExtra("directory")
val name = intent.getStringExtra("name")
val configName = intent.getStringExtra("configName")
val channelId = intent.getIntExtra("channelId", 0).toLong()
val daysOfWeek = intent.getIntExtra("daysOfWeek", 0).toLong()
val priority = intent.getIntExtra("priority", 2).toLong()
val start = intent.getLongExtra("start", -1)
val stop = intent.getLongExtra("stop", -1)
val retention = intent.getIntExtra("retention", -1).toLong()
val comment = intent.getStringExtra("comment")
val request = HtspMessage()
if (htspVersion >= 19) {
request["enabled"] = enabled
}
request["title"] = title
if (directory != null) {
request["directory"] = directory
}
if (name != null) {
request["name"] = name
}
if (configName != null) {
request["configName"] = configName
}
if (channelId > 0) {
request["channelId"] = channelId
}
request["daysOfWeek"] = daysOfWeek
request["priority"] = priority
if (start >= 0) {
request["start"] = start
}
if (stop >= 0) {
request["stop"] = stop
}
if (retention > 0) {
request["retention"] = retention
}
if (comment != null) {
request["comment"] = comment
}
return request
}
fun convertIntentToEventMessage(intent: Intent): HtspMessage {
val eventId = intent.getIntExtra("eventId", 0)
val channelId = intent.getIntExtra("channelId", 0)
val numFollowing = intent.getIntExtra("numFollowing", 0)
val maxTime = intent.getLongExtra("maxTime", 0)
val request = HtspMessage()
request["method"] = "getEvents"
if (eventId > 0) {
request["eventId"] = eventId
}
if (channelId > 0) {
request["channelId"] = channelId
}
if (numFollowing > 0) {
request["numFollowing"] = numFollowing
}
if (maxTime > 0) {
request["maxTime"] = maxTime
}
return request
}
fun convertIntentToEpgQueryMessage(intent: Intent): HtspMessage {
val query = intent.getStringExtra("query")
val channelId = intent.getIntExtra("channelId", 0).toLong()
val tagId = intent.getIntExtra("tagId", 0).toLong()
val contentType = intent.getIntExtra("contentType", 0)
val minDuration = intent.getIntExtra("minduration", 0)
val maxDuration = intent.getIntExtra("maxduration", 0)
val language = intent.getStringExtra("language")
val full = intent.getBooleanExtra("full", false)
val request = HtspMessage()
request["method"] = "epgQuery"
request["query"] = query
if (channelId > 0) {
request["channelId"] = channelId
}
if (tagId > 0) {
request["tagId"] = tagId
}
if (contentType > 0) {
request["contentType"] = contentType
}
if (minDuration > 0) {
request["minDuration"] = minDuration
}
if (maxDuration > 0) {
request["maxDuration"] = maxDuration
}
if (language != null) {
request["language"] = language
}
request["full"] = full
return request
}
// Current timezone and date
val daylightSavingOffset: Int
get() {
val timeZone = TimeZone.getDefault()
val nowDate = Date()
val offsetFromUtc = timeZone.getOffset(nowDate.time)
Timber.d("Offset from UTC is $offsetFromUtc")
if (timeZone.useDaylightTime()) {
Timber.d("Daylight saving is used")
val dstOffset = timeZone.dstSavings
if (timeZone.inDaylightTime(nowDate)) {
Timber.d("Daylight saving offset is $dstOffset")
return dstOffset
}
}
Timber.d("Daylight saving is not used")
return 0
}
|
gpl-3.0
|
96d3077e99e3eb3636de4db8588832e8
| 33.15331 | 111 | 0.597327 | 4.448041 | false | false | false | false |
aglne/mycollab
|
mycollab-caching/src/main/java/com/mycollab/concurrent/DistributionLockUtil.kt
|
3
|
2130
|
/**
* Copyright © MyCollab
*
* 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.mycollab.concurrent
import com.mycollab.spring.AppContextUtil
import org.apache.commons.collections.map.AbstractReferenceMap
import org.apache.commons.collections.map.ReferenceMap
import org.slf4j.LoggerFactory
import java.util.*
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
/**
* @author MyCollab Ltd.
* @since 4.5.2
*/
object DistributionLockUtil {
private val LOG = LoggerFactory.getLogger(DistributionLockUtil::class.java)
private val map = Collections.synchronizedMap(ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK))
@JvmStatic
fun getLock(lockName: String): Lock = try {
val lockService = AppContextUtil.getSpringBean(DistributionLockService::class.java)
val lock = lockService.getLock(lockName)
lock ?: getStaticDefaultLock(lockName)
} catch (e: Exception) {
LOG.warn("Can not get lock service")
getStaticDefaultLock(lockName)
}
@JvmStatic
fun removeLock(lockName: String) {
map.remove(lockName)
}
private fun getStaticDefaultLock(lockName: String): Lock {
synchronized(map) {
var lock: Lock? = map[lockName] as? Lock
when (lock) {
null -> {
lock = ReentrantLock()
map[lockName] = lock
}
}
return lock!!
}
}
}
|
agpl-3.0
|
71358e8365d176b8fa555ce5455b1547
| 32.793651 | 117 | 0.688586 | 4.389691 | false | false | false | false |
lunivore/montecarluni
|
src/main/kotlin/com/lunivore/montecarluni/app/Styles.kt
|
1
|
826
|
package com.lunivore.montecarluni.app
import javafx.scene.layout.BorderStrokeStyle.SOLID
import tornadofx.*
class Styles : Stylesheet() {
companion object {
val buttonBox by cssclass()
val borderBox by cssclass()
private val lightGrey = c("#f4f4f4")
private val midGrey = c("#cfcfcf")
}
init {
buttonBox {
padding = box(10.px, 10.px, 10.px, 0.px)
spacing = 10.px
hgap = 10.px
vgap = 10.px
}
borderBox {
padding = box(10.px, 10.px, 10.px, 10.px)
}
tabHeaderBackground {
backgroundColor += lightGrey
}
tabContentArea {
borderColor += box(midGrey)
borderWidth += box(1.px)
borderStyle += SOLID
}
}
}
|
apache-2.0
|
eb634a9ae9fdce8a6124318f4bf65a1e
| 19.675 | 53 | 0.525424 | 4.068966 | false | false | false | false |
kiruto/kotlin-android-mahjong
|
app/src/main/java/dev/yuriel/mahjan/presenter/PlayPresenter.kt
|
1
|
5713
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.mahjan.presenter
import dev.yuriel.kotmahjan.ai.I
import dev.yuriel.kotmahjan.ctrl.impl.Kaze
import dev.yuriel.kotmahjan.ctrl.impl.Round
import dev.yuriel.kotmahjan.ctrl.reactive.RoundController
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.PlayerModel
import dev.yuriel.kotmahjan.models.UnbelievableException
import dev.yuriel.mahjan.commander.GamePlayerMgr
import dev.yuriel.mahjan.group.HandsGroup
import dev.yuriel.mahjan.interfaces.Interaction
import dev.yuriel.mahjan.interfaces.PlayViewsInterface
import dev.yuriel.mahjan.model.GamePlayerModel
import dev.yuriel.mahjan.texture.Naki
import dev.yuriel.mahjan.texture.NakiBtn
import rx.Observable
import rx.schedulers.Schedulers
import java.util.concurrent.CountDownLatch
/**
* Created by yuriel on 8/13/16.
*/
class PlayPresenter(private val view: PlayViewsInterface):
Interaction, HandsGroup.Listener, NakiBtn.Listener {
private val ID_LAST = 0x103
private val ID_KAWA_LISTENER = 0x100
private val ID_TEHAI_LISTENER = 0x101
private val ID_TSUMO_LISTENER = 0x102
private val round = Round()
private val ctrl = RoundController(round)
//private val playerA = I("東方不敗")
private val playerB = I("南夏奈")
private val playerC = I("西山")
private val playerD = I("堀北")
private val playerModel = GamePlayerModel()
private val player = GamePlayerMgr(this)
//private val viewer = playerA
private val viewer = playerModel
private val tileModels = listOf<PlayerModel>(playerModel, playerB, playerC, playerD)
@Volatile
private var touch: Hai? = null
init {
for (t in tileModels) {
t.kawa.listen(ID_KAWA_LISTENER) { list ->
view.updateKawaFor(indexOf(t), list)
}
t.tehai.listen(ID_TEHAI_LISTENER) { list ->
view.updateTehaiFor(indexOf(t), list)
}
t.tsumo.listen(ID_TSUMO_LISTENER) { hai ->
view.updateTsumoFor(indexOf(t), hai)
}
}
ctrl.listen(ID_LAST) { last ->
view.updateHaisanLast(last)
}
var roundText = ""
roundText += when(round.kazeRound) {
0 -> "東"
1 -> "南"
2 -> "西"
3 -> "北"
else -> throw UnbelievableException()
}
roundText += when(round.bakaze) {
Kaze.EAST -> "一"
Kaze.SOUTH -> "二"
Kaze.WEST -> "三"
Kaze.NORTH -> "四"
}
roundText += "局"
view.updateRoundText(roundText)
}
fun addPlayer() {
round.addPlayer(tileModels[0], 0, player)
.addPlayer(tileModels[1], 1, playerB)
.addPlayer(tileModels[2], 2, playerC)
.addPlayer(tileModels[3], 3, playerD)
}
fun start() {
Observable.just(0)
.observeOn(Schedulers.newThread())
.map { ctrl.mainLoop() }
.subscribe()
}
override fun getPlayerModel() = playerModel
override fun waiting4Flod(): Hai {
val latch = CountDownLatch(1)
touch = null
Observable.just(0)
.observeOn(Schedulers.newThread())
.map {
while (touch == null){}
latch.countDown()
touch
}.subscribe()
latch.await()
return touch!!
}
override fun waiting4Kan(): Boolean {
Thread.sleep(5000)
return false
}
override fun waiting4Pon(): Boolean {
Thread.sleep(5000)
return false
}
override fun waiting4Chi(): Boolean {
Thread.sleep(5000)
return false
}
override fun waiting4Ron(): Boolean {
Thread.sleep(5000)
return false
}
override fun onTileTouchDown(hai: Hai) {
}
override fun onTileTouchUp(hai: Hai) {
touch = hai
}
override fun onNakiBtnTouchDown(btn: NakiBtn) {
}
override fun onNakiBtnTouchUp(btn: NakiBtn) {
when(btn.naki) {
Naki.YES -> view.hideNaki()
Naki.NO -> view.showNaki()
}
}
private fun roleOf(tileModel: PlayerModel): Kaze {
return Kaze.values()[tileModels.indexOf(tileModel)]
}
private fun indexOf(model: PlayerModel): Int {
val result = tileModels.indexOf(model) - tileModels.indexOf(viewer)
if (result >= 0) return result
return 4 + result
}
}
|
mit
|
09cb3263c1d49006689219d76b6eae98
| 28.552083 | 88 | 0.630178 | 4.060845 | false | false | false | false |
soywiz/korge
|
korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/utils/SpineJsonValue.kt
|
1
|
5422
|
package com.esotericsoftware.spine.utils
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
internal class SpineJsonValue {
enum class ValueType { OBJECT, ARRAY, STRING, DOUBLE, BOOLEAN, NULL }
private var type: ValueType? = null
private var stringValue: String? = null
private var doubleValue: Double = 0.toDouble()
var name: String? = null
var children: List<SpineJsonValue>? = null
var map: Map<String, SpineJsonValue>? = null
val size: Int get() = children?.size ?: 0
val isString: Boolean get() = type == ValueType.STRING
val isNull: Boolean get() = type == ValueType.NULL
val isValue: Boolean get() = type == ValueType.STRING || type == ValueType.DOUBLE || type == ValueType.BOOLEAN || type == ValueType.NULL
constructor(type: ValueType) { this.type = type }
constructor(type: ValueType, children: List<SpineJsonValue>) {
this.type = type
this.children = children
if (type == ValueType.OBJECT) {
this.map = children.associateBy { it.name!! }.toCaseInsensitiveMap()
}
}
constructor(value: String) { set(value) }
constructor(value: Double, stringValue: String) { set(value, stringValue) }
constructor(value: Boolean) { set(value) }
operator fun get(index: Int): SpineJsonValue? = children?.getOrNull(index)
operator fun get(name: String): SpineJsonValue? = map?.get(name)
fun getSure(name: String): SpineJsonValue = get(name) ?: throw IllegalArgumentException("Named value not found: $name")
fun has(name: String): Boolean = get(name) != null
inline fun fastForEach(block: (value: SpineJsonValue) -> Unit) = run { children?.fastForEach(block) }
fun require(name: String): SpineJsonValue {
fastForEach { current -> if (current.name?.equals(name, ignoreCase = true) == true) return current }
error("Child not found with name: $name")
}
fun asString(): String? = when (type) {
ValueType.STRING -> stringValue
ValueType.DOUBLE -> if (stringValue != null) stringValue else (doubleValue).toString()
ValueType.BOOLEAN -> if (doubleValue != 0.0) "true" else "false"
ValueType.NULL -> null
else -> throw IllegalStateException("Value cannot be converted to string: ${type!!}")
}
fun asDouble(): Double = when (type) {
ValueType.STRING -> (stringValue!!).toDouble()
ValueType.DOUBLE, ValueType.BOOLEAN -> doubleValue
else -> throw IllegalStateException("Value cannot be converted to float: ${type!!}")
}
fun asFloat(): Float = asDouble().toFloat()
fun asInt(): Int = asDouble().toInt()
fun asBoolean(): Boolean = asDouble() != 0.0
fun checkArray() = check(type == ValueType.ARRAY) { "Value is not an array: " + type!! }
private inline fun <T> asAnyArray(new: (size: Int) -> T, set: (array: T, index: Int, value: SpineJsonValue) -> Unit): T =
checkArray().let { new(size).also { array -> children?.fastForEachWithIndex { index, value -> set(array, index, value) } } }
fun asFloatArray(): FloatArray = asAnyArray({ FloatArray(it) }, { array, index, value -> array[index] = value.asFloat() })
fun asShortArray(): ShortArray = asAnyArray({ ShortArray(it) }, { array, index, value -> array[index] = value.asInt().toShort() })
private inline fun <T> getAny(name: String, defaultValue: T, convert: (value: SpineJsonValue) -> T): T {
val child = get(name)
return if (child == null || !child.isValue || child.isNull) defaultValue else convert(child)
}
fun getString(name: String, defaultValue: String?): String? = getAny(name, defaultValue) { it.asString() }
fun getStringNotNull(name: String, defaultValue: String): String = getAny(name, defaultValue) { it?.asString()?: defaultValue }
fun getFloat(name: String, defaultValue: Float): Float = getAny(name, defaultValue) { it.asFloat() }
fun getInt(name: String, defaultValue: Int): Int = getAny(name, defaultValue) { it.asInt() }
fun getBoolean(name: String, defaultValue: Boolean): Boolean = getAny(name, defaultValue) { it.asBoolean() }
fun getString(name: String): String? = getSure(name).asString()
fun getFloat(name: String): Float = getSure(name).asFloat()
fun getInt(name: String): Int = getSure(name).asInt()
fun set(value: String?) {
stringValue = value
type = if (value == null) ValueType.NULL else ValueType.STRING
}
operator fun set(value: Double, stringValue: String?) {
doubleValue = value
this.stringValue = stringValue
type = ValueType.DOUBLE
}
fun set(value: Boolean) {
doubleValue = if (value) 1.0 else 0.0
type = ValueType.BOOLEAN
}
override fun toString(): String = "JsonValue"
companion object {
fun fromPrimitiveTree(value: Any?, name: String? = null): SpineJsonValue = when (value) {
null -> SpineJsonValue(ValueType.NULL)
is String -> SpineJsonValue(value)
is Boolean -> SpineJsonValue(value)
is Number -> SpineJsonValue(value.toDouble(), value.toString())
is List<*> -> SpineJsonValue(ValueType.ARRAY, value.map { fromPrimitiveTree(it) })
is Map<*, *> -> SpineJsonValue(ValueType.OBJECT, value.map { fromPrimitiveTree(it.value, it.key as String) })
else -> TODO()
}.also {
it.name = name
}
}
}
|
apache-2.0
|
420faa1d182276eaffb88291a2bbf151
| 45.741379 | 140 | 0.647363 | 4.242567 | false | false | false | false |
yiyocx/GitlabAndroid
|
app/src/main/kotlin/yiyo/gitlabandroid/model/rest/RestClient.kt
|
2
|
1615
|
package yiyo.gitlabandroid.model.rest
import android.content.Context
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import yiyo.gitlabandroid.utils.Configuration
/**
* Created by yiyo
*/
class RestClient {
companion object {
val BASE_ULR = "https://gitlab.com/api/v3/"
fun getApiService(context: Context): ApiService {
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor { chain ->
val configuration = Configuration(context);
val originalRequest = chain.request()
val request = originalRequest.newBuilder()
.addHeader("PRIVATE-TOKEN", configuration.getPrivateToken())
.addHeader("Content-Type", "application/json")
.method(originalRequest.method(), originalRequest.body())
.build()
chain.proceed(request)
}
val client = httpClient.build()
val gson = GsonBuilder().setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'").create()
val restAdapter = Retrofit.Builder()
.baseUrl(BASE_ULR)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build()
return restAdapter.create(ApiService::class.java)
}
}
}
|
gpl-2.0
|
40bbf18316ab57e3bf6e0c86704c6a40
| 34.888889 | 101 | 0.612384 | 5.159744 | false | true | false | false |
alexcustos/linkasanote
|
app/src/main/java/com/bytesforge/linkasanote/manageaccounts/AccountItem.kt
|
1
|
2037
|
/*
* LaaNo Android application
*
* @author Aleksandr Borisenko <[email protected]>
* Copyright (C) 2017 Aleksandr Borisenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bytesforge.linkasanote.manageaccounts
import android.accounts.Account
import com.google.common.base.Objects
class AccountItem {
var account: Account? = null
private set
var displayName: String? = null
var type: Int
private set
constructor(account: Account) {
this.account = account
type = TYPE_ACCOUNT
}
constructor() {
type = TYPE_ACTION_ADD
}
val accountName: String?
get() = if (account == null) null else account!!.name
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val accountItem = other as AccountItem
if ((account == null) xor (accountItem.account == null)) return false
// NOTE: (account == null && accountItem.account == null)
return ((account == null || Objects.equal(account!!.name, accountItem.account!!.name))
&& Objects.equal(displayName, accountItem.displayName))
}
override fun hashCode(): Int {
return Objects.hashCode(account, displayName, type)
}
companion object {
const val TYPE_ACCOUNT = 0
const val TYPE_ACTION_ADD = 1
}
}
|
gpl-3.0
|
5b54e24d5b506bf0b70d79650dc102bc
| 30.84375 | 94 | 0.669612 | 4.399568 | false | false | false | false |
android-gems/inspector
|
inspector/src/main/kotlin/kotlinx/html/Attributes.kt
|
3
|
2539
|
package kotlinx.html
public object Attributes {
public val id: Attribute<String> = IdAttribute("id")
public val style: Attribute<String> = StringAttribute("style")
public val title: Attribute<String> = IdAttribute("title")
public val href: Attribute<Link> = LinkAttribute("href")
public val cite: Attribute<Link> = LinkAttribute("cite")
public val rel: Attribute<String> = StringAttribute("rel")
public val target: Attribute<String> = StringAttribute("target")
public val mimeType: Attribute<String> = MimeAttribute("type")
public val width: Attribute<Int> = IntAttribute("width")
public val height: Attribute<Int> = IntAttribute("height")
public val action: Attribute<Link> = LinkAttribute("action")
public val enctype: Attribute<String> = StringAttribute("enctype")
public val method: Attribute<String> = StringAttribute("method")
public val src: Attribute<Link> = LinkAttribute("src")
public val alt: Attribute<String> = TextAttribute("alt")
public val autocomplete: Attribute<Boolean> = BooleanAttribute("autocomplete", "on", "off")
public val autofocus: Attribute<Boolean> = TickerAttribute("autofocus")
public val checked: Attribute<Boolean> = TickerAttribute("checked")
public val disabled: Attribute<Boolean> = TickerAttribute("disabled")
public val maxlength: Attribute<Int> = IntAttribute("maxlength")
public val multiple: Attribute<Boolean> = TickerAttribute("multiple")
public val inputType: Attribute<String> = StringAttribute("type")
public val buttonType: Attribute<String> = StringAttribute("type")
public val name: Attribute<String> = StringAttribute("name")
public val pattern: Attribute<String> = RegexpAttribute("pattern")
public val placeholder: Attribute<String> = TextAttribute("placeholder")
public val readonly: Attribute<Boolean> = TickerAttribute("readonly")
public val required: Attribute<Boolean> = TickerAttribute("required")
public val size: Attribute<Int> = IntAttribute("size")
public val step: Attribute<Int> = IntAttribute("step")
public val value: Attribute<String> = StringAttribute("value")
public val forId: Attribute<String> = IdAttribute("for")
public val label: Attribute<String> = TextAttribute("label")
public val selected: Attribute<Boolean> = TickerAttribute("selected")
public val cols: Attribute<Int> = IntAttribute("cols")
public val rows: Attribute<Int> = IntAttribute("rows")
public val wrap: Attribute<String> = StringAttribute("wrap")
}
|
mit
|
d0822e79d9e85eb385c4ed83f1d79ea7
| 60.926829 | 95 | 0.730209 | 4.624772 | false | false | false | false |
AndroidX/androidx
|
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacType.kt
|
3
|
6928
|
/*
* Copyright (C) 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.room.compiler.processing.javac
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.processing.XEquality
import androidx.room.compiler.processing.XNullability
import androidx.room.compiler.processing.XRawType
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.javac.kotlin.KmType
import androidx.room.compiler.processing.javac.kotlin.KotlinMetadataElement
import androidx.room.compiler.processing.ksp.ERROR_JTYPE_NAME
import androidx.room.compiler.processing.safeTypeName
import com.google.auto.common.MoreTypes
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
import kotlin.reflect.KClass
internal abstract class JavacType(
internal val env: JavacProcessingEnv,
open val typeMirror: TypeMirror,
internal val maybeNullability: XNullability?,
) : XType, XEquality {
// Kotlin type information about the type if this type is driven from kotlin code.
abstract val kotlinType: KmType?
override val rawType: XRawType by lazy {
JavacRawType(env, this)
}
override val superTypes by lazy {
val superTypes = env.typeUtils.directSupertypes(typeMirror)
superTypes.map {
val element = MoreTypes.asTypeElement(it)
env.wrap<JavacType>(
typeMirror = it,
kotlinType = KotlinMetadataElement.createFor(element)?.kmType,
elementNullability = element.nullability
)
}
}
override val typeElement by lazy {
val element = try {
MoreTypes.asTypeElement(typeMirror)
} catch (notAnElement: IllegalArgumentException) {
null
}
element?.let {
env.wrapTypeElement(it)
}
}
override fun isError(): Boolean {
return typeMirror.kind == TypeKind.ERROR ||
// https://kotlinlang.org/docs/reference/kapt.html#non-existent-type-correction
(kotlinType != null && asTypeName().java == ERROR_JTYPE_NAME)
}
override val typeName by lazy {
xTypeName.java
}
private val xTypeName: XTypeName by lazy {
XTypeName(
typeMirror.safeTypeName(),
XTypeName.UNAVAILABLE_KTYPE_NAME,
maybeNullability ?: XNullability.UNKNOWN
)
}
override fun asTypeName() = xTypeName
override fun equals(other: Any?): Boolean {
return XEquality.equals(this, other)
}
override fun hashCode(): Int {
return XEquality.hashCode(equalityItems)
}
override fun defaultValue(): String {
return when (typeMirror.kind) {
TypeKind.BOOLEAN -> "false"
TypeKind.BYTE, TypeKind.SHORT, TypeKind.INT, TypeKind.CHAR -> "0"
TypeKind.LONG -> "0L"
TypeKind.FLOAT -> "0f"
TypeKind.DOUBLE -> "0.0"
else -> "null"
}
}
override fun boxed(): JavacType {
return when {
typeMirror.kind.isPrimitive -> {
env.wrap(
typeMirror = env.typeUtils.boxedClass(MoreTypes.asPrimitiveType(typeMirror))
.asType(),
kotlinType = kotlinType,
elementNullability = XNullability.NULLABLE
)
}
typeMirror.kind == TypeKind.VOID -> {
env.wrap(
typeMirror = env.elementUtils.getTypeElement("java.lang.Void").asType(),
kotlinType = kotlinType,
elementNullability = XNullability.NULLABLE
)
}
else -> {
this
}
}
}
override fun isNone() = typeMirror.kind == TypeKind.NONE
override fun toString(): String {
return typeMirror.toString()
}
override fun extendsBound(): XType? {
return typeMirror.extendsBound()?.let {
env.wrap<JavacType>(
typeMirror = it,
kotlinType = kotlinType?.extendsBound,
elementNullability = maybeNullability
)
}
}
override fun isAssignableFrom(other: XType): Boolean {
return other is JavacType && env.typeUtils.isAssignable(
other.typeMirror,
typeMirror
)
}
override fun isTypeOf(other: KClass<*>): Boolean {
return try {
MoreTypes.isTypeOf(
other.java,
typeMirror
)
} catch (notAType: IllegalArgumentException) {
// `MoreTypes.isTypeOf` might throw if the current TypeMirror is not a type.
// for Room, a `false` response is good enough.
false
}
}
override fun isSameType(other: XType): Boolean {
return other is JavacType && env.typeUtils.isSameType(typeMirror, other.typeMirror)
}
/**
* Create a copy of this type with the given nullability.
* This method is not called if the nullability of the type is already equal to the given
* nullability.
*/
protected abstract fun copyWithNullability(nullability: XNullability): JavacType
final override fun makeNullable(): JavacType {
if (nullability == XNullability.NULLABLE) {
return this
}
if (typeMirror.kind.isPrimitive || typeMirror.kind == TypeKind.VOID) {
return boxed().makeNullable()
}
return copyWithNullability(XNullability.NULLABLE)
}
final override fun makeNonNullable(): JavacType {
if (nullability == XNullability.NONNULL) {
return this
}
// unlike makeNullable, we don't try to degrade to primitives here because it is valid for
// a boxed primitive to be marked as non-null.
return copyWithNullability(XNullability.NONNULL)
}
override val nullability: XNullability get() {
return maybeNullability ?: error(
"XType#nullibility cannot be called from this type because it is missing nullability " +
"information. Was this type derived from a type created with " +
"TypeMirror#toXProcessing(XProcessingEnv)?"
)
}
override fun isTypeVariable() = typeMirror.kind == TypeKind.TYPEVAR
}
|
apache-2.0
|
b23e7554a5b35c957c2da228163b0944
| 32.795122 | 100 | 0.625866 | 5.056934 | false | false | false | false |
androidx/androidx
|
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/compiler/steps/KotlinCompilationStep.kt
|
3
|
5464
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.util.compiler.steps
import androidx.room.compiler.processing.util.DiagnosticLocation
import androidx.room.compiler.processing.util.DiagnosticMessage
import androidx.room.compiler.processing.util.Source
import androidx.room.compiler.processing.util.compiler.SourceSet
import java.io.File
import javax.tools.Diagnostic
/**
* Kotlin compilation is run in multiple steps:
* process KSP
* process KAPT
* compile kotlin sources
* compile java sources
*
* Each step implements the [KotlinCompilationStep] interfaces and provides the arguments for
* the following step.
*/
internal interface KotlinCompilationStep {
/**
* A name to identify the step.
*/
val name: String
fun execute(
/**
* Temporary folder that can be used by the step
*/
workingDir: File,
/**
* Compilation parameters for the step.
*/
arguments: CompilationStepArguments
): CompilationStepResult
}
/**
* Diagnostic message that was captured from the compiler, before it is processed.
*/
internal data class RawDiagnosticMessage(
val kind: Diagnostic.Kind,
val message: String,
val location: Location?
) {
data class Location(
val path: String,
val line: Int,
)
}
/**
* Parameters for each compilation step
*/
internal data class CompilationStepArguments(
/**
* List of source sets. Each source set has a root folder that can be used to pass to the
* compiler.
*/
val sourceSets: List<SourceSet>,
/**
* Any additional classpath provided to the compilation
*/
val additionalClasspaths: List<File>,
/**
* If `true`, the classpath of the test application should be provided to the compiler
*/
val inheritClasspaths: Boolean,
/**
* Arguments to pass to the java compiler. This is also important for KAPT where part of the
* compilation is run by javac.
*/
val javacArguments: List<String>,
/**
* Arguments to pass to the kotlin compiler.
*/
val kotlincArguments: List<String>,
)
/**
* Result of a compilation step.
*/
internal data class CompilationStepResult(
/**
* Whether it succeeded or not.
*/
val success: Boolean,
/**
* List of source sets generated by this step
*/
val generatedSourceRoots: List<SourceSet>,
/**
* List of diagnotic messages created by this step
*/
val diagnostics: List<DiagnosticMessage>,
/**
* Arguments for the next compilation step. Current step might've modified its own parameters
* (e.g. add generated sources etc) for this one.
*/
val nextCompilerArguments: CompilationStepArguments,
/**
* If the step compiled sources, this field includes the list of Files for each classpath.
*/
val outputClasspath: List<File>
) {
val generatedSources: List<Source> by lazy {
generatedSourceRoots.flatMap { it.sources }
}
companion object {
/**
* Creates a [CompilationStepResult] that does not create any outputs but instead simply
* passes the arguments to the next step.
*/
fun skip(arguments: CompilationStepArguments) = CompilationStepResult(
success = true,
generatedSourceRoots = emptyList(),
diagnostics = emptyList(),
nextCompilerArguments = arguments,
outputClasspath = emptyList()
)
}
}
/**
* Associates [RawDiagnosticMessage]s with sources and creates [DiagnosticMessage]s.
*/
internal fun resolveDiagnostics(
diagnostics: List<RawDiagnosticMessage>,
sourceSets: List<SourceSet>,
): List<DiagnosticMessage> {
return diagnostics.map { rawDiagnostic ->
// match it to source
val location = rawDiagnostic.location
if (location == null) {
DiagnosticMessage(
kind = rawDiagnostic.kind,
msg = rawDiagnostic.message,
location = null,
)
} else {
// find matching source file
val source = sourceSets.firstNotNullOfOrNull {
it.findSourceFile(location.path)
}
// source might be null for KAPT if it failed to match the diagnostic to a real
// source file (e.g. error is reported on the stub)
check(source != null || location.path.contains("kapt")) {
"Cannot find source file for the diagnostic :/ $rawDiagnostic"
}
DiagnosticMessage(
kind = rawDiagnostic.kind,
msg = rawDiagnostic.message,
location = DiagnosticLocation(
source = source,
line = location.line,
),
)
}
}
}
|
apache-2.0
|
5a4f942f02b2d81ed609457dfff234fe
| 29.52514 | 97 | 0.642936 | 4.909254 | false | false | false | false |
goldmansachs/obevo
|
obevo-utils/obevo-hibernate-util/src/main/java/com/gs/obevo/hibernate/HibernateDdlRevengAdapter.kt
|
1
|
3978
|
/**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.hibernate
import com.gs.obevo.api.platform.ChangeType
import com.gs.obevo.apps.reveng.AbstractReveng
import com.gs.obevo.apps.reveng.AquaRevengArgs
import com.gs.obevo.apps.reveng.LineParseOutput
import com.gs.obevo.apps.reveng.RevengPattern
import com.gs.obevo.db.apps.reveng.AbstractDdlReveng
import com.gs.obevo.impl.util.MultiLineStringSplitter
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.impl.factory.Lists
import java.io.File
import java.io.PrintStream
internal class HibernateDdlRevengAdapter<in T>(
private val hibSchGen: HibernateSchemaGenerator<T>,
private val revengArgs: HibernateRevengArgs<T>)
: AbstractDdlReveng(revengArgs.platform, MultiLineStringSplitter(DELIMITER, false), Lists.immutable.empty(), getRevengPatterns(revengArgs), null) {
init {
setStartQuote(QUOTE)
setEndQuote(QUOTE)
}
override fun doRevengOrInstructions(out: PrintStream, args: AquaRevengArgs, interimDir: File): Boolean {
interimDir.mkdirs()
hibSchGen.writeDdlsToFile(this.revengArgs.hibernateDialectClass, this.revengArgs.getConfig(), interimDir, DELIMITER)
return true
}
companion object {
private val QUOTE = ""
private val DELIMITER = ";"
private fun getRevengPatterns(revengArgs: HibernateRevengArgs<*>): ImmutableList<RevengPattern> {
val schemaNameSubPattern: String
val namePatternType: RevengPattern.NamePatternType
if (revengArgs.platform.isSubschemaSupported) {
schemaNameSubPattern = AbstractReveng.getCatalogSchemaObjectPattern(QUOTE, QUOTE)
namePatternType = RevengPattern.NamePatternType.THREE
} else {
schemaNameSubPattern = AbstractReveng.getSchemaObjectPattern(QUOTE, QUOTE)
namePatternType = RevengPattern.NamePatternType.TWO
}
val remapObjectName = { objectName: String ->
if (objectName.endsWith("_AUD"))
objectName.replace(Regex("_AUD$"), "")
else
objectName
}
return Lists.immutable.with(
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+table\\s+$schemaNameSubPattern")
.withPostProcessSql {
LineParseOutput(it + (revengArgs.postCreateTableSql ?: ""))
}
.withRemapObjectName(remapObjectName),
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+(?:\\w+\\s+)?index\\s+$schemaNameSubPattern\\s+on\\s+$schemaNameSubPattern", 2, 1, "INDEX")
.withRemapObjectName(remapObjectName),
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)alter\\s+table\\s+(?:if\\s+exists\\s+)?$schemaNameSubPattern\\s+add\\s+constraint\\s+$schemaNameSubPattern\\s+foreign\\s+key", 1, 2, "FK").withShouldBeIgnored(!revengArgs.isGenerateForeignKeys)
.withRemapObjectName(remapObjectName),
RevengPattern(ChangeType.SEQUENCE_STR, namePatternType, "(?i)create\\s+sequence\\s+$schemaNameSubPattern\\s+")
.withRemapObjectName(remapObjectName)
)
}
}
}
|
apache-2.0
|
80fe2663c3751d5b41df89c7878e55c3
| 45.8 | 271 | 0.667672 | 4.68 | false | false | false | false |
InfiniteSoul/ProxerAndroid
|
src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/TextPrototype.kt
|
1
|
4780
|
package me.proxer.app.ui.view.bbcode.prototype
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.os.Build
import android.text.Spannable
import android.util.TypedValue.COMPLEX_UNIT_PX
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.TextView
import androidx.core.content.getSystemService
import androidx.core.util.PatternsCompat
import androidx.core.widget.TextViewCompat
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import me.proxer.app.R
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.ui.view.BetterLinkGifAwareEmojiTextView
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.ui.view.bbcode.BBUtils
import me.proxer.app.ui.view.bbcode.toSpannableStringBuilder
import me.proxer.app.util.extension.linkClicks
import me.proxer.app.util.extension.linkLongClicks
import me.proxer.app.util.extension.linkify
import me.proxer.app.util.extension.toPrefixedHttpUrl
import me.proxer.app.util.extension.toast
/**
* @author Ruben Gees
*/
object TextPrototype : BBPrototype {
const val TEXT_COLOR_ARGUMENT = "text_color"
const val TEXT_SIZE_ARGUMENT = "text_size"
const val TEXT_APPEARANCE_ARGUMENT = "text_appearance"
private val spannableFactory = object : Spannable.Factory() {
override fun newSpannable(source: CharSequence): Spannable {
return source as Spannable
}
}
@SuppressLint("RestrictedApi")
private val webUrlRegex = PatternsCompat.AUTOLINK_WEB_URL.toRegex()
private val validLinkPredicate = { link: String -> link.startsWith("@") || webUrlRegex.matches(link) }
@Suppress("RegExpUnexpectedAnchor")
override val startRegex = Regex("x^")
@Suppress("RegExpUnexpectedAnchor")
override val endRegex = Regex("x^")
override fun construct(code: String, parent: BBTree): BBTree {
return BBTree(this, parent, args = BBArgs(text = code.toSpannableStringBuilder().linkify()))
}
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
return listOf(makeView(parent, args))
}
fun makeView(parent: BBCodeView, args: BBArgs): TextView {
return applyOnView(parent, BetterLinkGifAwareEmojiTextView(parent.context), args)
}
fun applyOnView(
parent: BBCodeView,
view: BetterLinkGifAwareEmojiTextView,
args: BBArgs
): BetterLinkGifAwareEmojiTextView {
view.layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT)
view.setSpannableFactory(spannableFactory)
view.setText(args.safeText, TextView.BufferType.SPANNABLE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
view.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
}
applyStyle(args, view)
setListeners(parent, view)
return view
}
private fun applyStyle(args: BBArgs, view: BetterLinkGifAwareEmojiTextView) {
(args[TEXT_APPEARANCE_ARGUMENT] as? Int).let {
if (it == null) {
TextViewCompat.setTextAppearance(view, R.style.TextAppearance_AppCompat_Small)
} else {
TextViewCompat.setTextAppearance(view, it)
}
}
(args[TEXT_COLOR_ARGUMENT] as? Int)?.let { view.setTextColor(it) }
(args[TEXT_SIZE_ARGUMENT] as? Float)?.let { view.setTextSize(COMPLEX_UNIT_PX, it) }
}
private fun setListeners(parent: BBCodeView, view: BetterLinkGifAwareEmojiTextView) {
view.linkClicks(validLinkPredicate)
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe {
val baseActivity = BBUtils.findBaseActivity(parent.context) ?: return@subscribe
when {
it.startsWith("@") -> ProfileActivity.navigateTo(baseActivity, null, it.trim().drop(1))
webUrlRegex.matches(it) -> baseActivity.showPage(it.toPrefixedHttpUrl())
}
}
view.linkLongClicks { webUrlRegex.matches(it) }
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe {
val title = view.context.getString(R.string.clipboard_title)
parent.context.getSystemService<ClipboardManager>()?.setPrimaryClip(
ClipData.newPlainText(title, it.toString())
)
parent.context.toast(R.string.clipboard_status)
}
}
}
|
gpl-3.0
|
3e8345d99840f6b984b4378cf3bf11d7
| 36.637795 | 107 | 0.700418 | 4.434137 | false | false | false | false |
InfiniteSoul/ProxerAndroid
|
src/main/kotlin/me/proxer/app/anime/schedule/ScheduleAdapter.kt
|
1
|
3641
|
package me.proxer.app.anime.schedule
import android.os.Parcelable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL
import androidx.recyclerview.widget.RecyclerView
import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.anime.schedule.ScheduleAdapter.ViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.extension.safeLayoutManager
import me.proxer.app.util.extension.toAppString
import me.proxer.library.entity.media.CalendarEntry
import me.proxer.library.enums.CalendarDay
import kotlin.math.max
/**
* @author Ruben Gees
*/
class ScheduleAdapter : BaseAdapter<Pair<CalendarDay, List<CalendarEntry>>, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, CalendarEntry>> = PublishSubject.create()
private val layoutManagerStates = mutableMapOf<CalendarDay, Parcelable?>()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int) = data[position].let { (day, _) -> day.ordinal.toLong() }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_schedule_day, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun onViewRecycled(holder: ViewHolder) {
withSafeAdapterPosition(holder) {
layoutManagerStates[data[it].first] = holder.childRecyclerView.safeLayoutManager.onSaveInstanceState()
}
holder.childRecyclerView.layoutManager = null
holder.childRecyclerView.adapter = null
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val weekDay by bindView<TextView>(R.id.weekDay)
internal val childRecyclerView by bindView<RecyclerView>(R.id.childRecyclerView)
init {
childRecyclerView.setHasFixedSize(true)
childRecyclerView.isNestedScrollingEnabled = false
GravitySnapHelper(Gravity.START).attachToRecyclerView(childRecyclerView)
}
fun bind(item: Pair<CalendarDay, List<CalendarEntry>>) {
val (day, calendarEntries) = item
val adapter = ScheduleEntryAdapter()
adapter.glide = glide
adapter.clickSubject.subscribe(clickSubject)
adapter.swapDataAndNotifyWithDiffing(calendarEntries)
weekDay.text = day.toAppString(weekDay.context)
childRecyclerView.layoutManager = LinearLayoutManager(childRecyclerView.context, HORIZONTAL, false).apply {
initialPrefetchItemCount = when (DeviceUtils.isLandscape(itemView.resources)) {
true -> max(5, calendarEntries.size)
false -> max(3, calendarEntries.size)
}
}
childRecyclerView.swapAdapter(adapter, false)
layoutManagerStates[item.first]?.let {
childRecyclerView.safeLayoutManager.onRestoreInstanceState(it)
}
}
}
}
|
gpl-3.0
|
9ffa001b29b054fdfa3d53e6cf05aef1
| 35.41 | 119 | 0.723702 | 5.015152 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin
|
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/input/selection/BaseSelectionHandler.kt
|
1
|
2705
|
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.input.selection
import com.commonsense.android.kotlin.base.*
/**
*
*/
abstract class BaseSelectionHandler<T, CallbackType, SelectionType>(
val callback: FunctionUnit<CallbackType>) {
protected abstract var selection: SelectionType
/**
*Simple guard against callback hell / massacre
*/
private var innerDisableSelectionChanged = false
/**
* The views we are working on, akk the once that can be selected and deselected (only 1 selected at a time).
*
* Consideration: should this be a Set, but will that cause any issues ?
*
*
*/
protected val viewsToWorkOn = mutableSetOf<ToggleableView<T>>()
/**
* Updates the internal selection of this view, via a guard, to avoid any kind of callback hell.
* It performs the action inside of the "guard"
* (where changing selection will not cause an infinite loop effect).
*/
protected fun updateSelection(action: EmptyFunction) {
if (innerDisableSelectionChanged) {
return
}
innerDisableSelectionChanged = true
action()
innerDisableSelectionChanged = false
}
/**
* Adds the given toggleable view to the list of views that we can select between.
*/
operator fun plusAssign(selectionToAdd: ToggleableView<T>) {
addView(selectionToAdd)
}
/**
* De attaches the given view from the views we are working on
*/
operator fun minusAssign(selectionToRemove: ToggleableView<T>) {
removeView(selectionToRemove)
}
/**
* De attaches the given view from the views we are working on
*/
fun removeView(view: ToggleableView<T>) = updateSelection {
view.deselect()
view.clearOnSelectionChanged()
if (isSelected(view)) {
removeSelected()
}
viewsToWorkOn.remove(view)
}
/**
* Adds the given toggleable view to the list of views that we can select between.
*/
//TODO preSelect: Boolean = false ?
fun addView(view: ToggleableView<T>) = updateSelection {
view.deselect()
view.setOnSelectionChanged(this::onSelectionChanged)
viewsToWorkOn.add(view)
}
protected fun onSelectionChanged(view: ToggleableView<T>, selection: Boolean) = updateSelection {
handleSelectionChanged(view, selection)
}
abstract fun handleSelectionChanged(view: ToggleableView<T>, selectedValue: Boolean)
protected abstract fun isSelected(view: ToggleableView<T>): Boolean
protected abstract fun removeSelected()
}
|
mit
|
22ad9a654b0cabdc819368e687e50e34
| 28.413043 | 113 | 0.669871 | 4.838998 | false | false | false | false |
teobaranga/T-Tasks
|
t-tasks/src/main/java/com/teo/ttasks/ui/fragments/accounts/AccountsInfoViewModel.kt
|
1
|
846
|
package com.teo.ttasks.ui.fragments.accounts
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import org.koin.core.KoinComponent
import org.koin.core.inject
class AccountsInfoViewModel: ViewModel(), KoinComponent {
private val firebaseAuth: FirebaseAuth by inject()
private val _accountName = MutableLiveData<String>()
val accountName: LiveData<String>
get() = _accountName
private val _accountEmail = MutableLiveData<String>()
val accountEmail: LiveData<String>
get() = _accountEmail
init {
firebaseAuth.currentUser?.let {
it.displayName?.let { name ->
_accountName.value = name
}
_accountEmail.value = it.email
}
}
}
|
apache-2.0
|
0ec5ad479bbd65bc63ec1a48fecfca85
| 27.2 | 57 | 0.692671 | 4.752809 | false | false | false | false |
anlun/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/util/ProcessRunner.kt
|
1
|
2657
|
package org.jetbrains.haskell.util
import java.io.*
import java.util.ArrayList
public class ProcessRunner(workingDirectory: String? = null) {
private val myWorkingDirectory: String? = workingDirectory
public fun executeNoFail(vararg cmd: String): String {
return executeNoFail(cmd.toList(), null)
}
public fun executeNoFail(cmd: List<String>, input: String?): String {
try {
return executeOrFail(cmd, input)
} catch (e: IOException) {
return "";
}
}
public fun executeOrFail(vararg cmd: String): String {
return executeOrFail(cmd.toList(), null)
}
public fun executeOrFail(cmd: List<String>, input: String?): String {
val process = getProcess(cmd.toList())
if (input != null) {
val streamWriter = OutputStreamWriter(process.getOutputStream()!!)
streamWriter.write(input)
streamWriter.close()
}
var myInput: InputStream = process.getInputStream()!!
val data = readData(myInput)
process.waitFor()
return data
}
public fun getProcess(cmd: List<String>, path: String? = null): Process {
val processBuilder: ProcessBuilder = ProcessBuilder(cmd)
if (path != null) {
val environment = processBuilder.environment()!!
environment.put("PATH", environment.get("PATH") + ":" + path)
}
if (OSUtil.isMac) {
// It's hack to make homebrew based HaskellPlatform work
val environment = processBuilder.environment()!!
environment.put("PATH", environment.get("PATH") + ":/usr/local/bin")
}
if (myWorkingDirectory != null) {
processBuilder.directory(File(myWorkingDirectory))
}
processBuilder.redirectErrorStream(true)
return processBuilder.start()
}
public fun readData(input: InputStream, callback: Callback): Unit {
val reader = BufferedReader(InputStreamReader(input))
while (true) {
var line = reader.readLine()
if (line == null) {
return
}
callback.call(line)
}
}
private fun readData(input: InputStream): String {
val builder = StringBuilder()
readData(input, object : Callback {
public override fun call(command: String?): Boolean {
builder.append(command).append("\n")
return true
}
})
return builder.toString()
}
public interface Callback {
public open fun call(command: String?): Boolean
}
}
|
apache-2.0
|
650ce2515589edca09a19d796db00482
| 27.265957 | 80 | 0.590139 | 4.893186 | false | false | false | false |
anlun/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/debugger/highlighting/HsExecutionPointHighlighter.kt
|
1
|
7197
|
package org.jetbrains.haskell.debugger.highlighting
import com.intellij.openapi.project.Project
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.util.Key
import java.util.concurrent.atomic.AtomicBoolean
import com.intellij.ui.AppUIUtil
import com.intellij.xdebugger.impl.XSourcePositionImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.xdebugger.impl.XDebuggerUtilImpl
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.xdebugger.ui.DebuggerColors
import org.jetbrains.haskell.debugger.frames.HsStackFrame
import org.jetbrains.haskell.debugger.parser.HsFilePosition
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.TextAttributes
import java.awt.Color
import com.intellij.openapi.editor.markup.HighlighterLayer
/**
* Modified copy of com.intellij.xdebugger.impl.ui.ExecutionPointHighlighter. Differences:
* 1) Simplified (not all methods are implemented)
* 2) Highlights code ranges, not just lines
*
* @author Habibullin Marat
*/
public class HsExecutionPointHighlighter(private val myProject: Project,
private val highlighterType: HsExecutionPointHighlighter.HighlighterType
= HsExecutionPointHighlighter.HighlighterType.STACK_FRAME) {
public enum class HighlighterType {
STACK_FRAME,
HISTORY
}
private var myRangeHighlighter: RangeHighlighter? = null
private var myEditor: Editor? = null
private var filePosition: HsFilePosition? = null
private var myOpenFileDescriptor: OpenFileDescriptor? = null
private var myUseSelection: Boolean = false
private var myGutterIconRenderer: GutterIconRenderer? = null
private val EXECUTION_POINT_HIGHLIGHTER_KEY: Key<Boolean>? = Key.create("EXECUTION_POINT_HIGHLIGHTER_KEY")
private val updateRequested = AtomicBoolean()
public fun show(stackFrame: HsStackFrame, useSelection: Boolean, gutterIconRenderer: GutterIconRenderer?) {
updateRequested.set(false)
if (stackFrame.hackSourcePosition == null) {
hide()
return
}
AppUIUtil.invokeLaterIfProjectAlive(myProject, object : Runnable {
override fun run() {
updateRequested.set(false)
filePosition = stackFrame.stackFrameInfo.filePosition
myOpenFileDescriptor = XSourcePositionImpl.createOpenFileDescriptor(myProject, stackFrame.hackSourcePosition!!)
myOpenFileDescriptor!!.setUseCurrentWindow(true)
myGutterIconRenderer = gutterIconRenderer
myUseSelection = useSelection
doShow()
}
})
}
public fun hide() {
AppUIUtil.invokeOnEdt(object : Runnable {
override fun run() {
updateRequested.set(false)
removeHighlighter()
myOpenFileDescriptor = null
myEditor = null
myGutterIconRenderer = null
}
})
}
private fun doShow() {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
removeHighlighter()
myEditor = if (myOpenFileDescriptor == null) null else XDebuggerUtilImpl.createEditor(myOpenFileDescriptor!!)
if (myEditor != null) {
addHighlighter()
}
}
private fun removeHighlighter() {
if (myRangeHighlighter == null || myEditor == null) {
return
}
if (myUseSelection) {
myEditor!!.getSelectionModel().removeSelection()
}
myRangeHighlighter!!.dispose()
myRangeHighlighter = null
}
private fun addHighlighter() {
if (filePosition != null) {
val document = myEditor!!.getDocument()
val startLineOffset = document.getLineStartOffset(filePosition!!.normalizedStartLine)
val endLineOffset = document.getLineStartOffset(filePosition!!.normalizedEndLine)
val startOffset = startLineOffset + filePosition!!.normalizedStartSymbol - 1
val endOffset = endLineOffset + filePosition!!.normalizedEndSymbol - 1
if (myUseSelection) {
myEditor!!.getSelectionModel().setSelection(startOffset, endOffset)
return
}
if (myRangeHighlighter != null) return
myRangeHighlighter = myEditor!!.getMarkupModel().addRangeHighlighter(
startOffset,
endOffset,
getHighlightLayer(),
getTextAttributes(),
HighlighterTargetArea.EXACT_RANGE)
myRangeHighlighter!!.putUserData(EXECUTION_POINT_HIGHLIGHTER_KEY!!, true)
myRangeHighlighter!!.setGutterIconRenderer(myGutterIconRenderer)
}
}
/**
* Returns needed color scheme, based on current highlighter type and on the current global scheme,
* so that highlighters with different types have different colors.
*/
private fun getTextAttributes(): TextAttributes? {
when (highlighterType) {
HsExecutionPointHighlighter.HighlighterType.STACK_FRAME ->
return EditorColorsManager.getInstance()!!.getGlobalScheme().getAttributes(DebuggerColors.EXECUTIONPOINT_ATTRIBUTES)
HsExecutionPointHighlighter.HighlighterType.HISTORY -> {
val scheme = EditorColorsManager.getInstance()!!.getGlobalScheme()
val attr1 = scheme.getAttributes(DebuggerColors.EXECUTIONPOINT_ATTRIBUTES)
val attr2 = scheme.getAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES)
if (attr1 == null) {
return null
}
return TextAttributes(mix(attr1.getForegroundColor(), attr2?.getForegroundColor()),
mix(attr1.getBackgroundColor(), attr2?.getBackgroundColor()),
mix(attr1.getEffectColor(), attr2?.getEffectColor()),
attr1.getEffectType(),
attr1.getFontType())
}
else -> return null
}
}
private fun getHighlightLayer(): Int {
when (highlighterType) {
HsExecutionPointHighlighter.HighlighterType.STACK_FRAME ->
return DebuggerColors.EXECUTION_LINE_HIGHLIGHTERLAYER
HsExecutionPointHighlighter.HighlighterType.HISTORY ->
return DebuggerColors.EXECUTION_LINE_HIGHLIGHTERLAYER - 1
else ->
return HighlighterLayer.SELECTION
}
}
private fun mix(a: Color?, b: Color?): Color? {
if (a == null) {
return b
}
if (b == null) {
return a
}
return Color((a.getRed() + b.getRed()) / 2, (a.getGreen() + b.getGreen()) / 2, (a.getBlue() + b.getBlue()) / 2,
(a.getAlpha() + b.getAlpha()) / 2)
}
}
|
apache-2.0
|
8e81ad8e3e1d4218bf5a87e08ac247bf
| 39.206704 | 132 | 0.649576 | 5.631455 | false | false | false | false |
PassionateWsj/YH-Android
|
app/src/main/java/com/intfocus/template/dashboard/mine/adapter/MinePageVPAdapter.kt
|
1
|
809
|
package com.intfocus.template.dashboard.mine.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
/**
* Created by liuruilin on 2017/6/6.
*/
class MinePageVPAdapter(fragmentManager: FragmentManager,
val mFragmentList: ArrayList<Fragment>,
val titleList: ArrayList<String>) : FragmentPagerAdapter(fragmentManager) {
var mCurrentFragment: Fragment? = null
override fun getItem(position: Int): Fragment = mFragmentList[position]
override fun getCount(): Int = mFragmentList.size
fun switchTo(position: Int) {
mCurrentFragment = mFragmentList[position]
}
override fun getPageTitle(position: Int): CharSequence = titleList[position]
}
|
gpl-3.0
|
5c3ff382dc05391ebc99ef9b3139e38e
| 32.708333 | 99 | 0.725587 | 4.815476 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/about/CreditsFragment.kt
|
1
|
4084
|
package de.westnordost.streetcomplete.about
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.getYamlObject
import kotlinx.android.synthetic.main.fragment_credits.*
import kotlinx.coroutines.*
import org.sufficientlysecure.htmltextview.HtmlTextView
/** Shows the credits of this app */
class CreditsFragment : Fragment(R.layout.fragment_credits),
CoroutineScope by CoroutineScope(Dispatchers.Main) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
launch(Dispatchers.Main) {
addContributorsTo(readMainContributors(), mainCredits)
addContributorsTo(readProjectsContributors(), projectsCredits)
addContributorsTo(readArtContributors(), artCredits)
addContributorsTo(readCodeContributors(), codeCredits)
val inflater = LayoutInflater.from(view.context)
for ((language, translators) in readTranslators()) {
val item = inflater.inflate(R.layout.row_credits_translators, translationCredits, false)
(item.findViewById<View>(R.id.language) as TextView).text = language
(item.findViewById<View>(R.id.contributors) as TextView).text = translators
translationCredits.addView(item)
}
}
authorText.setHtml("Tobias Zwick (<a href=\"https://github.com/westnordost\">westnordost</a>)")
val translationCreditsMore = view.findViewById<HtmlTextView>(R.id.translationCreditsMore)
translationCreditsMore.setHtml(getString(R.string.credits_translations))
val contributorMore = view.findViewById<HtmlTextView>(R.id.contributorMore)
contributorMore.setHtml(getString(R.string.credits_contributors))
}
override fun onStart() {
super.onStart()
activity?.setTitle(R.string.about_title_authors)
}
override fun onDestroy() {
super.onDestroy()
coroutineContext.cancel()
}
private fun addContributorsTo(contributors: List<String>, view: ViewGroup) {
val items = contributors.map { "<li>$it</li>" }.joinToString("")
val textView = HtmlTextView(activity)
TextViewCompat.setTextAppearance(textView, R.style.TextAppearance_Body)
textView.setTextIsSelectable(true)
textView.setHtml("<ul>$items</ul>")
view.addView(textView, LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT))
}
private suspend fun readMainContributors() = withContext(Dispatchers.IO) {
resources.getYamlObject<List<String>>(R.raw.credits_main).map(::withLinkToGithubAccount)
}
private suspend fun readProjectsContributors() = withContext(Dispatchers.IO) {
resources.getYamlObject<List<String>>(R.raw.credits_projects)
}
private suspend fun readCodeContributors() = withContext(Dispatchers.IO) {
resources.getYamlObject<List<String>>(R.raw.credits_code).map(::withLinkToGithubAccount) +
getString(R.string.credits_and_more)
}
private suspend fun readArtContributors() = withContext(Dispatchers.IO) {
resources.getYamlObject<List<String>>(R.raw.credits_art)
}
private suspend fun readTranslators() = withContext(Dispatchers.IO) {
resources.getYamlObject<LinkedHashMap<String, String>>(R.raw.credits_translations)
}
}
private fun withLinkToGithubAccount(contributor: String): String {
val regex = Regex("(.*?)\\s?(?:\\((.+)\\))?")
val match = regex.matchEntire(contributor)!!
val name = match.groupValues[1]
val githubName = match.groupValues[2]
return if (githubName.isEmpty()) {
"<a href=\"https://github.com/$name\">$name</a>"
} else {
"$name (<a href=\"https://github.com/$githubName\">$githubName</a>)"
}
}
|
gpl-3.0
|
0e2bec1040ce5c1c38c119f62479d091
| 41.103093 | 104 | 0.707884 | 4.502756 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/FullTextSpec.kt
|
1
|
2091
|
/*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.lang
import com.intellij.navigation.ItemPresentation
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion
import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification
import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons
import javax.swing.Icon
@Suppress("MemberVisibilityCanBePrivate", "unused")
object FullTextSpec : ItemPresentation, XpmSpecificationType {
// region ItemPresentation
override fun getPresentableText(): String = "XQuery and XPath Full Text"
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product
// endregion
// region XpmSpecificationType
override val id: String = "xpath-full-text"
override val presentation: ItemPresentation
get() = this
// endregion
// region Versions
val REC_1_0_20110317: XpmSpecificationVersion = W3CSpecification(
this,
"1.0-20110317",
"1.0",
"http://www.w3.org/TR/2011/REC-xpath-full-text-10-20110317/"
)
val REC_3_0_20151124: XpmSpecificationVersion = W3CSpecification(
this,
"3.0-20151124",
"3.0",
"http://www.w3.org/TR/2015/REC-xpath-full-text-30-20151124/"
)
val versions: List<XpmSpecificationVersion> = listOf(
REC_1_0_20110317,
REC_3_0_20151124
)
// endregion
}
|
apache-2.0
|
9082b77f02dac9d0e0a41b3d31b8dccc
| 30.681818 | 76 | 0.713534 | 3.945283 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/guilds/GuildDetailFragment.kt
|
1
|
8953
|
package com.habitrpg.android.habitica.ui.fragments.social.guilds
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.MainNavDirections
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentGuildDetailBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.activities.GroupInviteActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIcons
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.common.habitica.helpers.setMarkdown
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
class GuildDetailFragment : BaseFragment<FragmentGuildDetailBinding>() {
@Inject
lateinit var configManager: AppConfigManager
override var binding: FragmentGuildDetailBinding? = null
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var userRepository: UserRepository
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentGuildDetailBinding {
return FragmentGuildDetailBinding.inflate(inflater, container, false)
}
var viewModel: GroupViewModel? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.refreshLayout?.setOnRefreshListener { this.refresh() }
viewModel?.getGroupData()?.observe(viewLifecycleOwner, { updateGuild(it) })
viewModel?.getLeaderData()?.observe(viewLifecycleOwner, { setLeader(it) })
viewModel?.getIsMemberData()?.observe(viewLifecycleOwner, { updateMembership(it) })
binding?.guildDescription?.movementMethod = LinkMovementMethod.getInstance()
binding?.guildSummary?.movementMethod = LinkMovementMethod.getInstance()
binding?.guildBankIcon?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
binding?.leaveButton?.setOnClickListener {
leaveGuild()
}
binding?.joinButton?.setOnClickListener {
viewModel?.joinGroup {
(this.activity as? SnackbarActivity)?.showSnackbar(title = getString(R.string.joined_guild))
}
}
binding?.inviteButton?.setOnClickListener {
val intent = Intent(activity, GroupInviteActivity::class.java)
sendInvitesResult.launch(intent)
}
binding?.leaderWrapper?.setOnClickListener {
viewModel?.leaderID?.let { leaderID ->
val profileDirections = MainNavDirections.openProfileActivity(leaderID)
MainNavigationController.navigate(profileDirections)
}
}
}
private fun setLeader(leader: Member?) {
if (leader == null) {
return
}
binding?.leaderAvatarView?.setAvatar(leader)
binding?.leaderProfileName?.username = leader.displayName
binding?.leaderProfileName?.tier = leader.contributor?.level ?: 0
binding?.leaderUsername?.text = leader.formattedUsername
}
private fun updateMembership(isMember: Boolean?) {
binding?.joinButton?.visibility = if (isMember == true) View.GONE else View.VISIBLE
binding?.leaveButton?.visibility = if (isMember == true) View.VISIBLE else View.GONE
}
private val sendInvitesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
val inviteData = HashMap<String, Any>()
inviteData["inviter"] = viewModel?.user?.value?.profile?.name ?: ""
val emails = it.data?.getStringArrayExtra(GroupInviteActivity.EMAILS_KEY)
if (emails != null && emails.isNotEmpty()) {
val invites = ArrayList<HashMap<String, String>>()
emails.forEach { email ->
val invite = HashMap<String, String>()
invite["name"] = ""
invite["email"] = email
invites.add(invite)
}
inviteData["emails"] = invites
}
val userIDs = it.data?.getStringArrayExtra(GroupInviteActivity.USER_IDS_KEY)
if (userIDs != null && userIDs.isNotEmpty()) {
val invites = ArrayList<String>()
userIDs.forEach { invites.add(it) }
inviteData["usernames"] = invites
}
viewModel?.inviteToGroup(inviteData)
}
}
private fun refresh() {
viewModel?.retrieveGroup {
binding?.refreshLayout?.isRefreshing = false
}
}
private fun getGroupChallenges(): List<Challenge> {
val groupChallenges = mutableListOf<Challenge>()
userRepository.getUserFlowable().forEach {
it.challenges?.forEach {
challengeRepository.getChallenge(it.challengeID).forEach {
if (it.groupId.equals(viewModel?.groupID)) {
groupChallenges.add(it)
}
}
}
}
return groupChallenges
}
internal fun leaveGuild() {
val context = context
if (context != null) {
val groupChallenges = getGroupChallenges()
lifecycleScope.launch(Dispatchers.Main) {
delay(500)
if (groupChallenges.isNotEmpty()) {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.guild_challenges)
alert.setMessage(R.string.leave_guild_challenges_confirmation)
alert.addButton(R.string.keep_challenges, true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, true) { showLeaveSnackbar() }
}
alert.addButton(R.string.leave_challenges_delete_tasks, isPrimary = false, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) { showLeaveSnackbar() }
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
} else {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.leave_guild_confirmation)
alert.setMessage(R.string.rejoin_guild)
alert.addButton(R.string.leave, isPrimary = true, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) {
showLeaveSnackbar()
}
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
}
}
}
}
private fun showLeaveSnackbar() {
(this.activity as? MainActivity)?.showSnackbar(title = getString(R.string.left_guild))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun updateGuild(guild: Group?) {
binding?.titleView?.text = guild?.name
binding?.guildMembersIcon?.setImageBitmap(HabiticaIcons.imageOfGuildCrestMedium((guild?.memberCount ?: 0).toFloat()))
binding?.guildMembersText?.text = guild?.memberCount.toString()
binding?.guildBankText?.text = guild?.gemCount.toString()
binding?.guildSummary?.setMarkdown(guild?.summary)
binding?.guildDescription?.setMarkdown(guild?.description)
}
companion object {
fun newInstance(viewModel: GroupViewModel?): GuildDetailFragment {
val args = Bundle()
val fragment = GuildDetailFragment()
fragment.arguments = args
fragment.viewModel = viewModel
return fragment
}
}
}
|
gpl-3.0
|
e70c35fe7f61b6daa68a00cd199d7f2b
| 41.837321 | 126 | 0.657322 | 5.386883 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
player_domain/src/main/java/com/vmenon/mpo/player/domain/PlaybackMedia.kt
|
1
|
333
|
package com.vmenon.mpo.player.domain
import java.io.Serializable
data class PlaybackMedia(
val mediaId: String,
val durationInMillis: Long,
val title: String? = null,
val author: String? = null,
val artworkUrl: String? = null,
val album: String? = null,
val genres: List<String>? = null
) : Serializable
|
apache-2.0
|
1617229fca4cb386c2c6e63318c704da
| 24.692308 | 36 | 0.687688 | 3.784091 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
player_usecases/src/main/java/com/vmenon/mpo/player/usecases/ListenForPlaybackStateChanges.kt
|
1
|
1609
|
package com.vmenon.mpo.player.usecases
import com.vmenon.mpo.player.domain.MediaPlayerEngine
import com.vmenon.mpo.player.domain.PlaybackState
import com.vmenon.mpo.system.domain.Clock
import com.vmenon.mpo.system.domain.ThreadUtil
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.transformLatest
class ListenForPlaybackStateChanges(
private val playerEngine: MediaPlayerEngine,
private val clock: Clock,
private val threadUtil: ThreadUtil,
private val initialDelay: Long = 100L,
private val delay: Long = 1000L
) {
@ExperimentalCoroutinesApi
operator fun invoke() = playerEngine.playbackStateChanges.transformLatest { playbackState ->
emit(playbackState)
val comparisonTime = clock.currentTimeMillis()
threadUtil.delay(initialDelay) // Initial delay
while (true) {
var estimatedPosition = playbackState.positionInMillis
if (playbackState.state == PlaybackState.State.PLAYING) {
// Calculate the elapsed time between the last position update and now and unless
// paused, we can assume (delta * speed) + current position is approximately the
// latest position. This ensure that we do not repeatedly query the MediaPlayerEngine
val timeDelta = clock.currentTimeMillis() - comparisonTime
estimatedPosition += (timeDelta.toInt() * playbackState.playbackSpeed).toLong()
}
emit(playbackState.copy(positionInMillis = estimatedPosition))
threadUtil.delay(delay)
}
}
}
|
apache-2.0
|
86d8249a7dcd7f9607f9e0446e4209c3
| 45 | 101 | 0.712244 | 5.173633 | false | true | false | false |
NerdNumber9/TachiyomiEH
|
app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaUrlPutResolver.kt
|
1
|
1248
|
package eu.kanade.tachiyomi.data.database.resolvers
import android.content.ContentValues
import com.pushtorefresh.storio.sqlite.StorIOSQLite
import com.pushtorefresh.storio.sqlite.operations.put.PutResolver
import com.pushtorefresh.storio.sqlite.operations.put.PutResult
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import eu.kanade.tachiyomi.data.database.inTransactionReturn
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.tables.MangaTable
// [EXH]
class MangaUrlPutResolver : PutResolver<Manga>() {
override fun performPut(db: StorIOSQLite, manga: Manga) = db.inTransactionReturn {
val updateQuery = mapToUpdateQuery(manga)
val contentValues = mapToContentValues(manga)
val numberOfRowsUpdated = db.lowLevel().update(updateQuery, contentValues)
PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table())
}
fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder()
.table(MangaTable.TABLE)
.where("${MangaTable.COL_ID} = ?")
.whereArgs(manga.id)
.build()
fun mapToContentValues(manga: Manga) = ContentValues(1).apply {
put(MangaTable.COL_URL, manga.url)
}
}
|
apache-2.0
|
c48d57577147f850cd3efb25ad11f0ff
| 35.705882 | 86 | 0.745192 | 4.244898 | false | false | false | false |
walleth/walleth
|
app/src/withGeth/java/org/walleth/geth/GethKethereumTransfomer.kt
|
1
|
1320
|
package org.walleth.geth
import org.ethereum.geth.BigInt
import org.ethereum.geth.Geth
import org.json.JSONObject
import org.kethereum.model.Address
import org.kethereum.model.SignatureData
import org.kethereum.model.Transaction
import java.math.BigInteger
import org.ethereum.geth.Address as GethAddress
fun BigInt.toBigInteger() = BigInteger(bytes)
fun Address.toGethAddr() = Geth.newAddressFromHex(hex)
fun GethAddress.toKethereumAddress() = Address(hex)
fun Transaction.toGethTransaction(): org.ethereum.geth.Transaction = Geth.newTransaction(nonce!!.toLong(),
to!!.toGethAddr(),
BigInt(value!!.toLong()),
gasLimit!!.toLong(),
gasPrice!!.toGethInteger(),
input
)
fun String.hexToBigInteger() = BigInteger(replace("0x", ""), 16)
fun org.ethereum.geth.Transaction.extractSignatureData(): SignatureData? {
val jsonObject = JSONObject(encodeJSON())
return if (jsonObject.getString("r") == "0x0" && jsonObject.getString("s") == "0x0")
null
else
jsonObject.let {
SignatureData(
r = it.getString("r").hexToBigInteger(),
s = it.getString("s").hexToBigInteger(),
v = it.getString("v").hexToBigInteger()
)
}
}
fun BigInteger.toGethInteger() = BigInt(toLong())
|
gpl-3.0
|
0d8842bce547342caa209d9304583900
| 31.219512 | 106 | 0.672727 | 4.150943 | false | false | false | false |
Heiner1/AndroidAPS
|
database/src/main/java/info/nightscout/androidaps/database/transactions/InsertOrUpdateBolusCalculatorResultTransaction.kt
|
1
|
1164
|
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.BolusCalculatorResult
/**
* Creates or updates the BolusCalculatorResult
*/
class InsertOrUpdateBolusCalculatorResultTransaction(
private val bolusCalculatorResult: BolusCalculatorResult
) : Transaction<InsertOrUpdateBolusCalculatorResultTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val current = database.bolusCalculatorResultDao.findById(bolusCalculatorResult.id)
if (current == null) {
database.bolusCalculatorResultDao.insertNewEntry(bolusCalculatorResult)
result.inserted.add(bolusCalculatorResult)
} else {
database.bolusCalculatorResultDao.updateExistingEntry(bolusCalculatorResult)
result.updated.add(bolusCalculatorResult)
}
return result
}
class TransactionResult {
val inserted = mutableListOf<BolusCalculatorResult>()
val updated = mutableListOf<BolusCalculatorResult>()
}
}
|
agpl-3.0
|
ee8dce0c638f1cd400b660776cc73396
| 36.580645 | 90 | 0.755155 | 6.395604 | false | false | false | false |
square/wire
|
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/SchemaEncoder.kt
|
1
|
17563
|
/*
* Copyright 2021 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema.internal
import com.squareup.wire.FieldEncoding
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.ProtoReader
import com.squareup.wire.ProtoWriter
import com.squareup.wire.ReverseProtoWriter
import com.squareup.wire.Syntax
import com.squareup.wire.internal.camelCase
import com.squareup.wire.schema.EnumConstant
import com.squareup.wire.schema.EnumType
import com.squareup.wire.schema.Field
import com.squareup.wire.schema.MessageType
import com.squareup.wire.schema.Options
import com.squareup.wire.schema.ProtoFile
import com.squareup.wire.schema.ProtoMember
import com.squareup.wire.schema.ProtoType
import com.squareup.wire.schema.Rpc
import com.squareup.wire.schema.Schema
import com.squareup.wire.schema.Service
import okio.ByteString
import okio.ByteString.Companion.toByteString
/**
* This class encodes files from a Wire schema using the types in protobuf's `descriptor.proto`.
* Unfortunately, the two models don't line up directly:
*
* * Wire keeps a heterogeneous list of messages and enums; `descriptor.proto` keeps each in its
* own list.
*
* * Descriptors don't have first class support for [Field.EncodeMode.OMIT_IDENTITY], which is the
* default in proto3. Instead these are synthesized with oneofs.
*
* * Descriptors don't support maps. Instead these are synthesized with entry classes.
*
* This file requires we manually keep tags and types in sync with `descriptor.proto`.
*
* TODO(jwilson): this class doesn't yet extension ranges and several other fields that are
* commented out below.
*/
class SchemaEncoder(
private val schema: Schema
) {
private val fileOptionsProtoAdapter =
schema.protoAdapter(Options.FILE_OPTIONS.toString(), false)
private val messageOptionsProtoAdapter =
schema.protoAdapter(Options.MESSAGE_OPTIONS.toString(), false)
private val fieldOptionsProtoAdapter =
schema.protoAdapter(Options.FIELD_OPTIONS.toString(), false)
private val enumOptionsProtoAdapter =
schema.protoAdapter(Options.ENUM_OPTIONS.toString(), false)
private val enumValueOptionsProtoAdapter =
schema.protoAdapter(Options.ENUM_VALUE_OPTIONS.toString(), false)
private val serviceOptionsProtoAdapter =
schema.protoAdapter(Options.SERVICE_OPTIONS.toString(), false)
private val rpcOptionsProtoAdapter =
schema.protoAdapter(Options.METHOD_OPTIONS.toString(), false)
fun encode(protoFile: ProtoFile): ByteString {
return fileEncoder.encode(protoFile).toByteString()
}
private val fileEncoder: Encoder<ProtoFile> = object : Encoder<ProtoFile>() {
override fun encode(writer: ReverseProtoWriter, value: ProtoFile) {
if (value.syntax != Syntax.PROTO_2) {
STRING.encodeWithTag(writer, 12, value.syntax?.toString())
}
// SourceCodeInfo.ADAPTER.encodeWithTag(writer, 9, value.source_code_info)
fileOptionsProtoAdapter.encodeWithTag(writer, 8, value.options.toJsonOptions())
// TODO(jwilson): can extension fields be maps?
for (extend in value.extendList.reversed()) {
fieldEncoder.asRepeated().encodeWithTag(
writer, 7,
extend.fields.map {
EncodedField(
syntax = value.syntax,
field = it,
extendee = extend.type!!.dotName
)
}
)
}
serviceEncoder.asRepeated().encodeWithTag(writer, 6, value.services)
enumEncoder.asRepeated().encodeWithTag(writer, 5, value.types.filterIsInstance<EnumType>())
messageEncoder.asRepeated()
.encodeWithTag(writer, 4, value.types.filterIsInstance<MessageType>())
// INT32.asRepeated().encodeWithTag(writer, 11, value.weak_dependency)
// INT32.asRepeated().encodeWithTag(writer, 10, value.public_dependency)
STRING.asRepeated().encodeWithTag(writer, 3, value.imports)
STRING.encodeWithTag(writer, 2, value.packageName)
STRING.encodeWithTag(writer, 1, value.location.path)
}
}
private val messageEncoder: Encoder<MessageType> = object : Encoder<MessageType>() {
override fun encode(writer: ReverseProtoWriter, value: MessageType) {
val syntax = schema.protoFile(value.type)!!.syntax
val syntheticMaps = collectSyntheticMapEntries(value.type.toString(), value.declaredFields)
val encodedOneOfs = mutableListOf<EncodedOneOf>()
// Collect the true oneofs.
for (oneOf in value.oneOfs) {
val oneOfFields = oneOf.fields.map {
EncodedField(
syntax = syntax,
field = it,
oneOfIndex = encodedOneOfs.size
)
}
encodedOneOfs.add(EncodedOneOf(oneOf.name, fields = oneOfFields))
}
// Collect encoded fields, synthesizing map types and oneofs.
val encodedFields = mutableListOf<EncodedField>()
for (field in value.declaredFields) {
val syntheticMap = syntheticMaps[field]
var encodedField = EncodedField(
syntax = syntax,
field = field,
type = syntheticMap?.fieldType ?: field.type!!
)
if (encodedField.isProto3Optional) {
encodedField = encodedField.copy(oneOfIndex = encodedOneOfs.size)
encodedOneOfs += EncodedOneOf("_${field.name}")
}
encodedFields += encodedField
}
// STRING.asRepeated().encodeWithTag(writer, 10, value.reserved_name)
// ReservedRange.ADAPTER.asRepeated().encodeWithTag(writer, 9, value.reserved_range)
messageOptionsProtoAdapter.encodeWithTag(writer, 7, value.options.toJsonOptions())
// Real and synthetic oneofs.
oneOfEncoder.asRepeated().encodeWithTag(writer, 8, encodedOneOfs)
extensionRangeEncoder.asRepeated()
.encodeWithTag(writer, 5, value.extensionsList.flatMap { it.values })
enumEncoder.asRepeated()
.encodeWithTag(writer, 4, value.nestedTypes.filterIsInstance<EnumType>())
// Real and synthetic nested types.
syntheticMapEntryEncoder.asRepeated().encodeWithTag(writer, 3, syntheticMaps.values.toList())
this.asRepeated().encodeWithTag(writer, 3, value.nestedTypes.filterIsInstance<MessageType>())
// FieldDescriptorProto.ADAPTER.asRepeated().encodeWithTag(writer, 6, value.extension)
val fieldsAndOneOfFields = (encodedFields + encodedOneOfs.flatMap { it.fields })
.sortedWith(compareBy({ it.field.location.line }, { it.field.location.column }))
fieldEncoder.asRepeated().encodeWithTag(writer, 2, fieldsAndOneOfFields)
STRING.encodeWithTag(writer, 1, value.type.simpleName)
}
}
/**
* Create synthetic map entry types for [fields]. These replace the fields' natural types and will
* be emitted as children of the fields' declaring message.
*/
private fun collectSyntheticMapEntries(
enclosingTypeOrPackage: String?,
fields: List<Field>
): Map<Field, SyntheticMapEntry> {
val result = mutableMapOf<Field, SyntheticMapEntry>()
for (field in fields) {
val fieldType = field.type!!
if (fieldType.isMap) {
val name = camelCase(field.name, upperCamel = true) + "Entry"
result[field] = SyntheticMapEntry(
enclosingTypeOrPackage = enclosingTypeOrPackage,
name = name,
keyType = fieldType.keyType!!,
valueType = fieldType.valueType!!
)
}
}
return result
}
private class SyntheticMapEntry(
enclosingTypeOrPackage: String?,
val name: String,
val keyType: ProtoType,
val valueType: ProtoType
) {
val fieldType = ProtoType.get(enclosingTypeOrPackage, name)
}
private val syntheticMapEntryEncoder: Encoder<SyntheticMapEntry> =
object : Encoder<SyntheticMapEntry>() {
val keyFieldEncoder = object : Encoder<SyntheticMapEntry>() {
override fun encode(writer: ReverseProtoWriter, value: SyntheticMapEntry) {
STRING.encodeWithTag(writer, 10, "key")
if (!value.keyType.isScalar) {
STRING.encodeWithTag(writer, 6, value.keyType.dotName)
}
INT32.encodeWithTag(writer, 5, value.keyType.typeTag)
INT32.encodeWithTag(writer, 4, 1) // 1 = Field.Label.OPTIONAL
INT32.encodeWithTag(writer, 3, 1)
STRING.encodeWithTag(writer, 1, "key")
}
}
val valueFieldEncoder = object : Encoder<SyntheticMapEntry>() {
override fun encode(writer: ReverseProtoWriter, value: SyntheticMapEntry) {
STRING.encodeWithTag(writer, 10, "value")
if (!value.valueType.isScalar) {
STRING.encodeWithTag(writer, 6, value.valueType.dotName)
}
INT32.encodeWithTag(writer, 5, value.valueType.typeTag)
INT32.encodeWithTag(writer, 4, 1) // 1 = Field.Label.OPTIONAL
INT32.encodeWithTag(writer, 3, 2)
STRING.encodeWithTag(writer, 1, "value")
}
}
override fun encode(writer: ReverseProtoWriter, value: SyntheticMapEntry) {
messageOptionsProtoAdapter.encodeWithTag(writer, 7, mapOf("map_entry" to true))
valueFieldEncoder.encodeWithTag(writer, 2, value)
keyFieldEncoder.encodeWithTag(writer, 2, value)
STRING.encodeWithTag(writer, 1, value.name)
}
}
/** Supplements the schema [Field] with overrides. */
private data class EncodedField(
val syntax: Syntax?,
val field: Field,
val type: ProtoType = field.type!!,
val extendee: String? = null,
val oneOfIndex: Int? = null
) {
val isProto3Optional
get() = syntax == Syntax.PROTO_3 && field.label == Field.Label.OPTIONAL
}
private val fieldEncoder: Encoder<EncodedField> = object : Encoder<EncodedField>() {
override fun encode(writer: ReverseProtoWriter, value: EncodedField) {
INT32.encodeWithTag(writer, 9, value.oneOfIndex)
if (value.isProto3Optional) {
BOOL.encodeWithTag(writer, 17, true)
}
fieldOptionsProtoAdapter.encodeWithTag(writer, 8, value.field.options.toJsonOptions())
if (value.syntax == Syntax.PROTO_2 && value.field.jsonName != value.field.name) {
STRING.encodeWithTag(writer, 10, value.field.jsonName)
}
STRING.encodeWithTag(writer, 7, value.field.default)
STRING.encodeWithTag(writer, 2, value.extendee)
if (!value.type.isScalar) {
STRING.encodeWithTag(writer, 6, value.type.dotName)
}
INT32.encodeWithTag(writer, 5, value.field.type!!.typeTag)
INT32.encodeWithTag(writer, 4, value.field.labelTag)
INT32.encodeWithTag(writer, 3, value.field.tag)
STRING.encodeWithTag(writer, 1, value.field.name)
}
}
private val Field.labelTag: Int
get() {
return when (encodeMode) {
Field.EncodeMode.NULL_IF_ABSENT, Field.EncodeMode.OMIT_IDENTITY -> 1
Field.EncodeMode.REQUIRED -> 2
Field.EncodeMode.REPEATED, Field.EncodeMode.PACKED, Field.EncodeMode.MAP -> 3
else -> error("unexpected encodeMode: $encodeMode")
}
}
private val ProtoType.dotName
get() = ".$this"
private val ProtoType.typeTag: Int
get() {
return when {
this == ProtoType.DOUBLE -> 1
this == ProtoType.FLOAT -> 2
this == ProtoType.INT64 -> 3
this == ProtoType.UINT64 -> 4
this == ProtoType.INT32 -> 5
this == ProtoType.FIXED64 -> 6
this == ProtoType.FIXED32 -> 7
this == ProtoType.BOOL -> 8
this == ProtoType.STRING -> 9
schema.getType(this) is MessageType -> 11
this == ProtoType.BYTES -> 12
this == ProtoType.UINT32 -> 13
schema.getType(this) is EnumType -> 14
this == ProtoType.SFIXED32 -> 15
this == ProtoType.SFIXED64 -> 16
this == ProtoType.SINT32 -> 17
this == ProtoType.SINT64 -> 18
this.isMap -> 11 // Maps are encoded as messages.
else -> error("unexpected type: $this")
}
}
private class EncodedOneOf(
val name: String,
val fields: List<EncodedField> = listOf()
)
private val oneOfEncoder: Encoder<EncodedOneOf> = object : Encoder<EncodedOneOf>() {
override fun encode(writer: ReverseProtoWriter, value: EncodedOneOf) {
// OneofOptions.ADAPTER.encodeWithTag(writer, 2, value.options)
STRING.encodeWithTag(writer, 1, value.name)
}
}
private val enumEncoder: Encoder<EnumType> = object : Encoder<EnumType>() {
override fun encode(writer: ReverseProtoWriter, value: EnumType) {
// STRING.asRepeated().encodeWithTag(writer, 5, value.reserved_name)
// EnumReservedRange.ADAPTER.asRepeated().encodeWithTag(writer, 4, value.reserved_range)
enumOptionsProtoAdapter.encodeWithTag(writer, 3, value.options.toJsonOptions())
enumConstantEncoder.asRepeated().encodeWithTag(writer, 2, value.constants)
STRING.encodeWithTag(writer, 1, value.name)
}
}
private val extensionRangeEncoder: Encoder<Any> = object : Encoder<Any>() {
override fun encode(writer: ReverseProtoWriter, value: Any) {
when (value) {
is IntRange -> {
INT32.encodeWithTag(writer, 2, value.last + 1) // Exclusive.
INT32.encodeWithTag(writer, 1, value.first) // Inclusive.
}
is Int -> {
INT32.encodeWithTag(writer, 2, value + 1) // Exclusive.
INT32.encodeWithTag(writer, 1, value) // Inclusive.
}
else -> error("unexpected extension range: $value")
}
}
}
private val enumConstantEncoder: Encoder<EnumConstant> = object : Encoder<EnumConstant>() {
override fun encode(writer: ReverseProtoWriter, value: EnumConstant) {
enumValueOptionsProtoAdapter.encodeWithTag(writer, 3, value.options.toJsonOptions())
INT32.encodeWithTag(writer, 2, value.tag)
STRING.encodeWithTag(writer, 1, value.name)
}
}
private val serviceEncoder: Encoder<Service> = object : Encoder<Service>() {
override fun encode(writer: ReverseProtoWriter, value: Service) {
serviceOptionsProtoAdapter.encodeWithTag(writer, 3, value.options.toJsonOptions())
rpcEncoder.asRepeated().encodeWithTag(writer, 2, value.rpcs)
STRING.encodeWithTag(writer, 1, value.name)
}
}
private val rpcEncoder: Encoder<Rpc> = object : Encoder<Rpc>() {
override fun encode(writer: ReverseProtoWriter, value: Rpc) {
if (value.responseStreaming) {
BOOL.encodeWithTag(writer, 6, value.responseStreaming)
}
if (value.requestStreaming) {
BOOL.encodeWithTag(writer, 5, value.requestStreaming)
}
rpcOptionsProtoAdapter.encodeWithTag(writer, 4, value.options.toJsonOptions())
STRING.encodeWithTag(writer, 3, value.responseType!!.dotName)
STRING.encodeWithTag(writer, 2, value.requestType!!.dotName)
STRING.encodeWithTag(writer, 1, value.name)
}
}
/** Encodes a synthetic map type. */
private abstract class Encoder<T> : ProtoAdapter<T>(
FieldEncoding.LENGTH_DELIMITED, null, null, Syntax.PROTO_2
) {
override fun redact(value: T) = value
override fun encodedSize(value: T): Int = throw UnsupportedOperationException()
override fun encode(writer: ProtoWriter, value: T) = throw UnsupportedOperationException()
override fun decode(reader: ProtoReader): T = throw UnsupportedOperationException()
}
/**
* Converts this options instance to a JSON-style value that the runtime adapter can process.
*
* TODO: offer an alternative to SchemaProtoAdapterFactory that uses ProtoMember or tag keys so
* we don't need a clumsy conversion through JSON.
*/
private fun Options.toJsonOptions(): Any? {
val optionsMap = map
if (optionsMap.isEmpty()) return null
val result = mutableMapOf<String, Any>()
for ((key, value) in optionsMap) {
val field = schema.getField(key) ?: error("unexpected options field: $key")
result[field.name] = toJson(field, value!!)
}
return result
}
private fun toJson(field: Field, value: Any): Any {
return when {
field.isRepeated -> (value as List<*>).map { toJsonSingle(field.type!!, it!!) }
else -> toJsonSingle(field.type!!, value)
}
}
private fun toJsonSingle(type: ProtoType, value: Any): Any {
// TODO: use optionValueToInt(value) when that's available in commonMain.
return when (type) {
ProtoType.INT32 -> (value as String).toInt()
ProtoType.DOUBLE -> (value as String).toDouble()
ProtoType.BOOL -> (value as String).toBoolean()
ProtoType.STRING -> value as String
else -> {
when (schema.getType(type)) {
is MessageType -> toJsonMap(value as Map<ProtoMember, Any>)
is EnumType -> value as String
else -> error("not implemented yet!!")
}
}
}
}
private fun toJsonMap(map: Map<ProtoMember, Any>): Map<String, Any?> {
val result = mutableMapOf<String, Any?>()
for ((key, value) in map) {
val field = schema.getField(key) ?: continue // TODO: warn about this??
result[key.simpleName] = toJson(field, value)
}
return result
}
}
|
apache-2.0
|
7f2dab94a5c62bda419b4f652492bff5
| 38.290828 | 100 | 0.681831 | 4.392946 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.