repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/CleaningMap.kt | 1 | 1203 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
import java.util.Date
@Parcelize
class CleaningMap(
var url: String? = null,
var id: String? = null,
var startAt: String? = null,
var endAt: String? = null,
var error: String? = null,
var status: String? = null,
var isDocked: Boolean = false,
var isDelocalized: Boolean = false,
var isValidAsPersistentMap: Boolean = false,
var area: Double = 0.toDouble(),
var chargingTimeSeconds: Double = 0.toDouble(),
var timeInError: Double = 0.toDouble(),
var timeInPause: Double = 0.toDouble(),
var urlExpiresAt: Date? = null,
var rotation:Int = 0
) : Parcelable {
//milliseconds
//30 secs of margin
val isExpired: Boolean
get() {
val difference = urlExpiresAt!!.time - System.currentTimeMillis()
return difference < 30 * 1000
}
companion object {
val COMPLETE = "complete"
val INCOMPLETE = "incomplete"
val CANCELLED = "cancelled"
val INVALID = "invalid"
}
}
| mit | 933aeae967e430e893561122208b580a | 24.595745 | 77 | 0.641729 | 3.983444 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/test/java/com/masahirosaito/spigot/homes/testutils/HomesConsoleCommandSender.kt | 1 | 2655 | package com.masahirosaito.spigot.homes.testutils
import org.bukkit.Server
import org.bukkit.command.ConsoleCommandSender
import org.bukkit.conversations.Conversation
import org.bukkit.conversations.ConversationAbandonedEvent
import org.bukkit.permissions.Permissible
import org.bukkit.permissions.Permission
import org.bukkit.permissions.PermissionAttachment
import org.bukkit.permissions.PermissionAttachmentInfo
import org.bukkit.plugin.Plugin
import org.powermock.api.mockito.PowerMockito.mock
class HomesConsoleCommandSender(val mockServer: Server) : ConsoleCommandSender {
override fun sendMessage(message: String?) {
mockServer.logger.info(message)
}
override fun sendMessage(messages: Array<out String>?) {
messages?.forEach { mockServer.logger.info(it) }
}
override fun beginConversation(conversation: Conversation?): Boolean = true
override fun isPermissionSet(name: String?): Boolean = true
override fun isPermissionSet(perm: Permission?): Boolean = true
override fun addAttachment(plugin: Plugin?, name: String?, value: Boolean): PermissionAttachment {
return PermissionAttachment(plugin, mock(Permissible::class.java))
}
override fun addAttachment(plugin: Plugin?): PermissionAttachment {
return PermissionAttachment(plugin, mock(Permissible::class.java))
}
override fun addAttachment(plugin: Plugin?, name: String?, value: Boolean, ticks: Int): PermissionAttachment {
return PermissionAttachment(plugin, mock(Permissible::class.java))
}
override fun addAttachment(plugin: Plugin?, ticks: Int): PermissionAttachment {
return PermissionAttachment(plugin, mock(Permissible::class.java))
}
override fun getName(): String = "HomesConsoleSender"
override fun isOp(): Boolean = true
override fun acceptConversationInput(input: String?) { }
override fun sendRawMessage(message: String?) {
mockServer.logger.info(message)
}
override fun getEffectivePermissions(): MutableSet<PermissionAttachmentInfo> = mutableSetOf()
override fun isConversing(): Boolean = true
override fun getServer(): Server = mockServer
override fun removeAttachment(attachment: PermissionAttachment?) { }
override fun recalculatePermissions() { }
override fun hasPermission(name: String?): Boolean = true
override fun hasPermission(perm: Permission?): Boolean = true
override fun abandonConversation(conversation: Conversation?) { }
override fun abandonConversation(conversation: Conversation?, details: ConversationAbandonedEvent?) { }
override fun setOp(value: Boolean) { }
}
| apache-2.0 | b7e1092a1366acca878db89091be04be | 34.4 | 114 | 0.754049 | 4.934944 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/mediaview/ImageFragment.kt | 1 | 3121 | /*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte.mediaview
import android.os.Bundle
import android.view.View
import android.view.View.SYSTEM_UI_FLAG_FULLSCREEN
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
import com.github.chrisbanes.photoview.PhotoView
import com.github.chuross.flinglayout.FlingLayout
import com.github.moko256.twitlatte.R
import com.github.moko256.twitlatte.preferenceRepository
import com.github.moko256.twitlatte.repository.KEY_TIMELINE_IMAGE_LOAD_MODE
import com.github.moko256.twitlatte.text.TwitterStringUtils
/**
* Created by moko256 on 2018/10/07.
*
* @author moko256
*/
class ImageFragment : AbstractMediaFragment() {
private lateinit var imageView: PhotoView
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val flingLayout = view as FlingLayout
setSystemUIVisibilityListener { visibility ->
if (visibility and SYSTEM_UI_FLAG_FULLSCREEN == 0) {
showActionbar()
}
}
imageView = view.findViewById(R.id.fragment_image_pager_image)
imageView.setOnClickListener {
if (isShowingSystemUI()) {
hideSystemUI()
} else {
showSystemUI()
}
}
imageView.setOnScaleChangeListener { _: Float, _: Float, _: Float ->
flingLayout.isDragEnabled = imageView.scale <= 1.1f
}
val requests = Glide.with(this)
val url = media.originalUrl
requests
.load(TwitterStringUtils.convertLargeImageUrl(clientType, url))
.override(SIZE_ORIGINAL)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.thumbnail(
requests.load(
if (preferenceRepository.getString(KEY_TIMELINE_IMAGE_LOAD_MODE, "normal") == "normal") {
TwitterStringUtils.convertSmallImageUrl(clientType, url)
} else {
TwitterStringUtils.convertThumbImageUrl(clientType, url)
}
).override(SIZE_ORIGINAL)
)
.into(imageView)
}
override fun returnLayoutId() = R.layout.fragment_image
override fun returnMenuId() = R.menu.fragment_image_toolbar
} | apache-2.0 | 6d391b03c496c46c28842f3dc755271c | 35.729412 | 121 | 0.649471 | 4.67916 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitWorkflowHandler.kt | 1 | 4528 | // 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.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcses
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcsesForFiles
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
class SingleChangeListCommitWorkflowHandler(
override val workflow: SingleChangeListCommitWorkflow,
override val ui: SingleChangeListCommitWorkflowUi
) : AbstractCommitWorkflowHandler<SingleChangeListCommitWorkflow, SingleChangeListCommitWorkflowUi>(),
CommitWorkflowUiStateListener,
SingleChangeListCommitWorkflowUi.ChangeListListener {
override val commitPanel: CheckinProjectPanel = object : CommitProjectPanelAdapter(this) {
override fun setCommitMessage(currentDescription: String?) {
commitMessagePolicy.defaultNameChangeListMessage = currentDescription
super.setCommitMessage(currentDescription)
}
}
override val amendCommitHandler: AmendCommitHandlerImpl = AmendCommitHandlerImpl(this)
private fun getChangeList() = ui.getChangeList()
private fun getCommitState() = ChangeListCommitState(getChangeList(), getIncludedChanges(), getCommitMessage())
private val commitMessagePolicy get() = workflow.commitMessagePolicy
init {
Disposer.register(this, Disposable { workflow.disposeCommitOptions() })
Disposer.register(ui, this)
workflow.addListener(this, this)
workflow.addCommitCustomListener(CommitCustomListener(), this)
ui.addStateListener(this, this)
ui.addExecutorListener(this, this)
ui.addDataProvider(createDataProvider())
ui.addChangeListListener(this, this)
}
override fun vcsesChanged() = Unit
fun activate(): Boolean {
initCommitHandlers()
ui.addInclusionListener(this, this)
ui.defaultCommitActionName = getCommitActionName()
initCommitMessage()
initCommitOptions()
amendCommitHandler.initialMessage = getCommitMessage()
return ui.activate()
}
override fun cancelled() {
commitOptions.saveChangeListSpecificOptions()
saveCommitMessage(false)
LineStatusTrackerManager.getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
override fun changeListChanged() {
updateCommitMessage()
updateCommitOptions()
}
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) {
super.beforeCommitChecksEnded(isDefaultCommit, result)
if (result == CheckinHandler.ReturnResult.COMMIT) {
// commit message could be changed during before-commit checks - ensure updated commit message is used for commit
workflow.commitState = workflow.commitState.copy(getCommitMessage())
if (isDefaultCommit) ui.deactivate()
}
}
override fun updateWorkflow() {
workflow.commitState = getCommitState()
}
override fun addUnversionedFiles() = addUnversionedFiles(getChangeList())
private fun initCommitMessage() {
commitMessagePolicy.init(getChangeList(), getIncludedChanges())
setCommitMessage(commitMessagePolicy.commitMessage)
}
private fun updateCommitMessage() {
commitMessagePolicy.update(getChangeList(), getCommitMessage())
setCommitMessage(commitMessagePolicy.commitMessage)
}
override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(getCommitState(), success)
private fun initCommitOptions() {
workflow.initCommitOptions(createCommitOptions())
ui.commitOptionsUi.setOptions(commitOptions)
commitOptions.restoreState()
updateCommitOptions()
}
private fun updateCommitOptions() {
commitOptions.changeListChanged(getChangeList())
updateCommitOptionsVisibility()
}
private fun updateCommitOptionsVisibility() {
val unversionedFiles = ChangeListManagerImpl.getInstanceImpl(project).unversionedFiles
val vcses = getAffectedVcses(getChangeList().changes, project) + getAffectedVcsesForFiles(unversionedFiles, project)
ui.commitOptionsUi.setVisible(vcses)
}
private inner class CommitCustomListener : CommitResultHandler {
override fun onSuccess(commitMessage: String) = ui.deactivate()
}
} | apache-2.0 | c5fc5fcc4bfa87e31ad2483cc4f2083a | 34.382813 | 140 | 0.789532 | 5.240741 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-jobs/src/main/kotlin/slatekit/jobs/Manager.kt | 1 | 11942 | package slatekit.jobs
import kotlinx.coroutines.*
import slatekit.actors.*
import slatekit.common.Identity
import slatekit.jobs.support.Rules
import slatekit.jobs.support.Work
/**
* A Job is the top level model in this Background Job/Task Queue system. A job is composed of the following:
*
* TERMS:
* 1. Identity : An id, @see[slatekit.common.Identity] to distinctly identify a job
* 3. Task : A single work item with a payload that a worker can work on. @see[slatekit.jobs.Task]
* 2. Queue : Interface for a Queue that workers can optional source tasks from
* 4. Workers : 1 or more @see[slatekit.jobs.workers.Worker]s that can work on this job
* 5. Action : Actions ( start | stop | pause | resume | delay ) to control a job or individual worker
* 6. Events : Used to subscribe to events on the job/worker ( only status changes for now )
* 7. Stats : Reasonable statistics / diagnostics for workers such as total calls, processed, logging
* 8. Policies : @see[slatekit.policy.Policy] associated with a worker such as limits, retries
* 9. Backoffs : Exponential sequence of seconds to use to back off from processing queues when queue is empty
* 10. Channel : The mode of communication to send commands to a job for safe access to shared state
*
*
* NOTES:
* 1. Coordination is kept thread safe as all requests to manage / control a job are handled via channels
* 2. A worker does not need to work from a Task Queue
* 3. You can stop / pause / resume the whole job which means all workers are paused
* 4. You can stop / pause / resume a single worker also
* 5. Policies such as limiting the amount of runs, processed work, error rates, retries are done via policies
* 6. The identity of a worker is based on the identity of its parent job + a workers uuid/unique
* 7. A default implementation of the Queue is available in slatekit.connectors.jobs.JobQueue
*
*
* INSPIRED BY:
* 1. Inspired by Ruby Rails SideKiq, NodesJS Bull, Python Celery
* 2. Kotlin Structured Concurrency via Channels ( misc blog posts by Kotlin Team )
* 3. Actor model see https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html
*
*
* LIMITS:
* 1. No database support ( e.g. for storing status/state/results in the database, etc )
* 2. No distributed jobs support
*
*
* FUTURE:
* 1. Address the limits listed above
* 2. Add support for Redis as a Queue
* 3. Integration with Kotlin Flow ( e.g. a job could feed data into a Flow )
*
*/
class Manager(val jctx: Context, val settings: Settings = Settings())
: Loader<Task>(Context(jctx.id.name, jctx.scope), jctx.channel, enableStrictMode = settings.isStrictlyPaused), Ops, Issuable<Task> {
val workers = Workers(jctx)
private val events = jctx.notifier.jobEvents
private val work = Work(this)
/**
* Subscribe to any @see[slatekit.actors.Status] being changed
*/
fun on(op: suspend (Event) -> Unit) = events.on(op)
/**
* Subscribe to @see[slatekit.actors.Status] beging changed to the one supplied
*/
fun on(status: Status, op: suspend (Event) -> Unit) = events.on(status.name, op)
/**
* Subscribe to @see[slatekit.actors.Status] beging changed to the one supplied
*/
fun onErr(op: suspend (Event) -> Unit) = events.on(ERROR_KEY, op)
/**
* Get worker context by identity
*/
fun get(id: Identity): WorkerContext? = workers[id]
/**
* Get WorkerContext by worker name
*/
fun get(name: String): WorkerContext? = workers[name]
/**
* Get WorkerContext by index
*/
fun get(index: Int): WorkerContext? = workers.contexts[index]
suspend fun close() {
jctx.channel.close()
}
/**
* Supports direct issuing of messages
* For internal/support/test purposes.
* This should not be used for regular usage
*/
override suspend fun issue(item: Message<Task>) {
work(item)
}
/**
* Handles each message based on its type @see[Content], @see[Control],
* This handles following message types and moves this actor to a running state correctly
* 1. @see[Control] messages to start, stop, pause, resume the actor
* 2. @see[Request] messages to load payloads from a source ( e.g. queue )
* 3. @see[Content] messages are simply delegated to the work method
*/
override suspend fun work(item: Message<Task>) {
val middleware = jctx.middleware
when (item) {
is Control -> {
when(middleware){
null -> handle(item)
else -> middleware.handle(this,"JOBS", item) { handle(item) }
}
}
is Request -> {
state.begin(false)
when(middleware){
null -> handle(item)
else -> middleware.handle(this,"JOBS", item) { handle(item) }
}
}
else -> {
// Does not support Request<T>
}
}
}
/**
* Responds to changes in job state.
* Notifies listeners and transitions all workers to the correct state.
*/
override suspend fun onChanged(action: Action, oldStatus: Status, newStatus: Status) {
// Notify listeners of job state change
notify()
// Transition all workers here
val canChangeWorkers = when {
action == Action.Kill -> true
else -> state.validate(action)
}
if (canChangeWorkers) {
all { process(action, 30, it) }
}
}
/**
* Handles a request for a @see[Task] and dispatches it to the default or target @see[Worker]
*/
override suspend fun handle(req: Request<Task>) {
// Id of worker
val id = when (req.reference) {
Message.NONE -> Workers.shortId(jctx.workers[0].id)
else -> req.reference
}
// Run
if(Rules.canWork(status())) {
one(id) { run(it) }
}
}
/**
* Handles a request for a @see[Task] and dispatches it to the default or target @see[Worker]
*/
private suspend fun handle(item: Control<Task>) {
if (item.action == Action.Check) {
val allDone = jctx.workers.all { it.isCompleted() }
if (allDone) {
complete()
}
return
}
when (item.reference) {
Message.NONE -> state.handle(item.action)
else -> manage(item)
}
}
/**
* Completes this job ( when all workers completed )
*/
private suspend fun complete() {
state.complete(false)
notify()
}
/**
* Manages a request to control a specific worker
*/
private suspend fun manage(cmd: Control<Task>) {
// Ensure only processing of running job
if (cmd.action == Action.Process && !Rules.canWork(this.status())) {
notify("CMD_WARN")
return
}
one(cmd.reference) { process(cmd.action, cmd.seconds, it) }
}
private suspend fun process(action: Action, seconds: Long?, wctx: WorkerContext) {
val finalSeconds = seconds ?: 30
when (action) {
is Action.Delay -> work.delay(wctx, seconds = finalSeconds)
is Action.Start -> work.start(wctx)
is Action.Pause -> work.pause(wctx, seconds = finalSeconds)
is Action.Resume -> work.resume(wctx)
is Action.Stop -> work.stop(wctx)
is Action.Process -> run(wctx)
is Action.Check -> work.check(wctx)
is Action.Kill -> work.kill(wctx)
}
}
private suspend fun nextTask(empty: Task): Task {
return when (jctx.queue) {
null -> empty
else -> jctx.queue.next() ?: empty
}
}
/**
* Transitions all workers to the new status supplied
*/
private suspend fun all(op: suspend (WorkerContext) -> Unit) {
workers.contexts.forEach { op(it) }
}
/**
* Transitions all workers to the new status supplied
*/
private suspend fun one(id: String, op: suspend (WorkerContext) -> Unit) {
workers[id]?.let { op(it) }
}
/**
* Transitions all workers to the new status supplied
*/
private suspend fun run(wctx:WorkerContext) {
val task = nextTask(wctx.task)
when(settings.isWorkLaunchable) {
true -> jctx.scope.launch { work.work(wctx, task) }
false -> work.work(wctx, task)
}
}
private fun notify(eventName: String? = null) {
val job = this
ctx.scope.launch {
jctx.notifier.notify(job, eventName)
}
}
companion object {
const val ERROR_KEY = "Error"
fun worker(call: suspend () -> WResult): suspend (Task) -> WResult {
return { t ->
call()
}
}
fun workers(id: Identity, lamdas: List<suspend (Task) -> WResult>): List<Worker<*>> {
return lamdas.map {
WorkerF<String>(id, op = it)
}
}
/**
* Initialize with just a function that will handle the work
* @sample
* val job1 = Job(Identity.job("signup", "email"), ::sendEmail)
* val job2 = Job(Identity.job("signup", "email"), suspend {
* // do work here
* WResult.Done
* })
*/
operator fun invoke(id: Identity, op: suspend () -> WResult,
scope: CoroutineScope = Jobs.scope,
middleware: Middleware? = null,
settings: Settings = Settings()): Manager {
return Manager(id, worker(op), null, scope, middleware, settings)
}
/**
* Initialize with just a function that will handle the work
* @param queue: Queue
* @sample
* val job1 = Job(Identity.job("signup", "email"), ::sendEmail)
* val job2 = Job(Identity.job("signup", "email"), suspend { task ->
* println("task id=${task.id}")
* // do work here
* WResult.Done
* })
*/
operator fun invoke(id: Identity, op: suspend (Task) -> WResult,
queue: Queue? = null,
scope: CoroutineScope = Jobs.scope,
middleware: Middleware? = null,
settings: Settings = Settings()): Manager {
return Manager(id, listOf(op), queue, scope, middleware, settings)
}
/**
* Initialize with a list of functions to excecute work
*/
operator fun invoke(id: Identity, ops: List<suspend (Task) -> WResult>,
queue: Queue? = null,
scope: CoroutineScope = Jobs.scope,
middleware: Middleware? = null,
settings: Settings = Settings()): Manager {
return Manager(Context(id, workers(id, ops), queue = queue, scope = scope, middleware = middleware), settings)
}
/**
* Initialize with just a function that will handle the work
* val id = Identity.job("signup", "email")
* val job1 = Job(id, EmailWorker(id.copy(tags = listOf("worker")))
*/
operator fun invoke(id: Identity, worker: Worker<*>,
queue: Queue? = null,
scope: CoroutineScope = Jobs.scope,
middleware: Middleware? = null,
settings: Settings = Settings()): Manager {
return Manager(Context(id, listOf(worker), queue = queue, scope = scope, middleware = middleware), settings)
}
}
}
| apache-2.0 | fd4fd38f0825260d5a501656a7e4adbb | 33.022792 | 136 | 0.573522 | 4.24831 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/unaryOp/intrinsicNullable.kt | 5 | 427 | fun box(): String {
val a1: Byte? = -1
val a2: Short? = -1
val a3: Int? = -1
val a4: Long? = -1
val a5: Double? = -1.0
val a6: Float? = -1f
if (a1!! != (-1).toByte()) return "fail 1"
if (a2!! != (-1).toShort()) return "fail 2"
if (a3!! != -1) return "fail 3"
if (a4!! != -1L) return "fail 4"
if (a5!! != -1.0) return "fail 5"
if (a6!! != -1f) return "fail 6"
return "OK"
}
| apache-2.0 | 60f7406f3a652136b3b95cfa3833446d | 24.117647 | 47 | 0.461358 | 2.454023 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/classes/delegation2.kt | 4 | 396 | interface Trait1 {
fun foo() : String
}
interface Trait2 {
fun bar() : String
}
class T1 : Trait1{
override fun foo() = "aaa"
}
class T2 : Trait2{
override fun bar() = "bbb"
}
class C(a:Trait1, b:Trait2) : Trait1 by a, Trait2 by b
fun box() : String {
val c = C(T1(),T2())
if(c.foo() != "aaa") return "fail"
if(c.bar() != "bbb") return "fail"
return "OK"
}
| apache-2.0 | d1db3a6fdc0d3ed09a48c05826053586 | 15.5 | 54 | 0.55303 | 2.622517 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/compileKotlinAgainstKotlin/constPropertyReferenceFromMultifileClass.kt | 2 | 497 | // IGNORE_BACKEND: NATIVE
// FILE: A.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
annotation class A
@A
const val OK: String = "OK"
// FILE: B.kt
import a.OK
fun box(): String {
val okRef = ::OK
// TODO: see KT-10892
// val annotations = okRef.annotations
// val numAnnotations = annotations.size
// if (numAnnotations != 1) {
// throw AssertionError("Failed, annotations: $annotations")
// }
val result = okRef.get()
return result
}
| apache-2.0 | 8ed612f90ca6f29d2da3775cb92c017b | 16.75 | 67 | 0.639839 | 3.380952 | false | false | false | false |
room-15/ChatSE | app/src/main/java/com/tristanwiley/chatse/chat/ChatActivity.kt | 1 | 23365 | package com.tristanwiley.chatse.chat
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.text.InputType
import android.view.ContextThemeWrapper
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.squareup.okhttp.FormEncodingBuilder
import com.squareup.okhttp.Request
import com.tristanwiley.chatse.App
import com.tristanwiley.chatse.R
import com.tristanwiley.chatse.about.AboutActivity
import com.tristanwiley.chatse.chat.adapters.RoomAdapter
import com.tristanwiley.chatse.chat.service.IncomingEventService
import com.tristanwiley.chatse.chat.service.IncomingEventServiceBinder
import com.tristanwiley.chatse.login.LoginActivity
import com.tristanwiley.chatse.network.Client
import com.tristanwiley.chatse.network.ClientManager
import com.tristanwiley.chatse.network.cookie.PersistentCookieStore
import com.tristanwiley.chatse.util.RoomPreferenceKeys
import com.tristanwiley.chatse.util.SharedPreferenceManager
import com.tristanwiley.chatse.util.UserPreferenceKeys
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.android.synthetic.main.room_nav_header.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.io.IOException
/**
* ChatActivity sets the Fragment and Drawer layouts
*
* @property serviceBinder: IncomingEventServiceBinder that is used to load rooms
* @property soRoomList: A list of all the rooms the user is currently in for StackOverflow
* @property seRoomList: A list of all the rooms the user is currently in for StackExchange
* @property fkey: The glorious fkey used to authenticate requests
* @property soRoomAdapter: Adapter for StackOverflow Rooms the user is in
* @property seRoomAdapter: Adapter for StackExchange Rooms the user is in
*/
class ChatActivity : AppCompatActivity(), ServiceConnection, RoomAdapter.OnItemClickListener {
private lateinit var serviceBinder: IncomingEventServiceBinder
private val soRoomList = arrayListOf<Room>()
private val seRoomList = arrayListOf<Room>()
private lateinit var fkey: String
private lateinit var soRoomAdapter: RoomAdapter
private lateinit var seRoomAdapter: RoomAdapter
private var isBound = false
private val prefs = SharedPreferenceManager.sharedPreferences
private var currentRoomNum: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_chat)
//Create adapters for current user's rooms
soRoomAdapter = RoomAdapter(Client.SITE_STACK_OVERFLOW, soRoomList, this,this)
seRoomAdapter = RoomAdapter(Client.SITE_STACK_EXCHANGE, seRoomList, this,this)
//Set adapters to RecyclerViews along with LayoutManagers
stackoverflow_room_list.addItemDecoration(DividerItemDecoration(this))
stackoverflow_room_list.adapter = soRoomAdapter
stackoverflow_room_list.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
stackexchange_room_list.addItemDecoration(DividerItemDecoration(this))
stackexchange_room_list.adapter = seRoomAdapter
stackexchange_room_list.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
//Set toolbar as SupportActionBar
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
//Color the toolbar for StackOverflow as a default
supportActionBar?.setBackgroundDrawable(ColorDrawable(ContextCompat.getColor(applicationContext, R.color.stackoverflow_orange)))
//On the toggle button pressed open the NavigationDrawer
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
//Load the user data for the NavigationDrawer header
loadUserData()
val serviceIntent = Intent(this, IncomingEventService::class.java)
this.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE)
isBound = true
}
/**
* Function to load user data and set it to the NavigationDrawer header
*/
private fun loadUserData() {
val userID = prefs.getInt("SOID", -1)
val seID = prefs.getInt("SEID", -1)
//Does the user have a SO account? What about SE?
when {
userID != -1 -> doAsync {
val client = ClientManager.client
val request = Request.Builder()
.url("https://chat.stackoverflow.com/users/thumbs/$userID")
.build()
val response = client.newCall(request).execute()
val jsonResult = JSONObject(response.body().string())
uiThread {
userName.text = jsonResult.getString("name")
userEmail.text = prefs.getString("email", "")
}
}
seID != -1 -> doAsync {
val client = ClientManager.client
val request = Request.Builder()
.url("https://chat.stackoverflow.com/users/thumbs/$userID")
.build()
val response = client.newCall(request).execute()
val jsonResult = JSONObject(response.body().string())
uiThread {
userName.text = jsonResult.getString("name")
userEmail.text = prefs.getString("email", "")
}
}
else -> Timber.e("ChatActivity UserId not found")
}
}
/**
* When network is connected add the rooms to the drawer
*/
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
Timber.d("onServiceConnected Service connect")
serviceBinder = binder as IncomingEventServiceBinder
//Asynchronously add rooms to drawer
doAsync {
fkey = serviceBinder.loadRoom(ChatRoom(Client.SITE_STACK_OVERFLOW, 1)).fkey
addRoomsToDrawer(fkey)
}
//Load a default room
loadChatFragment(ChatRoom(prefs.getString(RoomPreferenceKeys.LAST_ROOM_SITE, Client.SITE_STACK_OVERFLOW)!!, prefs.getInt(RoomPreferenceKeys.LAST_ROOM_NUM, 15)))
currentRoomNum = prefs.getInt(RoomPreferenceKeys.LAST_ROOM_NUM, 15)
}
/**
* onDestroy unbind the bound IncomingEventService
* Protects from leaking.
*/
override fun onDestroy() {
super.onDestroy()
if (isBound) {
unbindService(this)
isBound = false
}
if (!prefs.getBoolean(UserPreferenceKeys.IS_LOGGED_IN, false)) {
PersistentCookieStore(App.instance).removeAll()
startActivity(Intent(applicationContext, LoginActivity::class.java))
finish()
}
}
/**
* On resume rebind the service to listen for incoming events
*/
override fun onResume() {
super.onResume()
if (!isBound) {
val serviceIntent = Intent(this, IncomingEventService::class.java)
this.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE)
isBound = true
}
}
/**
* Add all the rooms that the user is in to the NavigationDrawer
*/
private fun addRoomsToDrawer(fkey: String) {
val soID = prefs.getInt("SOID", -1)
soRoomList.clear()
seRoomList.clear()
doAsync {
//If the user has a StackOverflow ID then load rooms
if (soID != -1) {
val client = ClientManager.client
val soChatPageRequest = Request.Builder()
.url("${Client.SITE_STACK_OVERFLOW}/users/thumbs/$soID")
.build()
val response = client.newCall(soChatPageRequest).execute()
val jsonData = response.body().string()
Timber.wtf("JSON $jsonData")
val result = JSONObject(jsonData)
runOnUiThread {
//Clear all the rooms and make the text visible
so_header_text.visibility = View.VISIBLE
stackoverflow_room_list.visibility = View.VISIBLE
//For each room, create a room and add it to the list
val rooms = result.getJSONArray("rooms")
for (i in 0..(rooms.length() - 1)) {
val room = rooms.getJSONObject(i)
val roomName = room.getString("name")
val roomNum = room.getLong("id")
//Create room and add it to the list
createRoom(Client.SITE_STACK_OVERFLOW, roomName, roomNum, 0, fkey)
}
//If the rooms are empty then remove the list and header
if (rooms.length() == 0) {
so_header_text.visibility = View.GONE
stackoverflow_room_list.visibility = View.GONE
}
}
} else {
runOnUiThread {
so_header_text.visibility = View.GONE
stackoverflow_room_list.visibility = View.GONE
}
}
//If the user has a StackExchange ID then load rooms
val seID = prefs.getInt("SEID", -1)
if (seID != -1) {
val client = ClientManager.client
val soChatPageRequest = Request.Builder()
.url("${Client.SITE_STACK_EXCHANGE}/users/thumbs/$seID")
.build()
val response = client.newCall(soChatPageRequest).execute()
val jsonData = response.body().string()
val result = JSONObject(jsonData)
runOnUiThread {
se_header_text.visibility = View.VISIBLE
stackexchange_room_list.visibility = View.VISIBLE
}
//For each room, create a room and add it to the list
val rooms = result.getJSONArray("rooms")
for (i in 0..(rooms.length() - 1)) {
val room = rooms.getJSONObject(i)
val roomName = room.getString("name")
val roomNum = room.getLong("id")
//Create room and add it to the list
createRoom(Client.SITE_STACK_EXCHANGE, roomName, roomNum, 0, fkey)
}
//If the rooms are empty then remove the list and header
if (rooms.length() == 0) {
runOnUiThread {
se_header_text.visibility = View.GONE
stackexchange_room_list.visibility = View.GONE
}
}
} else {
runOnUiThread {
se_header_text.visibility = View.GONE
stackexchange_room_list.visibility = View.GONE
}
}
}
}
/**
* Create a room from the information we got in addRoomsToDrawer(), but get more information
*/
fun createRoom(site: String, roomName: String, roomNum: Long, lastActive: Long, fkey: String) {
if (site == Client.SITE_STACK_OVERFLOW) {
if (soRoomList.any { it.roomID == roomNum }) return
} else {
if (seRoomList.any { it.roomID == roomNum }) return
}
doAsync {
val client = ClientManager.client
val soChatPageRequest = Request.Builder()
.url("$site/rooms/thumbs/$roomNum/")
.build()
val response = client.newCall(soChatPageRequest).execute()
val jsonData = response.body().string()
val json = JSONObject(jsonData)
//Get description for room
val description = json.getString("description")
//Is this a user's favorite?
val isFavorite = json.getBoolean("isFavorite")
//Get the room's tags
val tags = json.getString("tags")
//If this is for StackOverflow then add it to the SO list
//Otherwise, add it to the SE list
if (site == Client.SITE_STACK_OVERFLOW) {
soRoomList.add(Room(roomName, roomNum, description, lastActive, isFavorite, tags, fkey))
runOnUiThread {
soRoomAdapter.notifyDataSetChanged()
}
} else {
runOnUiThread {
seRoomList.add(Room(roomName, roomNum, description, lastActive, isFavorite, tags, fkey))
seRoomAdapter.notifyDataSetChanged()
}
}
}
}
//Inflate the menu for the Toolbar
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_chat, menu)
return true
}
/**
* Manage each menu item selected
* With search_rooms we allow the user to join a room by id (eventually search for rooms)
* With action_logout we log out of the app
*/
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item != null) {
when (item.itemId) {
R.id.search_rooms -> {
//Create an AlertDialog to join a room
val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AppTheme_SO))
//Set the title
builder.setTitle("Join Room")
//Create a layout to set as Dialog view
val l = LinearLayout(applicationContext)
//Set orientation
l.orientation = LinearLayout.VERTICAL
//Get DPI so we can add padding and look natural
val dpi = application.resources.displayMetrics.density.toInt()
l.setPadding((19 * dpi), (5 * dpi), (14 * dpi), (5 * dpi))
//Input for inputting room ID
val input = EditText(applicationContext)
//Set hint, input type as a number, and match parent
input.hint = "Enter Room ID"
input.inputType = InputType.TYPE_CLASS_NUMBER
input.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
//Add EditText to view
l.addView(input)
//Create dropdown to choose which site
val spinner = Spinner(applicationContext)
input.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
spinner.adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayListOf("StackOverflow", "StackExchange"))
var site = Client.SITE_STACK_OVERFLOW
//Add dropdown to View
l.addView(spinner)
//On dropdown click set the site as the appropriate site
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
when (pos) {
//If the first item is clicked, set the site as SO
0 -> site = Client.SITE_STACK_OVERFLOW
//Otherwise set to SE
1 -> site = Client.SITE_STACK_EXCHANGE
}
}
//Default as StackOverflow
override fun onNothingSelected(parent: AdapterView<out Adapter>?) {
site = Client.SITE_STACK_OVERFLOW
}
}
//Set the view to the layout built above
builder.setView(l)
//Join the room the user chose and load it into the container
builder.setPositiveButton("Join Room") { dialog, _ ->
loadChatFragment(ChatRoom(site, input.text.toString().toInt()))
currentRoomNum = input.text.toString().toInt()
//Dismiss the dialog
dialog.dismiss()
}
builder.setNegativeButton("Cancel") { dialog, _ ->
//Dismiss the dialog and cancel
dialog.cancel()
}
//Show the dialog
builder.show()
}
R.id.action_about -> {
startActivity(Intent(this, AboutActivity::class.java))
}
//Logout of app by clearing all SharedPreferences and loading the LoginActivity
R.id.action_logout -> {
prefs.edit().clear().apply()
finish()
}
//This is handled by the ChatFragment
R.id.room_information -> return false
R.id.room_stars -> return false
}
}
return super.onOptionsItemSelected(item)
}
override fun onServiceDisconnected(name: ComponentName) {
Timber.d("ChatActivity Service disconnect")
}
override fun onItemClick(chatRoom: ChatRoom) {
val clickedRoomNo = chatRoom.num
if ((currentRoomNum != null) && currentRoomNum != clickedRoomNo) {
currentRoomNum = clickedRoomNo
doAsync {
addChatFragment(createChatFragment(chatRoom))
}
prefs.edit().putString(RoomPreferenceKeys.LAST_ROOM_SITE, chatRoom.site).putInt(RoomPreferenceKeys.LAST_ROOM_NUM,clickedRoomNo).apply()
}
drawer_layout.closeDrawers()
}
//Load the chat fragment by creating it and adding it
private fun loadChatFragment(room: ChatRoom) {
doAsync {
addChatFragment(createChatFragment(room))
}
prefs.edit().putString(RoomPreferenceKeys.LAST_ROOM_SITE, room.site).putInt(RoomPreferenceKeys.LAST_ROOM_NUM, room.num).apply()
drawer_layout.closeDrawers()
}
//Add the fragment by replacing the current fragment with the new ChatFragment
private fun addChatFragment(fragment: ChatFragment) {
runOnUiThread {
supportFragmentManager
.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.commitAllowingStateLoss()
}
}
//Create the ChatFragment by joining room and creating an instance of the ChatFragment
@Throws(IOException::class, JSONException::class)
private fun createChatFragment(room: ChatRoom): ChatFragment {
val roomInfo = serviceBinder.loadRoom(room)
rejoinFavoriteRooms()
serviceBinder.joinRoom(room, roomInfo.fkey)
val chatFragment = ChatFragment.createInstance(room, roomInfo.name, roomInfo.fkey)
serviceBinder.registerListener(room, chatFragment)
//Set the title and color of Toolbar depending on room
runOnUiThread {
supportActionBar?.title = roomInfo.name
//If the room is for StackOverflow set the color orange, otherwise SE is blue
if (room.site == Client.SITE_STACK_OVERFLOW) {
supportActionBar?.setBackgroundDrawable(ColorDrawable(ContextCompat.getColor(applicationContext, R.color.stackoverflow_orange)))
//Set the multitasking color to orange
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setTaskDescription(ActivityManager.TaskDescription(ActivityManager.TaskDescription().label, ActivityManager.TaskDescription().icon, ContextCompat.getColor(applicationContext, R.color.stackoverflow_orange)))
}
} else if (room.site == Client.SITE_STACK_EXCHANGE) {
supportActionBar?.setBackgroundDrawable(ColorDrawable(ContextCompat.getColor(applicationContext, R.color.stackexchange_blue)))
//Set the multitasking color to blue
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setTaskDescription(ActivityManager.TaskDescription(ActivityManager.TaskDescription().label, ActivityManager.TaskDescription().icon, ContextCompat.getColor(applicationContext, R.color.stackexchange_blue)))
}
}
}
return chatFragment
}
/**
* Function to rejoin the user's favorite rooms
*/
private fun rejoinFavoriteRooms() {
val client = ClientManager.client
doAsync {
//Get the fkey to make a call
val soRoomInfo = serviceBinder.loadRoom(ChatRoom(Client.SITE_STACK_OVERFLOW, 1))
//Create a body and add appropriate parameters
val soRequestBody = FormEncodingBuilder()
.add("fkey", soRoomInfo.fkey)
.add("immediate", "true")
.add("quiet", "true")
.build()
//Add body and url and build call
val soChatPageRequest = Request.Builder()
.url(Client.SITE_STACK_OVERFLOW + "/chats/join/favorite")
.post(soRequestBody)
.build()
//Execute call
client.newCall(soChatPageRequest).execute()
//Do the same for StackExchange
val seRoomInfo = serviceBinder.loadRoom(ChatRoom(Client.SITE_STACK_EXCHANGE, 1))
val seRequestBody = FormEncodingBuilder()
.add("fkey", seRoomInfo.fkey)
.add("immediate", "true")
.add("quiet", "true")
.build()
val seChatPageRequest = Request.Builder()
.url(Client.SITE_STACK_EXCHANGE + "/chats/join/favorite")
.post(seRequestBody)
.build()
client.newCall(seChatPageRequest).execute()
}
}
}
//A class for a room with all the things we get from /rooms/thumbs/{id}
data class Room(
val name: String,
val roomID: Long,
val description: String,
val lastActive: Long?,
var isFavorite: Boolean,
val tags: String,
val fkey: String
) | apache-2.0 | 619ad6c278ba1a5d070c4b0f10293403 | 41.638686 | 231 | 0.597518 | 5.143077 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/DebugBuildRequestsHandler.kt | 1 | 1183 | package au.com.codeka.warworlds.server.admin.handlers
import au.com.codeka.warworlds.common.proto.BuildRequest
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.server.store.DataStore
import java.util.*
class DebugBuildRequestsHandler : AdminHandler() {
override fun get() {
val data = TreeMap<String, Any>()
// Similar to moving fleets, the simulation queue is what we'll use as a proxy for build
// requests. A build request will, by necessity, cause a re-simulation, so these stars are where
// the requests will be. We can just do a little bit of extra filtering.
val buildRequestStars = HashMap<Long, Star>()
val buildRequests = ArrayList<BuildRequest>()
for (star in DataStore.i.stars().fetchSimulationQueue(100)) {
for (planet in star.planets) {
val colony = planet.colony ?: continue
for (buildRequest in colony.build_requests) {
buildRequestStars[buildRequest.id] = star
buildRequests.add(buildRequest)
}
}
}
data["build_requests"] = buildRequests
data["request_stars"] = buildRequestStars
render("debug/build-requests.html", data)
}
}
| mit | 28a698253cfdd8034a7549dfc2457d1d | 37.16129 | 100 | 0.705833 | 4.093426 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/SelectProjectOpenProcessorDialog.kt | 2 | 2633 | // 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.ide.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.ui.layout.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import javax.swing.JComponent
@ApiStatus.Internal
class SelectProjectOpenProcessorDialog(
val processors: List<ProjectOpenProcessor>,
val file: VirtualFile
) : DialogWrapper(null, false) {
private var selectedProcessor: ProjectOpenProcessor = processors.first()
init {
title = ProjectBundle.message("project.open.select.from.multiple.processors.dialog.title")
init()
}
override fun createCenterPanel(): JComponent? = panel {
row {
label(ProjectBundle.message("project.open.select.from.multiple.processors.dialog.description.line1", processors.size, file.name))
}
row {
label(ProjectBundle.message("project.open.select.from.multiple.processors.dialog.description.line2"))
}
buttonGroup(::selectedProcessor) {
processors.forEach { processor ->
row {
radioButton(ProjectBundle.message("project.open.select.from.multiple.processors.dialog.choice", processor.name), processor)
}
}
}
}
override fun getHelpId(): String? = "project.open.select.from.multiple.providers"
fun showAndGetChoice(): ProjectOpenProcessor? = if (showAndGet()) selectedProcessor else null
companion object {
private var testShowAndGetChoice: (List<ProjectOpenProcessor>, VirtualFile) -> ProjectOpenProcessor? = { it, _ -> it.firstOrNull() }
@TestOnly
fun setTestDialog(showAndGetChoice: (List<ProjectOpenProcessor>, VirtualFile) -> ProjectOpenProcessor?, parentDisposable: Disposable) {
val prevDialog = testShowAndGetChoice
testShowAndGetChoice = showAndGetChoice
Disposer.register(parentDisposable, Disposable { testShowAndGetChoice = prevDialog })
}
@JvmStatic
fun showAndGetChoice(processors: List<ProjectOpenProcessor>, file: VirtualFile): ProjectOpenProcessor? {
if (Messages.isApplicationInUnitTestOrHeadless()) {
return testShowAndGetChoice(processors, file)
}
val dialog = SelectProjectOpenProcessorDialog(processors, file)
return dialog.showAndGetChoice()
}
}
} | apache-2.0 | a305c4862dfdf1abebfce7037c1f135e | 37.735294 | 140 | 0.757311 | 4.611208 | false | true | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/module/GroupModulesByQualifiedNamesTest.kt | 12 | 6066 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.module
import com.intellij.ide.projectView.impl.ModuleGroup
import com.intellij.openapi.module.ModuleGrouper
import com.intellij.testFramework.HeavyPlatformTestCase
import org.junit.Assert
class GroupModulesByQualifiedNamesTest : HeavyPlatformTestCase() {
fun `test single module`() {
val module = createModule("a.b.module")
assertEquals("module", grouper.getShortenedName(module))
val parentGroup = ModuleGroup(listOf("a"))
assertEmpty(parentGroup.modulesInGroup(grouper, false))
assertEmpty(parentGroup.modulesInGroup(myProject, false))
assertSameElements(parentGroup.modulesInGroup(grouper, true), module)
val group = assertOneElement(parentGroup.childGroups(grouper))
Assert.assertArrayEquals(group.groupPath, arrayOf("a", "b"))
Assert.assertArrayEquals(assertOneElement(parentGroup.childGroups(myProject)).groupPath, arrayOf("a", "b"))
assertSameElements(group.modulesInGroup(grouper, false), module)
assertSameElements(group.modulesInGroup(myProject), module)
assertEmpty(group.childGroups(grouper))
assertEmpty(group.childGroups(myProject))
}
fun `test two modules`() {
val module1 = createModule("a.module1")
val module2 = createModule("a.b.module2")
assertEquals("module1", grouper.getShortenedName(module1))
assertEquals("module2", grouper.getShortenedName(module2))
val parentGroup = ModuleGroup(listOf("a"))
assertSameElements(parentGroup.modulesInGroup(grouper, false), module1)
assertSameElements(parentGroup.modulesInGroup(myProject), module1)
assertSameElements(parentGroup.modulesInGroup(grouper, true), module1, module2)
val group = assertOneElement(parentGroup.childGroups(grouper))
Assert.assertArrayEquals(group.groupPath, arrayOf("a", "b"))
Assert.assertArrayEquals(assertOneElement(parentGroup.childGroups(myProject)).groupPath, arrayOf("a", "b"))
assertSameElements(group.modulesInGroup(grouper, false), module2)
assertSameElements(group.modulesInGroup(myProject), module2)
assertEmpty(group.childGroups(grouper))
assertEmpty(group.childGroups(myProject))
}
fun `test module as a group`() {
val module1 = createModule("a.foo")
val module2 = createModule("a.foo.bar")
val module3 = createModule("a.foo.bar.baz")
assertEquals("foo", grouper.getShortenedName(module1))
assertEquals("bar", grouper.getShortenedName(module2))
assertEquals("baz", grouper.getShortenedName(module3))
val parentGroup = ModuleGroup(listOf("a"))
assertSameElements(parentGroup.modulesInGroup(grouper, false), module1, module2, module3)
assertSameElements(parentGroup.modulesInGroup(myProject), module1, module2, module3)
assertSameElements(parentGroup.modulesInGroup(grouper, true), module1, module2, module3)
assertEmpty(parentGroup.childGroups(grouper))
assertEmpty(parentGroup.childGroups(myProject))
}
fun `test module as a group with deep ancestor`() {
val module1 = createModule("a.foo")
val module2 = createModule("a.foo.bar.baz")
assertEquals("foo", grouper.getShortenedName(module1))
assertEquals("baz", grouper.getShortenedName(module2))
val parentGroup = ModuleGroup(listOf("a"))
assertSameElements(parentGroup.modulesInGroup(grouper, false), module1, module2)
assertSameElements(parentGroup.modulesInGroup(myProject), module1, module2)
assertSameElements(parentGroup.modulesInGroup(grouper, true), module1, module2)
assertEmpty(parentGroup.childGroups(grouper))
assertEmpty(parentGroup.childGroups(myProject))
}
fun `test grand parent group`() {
val module1 = createModule("a.foo.x.m1")
val module2 = createModule("a.foo.x.m2")
val module3 = createModule("a.bar.x.m3")
val module4 = createModule("a.bar.x.m4")
val parentGroup = ModuleGroup(listOf("a"))
assertEmpty(parentGroup.modulesInGroup(grouper, false))
assertEmpty(parentGroup.modulesInGroup(myProject))
assertSameElements(parentGroup.modulesInGroup(grouper, true), module1, module2, module3, module4)
val fooGroup = ModuleGroup(listOf("a", "foo"))
val barGroup = ModuleGroup(listOf("a", "bar"))
assertSameElements(parentGroup.childGroups(grouper), fooGroup, barGroup)
assertSameElements(parentGroup.childGroups(myProject), fooGroup, barGroup)
val fooXGroup = ModuleGroup(listOf("a", "foo", "x"))
val barXGroup = ModuleGroup(listOf("a", "bar", "x"))
assertSameElements(fooGroup.childGroups(grouper), fooXGroup)
assertSameElements(fooGroup.childGroups(myProject), fooXGroup)
assertSameElements(barGroup.childGroups(grouper), barXGroup)
assertSameElements(barGroup.childGroups(myProject), barXGroup)
}
fun `test names with incorrect chars after dots`() {
val module1 = createModule("a.foo-1.2")
val module2 = createModule("a.foo-1.3")
assertEquals("foo-1.2", grouper.getShortenedName(module1))
assertEquals("foo-1.3", grouper.getShortenedName(module2))
val parentGroup = ModuleGroup(listOf("a"))
assertSameElements(parentGroup.modulesInGroup(grouper, false), module1, module2)
assertSameElements(parentGroup.modulesInGroup(myProject), module1, module2)
assertSameElements(parentGroup.modulesInGroup(grouper, true), module1, module2)
assertEmpty(parentGroup.childGroups(grouper))
assertEmpty(parentGroup.childGroups(myProject))
}
private val grouper: ModuleGrouper
get() = getQualifiedNameModuleGrouper(myProject)
}
| apache-2.0 | 4eeb832d1634adc221ca4b9d29ab78f6 | 42.956522 | 111 | 0.755193 | 4.171939 | false | true | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/core/tag/extension/ServerTimeTag.kt | 2 | 1299 | package chat.willow.kale.core.tag.extension
import chat.willow.kale.core.tag.ITagParser
import chat.willow.kale.core.tag.ITagSerialiser
import chat.willow.kale.core.tag.Tag
import chat.willow.kale.loggerFor
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.*
data class ServerTimeTag(val time: Instant) {
companion object Factory: ITagParser<ServerTimeTag>, ITagSerialiser<ServerTimeTag> {
private val LOGGER = loggerFor<Factory>()
private val timeZone = TimeZone.getTimeZone("UTC")
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.sss'Z'")
val name = "time"
init {
dateFormat.timeZone = timeZone
}
override fun parse(tag: Tag): ServerTimeTag? {
val value = tag.value ?: return null
val instant = try {
Instant.parse(value)
} catch (exception: Exception) {
LOGGER.warn("failed to parse date for tag: $tag $exception")
null
} ?: return null
return ServerTimeTag(time = instant)
}
override fun serialise(tag: ServerTimeTag): Tag? {
val instant = tag.time.toString()
return Tag(name = name, value = instant)
}
}
} | isc | f5130a0cc9a1d5f49b3f6ef302614b24 | 26.083333 | 88 | 0.624326 | 4.259016 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveUselessIsCheckFix.kt | 2 | 1469 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtIsExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class RemoveUselessIsCheckFix(element: KtIsExpression) : KotlinQuickFixAction<KtIsExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("remove.useless.is.check")
override fun getText(): String = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.run {
val expressionsText = this.isNegated.not().toString()
val newExpression = KtPsiFactory(project).createExpression(expressionsText)
replace(newExpression)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtIsExpression>? {
val expression = diagnostic.psiElement.getNonStrictParentOfType<KtIsExpression>() ?: return null
return RemoveUselessIsCheckFix(expression)
}
}
}
| apache-2.0 | 364dfd3c50bc23117c283fb0081a4dca | 43.515152 | 158 | 0.758339 | 4.848185 | false | false | false | false |
Flank/flank | common/src/main/kotlin/flank/common/OutputReportKeys.kt | 1 | 203 | package flank.common
const val OUTPUT_ARGS = "args"
const val OUTPUT_WEBLINKS = "weblinks"
const val OUTPUT_TEST_RESULTS = "test_results"
const val OUTPUT_COST = "cost"
const val OUTPUT_ERROR = "error"
| apache-2.0 | 2a24531ed4fe103043320fc0cadb95af | 28 | 46 | 0.748768 | 3.274194 | false | true | false | false |
serssp/reakt | reakt/src/main/kotlin/com/github/andrewoma/react/ReactSpec.kt | 2 | 10271 | package com.github.andrewoma.react
/**
* Interface describing ReactComponentSpec
*/
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
interface ReactMixin<P, S> {
/**
* Invoked immediately before rendering occurs.
* If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.
*/
fun componentWillMount(): Unit {
}
/**
* Invoked immediately after rendering occurs.
* At this point in the lifecycle, the component has a DOM representation which you can access via the rootNode argument or by calling this.getDOMNode().
* If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval,
* or send AJAX requests, perform those operations in this method.
*/
fun componentDidMount(): Unit {
}
/**
* Invoked when a component is receiving new props. This method is not called for the initial render.
*
* Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState().
* The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
*
* @param nextProps the props object that the component will receive
*/
fun componentWillReceiveProps(nextProps: P): Unit {
}
/**
* Invoked before rendering when new props or state are being received.
* This method is not called for the initial render or when forceUpdate is used.
* Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update.
* By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place,
* but if you are careful to always treat state as immutable and to read only from props and state in render()
* then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.
*
* If performance is a bottleneck, especially with dozens or hundreds of components, use shouldComponentUpdate to speed up your app.
*
* @param nextProps the props object that the component will receive
* @param nextState the state object that the component will receive
*/
fun shouldComponentUpdate(nextProps: P, nextState: S): Boolean {
return true
}
/**
* Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
* Use this as an opportunity to perform preparation before an update occurs.
*
* @param nextProps the props object that the component has received
* @param nextState the state object that the component has received
*/
fun componentWillUpdate(nextProps: P, nextState: S): Unit {
}
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
* Use this as an opportunity to operate on the DOM when the component has been updated.
*
* @param nextProps the props object that the component has received
* @param nextState the state object that the component has received
*/
fun componentDidUpdate(nextProps: P, nextState: S): Unit {
}
/**
* Invoked immediately before a component is unmounted from the DOM.
* Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount.
*/
fun componentWillUnmount(): Unit {
}
}
class Ref<T : Any>(val value: T?)
class RefContent(val realRef: dynamic) {
fun asComponent(): ReactComponent<Any, Any> = realRef
fun asDomNode(): HTMLElement = realRef
}
abstract class ReactComponentSpec<P : Any, S : Any>() : ReactMixin<P, S> {
var component: ReactComponent<Ref<P>, Ref<S>>? = null
/**
* The mixins array allows you to use mixins to share behavior among multiple components.
*/
var mixins: Array<ReactMixin<Any, Any>> = arrayOf()
/**
* The displayName string is used in debugging messages. JSX sets this value automatically.
*/
var displayName: String = ""
fun refs(refName: String): RefContent {
return RefContent(component!!.refs[refName]!!)
}
var state: S
get() = component!!.state.value!!
set(value) = component!!.setState(Ref(value))
var props: P
get() = component!!.props.value!!
set(value) = component!!.setProps(Ref(value), null)
/**
* The propTypes object allows you to validate props being passed to your components.
*/
//var propTypes: PropTypeValidatorOptions
/**
* Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
*/
fun getInitialState(): Ref<S>? {
val state = initialState()
return if (state == null) null else Ref(state)
}
open fun initialState(): S? {
return null
}
/**
* The render() method is required. When called, it should examine this.props and this.state and return a single child component.
* This child component can be either a virtual representation of a native DOM component (such as <div /> or React.DOM.div())
* or another composite component that you've defined yourself.
* The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked,
* and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout).
* If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead.
* Keeping render() pure makes server rendering more practical and makes components easier to think about.
*/
abstract fun render(): ReactElement<P>?
// DefaultProps don't work very well as Kotlin set all the keys on an object and makes set versus null ambiguous
// So prevent the usage.
/**
* Invoked once when the component is mounted.
* Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check).
* This method is invoked before getInitialState and therefore cannot rely on this.state or use this.setState.
*/
fun getDefaultProps(): Ref<P>? {
return null
}
}
/**
* Component classses created by createClass() return instances of ReactComponent when called.
* Most of the time when you're using React you're either creating or consuming these component objects.
*/
@native
interface ReactComponent<P, S> {
val refs: dynamic
val state: S
val props: P
/**
* If this component has been mounted into the DOM, this returns the corresponding native browser DOM element.
* This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
*/
fun getDOMNode(): Element
/**
* When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with renderComponent().
* Simply call setProps() to change its properties and trigger a re-render.
*
* @param nextProps the object that will be merged with the component's props
* @param callback an optional callback function that is executed once setProps is completed.
*/
fun setProps(nextProps: P, callback: (() -> Unit)?): Unit
/**
* Like setProps() but deletes any pre-existing props instead of merging the two objects.
*
* @param nextProps the object that will replace the component's props
* @param callback an optional callback function that is executed once replaceProps is completed.
*/
fun replaceProps(nextProps: P, callback: () -> Unit): Unit
/**
* Transfer properties from this component to a target component that have not already been set on the target component.
* After the props are updated, targetComponent is returned as a convenience.
*
* @param target the component that will receive the props
*/
fun <C : ReactComponent<P, Any>> transferPropsTo(target: C): C
/**
* Merges nextState with the current state.
* This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
* In addition, you can supply an optional callback function that is executed once setState is completed.
*
* @param nextState the object that will be merged with the component's state
* @param callback an optional callback function that is executed once setState is completed.
*/
fun setState(nextState: S, callback: () -> Unit = {}): Unit
/**
* Like setState() but deletes any pre-existing state keys that are not in nextState.
*
* @param nextState the object that will replace the component's state
* @param callback an optional callback function that is executed once replaceState is completed.
*/
fun replaceState(nextState: S, callback: () -> Unit): Unit
/**
* If your render() method reads from something other than this.props or this.state,
* you'll need to tell React when it needs to re-run render() by calling forceUpdate().
* You'll also need to call forceUpdate() if you mutate this.state directly.
* Calling forceUpdate() will cause render() to be called on the component and its children,
* but React will still only update the DOM if the markup changes.
* Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
* This makes your application much simpler and more efficient.
*
* @param callback an optional callback that is executed once forceUpdate is completed.
*/
fun forceUpdate(callback: () -> Unit): Unit
}
@native
interface ReactComponentFactory<P : Any, S : Any> {
operator fun invoke(properties: Ref<P>?, vararg children: Any?): ReactComponent<Ref<P>, Ref<S>>
}
@native
interface ReactElement<P> {
} | mit | 5f1bc1bd030e3940767a4fd819e384c1 | 42.159664 | 157 | 0.698958 | 4.641211 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/Button.kt | 1 | 3382 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2f
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.Time
interface ButtonScope : UiScope {
override val modifier: ButtonModifier
val isHovered: Boolean
}
open class ButtonModifier(surface: UiSurface) : TextModifier(surface) {
var buttonColor: Color by property { it.colors.secondaryVariant }
var buttonHoverColor: Color by property { it.colors.secondary }
var textHoverColor: Color by property{ it.colors.onSecondary }
var isClickFeedback: Boolean by property(true)
}
fun <T: ButtonModifier> T.isClickFeedback(value: Boolean): T { this.isClickFeedback = value; return this }
fun <T: ButtonModifier> T.colors(
buttonColor: Color = this.buttonColor,
textColor: Color = this.textColor,
buttonHoverColor: Color = this.buttonHoverColor,
textHoverColor: Color = this.textHoverColor
): T {
this.buttonColor = buttonColor
this.textColor = textColor
this.buttonHoverColor = buttonHoverColor
this.textHoverColor = textHoverColor
return this
}
inline fun UiScope.Button(text: String = "", block: ButtonScope.() -> Unit): TextScope {
val button = uiNode.createChild(ButtonNode::class, ButtonNode.factory)
button.modifier
.text(text)
.colors(textColor = colors.onSecondary)
.textAlign(AlignmentX.Center, AlignmentY.Center)
.padding(horizontal = sizes.gap, vertical = sizes.smallGap)
.onClick(button)
.hoverListener(button)
button.block()
return button
}
class ButtonNode(parent: UiNode?, surface: UiSurface) : TextNode(parent, surface), ButtonScope, Clickable, Hoverable {
override val modifier = ButtonModifier(surface)
override val isHovered: Boolean get() = isHoveredState.value
private var isHoveredState = mutableStateOf(false)
private val clickAnimator = AnimationState(0.3f)
private val clickPos = MutableVec2f()
override fun render(ctx: KoolContext) {
var bgColor = modifier.buttonColor
if (isHoveredState.use()) {
// overwrite text color with text hover color, so TextNode uses the desired color
modifier.textColor(modifier.textHoverColor)
bgColor = modifier.buttonHoverColor
}
if (modifier.background == null) {
// only set default button background if no custom one was configured
modifier.background(RoundRectBackground(bgColor, sizes.smallGap))
}
super.render(ctx)
if (modifier.isClickFeedback) {
val p = clickAnimator.use()
if (clickAnimator.isActive) {
clickAnimator.progress(Time.deltaT)
getUiPrimitives().localCircle(
clickPos.x, clickPos.y,
p * 128.dp.px,
Color.WHITE.withAlpha(0.7f - p * 0.5f)
)
}
}
}
override fun onClick(ev: PointerEvent) {
clickAnimator.start()
clickPos.set(ev.position)
}
override fun onEnter(ev: PointerEvent) {
isHoveredState.set(true)
}
override fun onExit(ev: PointerEvent) {
isHoveredState.set(false)
}
companion object {
val factory: (UiNode, UiSurface) -> ButtonNode = { parent, surface -> ButtonNode(parent, surface) }
}
}
| apache-2.0 | be2b4631ae1fdea6fe6cb6d6a5ce7780 | 33.161616 | 118 | 0.668244 | 4.206468 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/Slider.kt | 1 | 6878 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2f
import de.fabmax.kool.math.clamp
import de.fabmax.kool.util.Color
import kotlin.math.floor
interface SliderScope : UiScope {
override val modifier: SliderModifier
}
open class SliderModifier(surface: UiSurface) : TextModifier(surface) {
var value: Float by property(0.5f)
var minValue: Float by property(0f)
var maxValue: Float by property(1f)
var onChange: ((Float) -> Unit)? by property(null)
var onChangeEnd: ((Float) -> Unit)? by property(null)
var orientation: SliderOrientation by property(SliderOrientation.Horizontal)
var knobColor: Color by property { it.colors.primary }
var trackColor: Color by property { it.colors.secondaryVariant }
var trackColorActive: Color? by property { it.colors.secondary }
}
fun <T: SliderModifier> T.value(value: Float): T { this.value = value; return this }
fun <T: SliderModifier> T.minValue(min: Float): T { this.minValue = min; return this }
fun <T: SliderModifier> T.maxValue(max: Float): T { this.maxValue = max; return this }
fun <T: SliderModifier> T.onChange(block: ((Float) -> Unit)?): T { onChange = block; return this }
fun <T: SliderModifier> T.onChangeEnd(block: ((Float) -> Unit)?): T { onChangeEnd = block; return this }
fun <T: SliderModifier> T.orientation(orientation: SliderOrientation): T { this.orientation = orientation; return this }
fun <T: SliderModifier> T.colors(
knobColor: Color = this.knobColor,
trackColor: Color = this.trackColor,
trackColorActive: Color? = this.trackColorActive
): T {
this.knobColor = knobColor
this.trackColor = trackColor
this.trackColorActive = trackColorActive
return this
}
enum class SliderOrientation {
Horizontal,
Vertical
}
inline fun UiScope.Slider(value: Float = 0.5f, min: Float = 0f, max: Float = 1f, block: SliderScope.() -> Unit): SliderScope {
val slider = uiNode.createChild(SliderNode::class, SliderNode.factory)
slider.modifier
.value(value)
.minValue(min)
.maxValue(max)
.dragListener(slider)
slider.block()
return slider
}
class SliderNode(parent: UiNode?, surface: UiSurface) : UiNode(parent, surface), SliderScope, Draggable {
override val modifier = SliderModifier(surface)
private val knobCenter = MutableVec2f()
private val dragStart = MutableVec2f()
private val knobDiameter: Dp get() = sizes.sliderHeight
private val trackHeightPx: Float get() = knobDiameter.px * 0.4f
override fun measureContentSize(ctx: KoolContext) {
val w: Float
val h: Float
if (modifier.orientation == SliderOrientation.Horizontal) {
w = knobDiameter.px * 5 + 2f
h = knobDiameter.px
} else {
w = knobDiameter.px
h = knobDiameter.px * 5 + 2f
}
val modWidth = modifier.width
val modHeight = modifier.height
val measuredWidth = if (modWidth is Dp) modWidth.px else w + paddingStartPx + paddingEndPx
val measuredHeight = if (modHeight is Dp) modHeight.px else h + paddingTopPx + paddingBottomPx
setContentSize(measuredWidth, measuredHeight)
}
override fun render(ctx: KoolContext) {
super.render(ctx)
val draw = getUiPrimitives()
val knobPos = ((modifier.value - modifier.minValue) / (modifier.maxValue - modifier.minValue)).clamp()
val kR = floor(knobDiameter.px * 0.5f)
val tH = trackHeightPx
val tR = tH * 0.5f
if (modifier.orientation == SliderOrientation.Horizontal) {
val c = heightPx * 0.5f
val xMin = paddingStartPx + kR
val xMax = widthPx - paddingEndPx - kR
val moveW = xMax - xMin
val knobX = xMin + moveW * knobPos
if (modifier.trackColorActive != null) {
val colorAct = modifier.trackColorActive ?: modifier.trackColor
draw.localRoundRect(
xMin - tR, c - tR,
knobX - xMin + tH, tH, tR, colorAct)
draw.localRoundRect(
knobX - tR, c - tR,
xMax - knobX + tH, tH, tR, modifier.trackColor)
} else {
draw.localRoundRect(
xMin - tR, c - tR,
xMax - xMin + tH, tH, tR, modifier.trackColor)
}
knobCenter.set(knobX, c)
draw.localCircle(knobX, c, kR, modifier.knobColor)
} else {
val c = widthPx * 0.5f
val yMin = paddingTopPx + kR
val yMax = heightPx - paddingBottomPx - kR
val moveH = yMax - yMin
val knobY = yMin + moveH * (1f - knobPos)
if (modifier.trackColorActive != null) {
val colorAct = modifier.trackColorActive ?: modifier.trackColor
draw.localRoundRect(
c - tR, yMin - tR,
tH, knobY - yMin + tH, tR, modifier.trackColor)
draw.localRoundRect(
c - tR, knobY - tR,
tH, yMax - knobY + tH, tR, colorAct)
} else {
draw.localRoundRect(
c - tR, yMin - tR,
tH, yMax - yMin + tH, tR, modifier.trackColor)
}
knobCenter.set(c, knobY)
draw.localCircle(c, knobY, kR, modifier.knobColor)
}
}
private fun computeValue(ev: PointerEvent): Float {
val kD = knobDiameter.px
return if (modifier.orientation == SliderOrientation.Horizontal) {
val innerW = innerWidthPx - kD
val dragKnobPos = dragStart.x + ev.pointer.dragDeltaX.toFloat() - paddingStartPx - kD * 0.5f
val f = (dragKnobPos / innerW).clamp()
f * (modifier.maxValue - modifier.minValue) + modifier.minValue
} else {
val innerH = innerHeightPx - kD
val dragKnobPos = dragStart.y + ev.pointer.dragDeltaY.toFloat() - paddingTopPx - kD * 0.5f
val f = 1f - (dragKnobPos / innerH).clamp()
f * (modifier.maxValue - modifier.minValue) + modifier.minValue
}
}
override fun onDragStart(ev: PointerEvent) {
if (ev.position.distance(knobCenter) < knobDiameter.px) {
dragStart.set(knobCenter)
} else {
ev.reject()
}
}
override fun onDrag(ev: PointerEvent) {
val newValue = computeValue(ev)
if (newValue != modifier.value) {
modifier.onChange?.invoke(newValue)
}
}
override fun onDragEnd(ev: PointerEvent) {
modifier.onChangeEnd?.invoke(computeValue(ev))
}
companion object {
val factory: (UiNode, UiSurface) -> SliderNode = { parent, surface -> SliderNode(parent, surface) }
}
} | apache-2.0 | ef2a3d4627257dab0deaad466efa304e | 36.796703 | 126 | 0.607444 | 4.003492 | false | false | false | false |
SimpleMobileTools/Simple-Music-Player | app/src/main/kotlin/com/simplemobiletools/musicplayer/fragments/ArtistsFragment.kt | 1 | 4505 | package com.simplemobiletools.musicplayer.fragments
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import com.google.gson.Gson
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.extensions.areSystemAnimationsEnabled
import com.simplemobiletools.commons.extensions.beGoneIf
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.hideKeyboard
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.musicplayer.R
import com.simplemobiletools.musicplayer.activities.AlbumsActivity
import com.simplemobiletools.musicplayer.activities.SimpleActivity
import com.simplemobiletools.musicplayer.adapters.ArtistsAdapter
import com.simplemobiletools.musicplayer.dialogs.ChangeSortingDialog
import com.simplemobiletools.musicplayer.extensions.artistDAO
import com.simplemobiletools.musicplayer.extensions.config
import com.simplemobiletools.musicplayer.helpers.ARTIST
import com.simplemobiletools.musicplayer.helpers.TAB_ARTISTS
import com.simplemobiletools.musicplayer.models.Artist
import kotlinx.android.synthetic.main.fragment_artists.view.*
// Artists -> Albums -> Tracks
class ArtistsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerFragment(context, attributeSet) {
private var artistsIgnoringSearch = ArrayList<Artist>()
override fun setupFragment(activity: BaseSimpleActivity) {
Artist.sorting = context.config.artistSorting
ensureBackgroundThread {
val cachedArtists = activity.artistDAO.getAll() as ArrayList<Artist>
activity.runOnUiThread {
gotArtists(activity, cachedArtists)
}
}
}
private fun gotArtists(activity: BaseSimpleActivity, artists: ArrayList<Artist>) {
artists.sort()
artistsIgnoringSearch = artists
activity.runOnUiThread {
artists_placeholder.text = context.getString(R.string.no_items_found)
artists_placeholder.beVisibleIf(artists.isEmpty())
val adapter = artists_list.adapter
if (adapter == null) {
ArtistsAdapter(activity, artists, artists_list) {
activity.hideKeyboard()
Intent(activity, AlbumsActivity::class.java).apply {
putExtra(ARTIST, Gson().toJson(it as Artist))
activity.startActivity(this)
}
}.apply {
artists_list.adapter = this
}
if (context.areSystemAnimationsEnabled) {
artists_list.scheduleLayoutAnimation()
}
} else {
val oldItems = (adapter as ArtistsAdapter).artists
if (oldItems.sortedBy { it.id }.hashCode() != artists.sortedBy { it.id }.hashCode()) {
adapter.updateItems(artists)
}
}
}
}
override fun finishActMode() {
(artists_list.adapter as? MyRecyclerViewAdapter)?.finishActMode()
}
override fun onSearchQueryChanged(text: String) {
val filtered = artistsIgnoringSearch.filter { it.title.contains(text, true) }.toMutableList() as ArrayList<Artist>
(artists_list.adapter as? ArtistsAdapter)?.updateItems(filtered, text)
artists_placeholder.beVisibleIf(filtered.isEmpty())
}
override fun onSearchOpened() {
artistsIgnoringSearch = (artists_list?.adapter as? ArtistsAdapter)?.artists ?: ArrayList()
}
override fun onSearchClosed() {
(artists_list.adapter as? ArtistsAdapter)?.updateItems(artistsIgnoringSearch)
artists_placeholder.beGoneIf(artistsIgnoringSearch.isNotEmpty())
}
override fun onSortOpen(activity: SimpleActivity) {
ChangeSortingDialog(activity, TAB_ARTISTS) {
val adapter = artists_list.adapter as? ArtistsAdapter ?: return@ChangeSortingDialog
val artists = adapter.artists
Artist.sorting = activity.config.artistSorting
artists.sort()
adapter.updateItems(artists, forceUpdate = true)
}
}
override fun setupColors(textColor: Int, adjustedPrimaryColor: Int) {
artists_placeholder.setTextColor(textColor)
artists_fastscroller.updateColors(adjustedPrimaryColor)
}
}
| gpl-3.0 | dfef90e9ace012afc08f43f30db10c2b | 41.904762 | 122 | 0.701665 | 5.269006 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/idea/IdeStarter.kt | 2 | 9807 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.idea
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.startActivity
import com.intellij.diagnostic.runActivity
import com.intellij.diagnostic.runChild
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.internal.inspector.UiInspectorAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.AppUIUtil
import com.intellij.ui.mac.touchbar.TouchbarSupport
import com.intellij.util.io.URLUtil.SCHEME_SEPARATOR
import com.intellij.util.ui.accessibility.ScreenReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.beans.PropertyChangeListener
import java.nio.file.Path
import java.util.*
import javax.swing.JOptionPane
open class IdeStarter : ModernApplicationStarter() {
companion object {
private var filesToLoad: List<Path> = Collections.emptyList()
private var uriToOpen: String? = null
@JvmStatic
fun openFilesOnLoading(value: List<Path>) {
filesToLoad = value
}
@JvmStatic
fun openUriOnLoading(value: String) {
uriToOpen = value
}
}
override val isHeadless: Boolean
get() = false
override val commandName: String?
get() = null
override suspend fun start(args: List<String>) {
val app = ApplicationManagerEx.getApplicationEx()
assert(!app.isDispatchThread)
coroutineScope {
if (app.isLightEditMode && !app.isHeadlessEnvironment) {
// In a light mode UI is shown very quickly, tab layout requires ActionManager, but it is forbidden to init ActionManager in EDT,
// so, preload
launch {
ActionManager.getInstance()
}
}
val lifecyclePublisher = app.messageBus.syncPublisher(AppLifecycleListener.TOPIC)
openProjectIfNeeded(args, app, lifecyclePublisher)
launch { reportPluginErrors() }
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.APP_STARTED)
lifecyclePublisher.appStarted()
if (!app.isHeadlessEnvironment) {
postOpenUiTasks(app)
}
}
}
@OptIn(IntellijInternalApi::class)
protected open suspend fun openProjectIfNeeded(args: List<String>,
app: ApplicationEx,
lifecyclePublisher: AppLifecycleListener) {
val frameInitActivity = startActivity("frame initialization")
frameInitActivity.runChild("app frame created callback") {
lifecyclePublisher.appFrameCreated(args)
}
// must be after `AppLifecycleListener#appFrameCreated`, because some listeners can mutate the state of `RecentProjectsManager`
if (app.isHeadlessEnvironment) {
frameInitActivity.end()
LifecycleUsageTriggerCollector.onIdeStart()
return
}
if (app.isInternal) {
app.coroutineScope.launch(Dispatchers.EDT + ModalityState.any().asContextElement()) {
UiInspectorAction.initGlobalInspector()
}
}
app.coroutineScope.launch {
LifecycleUsageTriggerCollector.onIdeStart()
}
if (uriToOpen != null || args.isNotEmpty() && args.first().contains(SCHEME_SEPARATOR)) {
frameInitActivity.end()
processUriParameter(uriToOpen ?: args.first(), lifecyclePublisher)
return
}
val recentProjectManager = RecentProjectsManager.getInstance()
val willReopenRecentProjectOnStart = recentProjectManager.willReopenProjectOnStart()
val willOpenProject = willReopenRecentProjectOnStart || !args.isEmpty() || !filesToLoad.isEmpty()
val needToOpenProject = willOpenProject || showWelcomeFrame(lifecyclePublisher)
frameInitActivity.end()
if (!needToOpenProject) {
return
}
val project = when {
filesToLoad.isNotEmpty() -> ProjectUtil.openOrImportFilesAsync(filesToLoad, "IdeStarter")
args.isNotEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
when {
project != null -> {
return
}
willReopenRecentProjectOnStart -> {
if (!recentProjectManager.reopenLastProjectsOnStart()) {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
else -> {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
}
private fun showWelcomeFrame(lifecyclePublisher: AppLifecycleListener): Boolean {
val showWelcomeFrameTask = WelcomeFrame.prepareToShow() ?: return true
ApplicationManager.getApplication().invokeLater {
showWelcomeFrameTask.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
return false
}
private suspend fun processUriParameter(uri: String, lifecyclePublisher: AppLifecycleListener) {
val result = CommandLineProcessor.processProtocolCommand(uri)
if (result.exitCode == ProtocolHandler.PLEASE_QUIT) {
withContext(Dispatchers.EDT) {
ApplicationManagerEx.getApplicationEx().exit(false, true)
}
}
else if (result.exitCode != ProtocolHandler.PLEASE_NO_UI) {
WelcomeFrame.showIfNoProjectOpened(lifecyclePublisher)
}
}
internal class StandaloneLightEditStarter : IdeStarter() {
override suspend fun openProjectIfNeeded(args: List<String>,
app: ApplicationEx,
lifecyclePublisher: AppLifecycleListener) {
val project = when {
filesToLoad.isNotEmpty() -> ProjectUtil.openOrImportFilesAsync(list = filesToLoad, location = "MacMenu")
args.isNotEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
if (project != null) {
return
}
val recentProjectManager = RecentProjectsManager.getInstance()
val isOpened = (if (recentProjectManager.willReopenProjectOnStart()) recentProjectManager.reopenLastProjectsOnStart() else true)
if (!isOpened) {
ApplicationManager.getApplication().invokeLater {
LightEditService.getInstance().showEditorWindow()
}
}
}
}
}
private suspend fun loadProjectFromExternalCommandLine(commandLineArgs: List<String>): Project? {
val currentDirectory = System.getenv(SocketLock.LAUNCHER_INITIAL_DIRECTORY_ENV_VAR)
@Suppress("SSBasedInspection")
Logger.getInstance("#com.intellij.idea.ApplicationLoader").info("ApplicationLoader.loadProject (cwd=${currentDirectory})")
val result = CommandLineProcessor.processExternalCommandLine(commandLineArgs, currentDirectory)
if (result.hasError) {
withContext(Dispatchers.EDT) {
result.showErrorIfFailed()
ApplicationManager.getApplication().exit(true, true, false)
}
}
return result.project
}
private suspend fun postOpenUiTasks(app: Application) {
if (PluginManagerCore.isRunningFromSources()) {
AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame())
}
coroutineScope {
if (SystemInfoRt.isMac) {
launch {
runActivity("mac touchbar on app init") {
TouchbarSupport.onApplicationLoaded()
}
}
}
else if (SystemInfoRt.isXWindow && SystemInfo.isJetBrainsJvm) {
launch {
runActivity("input method disabling on Linux") {
disableInputMethodsIfPossible()
}
}
}
invokeLaterWithAnyModality("ScreenReader") {
val generalSettings = GeneralSettings.getInstance()
generalSettings.addPropertyChangeListener(GeneralSettings.PROP_SUPPORT_SCREEN_READERS, app, PropertyChangeListener { e ->
ScreenReader.setActive(e.newValue as Boolean)
})
ScreenReader.setActive(generalSettings.isSupportScreenReaders)
}
startSystemHealthMonitor()
}
}
private suspend fun invokeLaterWithAnyModality(name: String, task: () -> Unit) {
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
runActivity(name, task = task)
}
}
private suspend fun reportPluginErrors() {
val pluginErrors = PluginManagerCore.getAndClearPluginLoadingErrors()
if (pluginErrors.isEmpty()) {
return
}
withContext(Dispatchers.EDT + ModalityState.NON_MODAL.asContextElement()) {
val title = IdeBundle.message("title.plugin.error")
val content = HtmlBuilder().appendWithSeparators(HtmlChunk.p(), pluginErrors).toString()
@Suppress("DEPRECATION")
NotificationGroupManager.getInstance().getNotificationGroup(
"Plugin Error").createNotification(title, content, NotificationType.ERROR)
.setListener { notification, event ->
notification.expire()
PluginManagerMain.onEvent(event.description)
}
.notify(null)
}
}
| apache-2.0 | 7b0c915bb85a7594893457529e13a005 | 34.791971 | 137 | 0.727847 | 4.945537 | false | false | false | false |
kivensolo/UiUsingListView | library/player/src/main/java/com/kingz/library/container/PlayerView.kt | 1 | 5091 | package com.kingz.library.container
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import com.kingz.library.entity.ScreenMode
import com.kingz.library.player.IPlayer
import com.kingz.library.player.exo.ExoPlayer
import com.kingz.library.player.render.IRender
import com.kingz.library.player.render.SurfaceRenderCallback
import com.kingz.library.player.render.TextureViewRender
import test.chinaiptv.com.player_library.R
/**
* @author zeke.wang
* @date 2020/4/28
* @maintainer zeke.wang
* @desc:
* 支持小窗的PlayerView容器
* NOTE: parent容器需限定为FrameLayout类型
*/
open class PlayerView( context: Context, val parent:FrameLayout, val viewRect: Rect? = null,
val player: IPlayer = ExoPlayer(context),
render: IRender = TextureViewRender(context, player),
var isLargestView: (isFullScreen: Boolean, playerView: PlayerView) -> Unit = { _, _ -> },
val containerSizeChange: ((rect: Rect) -> Unit) = { _ -> },
var onBackDown: (playerView: PlayerView) -> Boolean = { false }
) : FrameLayout(context), SurfaceRenderCallback {
companion object {
private const val TAG = "PlayerView"
}
//播放器视图的显示模式(默认为小屏)
private var screenMode: ScreenMode = ScreenMode.SMALL
private var drawFocus = true
private var focusLineDrawable: Drawable? = null
init {
Log.d(TAG, "init")
clipToPadding = false
clipChildren = false
focusLineDrawable = context.resources.getDrawable(R.drawable.play_focus_bg)
val pms = LayoutParams(1, 1)
viewRect?.apply {
pms.width = width
pms.height = height
pms.leftMargin = left
pms.topMargin = top
}
parent.addView(this,pms)
render.renderCallback = this
addView(render as View, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
//Player callback
//Render Callback
override fun surfaceChanged(width: Int, height: Int) {
Log.d(TAG,"surfaceChanged() [$width * $height]")
isLargestView(isFullScreen(), this)
}
override fun surfaceDestroyed() {
Log.d(TAG,"surfaceDestroyed()")
}
override fun surfaceCreated() {
Log.d(TAG,"surfaceCreated()")
}
fun isFullScreen():Boolean {
return screenMode == ScreenMode.FULL
}
fun setScreenMode(mode:ScreenMode){
drawFocus = (mode == ScreenMode.SMALL)
screenMode = mode
requestLayout()
}
/**
* 调整Surface大小为铺满父容器(不一定是全屏状态)
*/
fun changeSurfaceSizeFull() {
adjustSurfaceSize(MATCH_PARENT, MATCH_PARENT, 0, 0)
}
/**
* 调整Surface大小为最小
*/
fun changeSurfaceSizeSmallest() {
adjustSurfaceSize(1, 1, 0, 0)
}
/**
* 调整Surface在parent的位置、大小
*/
fun adjustSurfaceSize(width: Int, height: Int, marginLeft: Int, marginTop: Int) {
layoutParams = (layoutParams as LayoutParams).apply {
this.width = width
this.height = height
this.leftMargin = marginLeft
this.topMargin = marginTop
containerSizeChange(Rect(marginLeft,
marginTop,
marginLeft + width,
marginTop + height))
}
}
override fun dispatchDraw(canvas: Canvas) {
super.dispatchDraw(canvas)
//焦点框绘制在最上层
if (drawFocus) {
drawFrame(canvas, width, height)
}
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
//全屏模式 控制蒙层存在 按键事件分发
return if (isFullScreen()) {
if (viewRect != null && event.action == KeyEvent.ACTION_DOWN
&& event.keyCode == KeyEvent.KEYCODE_BACK) {
if (onBackDown(this)) {
return true
}
}
return super.dispatchKeyEvent(event)
} else {
super.dispatchKeyEvent(event)
}
}
private fun drawFrame(canvas: Canvas, w: Int, h: Int) { //焦点框绘制在最上层
if (hasFocus()) {
Log.d(TAG, "draw focus Frame")
drawDrawable(canvas, focusLineDrawable, w, h)
}
}
private val rect = Rect(0, 0, 0, 0)
private fun drawDrawable(canvas: Canvas, drawable: Drawable?, w: Int, h: Int) {
if (drawable == null) {
return
}
drawable.getPadding(rect)
//焦点框距中间图片的间距
val padding = 0
drawable.setBounds(
-rect.left - padding, -rect.top - padding, w + rect.right + padding,
h + rect.bottom + padding
)
drawable.draw(canvas)
}
} | gpl-2.0 | 79401b51e37b4fd87425226af467c0be | 28.011905 | 99 | 0.61379 | 4.030604 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/FindImplicitNothingAction.kt | 1 | 7187 | // 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.actions.internal
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.usageView.UsageInfo
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageViewManager
import com.intellij.usages.UsageViewPresentation
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.SwingUtilities
class FindImplicitNothingAction : AnAction() {
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.actions.internal.FindImplicitNothingAction")
}
override fun actionPerformed(e: AnActionEvent) {
val selectedFiles = selectedKotlinFiles(e).toList()
val project = CommonDataKeys.PROJECT.getData(e.dataContext)!!
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{ find(selectedFiles, project) },
KotlinBundle.message("finding.implicit.nothing.s"),
true,
project
)
}
private fun find(files: Collection<KtFile>, project: Project) {
val progressIndicator = ProgressManager.getInstance().progressIndicator
val found = ArrayList<KtCallExpression>()
for ((i, file) in files.withIndex()) {
progressIndicator?.text = KotlinBundle.message("scanning.files.0.fo.1.file.2.occurrences.found", i, files.size, found.size)
progressIndicator?.text2 = file.virtualFile.path
val resolutionFacade = file.getResolutionFacade()
file.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
ProgressManager.checkCanceled()
element.acceptChildren(this)
}
override fun visitCallExpression(expression: KtCallExpression) {
expression.acceptChildren(this)
try {
val bindingContext = resolutionFacade.analyze(expression)
val type = bindingContext.getType(expression) ?: return
if (KotlinBuiltIns.isNothing(type) && !expression.hasExplicitNothing(bindingContext)) { //TODO: what about nullable Nothing?
found.add(expression)
}
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) { // do not stop on internal error
LOG.error(t)
}
}
})
progressIndicator?.fraction = (i + 1) / files.size.toDouble()
}
SwingUtilities.invokeLater {
if (found.isNotEmpty()) {
val usages = found.map { UsageInfo2UsageAdapter(UsageInfo(it)) }.toTypedArray()
val presentation = UsageViewPresentation()
presentation.tabName = KotlinBundle.message("implicit.nothing.s")
UsageViewManager.getInstance(project).showUsages(arrayOf<UsageTarget>(), usages, presentation)
} else {
Messages.showInfoMessage(
project,
KotlinBundle.message("not.found.in.0.files", files.size),
KotlinBundle.message("titile.not.found")
)
}
}
}
private fun KtExpression.hasExplicitNothing(bindingContext: BindingContext): Boolean {
@Suppress("MoveVariableDeclarationIntoWhen")
val callee = getCalleeExpressionIfAny() ?: return false
when (callee) {
is KtSimpleNameExpression -> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee] ?: return false
val callableDescriptor = (target as? CallableDescriptor ?: return false).original
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as? KtCallableDeclaration
if (declaration != null && declaration.typeReference == null) return false // implicit type
val type = callableDescriptor.returnType ?: return false
return type.isNothingOrNothingFunctionType()
}
else -> {
return callee.hasExplicitNothing(bindingContext)
}
}
}
private fun KotlinType.isNothingOrNothingFunctionType(): Boolean {
return KotlinBuiltIns.isNothing(this) ||
(isFunctionType && this.getReturnTypeFromFunctionType().isNothingOrNothingFunctionType())
}
override fun update(e: AnActionEvent) {
e.presentation.isVisible = ApplicationManager.getApplication().isInternal
e.presentation.isEnabled = ApplicationManager.getApplication().isInternal
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 | 39f74488d56e16f804d48ed32c531bb5 | 44.77707 | 158 | 0.672603 | 5.457099 | false | false | false | false |
ncoe/rosetta | Metallic_ratios/Kotlin/src/Metallic.kt | 1 | 1306 | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
var x1 = 1L
print("$x0, $x1")
for (i in 1..13) {
val x2 = b * x1 + x0
print(", $x2")
x0 = x1
x1 = x2
}
println()
}
fun metallic(b: Long, dp:Int) {
var x0 = BigInteger.ONE
var x1 = BigInteger.ONE
var x2: BigInteger
val bb = BigInteger.valueOf(b)
val ratio = BigDecimal.ONE.setScale(dp)
var iters = 0
var prev = ratio.toString()
while (true) {
iters++
x2 = bb * x1 + x0
val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()
if (prev == thiz) {
var plural = "s"
if (iters == 1) {
plural = ""
}
println("Value after $iters iteration$plural: $thiz\n")
return
}
prev = thiz
x0 = x1
x1 = x2
}
}
fun main() {
for (b in 0L until 10L) {
lucas(b)
metallic(b, 32)
}
println("Golden ration, where b = 1:")
metallic(1, 256)
}
| mit | f0ba3f4cb1efb63d81aa532e8eb5e1ad | 23.185185 | 116 | 0.507657 | 3.102138 | false | false | false | false |
androidx/androidx | privacysandbox/tools/tools-core/src/main/java/androidx/privacysandbox/tools/core/model/Models.kt | 3 | 1952 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.privacysandbox.tools.core.model
fun ParsedApi.getOnlyService(): AnnotatedInterface {
check(services.size == 1) {
"Expected to find one annotated service, but found ${services.size}."
}
return services.first()
}
fun ParsedApi.hasSuspendFunctions(): Boolean {
val annotatedInterfaces = services + interfaces
return annotatedInterfaces
.flatMap(AnnotatedInterface::methods)
.any(Method::isSuspend)
}
object Types {
val unit = Type(packageName = "kotlin", simpleName = "Unit")
val boolean = Type(packageName = "kotlin", simpleName = "Boolean")
val int = Type(packageName = "kotlin", simpleName = "Int")
val long = Type(packageName = "kotlin", simpleName = "Long")
val float = Type(packageName = "kotlin", simpleName = "Float")
val double = Type(packageName = "kotlin", simpleName = "Double")
val string = Type(packageName = "kotlin", simpleName = "String")
val char = Type(packageName = "kotlin", simpleName = "Char")
val short = Type(packageName = "kotlin", simpleName = "Short")
val primitiveTypes = setOf(unit, boolean, int, long, float, double, string, char, short)
fun list(elementType: Type) = Type(
packageName = "kotlin.collections",
simpleName = "List",
typeParameters = listOf(elementType)
)
} | apache-2.0 | 9af2ea2d24e061cb64d24e496fb88813 | 38.857143 | 92 | 0.694672 | 4.318584 | false | false | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/androidTest/java/androidx/bluetooth/core/BluetoothGattCharacteristicTest.kt | 3 | 5357 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.os.Bundle
import java.util.UUID
import kotlin.random.Random
import androidx.test.filters.MediumTest
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@MediumTest
@RunWith(JUnit4::class)
class BluetoothGattCharacteristicTest {
companion object {
fun generateUUID(): UUID {
return UUID.randomUUID()
}
fun generatePermissions(): Int {
// Permission are bit from 1<<0 to 1<<8, but ignoring 1<<3
return Random.nextBits(20) and (BluetoothGattCharacteristic.PERMISSION_READ or
BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED or
BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM or
BluetoothGattCharacteristic.PERMISSION_WRITE or
BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED or
BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM or
BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED or
BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM)
}
fun generateProperties(): Int {
// Permission are bit from 1<<0 to 1<<7
return Random.nextBits(20) and (BluetoothGattCharacteristic.PROPERTY_BROADCAST or
BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS or
BluetoothGattCharacteristic.PROPERTY_INDICATE or
BluetoothGattCharacteristic.PROPERTY_NOTIFY or
BluetoothGattCharacteristic.PROPERTY_READ or
BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE or
BluetoothGattCharacteristic.PROPERTY_WRITE or
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)
}
}
@Test
fun constructorWithValues_createsInstanceCorrectly() {
repeat(5) {
val uuid = generateUUID()
val permissions = generatePermissions()
val properties = generateProperties()
val characteristic = BluetoothGattCharacteristic(uuid, properties, permissions)
Assert.assertEquals(permissions, characteristic.fwkCharacteristic.permissions)
Assert.assertEquals(properties, characteristic.fwkCharacteristic.properties)
Assert.assertEquals(uuid, characteristic.fwkCharacteristic.uuid)
Assert.assertEquals(permissions, characteristic.permissions)
Assert.assertEquals(properties, characteristic.properties)
Assert.assertEquals(uuid, characteristic.uuid)
Assert.assertEquals(null, characteristic.service)
}
}
@Test
fun bluetoothGattCharacteristicBundleable() {
repeat(5) {
val uuid = generateUUID()
val permissions = generatePermissions()
val properties = generateProperties()
val characteristic = BluetoothGattCharacteristic(uuid, properties, permissions)
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
repeat(5) {
val descriptorUUID = BluetoothGattDescriptorTest.generateUUID()
val descriptorPermission = BluetoothGattDescriptorTest.generatePermissions()
val descriptor = BluetoothGattDescriptor(descriptorUUID, descriptorPermission)
characteristic.addDescriptor(descriptor)
Assert.assertEquals(characteristic, descriptor.characteristic)
}
val bundle: Bundle = characteristic.toBundle()
val newCharacteristic: BluetoothGattCharacteristic =
BluetoothGattCharacteristic.CREATOR.fromBundle(bundle)
Assert.assertEquals(newCharacteristic.permissions, characteristic.permissions)
Assert.assertEquals(newCharacteristic.instanceId, characteristic.instanceId)
Assert.assertEquals(newCharacteristic.uuid, characteristic.uuid)
Assert.assertEquals(newCharacteristic.properties, characteristic.properties)
Assert.assertEquals(newCharacteristic.writeType, characteristic.writeType)
Assert.assertEquals(newCharacteristic.descriptors.size, characteristic.descriptors.size)
newCharacteristic.descriptors.forEach {
val foundDescriptor = characteristic.getDescriptor(it.uuid)
Assert.assertEquals(foundDescriptor?.permissions, it.permissions)
Assert.assertEquals(foundDescriptor?.uuid, it.uuid)
Assert.assertEquals(foundDescriptor?.characteristic, characteristic)
Assert.assertEquals(it.characteristic, newCharacteristic)
}
}
}
} | apache-2.0 | 6f58d63325ca80033e84097427c44bed | 43.65 | 100 | 0.696845 | 5.816504 | false | true | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/units/Volume.kt | 3 | 5518 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.units
/**
* Represents a unit of volume. Supported units:
*
* - liters - see [Volume.liters], [Double.liters]
* - milliliters - see [Volume.milliliters], [Double.milliliters]
* - US fluid ounces - see [Volume.fluidOuncesUs], [Double.fluidOuncesUs]
*/
class Volume private constructor(
private val value: Double,
private val type: Type,
) : Comparable<Volume> {
/** Returns the volume in liters. */
@get:JvmName("getLiters")
val inLiters: Double
get() = value * type.litersPerUnit
/** Returns the volume in milliliters. */
@get:JvmName("getMilliliters")
val inMilliliters: Double
get() = get(type = Type.MILLILITERS)
/** Returns the volume in US fluid ounces. */
@get:JvmName("getFluidOuncesUs")
val inFluidOuncesUs: Double
get() = get(type = Type.FLUID_OUNCES_US)
private fun get(type: Type): Double =
if (this.type == type) value else inLiters / type.litersPerUnit
/** Returns zero [Volume] of the same [Type]. */
internal fun zero(): Volume = ZEROS.getValue(type)
override fun compareTo(other: Volume): Int =
if (type == other.type) {
value.compareTo(other.value)
} else {
inLiters.compareTo(other.inLiters)
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Volume) return false
if (value != other.value) return false
if (type != other.type) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = value.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String = "$value ${type.title}"
companion object {
private val ZEROS = Type.values().associateWith { Volume(value = 0.0, type = it) }
/** Creates [Volume] with the specified value in liters. */
@JvmStatic
fun liters(value: Double): Volume = Volume(value, Type.LITERS)
/** Creates [Volume] with the specified value in milliliters. */
@JvmStatic
fun milliliters(value: Double): Volume = Volume(value, Type.MILLILITERS)
/** Creates [Volume] with the specified value in US fluid ounces. */
@JvmStatic
fun fluidOuncesUs(value: Double): Volume = Volume(value, Type.FLUID_OUNCES_US)
}
private enum class Type {
LITERS {
override val litersPerUnit: Double = 1.0
override val title: String = "L"
},
MILLILITERS {
override val litersPerUnit: Double = 0.001
override val title: String = "mL"
},
FLUID_OUNCES_US {
override val litersPerUnit: Double = 0.02957353
override val title: String = "fl. oz (US)"
};
abstract val litersPerUnit: Double
abstract val title: String
}
}
/** Creates [Volume] with the specified value in liters. */
@get:JvmSynthetic
val Double.liters: Volume
get() = Volume.liters(value = this)
/** Creates [Volume] with the specified value in liters. */
@get:JvmSynthetic
val Long.liters: Volume
get() = toDouble().liters
/** Creates [Volume] with the specified value in liters. */
@get:JvmSynthetic
val Float.liters: Volume
get() = toDouble().liters
/** Creates [Volume] with the specified value in liters. */
@get:JvmSynthetic
val Int.liters: Volume
get() = toDouble().liters
/** Creates [Volume] with the specified value in milliliters. */
@get:JvmSynthetic
val Double.milliliters: Volume
get() = Volume.milliliters(value = this)
/** Creates [Volume] with the specified value in milliliters. */
@get:JvmSynthetic
val Long.milliliters: Volume
get() = toDouble().milliliters
/** Creates [Volume] with the specified value in milliliters. */
@get:JvmSynthetic
val Float.milliliters: Volume
get() = toDouble().milliliters
/** Creates [Volume] with the specified value in milliliters. */
@get:JvmSynthetic
val Int.milliliters: Volume
get() = toDouble().milliliters
/** Creates [Volume] with the specified value in US fluid ounces. */
@get:JvmSynthetic
val Double.fluidOuncesUs: Volume
get() = Volume.fluidOuncesUs(value = this)
/** Creates [Volume] with the specified value in US fluid ounces. */
@get:JvmSynthetic
val Long.fluidOuncesUs: Volume
get() = toDouble().fluidOuncesUs
/** Creates [Volume] with the specified value in US fluid ounces. */
@get:JvmSynthetic
val Float.fluidOuncesUs: Volume
get() = toDouble().fluidOuncesUs
/** Creates [Volume] with the specified value in US fluid ounces. */
@get:JvmSynthetic
val Int.fluidOuncesUs: Volume
get() = toDouble().fluidOuncesUs
| apache-2.0 | 39edc60ce2452a0ab02a041198cd6b3b | 30.352273 | 90 | 0.656216 | 3.866854 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/device/bluetooth/BleDeviceManager.kt | 1 | 21744 | package com.zeke.demo.device.bluetooth
import android.Manifest
import android.bluetooth.*
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Message
import android.widget.Toast
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.zeke.kangaroo.utils.ToastUtils
import com.zeke.kangaroo.utils.ZLog
import java.util.*
import kotlin.collections.HashMap
/**
* author:ZekeWang
* date:2021/6/23
* description:
* BLE蓝牙设备管理器
*
* <!-- 蓝牙所需权限 -->
* <uses-permission android:name="android.permission.BLUETOOTH" /> //允许程序连接到已配对的蓝牙设备
* <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> //允许程序发现和配对蓝牙设备
* //定位权限
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
* <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
*
* >= 4.3
* <uses-feature
* android:name="android.hardware.bluetooth_le"
* android:required="true" />
* //true 应用只能在支持BLE的Android设备上安装运行
* //为false时,Android设备均可正常安装运行
*
* 坑点记录:
* 1.通知开启后,才能读到数据,否则读不到。
* 2.发送数据时,如果一包数据超过20字节,需要分包发送,一次最多发送二十字节。
* 接收也是。
* 3.每次发送数据或者数据分包发送时, 操作间要有至少15ms的间隔
* 4.有的蓝牙产品,发现获取不到需要的特征,后来打断点,发现他们蓝牙设备的通知特征根本没有,是他们给错协议了。。。
* 所以建议各位开发的时候,如果一直连接失败,也可以查看一下写特征和通知特征是否为空,
* 是不是卖家搞错了,协议和产品不匹配。(当然,这样马虎的卖家估计是少数)。
* 5.蓝牙如果出现扫描不到的情况,那是因为手机没有开启定位权限,清单文件中写上定位权限,代码中在动态获取下就OK了。
*
*/
class BleDeviceManager(val context: Context) {
val ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"
val ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"
val ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"
val ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"
val EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"
/**
* 蓝牙配置文件的类型 : HID
*/
private val INPUT_PROFILE = 4
/**
* 对话框显示连接成功的持续时间
*/
private val CONNECT_SUCCEED_SHOWING_TIME = 2000
/**
* 最大连接时间
*/
private val MAX_CONNECT_TIME = 30000
/**
* 最大搜索时间
*/
private val MAX_SCAN_TIMEOUT_MILLIS = 15 * 1000L
/**
* 自动重连等待时间
*/
private val AUTO_RECONNECT_DELAY_TIME = 2000
/**
* 搜索超时事件值
*/
private val CODE_MSG_SCAN_TIMEOUT = 0
/************** 当前状态定义区 *****************/
private val STATE_DEFAULT = 0 //默认状态,什么都没干
private val STATE_BONDING = 1 //正在绑定
private val STATE_CONNECTING = 2 //正在连接
private val STATE_CONNECTED = 3 //已连接
private val STATE_DISCONNECTED = 4 //已断开连接
private val STATE_DISSTATE_CONNECTING = 5 //已断开连接
private val STATE_REMOVE_BONDING = 6 //正在删除绑定
private val STATE_SEARCHING = 7
/**
* Current State
*/
private var currentState = STATE_DEFAULT
/************************************************/
protected var targetDevice: BluetoothDeviceWrapper? = null
/**
* List of devices found
*/
protected var foundDeviceList: MutableList<BluetoothDeviceWrapper> = ArrayList()
/**
* Map of devices connected.
*/
protected var currentConnectedDeviceMap: MutableMap<String, BluetoothDeviceWrapper> = HashMap()
// private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE){
// BluetoothAdapter.getDefaultAdapter()
// }
private var bluetoothAdapter: BluetoothAdapter? = null
/**
* Support API for the Bluetooth GATT Profile
*/
private var bluetoothGatt: BluetoothGatt? = null
var configCharacter: BluetoothGattCharacteristic? = null
var controlCharacter: BluetoothGattCharacteristic? = null
var uartCharacter: BluetoothGattCharacteristic? = null
var flashCharacter: BluetoothGattCharacteristic? = null
//------------- Some BluetoothProfiles
private var bluetoothHealth: BluetoothHealth? = null
private val profileListener = object : BluetoothProfile.ServiceListener{
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {
ZLog.e("onServiceConnected: profile=$profile proxy=$proxy")
if (profile == BluetoothProfile.HEALTH){
bluetoothHealth = proxy as BluetoothHealth
}
}
override fun onServiceDisconnected(profile: Int) {
ZLog.e("onServiceDisconnected: ")
if (profile == BluetoothProfile.HEALTH){
bluetoothHealth = null
}
}
}
private var leScanCallback: BleScanCallBack? = null
private val mHandler = BLEManagerHandler()
// ---------- 标准蓝牙 标准蓝牙service
private val UUID_STANDARD_SERVICE: UUID = UUID.fromString("0000xxxx-0000-1000-8000-00805F9B34FB")
//北斗手表NRF_SERVICE
private val UUID_OF_NRF_SERVICE: UUID = UUID.fromString("68680001-0000-5049-484E-4B3201000000")
private val UUID_OF_CONFIG_CHARACT: UUID = UUID.fromString("68680002-0000-5049-484E-4B3201000000")
private val UUID_OF_CONTROL_CHARACT: UUID = UUID.fromString("68680003-0000-5049-484E-4B3201000000")
//北斗手表APOLLO_SERVICE
private val UUID_OF_APOLLO_SERVICE: UUID = UUID.fromString("68680001-0000-5049-484E-4B3202000000")
private val UUID_OF_UARTCHARACT: UUID = UUID.fromString("68680002-0000-5049-484E-4B3202000000")
private val UUID_OF_FLASHCHARACT: UUID = UUID.fromString("68680003-0000-5049-484E-4B3202000000")
//蓝牙标准NOTIFY
private val UUID_NOTIFY: UUID = UUID.fromString("00000014-0000-1000-8000-00805F9B34FB")
//indicate通道(BLE-->App) uuid
private val UUID_INDICATE: UUID = UUID.fromString("00000015-0000-1000-8000-00805F9B34FB")
init {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (bluetoothAdapter == null) {
Toast.makeText(context, "当前设备不支持蓝牙!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "当前设备支持蓝牙!", Toast.LENGTH_SHORT).show()
}
}
fun setScanCallBack(callback: BleScanCallBack) {
leScanCallback = callback
}
fun requestLocalPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Check Location permision
XXPermissions.with(context)
.permission(Manifest.permission.ACCESS_COARSE_LOCATION)
.permission(Manifest.permission.ACCESS_FINE_LOCATION)
.request(object : OnPermissionCallback {
override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
if (all) {
ToastUtils.show(context, "获取到所有位置权限")
} else {
ToastUtils.show(context, "获取部分权限成功,但部分权限未正常授予")
}
}
override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
super.onDenied(permissions, never)
if (never) {
ToastUtils.show(context, "被永久拒绝授权,请手动授予储存权限")
// 如果是被永久拒绝就跳转到应用权限系统设置页面
XXPermissions.startPermissionActivity(context, permissions)
} else {
ToastUtils.show(context, "获取位置权限")
}
}
})
}
}
/**
* 蓝牙是否被打开
*/
fun isEnable(): Boolean {
return bluetoothAdapter?.isEnabled ?: false
}
/**
* 切换蓝牙状态
*/
fun enableBluetooth(enable: Boolean) {
if (enable) bluetoothAdapter?.enable() else bluetoothAdapter?.disable()
}
/**
* 获取绑定设备列表
*/
fun getBoudedDevices(): Set<BluetoothDevice>? {
return bluetoothAdapter?.bondedDevices
}
fun disconectDevice(){
bluetoothGatt?.apply {
disconnect() //触发BluetoothGattCallback#onConnectionStateChange()的回调 回调断开连接信息,
close()
}
}
fun readBleVersionCharacter(){
//写入需要传递给外设的特征值(即传递给外设的信息)
val byteArray = ByteArray(20)
//模拟寻找腕表
byteArray[0] = 0x16
byteArray[1] = 0x00000001
controlCharacter?.value = byteArray
bluetoothGatt?.writeCharacteristic(controlCharacter)
// val byteArray = ByteArray(20).apply {
// this[0] = 0x07
// }
// configCharacter?.value = byteArray
// bluetoothGatt?.writeCharacteristic(configCharacter)
}
/**
* 获取Profile
* @param profile eg: BluetoothProfile.HEALTH
*/
fun getProfile(profile: Int, lsr: BluetoothProfile.ServiceListener) {
bluetoothAdapter?.getProfileProxy(context, lsr, profile)
}
fun startDiscovery() {
val isSuccess = bluetoothAdapter?.startDiscovery()
ZLog.d("startFindDevices success? = $isSuccess")
}
/**
* 扫描搜索蓝牙设备
*/
fun startScanning() {
currentState = STATE_SEARCHING
// 如果想扫描特定类型的外围设备,则可使用
// startLeScan(UUID[], BluetoothAdapter.LeScanCallback),
// 它会提供一组 UUID 对象,用于指定App支持的 GATT 服务。
val scanner = bluetoothAdapter?.bluetoothLeScanner
val filter = ScanFilter.Builder().build()
val settings = ScanSettings.Builder()
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
// .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0)
.build()
scanner?.startScan(listOf(filter), settings, leScanCallback)
val msg = mHandler.obtainMessage(CODE_MSG_SCAN_TIMEOUT)
mHandler.sendMessageDelayed(msg, MAX_SCAN_TIMEOUT_MILLIS)
}
fun stopScan() {
leScanCallback?.onScanStop()
bluetoothAdapter?.bluetoothLeScanner?.stopScan(leScanCallback)
}
/**
* Connect BLE devices with GATT
* @param target Wrapper of BluetoothDevice
* @return BluetoothGatt
*/
fun connectDevice(target: BluetoothDeviceWrapper) {
ZLog.e("connectGattServer: ${target.device?.name}")
//Stop first
bluetoothAdapter?.bluetoothLeScanner?.stopScan(leScanCallback)
//false: 可用时不自动连接到 BLE 设备
bluetoothGatt = target.device?.connectGatt(context, false, BleGattCallback())
}
open class BleScanCallBack : ScanCallback() {
open fun onScanStop() {}
/**
* Callback when a BLE advertisement has been found.
*/
override fun onScanResult(callbackType: Int, result: ScanResult) {
// val deviceWrapper = BluetoothDeviceWrapper(
// result.rssi,
// result.device
// )
// if(!foundDeviceList.contains(deviceWrapper)){
// ZLog.d("found new device : $deviceWrapper")
// foundDeviceList.add(deviceWrapper)
// }
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
super.onBatchScanResults(results)
}
}
/**
* Open notification channle.
* 【NOTICE】: Befor read data, must enable notification
*/
private fun enableNotification( enable: Boolean,
characteristic: BluetoothGattCharacteristic?
): Boolean {
if (bluetoothGatt == null) {
ZLog.e("bluetoothGatt is null.")
return false
}
if (bluetoothGatt?.setCharacteristicNotification(characteristic, enable) == false) {
ZLog.e("Notification status was set failed.")
return false
}
//蓝牙标准Notification UUID
val clientConfig =
characteristic?.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"))
?: return false
if (enable) {
clientConfig.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
} else {
clientConfig.value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
}
return bluetoothGatt?.writeDescriptor(clientConfig) ?: false
}
/**
* BLE设备向客户端传递信息的回调
* TODO 开一个Service
*/
inner class BleGattCallback : BluetoothGattCallback() {
/**
* 连接状态发生改变时回调:
* Connect Steps:
* registerApp()
* |_onClientRegistered() - status=0 clientIf=7
* |__onClientConnectionState - status=0 clientIf=7 device=D4:5E:EC:D1:CC:21
*
* BLEDeviceManager.kt#OnConnectionStateChange: onConnectionStateChange()
*
*/
override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
ZLog.d("onConnectionStateChange() ")
when (newState) {
BluetoothProfile.STATE_CONNECTED -> {
currentState = STATE_CONNECTED
ZLog.e("Connected to GATT server.")
ZLog.d("Attempting to start service discovery: ${bluetoothGatt?.discoverServices()}")
}
BluetoothProfile.STATE_CONNECTING -> {
currentState = STATE_CONNECTING
ZLog.d("Connecting from GATT server.")
}
BluetoothProfile.STATE_DISCONNECTING -> {
currentState = STATE_DISSTATE_CONNECTING
ZLog.d("Disconnecting from GATT server.")
}
BluetoothProfile.STATE_DISCONNECTED -> {
ZLog.e("Disconnected from GATT server. ")
currentState = STATE_DISCONNECTED
}
}
}
override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) {
ZLog.d("onReadRemoteRssi() ")
super.onReadRemoteRssi(gatt, rssi, status)
}
/**
* 特征值读取成功回调
*/
override fun onCharacteristicRead(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?,
status: Int
) {
ZLog.d("数据读取成功 ")
super.onCharacteristicRead(gatt, characteristic, status)
when (status) {
BluetoothGatt.GATT_SUCCESS -> {
}
}
}
/**
* 特征值写入成功回调
*/
override fun onCharacteristicWrite(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?,
status: Int
) {
ZLog.d("数据写入成功 ${characteristic?.value}")
if (status == BluetoothGatt.GATT_SUCCESS) {
//获取写入到外设的特征值
ZLog.d("Data is ${characteristic?.value}")
}
super.onCharacteristicWrite(gatt, characteristic, status)
}
/**
* 监听notify通道数据
*/
override fun onCharacteristicChanged(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?
) {
//TODO 手表发送查找手机的数据, [19,1,0,0....] [19,2,0,0....]
ZLog.d("onCharacteristicChanged() command:${characteristic?.value}")
super.onCharacteristicChanged(gatt, characteristic)
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
super.onServicesDiscovered(gatt, status)
ZLog.d("onServicesDiscovered() status=${status}")
if (gatt == null) {
ZLog.e("onServicesDiscovered() gatt == null")
}
gatt?.apply {
val characteristicConfig =
getService(UUID_OF_NRF_SERVICE)?.getCharacteristic(UUID_OF_CONFIG_CHARACT)
val characteristicControl =
getService(UUID_OF_NRF_SERVICE)?.getCharacteristic(UUID_OF_CONTROL_CHARACT)
enableNotification(true, characteristicConfig)
enableNotification(true, characteristicControl)
readCharacteristic(characteristicConfig)
readCharacteristic(characteristicControl)
}
when (status) {
BluetoothGatt.GATT_SUCCESS -> {
val serviceList = gatt?.services
serviceList?.forEach { service ->
if (UUID_OF_NRF_SERVICE == service.uuid) {
val characterList = service.characteristics
characterList.forEach { character ->
when (character.uuid) {
UUID_OF_CONFIG_CHARACT -> {
configCharacter = character
ZLog.e(
"""Get Config Character:
serviceUUID=${service.uuid} characterUuid=${character.uuid}
serviceType=${service.type} characterValue=${character.value}"""
)
}
UUID_OF_CONTROL_CHARACT -> {
controlCharacter = character
ZLog.e(
"""Get Control Character:
serviceUUID=${service.uuid} characterUuid=${character.uuid}
serviceType=${service.type} characterValue=${character.value}"""
)
}
else ->{
ZLog.d(
"""Get Other Character:
serviceUUID=${service.uuid} characterUuid=${character.uuid}
serviceType=${service.type} characterValue=${character.value}"""
)
}
}
}
}
}
}
else -> ZLog.d("onServicesDiscovered received: $status")
}
}
override fun onPhyUpdate(gatt: BluetoothGatt?, txPhy: Int, rxPhy: Int, status: Int) {
ZLog.d("onPhyUpdate() ")
super.onPhyUpdate(gatt, txPhy, rxPhy, status)
}
override fun onPhyRead(gatt: BluetoothGatt?, txPhy: Int, rxPhy: Int, status: Int) {
ZLog.d("onPhyRead() ")
super.onPhyRead(gatt, txPhy, rxPhy, status)
}
override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
ZLog.d("onMtuChanged() ")
super.onMtuChanged(gatt, mtu, status)
}
override fun onReliableWriteCompleted(gatt: BluetoothGatt?, status: Int) {
ZLog.d("onReliableWriteCompleted() ")
super.onReliableWriteCompleted(gatt, status)
}
override fun onDescriptorWrite(
gatt: BluetoothGatt?,
descriptor: BluetoothGattDescriptor?,
status: Int
) {
ZLog.d("onDescriptorWrite() ")
super.onDescriptorWrite(gatt, descriptor, status)
}
override fun onDescriptorRead(
gatt: BluetoothGatt?,
descriptor: BluetoothGattDescriptor?,
status: Int
) {
ZLog.d("onDescriptorRead() ")
super.onDescriptorRead(gatt, descriptor, status)
}
}
inner class BLEManagerHandler : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
CODE_MSG_SCAN_TIMEOUT -> stopScan()
}
super.handleMessage(msg)
}
}
} | gpl-2.0 | bbf9b46933a730941c0844dc682ff983 | 34.558099 | 108 | 0.570509 | 4.417323 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt | 1 | 2360 | // 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.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class CopyWithoutNamedArgumentsInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(expression) {
val reference = expression.referenceExpression() as? KtNameReferenceExpression ?: return
if (reference.getReferencedNameAsName() != DataClassDescriptorResolver.COPY_METHOD_NAME) return
if (expression.valueArguments.all { it.isNamed() }) return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val call = expression.getResolvedCall(context) ?: return
val receiver = call.dispatchReceiver?.type?.constructor?.declarationDescriptor as? ClassDescriptor ?: return
if (!receiver.isData) return
if (call.candidateDescriptor != context[BindingContext.DATA_CLASS_COPY_FUNCTION, receiver]) return
holder.registerProblem(
expression.calleeExpression ?: return,
KotlinBundle.message("copy.method.of.data.class.is.called.without.named.arguments"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(AddNamesToCallArgumentsIntention(), expression.containingKtFile)
)
})
}
} | apache-2.0 | d742a905fde0b3625bb4b2272ac076ff | 51.466667 | 158 | 0.771186 | 5.256125 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/benchmark/HighlightingBenchmarkAction.kt | 1 | 8232 | // 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.actions.internal.benchmark
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBTextField
import com.intellij.uiDesigner.core.GridLayoutManager
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.addBoxWithLabel
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.collectSuitableKotlinFiles
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.shuffledSequence
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.psi.KtFile
import java.util.*
import javax.swing.JFileChooser
import kotlin.properties.Delegates
class HighlightingBenchmarkAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val settings = showSettingsDialog() ?: return
val random = Random(settings.seed)
fun collectFiles(): List<KtFile>? {
val ktFiles = collectSuitableKotlinFiles(project) { it.getLineCount() >= settings.lines }
if (ktFiles.size < settings.files) {
AbstractCompletionBenchmarkAction.showPopup(
project,
KotlinBundle.message("number.of.attempts.then.files.in.project.0", ktFiles.size)
)
return null
}
return ktFiles
}
val ktFiles = collectFiles() ?: return
val results = mutableListOf<Result>()
val connection = project.messageBus.connect()
ActionManager.getInstance().getAction("CloseAllEditors").actionPerformed(e)
val finishListener = DaemonFinishListener()
connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, finishListener)
GlobalScope.launch(EDT) {
try {
delay(100)
ktFiles
.shuffledSequence(random)
.take(settings.files)
.forEach { file ->
results += openFileAndMeasureTimeToHighlight(file, project, finishListener)
}
saveResults(results, project)
} finally {
connection.disconnect()
finishListener.channel.close()
}
}
}
private data class Settings(val seed: Long, val files: Int, val lines: Int)
private inner class DaemonFinishListener : DaemonCodeAnalyzer.DaemonListener {
val channel = Channel<String>(capacity = Channel.CONFLATED)
override fun daemonFinished() {
channel.offer(SUCCESS)
}
override fun daemonCancelEventOccurred(reason: String) {
channel.offer(reason)
}
}
companion object {
private const val SUCCESS = "Success"
}
private fun showSettingsDialog(): Settings? {
var cSeed: JBTextField by Delegates.notNull()
var cFiles: JBTextField by Delegates.notNull()
var cLines: JBTextField by Delegates.notNull()
val dialogBuilder = DialogBuilder()
val jPanel = JBPanel<JBPanel<*>>(GridLayoutManager(3, 2)).apply {
var i = 0
cSeed = addBoxWithLabel(KotlinBundle.message("random.seed"), default = "0", i = i++)
cFiles = addBoxWithLabel(KotlinBundle.message("files.to.visit"), default = "20", i = i++)
cLines = addBoxWithLabel(KotlinBundle.message("minimal.line.count"), default = "100", i = i)
}
dialogBuilder.centerPanel(jPanel)
if (!dialogBuilder.showAndGet()) return null
return Settings(cSeed.text.toLong(), cFiles.text.toInt(), cLines.text.toInt())
}
private sealed class Result(val location: String, val lines: Int) {
abstract fun toCSV(builder: StringBuilder)
class Success(location: String, lines: Int, val time: Long, val status: String) : Result(location, lines) {
override fun toCSV(builder: StringBuilder): Unit = with(builder) {
append(location)
append(", ")
append(lines)
append(", ")
append(status)
append(", ")
append(time)
}
}
class Error(location: String, lines: Int = 0, val reason: String) : Result(location, lines) {
override fun toCSV(builder: StringBuilder): Unit = with(builder) {
append(location)
append(", ")
append(lines)
append(", fail: ")
append(reason)
append(", ")
}
}
}
private suspend fun openFileAndMeasureTimeToHighlight(file: KtFile, project: Project, finishListener: DaemonFinishListener): Result {
NavigationUtil.openFileWithPsiElement(file.navigationElement, true, true)
val location = file.virtualFile.path
val lines = file.getLineCount()
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return Result.Error(location, lines, "No document")
val daemon = DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl
if (!daemon.isHighlightingAvailable(file)) return Result.Error(location, lines, "Highlighting not available")
if (!daemon.isRunningOrPending) return Result.Error(location, lines, "Analysis not running or pending")
val start = System.currentTimeMillis()
val outcome = finishListener.channel.receive()
if (outcome != SUCCESS) {
return Result.Error(location, lines, outcome)
}
val analysisTime = System.currentTimeMillis() - start
val model = DocumentMarkupModel.forDocument(document, project, true)
val severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project)
val maxSeverity = model.allHighlighters
.mapNotNull { highlighter ->
val info = highlighter.errorStripeTooltip as? HighlightInfo ?: return@mapNotNull null
info.severity
}.maxWithOrNull(severityRegistrar)
return Result.Success(location, lines, analysisTime, maxSeverity?.myName ?: "clean")
}
private fun saveResults(allResults: List<Result>, project: Project) {
val jfc = JFileChooser()
val result = jfc.showSaveDialog(null)
if (result == JFileChooser.APPROVE_OPTION) {
val file = jfc.selectedFile
file.writeText(buildString {
appendLine("n, file, lines, status, time")
var i = 0
allResults.forEach {
append(i++)
append(", ")
it.toCSV(this)
appendLine()
}
})
}
AbstractCompletionBenchmarkAction.showPopup(project, KotlinBundle.message("text.done"))
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
}
}
| apache-2.0 | a100f0c9086eed014bc5937b26f1e3f1 | 38.2 | 158 | 0.659257 | 5.090909 | false | false | false | false |
Meisolsson/PocketHub | app/src/main/java/com/github/pockethub/android/ui/issue/EditIssuesFilterActivity.kt | 1 | 8064 | /*
* Copyright (c) 2015 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.android.ui.issue
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View.GONE
import android.widget.RadioGroup
import com.github.pockethub.android.Intents.Builder
import com.github.pockethub.android.Intents.EXTRA_ISSUE_FILTER
import com.github.pockethub.android.R
import com.github.pockethub.android.core.issue.IssueFilter
import com.github.pockethub.android.ui.DialogResultListener
import com.github.pockethub.android.ui.base.BaseActivity
import com.github.pockethub.android.util.AvatarLoader
import com.github.pockethub.android.util.InfoUtils
import kotlinx.android.synthetic.main.activity_issues_filter_edit.*
import javax.inject.Inject
/**
* Activity to create or edit an issues filter for a repository
*/
class EditIssuesFilterActivity : BaseActivity(), DialogResultListener {
@Inject
lateinit var avatars: AvatarLoader
private var labelsDialog: LabelsDialog? = null
private var milestoneDialog: MilestoneDialog? = null
private var assigneeDialog: AssigneeDialog? = null
private var filter: IssueFilter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_issues_filter_edit)
if (savedInstanceState != null) {
filter = savedInstanceState.getParcelable(EXTRA_ISSUE_FILTER)
}
if (filter == null) {
filter = intent.getParcelableExtra(EXTRA_ISSUE_FILTER)
}
val repository = filter!!.repository
val actionBar = supportActionBar!!
actionBar.setTitle(R.string.filter_issues_title)
actionBar.subtitle = InfoUtils.createRepoId(repository)
updateAssignee()
updateMilestone()
updateLabels()
val status = findViewById<RadioGroup>(R.id.issue_filter_status)
val sortOrder = findViewById<RadioGroup>(R.id.issue_sort_order)
val sortType = findViewById<RadioGroup>(R.id.issue_sort_type)
status.setOnCheckedChangeListener(this::onStatusChanged)
sortOrder.setOnCheckedChangeListener(this::onSortOrderChanged)
sortType.setOnCheckedChangeListener(this::onSortTypeChanged)
tv_assignee.setOnClickListener { onAssigneeClicked() }
tv_assignee_label.setOnClickListener { onAssigneeClicked() }
tv_milestone.setOnClickListener { onMilestoneClicked() }
tv_milestone_label.setOnClickListener { onMilestoneClicked() }
tv_labels.setOnClickListener { onLabelsClicked() }
tv_labels_label.setOnClickListener { onLabelsClicked() }
if (filter!!.isOpen) {
status.check(R.id.rb_open)
} else {
status.check(R.id.rb_closed)
}
if (filter!!.direction == IssueFilter.DIRECTION_ASCENDING) {
sortOrder.check(R.id.rb_asc)
} else {
sortOrder.check(R.id.rb_desc)
}
when (filter!!.sortType) {
IssueFilter.SORT_CREATED -> sortType.check(R.id.rb_created)
IssueFilter.SORT_UPDATED -> sortType.check(R.id.rb_updated)
IssueFilter.SORT_COMMENTS -> sortType.check(R.id.rb_comments)
}
}
override fun onCreateOptionsMenu(options: Menu): Boolean {
menuInflater.inflate(R.menu.activity_issue_filter, options)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.m_apply -> {
val intent = Intent()
intent.putExtra(EXTRA_ISSUE_FILTER, filter)
setResult(RESULT_OK, intent)
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(EXTRA_ISSUE_FILTER, filter)
}
fun onAssigneeClicked() {
if (assigneeDialog == null) {
assigneeDialog = AssigneeDialog(this, REQUEST_ASSIGNEE, filter!!.repository)
}
assigneeDialog!!.show(filter!!.assignee)
}
fun onMilestoneClicked() {
if (milestoneDialog == null) {
milestoneDialog = MilestoneDialog(this, REQUEST_MILESTONE, filter!!.repository)
}
milestoneDialog!!.show(filter!!.milestone)
}
fun onLabelsClicked() {
if (labelsDialog == null) {
labelsDialog = LabelsDialog(this, REQUEST_LABELS, filter!!.repository)
}
labelsDialog!!.show(filter!!.labels)
}
private fun onStatusChanged(radioGroup: RadioGroup, checkedId: Int) {
filter!!.isOpen = checkedId == R.id.rb_open
}
private fun onSortOrderChanged(radioGroup: RadioGroup, checkedId: Int) {
if (checkedId == R.id.rb_asc) {
filter!!.direction = IssueFilter.DIRECTION_ASCENDING
} else {
filter!!.direction = IssueFilter.DIRECTION_DESCENDING
}
}
private fun onSortTypeChanged(radioGroup: RadioGroup, checkedId: Int) {
when (checkedId) {
R.id.rb_created -> filter!!.sortType = IssueFilter.SORT_CREATED
R.id.rb_updated -> filter!!.sortType = IssueFilter.SORT_UPDATED
R.id.rb_comments -> filter!!.sortType = IssueFilter.SORT_COMMENTS
else -> {
}
}
}
private fun updateLabels() {
val selected = filter!!.labels
if (selected != null) {
LabelDrawableSpan.setText(tv_labels, selected)
} else {
tv_labels.setText(R.string.none)
}
}
private fun updateMilestone() {
val selected = filter!!.milestone
if (selected != null) {
tv_milestone.text = selected.title()
} else {
tv_milestone.setText(R.string.none)
}
}
private fun updateAssignee() {
val selected = filter!!.assignee
if (selected != null) {
avatars.bind(iv_avatar, selected)
tv_assignee.text = selected.login()
} else {
iv_avatar.visibility = GONE
tv_assignee.setText(R.string.assignee_anyone)
}
}
override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) {
if (RESULT_OK != resultCode) {
return
}
when (requestCode) {
REQUEST_LABELS -> {
filter!!.setLabels(LabelsDialogFragment.getSelected(arguments))
updateLabels()
}
REQUEST_MILESTONE -> {
filter!!.milestone = MilestoneDialogFragment.getSelected(arguments)
updateMilestone()
}
REQUEST_ASSIGNEE -> {
filter!!.assignee = AssigneeDialogFragment.getSelected(arguments)
updateAssignee()
}
}
}
companion object {
/**
* Create intent for creating an issue filter for the given repository
*
* @param filter
* @return intent
*/
fun createIntent(filter: IssueFilter): Intent {
return Builder("repo.issues.filter.VIEW")
.add(EXTRA_ISSUE_FILTER, filter)
.toIntent()
}
private val REQUEST_LABELS = 1
private val REQUEST_MILESTONE = 2
private val REQUEST_ASSIGNEE = 3
}
}
| apache-2.0 | 5434b13188b6cc6aa04347f3da0bf479 | 31.647773 | 91 | 0.633929 | 4.610635 | false | false | false | false |
GunoH/intellij-community | platform/object-serializer/src/Int2IntMapBinding.kt | 7 | 2475 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.serialization
import com.amazon.ion.IonType
import it.unimi.dsi.fastutil.ints.Int2IntMap
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap
internal class Int2IntMapBinding : Binding {
override fun serialize(obj: Any, context: WriteContext) {
val map = obj as Int2IntMap
val writer = context.writer
if (context.filter.skipEmptyMap && map.isEmpty()) {
writer.writeInt(0)
return
}
writer.list {
writer.writeInt(map.size.toLong())
if (context.configuration.orderMapEntriesByKeys) {
val keys = map.keys.toIntArray()
keys.sort()
for (key in keys) {
writer.writeInt(key.toLong())
writer.writeInt(map.get(key).toLong())
}
}
else {
val entrySet = map.int2IntEntrySet()
for (entry in entrySet) {
writer.writeInt(entry.intKey.toLong())
writer.writeInt(entry.intValue.toLong())
}
}
}
}
override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) {
if (context.reader.type == IonType.NULL) {
property.set(hostObject, null)
return
}
val result = property.readUnsafe(hostObject) as Int2IntMap?
if (result == null) {
property.set(hostObject, readMap(context.reader))
return
}
result.clear()
val reader = context.reader
if (reader.type === IonType.INT) {
LOG.assertTrue(reader.intValue() == 0)
}
else {
reader.list {
reader.next()
val size = reader.intValue()
doRead(reader, size, result)
}
}
}
private fun doRead(reader: ValueReader, size: Int, result: Int2IntMap) {
for (i in 0 until size) {
reader.next()
val k = reader.intValue()
reader.next()
val v = reader.intValue()
result.put(k, v)
}
}
override fun deserialize(context: ReadContext, hostObject: Any?): Any {
return readMap(context.reader)
}
private fun readMap(reader: ValueReader): Int2IntOpenHashMap {
if (reader.type === IonType.INT) {
LOG.assertTrue(reader.intValue() == 0)
return Int2IntOpenHashMap()
}
return reader.list {
reader.next()
val size = reader.intValue()
val result = Int2IntOpenHashMap(size)
doRead(reader, size, result)
result
}
}
} | apache-2.0 | 39e18ab210fa49e925eb1a0904e83fec | 25.063158 | 120 | 0.628283 | 3.934817 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/ui/main/shots/ShotsPageFragment.kt | 1 | 5933 | /*
* Copyright (c) 2017 Lizhaotailang
*
* 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 io.github.tonnyl.mango.ui.main.shots
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.tonnyl.mango.R
import io.github.tonnyl.mango.data.Shot
import io.github.tonnyl.mango.databinding.FragmentSimpleListBinding
import io.github.tonnyl.mango.ui.shot.ShotActivity
import io.github.tonnyl.mango.ui.shot.ShotPresenter
import io.github.tonnyl.mango.ui.user.UserProfileActivity
import io.github.tonnyl.mango.ui.user.UserProfilePresenter
import kotlinx.android.synthetic.main.fragment_simple_list.*
import org.jetbrains.anko.startActivity
/**
* Created by lizhaotailang on 2017/6/29.
*
* Main ui for the shots page screen.
*/
class ShotsPageFragment : Fragment(), ShotsPageContract.View {
private lateinit var mPresenter: ShotsPageContract.Presenter
private var mAdapter: ShotsAdapter? = null
private var mIsLoading = false
private var _binding: FragmentSimpleListBinding? = null
private val binding get() = _binding!!
companion object {
@JvmStatic
fun newInstance(): ShotsPageFragment {
return ShotsPageFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentSimpleListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mPresenter.subscribe()
initViews()
binding.refreshLayout.setOnRefreshListener {
mIsLoading = true
mPresenter.listShots()
}
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
if (dy > 0 && layoutManager.findLastVisibleItemPosition() == binding.recyclerView.adapter.itemCount - 1 && !mIsLoading) {
mPresenter.listMoreShots()
mIsLoading = true
}
}
})
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.unsubscribe()
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
override fun setPresenter(presenter: ShotsPageContract.Presenter) {
mPresenter = presenter
}
override fun initViews() {
context?.let {
binding.refreshLayout.setColorSchemeColors(ContextCompat.getColor(it, R.color.colorAccent))
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.layoutManager = LinearLayoutManager(context)
}
}
override fun setLoadingIndicator(loading: Boolean) {
binding.refreshLayout.post({
binding.refreshLayout.isRefreshing = loading
})
}
override fun showResults(results: List<Shot>) {
if (mAdapter == null) {
context?.let {
mAdapter = ShotsAdapter(it, results)
mAdapter?.setItemClickListener(object : OnRecyclerViewItemClickListener {
override fun onItemClick(view: View, position: Int) {
it.startActivity<ShotActivity>(ShotPresenter.EXTRA_SHOT to results[position])
}
override fun onAvatarClick(view: View, position: Int) {
results[position].user?.let {
context?.startActivity<UserProfileActivity>(UserProfilePresenter.EXTRA_USER to it)
}
}
})
}
binding.recyclerView.adapter = mAdapter
}
mIsLoading = false
}
override fun showNetworkError() {
Snackbar.make(binding.recyclerView, R.string.network_error, Snackbar.LENGTH_SHORT).show()
}
override fun setEmptyContentVisibility(visible: Boolean) {
binding.emptyView.visibility = if (visible && (mAdapter == null)) View.VISIBLE else View.GONE
}
override fun notifyDataAllRemoved(size: Int) {
mAdapter?.notifyItemRangeRemoved(0, size)
mIsLoading = false
}
override fun notifyDataAdded(startPosition: Int, size: Int) {
mAdapter?.notifyItemRangeInserted(startPosition, size)
mIsLoading = false
}
} | mit | 7d3eb177cd93406d1fda7c25c8c060b4 | 34.532934 | 137 | 0.6806 | 4.969012 | false | false | false | false |
GunoH/intellij-community | java/java-features-trainer/src/com/intellij/java/ift/lesson/completion/JavaPostfixCompletionLesson.kt | 5 | 1393 | // 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.java.ift.lesson.completion
import com.intellij.java.ift.JavaLessonsBundle
import training.dsl.LearningDslBase
import training.dsl.LessonSample
import training.dsl.parseLessonSample
import training.learn.lesson.general.completion.PostfixCompletionLesson
class JavaPostfixCompletionLesson : PostfixCompletionLesson() {
override val sample: LessonSample = parseLessonSample("""
class PostfixCompletionDemo {
public void demonstrate(int show_times) {
(show_times == 10)<caret>
}
}
""".trimIndent())
override val result: String = parseLessonSample("""
class PostfixCompletionDemo {
public void demonstrate(int show_times) {
if (show_times == 10) {
}
}
}
""".trimIndent()).text
override val completionSuffix: String = "."
override val completionItem: String = "if"
override fun LearningDslBase.getTypeTaskText(): String {
return JavaLessonsBundle.message("java.postfix.completion.type", code(completionSuffix))
}
override fun LearningDslBase.getCompleteTaskText(): String {
return JavaLessonsBundle.message("java.postfix.completion.complete", code(completionItem), action("EditorChooseLookupItem"))
}
} | apache-2.0 | 841d4bbf76f23eb5d397b01b7174f598 | 34.74359 | 140 | 0.722182 | 4.853659 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModule.kt | 3 | 8247 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.buildsystem.model.DeclaredDependency
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.openapi.application.readAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import kotlinx.coroutines.future.future
import kotlinx.serialization.Serializable
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import java.io.File
import java.util.concurrent.CompletableFuture
/**
* Class representing a native [Module] enriched with Package Search data.
*
* @param name the name of the module.
* @param nativeModule the native [Module] it refers to.
* @param parent the parent [ProjectModule] of this object.
* @param buildFile The build file used by this module (e.g. `pom.xml` for Maven, `build.gradle` for Gradle).
* @param projectDir The corresponding directory instance for this module (a File could also be nonexistent).
* @param buildSystemType The type of the build system file used in this module (e.g., 'gradle-kotlin', 'gradle-groovy', etc.)
* @param moduleType The additional Package Search related data such as project icons, additional localizations and so on.
* listed in the Dependency Analyzer tool. At the moment the DA only supports Gradle and Maven.
* @param availableScopes Scopes available for the build system of this module (e.g. `implementation`, `api` for Gradle;
* `test`, `compile` for Maven).
* @param dependencyDeclarationCallback Given a [Dependency], it should return the indexes in the build file where given
* dependency has been declared.
*/
data class ProjectModule @JvmOverloads constructor(
@NlsSafe val name: String,
val nativeModule: Module,
val parent: ProjectModule?,
val buildFile: VirtualFile?,
val projectDir: File,
val buildSystemType: BuildSystemType,
val moduleType: ProjectModuleType,
val availableScopes: List<String> = emptyList(),
val dependencyDeclarationCallback: DependencyDeclarationCallback = { _ -> CompletableFuture.completedFuture(null) }
) {
@Suppress("UNUSED_PARAMETER")
@Deprecated(
"Use main constructor",
ReplaceWith("ProjectModule(name, nativeModule, parent, buildFile, projectDir, buildSystemType, moduleType)")
)
@ScheduledForRemoval
constructor(
name: String,
nativeModule: Module,
parent: ProjectModule,
buildFile: VirtualFile,
buildSystemType: BuildSystemType,
moduleType: ProjectModuleType,
navigatableDependency: (groupId: String, artifactId: String, version: PackageVersion) -> Navigatable?,
availableScopes: List<String>
) : this(name, nativeModule, parent, buildFile, buildFile.parent.toNioPath().toFile(), buildSystemType, moduleType, availableScopes)
fun getBuildFileNavigatableAtOffset(offset: Int): Navigatable? =
buildFile?.let { PsiManager.getInstance(nativeModule.project).findFile(it) }
?.let { psiFile -> PsiUtil.getElementAtOffset(psiFile, offset) }
?.takeIf { it != buildFile } as? Navigatable
@NlsSafe
fun getFullName(): String =
parent?.let { it.getFullName() + ":$name" } ?: name
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProjectModule) return false
if (name != other.name) return false
if (!nativeModule.isTheSameAs(other.nativeModule)) return false // This can't be automated
if (parent != other.parent) return false
if (buildFile?.path != other.buildFile?.path) return false
if (projectDir.path != other.projectDir.path) return false
if (buildSystemType != other.buildSystemType) return false
if (moduleType != other.moduleType) return false
// if (navigatableDependency != other.navigatableDependency) return false // Intentionally excluded
if (availableScopes != other.availableScopes) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + nativeModule.hashCodeOrZero()
result = 31 * result + (parent?.hashCode() ?: 0)
result = 31 * result + (buildFile?.path?.hashCode() ?: 0)
result = 31 * result + projectDir.path.hashCode()
result = 31 * result + buildSystemType.hashCode()
result = 31 * result + moduleType.hashCode()
// result = 31 * result + navigatableDependency.hashCode() // Intentionally excluded
result = 31 * result + availableScopes.hashCode()
return result
}
}
internal fun Module.isTheSameAs(other: Module) =
runCatching { moduleFilePath == other.moduleFilePath && name == other.name }
.getOrDefault(false)
private fun Module.hashCodeOrZero() =
runCatching { moduleFilePath.hashCode() + 31 * name.hashCode() }
.getOrDefault(0)
typealias DependencyDeclarationCallback = (DeclaredDependency) -> CompletableFuture<DependencyDeclarationIndexes?>
fun Project.dependencyDeclarationCallback(
action: (DeclaredDependency) -> DependencyDeclarationIndexes?
): DependencyDeclarationCallback = { lifecycleScope.future { readAction { action(it) } } }
/**
* Container class for declaration coordinates for a dependency in a build file. \
* Example for Gradle:
* ```
* implementation("io.ktor:ktor-server-cio:2.0.0")
* // ▲ ▲ ▲
* // | ∟ coordinatesStartIndex |
* // ∟ wholeDeclarationStartIndex ∟ versionStartIndex
* //
* ```
* Example for Maven:
* ```
* <dependency>
* // ▲ wholeDeclarationStartIndex
* <groupId>io.ktor</groupId>
* // ▲ coordinatesStartIndex
* <artifactId>ktor-server-cio</artifactId>
* <version>2.0.0</version>
* // ▲ versionStartIndex
* </dependency>
* ```
* @param wholeDeclarationStartIndex index of the first character where the whole declarations starts.
*
*/
@Serializable
data class DependencyDeclarationIndexes(
val wholeDeclarationStartIndex: Int,
val coordinatesStartIndex: Int,
val versionStartIndex: Int?
)
data class UnifiedDependencyKey(val scope: String, val groupId: String, val module: String)
val UnifiedDependency.key: UnifiedDependencyKey?
get() {
return UnifiedDependencyKey(scope ?: return null, coordinates.groupId!!, coordinates.artifactId ?: return null)
}
fun UnifiedDependency.asDependency(defaultScope: String? = null): Dependency? {
return Dependency(
scope = scope ?: defaultScope ?: return null,
groupId = coordinates.groupId ?: return null,
artifactId = coordinates.artifactId ?: return null,
version = coordinates.version ?: return null
)
}
data class Dependency(val scope: String, val groupId: String, val artifactId: String, val version: String) {
override fun toString() = "$scope(\"$groupId:$artifactId:$version\")"
}
fun Dependency.asUnifiedDependency() = UnifiedDependency(groupId, artifactId, version, scope)
| apache-2.0 | d5dc95699a6ffff570b7accf1e7f411b | 42.771277 | 136 | 0.698627 | 4.737478 | false | false | false | false |
junerver/CloudNote | app/src/main/java/com/junerver/cloudnote/Constants.kt | 1 | 663 | package com.junerver.cloudnote
/**
* Created by Junerver on 2016/9/1.
*/
object Constants {
//Bmob云后台APPID
const val BMOB_APP_ID = "fefce5edf036867d6bbddca07d71599a"
const val BMOB_REST_KEY = "2197ad856b9ea7ae9c96e93cf63dee6c"
//数据库名称
const val DB_NAME = "cloudnote"
//用户的全部字段信息 对应UserInfoResp对象
const val SP_USER_INFO = "USER_INFO"
//用户id 用去其他请求快速读取
const val SP_USER_ID = "USER_ID"
//序列化时默认排除字段
val DEFAULT_EXCLUDE_FIELDS: List<String> =
listOf("objectId", "updatedAt", "createdAt", "_updatedTime", "_createdTime")
} | apache-2.0 | 161466a00c4fc2984fbb2eeca97b0614 | 24.130435 | 84 | 0.677643 | 2.828431 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/sdk/PySdkToInstall.kt | 1 | 16856 | // 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.jetbrains.python.sdk
import com.google.common.hash.HashFunction
import com.google.common.hash.Hashing
import com.google.common.io.Files
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.util.ExecUtil.execAndGetOutput
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk.*
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.io.HttpRequests
import com.intellij.webcore.packaging.PackageManagementService
import com.intellij.webcore.packaging.PackagesNotificationPanel
import com.jetbrains.python.PyBundle
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.DownloadResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.InstallationResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.LookupResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkDownload
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkInstallation
import com.jetbrains.python.sdk.flavors.MacPythonSdkFlavor
import org.jetbrains.annotations.CalledInAny
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
private val LOGGER = Logger.getInstance(PySdkToInstall::class.java)
@CalledInAny
internal fun getSdksToInstall(): List<PySdkToInstall> {
return if (SystemInfo.isWindows) listOf(getPy39ToInstallOnWindows(), getPy310ToInstallOnWindows())
else if (SystemInfo.isMac) listOf(PySdkToInstallViaXCodeSelect())
else emptyList()
}
@RequiresEdt
fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>): Sdk? {
return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks) } else it }
}
@RequiresEdt
fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): Sdk? {
return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks, context) } else it }
}
private fun getPy39ToInstallOnWindows(): PySdkToInstallOnWindows {
val version = "3.9"
val name = "Python $version"
@Suppress("DEPRECATION") val hashFunction = Hashing.md5()
return PySdkToInstallOnWindows(
name,
version,
"https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe",
28895456,
"cc3eabc1f9d6c703d1d2a4e7c041bc1d",
hashFunction,
"python-3.9.7-amd64.exe"
)
}
private fun getPy310ToInstallOnWindows(): PySdkToInstallOnWindows {
val version = "3.10"
val name = "Python $version"
@Suppress("DEPRECATION") val hashFunction = Hashing.md5()
return PySdkToInstallOnWindows(
name,
version,
"https://www.python.org/ftp/python/3.10.0/python-3.10.0-amd64.exe",
28315928,
"c3917c08a7fe85db7203da6dcaa99a70",
hashFunction,
"python-3.10.0-amd64.exe"
)
}
abstract class PySdkToInstall internal constructor(name: String, version: String)
: ProjectJdkImpl(name, PythonSdkType.getInstance(), null, version) {
@CalledInAny
abstract fun renderInList(renderer: PySdkListCellRenderer)
@CalledInAny
@NlsContexts.DialogMessage
abstract fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String
@RequiresEdt
abstract fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk?
}
private class PySdkToInstallOnWindows(name: String,
private val version: String,
private val url: String,
private val size: Long,
private val hash: String,
private val hashFunction: HashFunction,
private val targetFileName: String) : PySdkToInstall(name, version) {
override fun renderInList(renderer: PySdkListCellRenderer) {
renderer.append(name)
renderer.append(" $url", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) // NON-NLS
renderer.icon = AllIcons.Actions.Download
}
@NlsContexts.DialogMessage
override fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String {
val fileSize = StringUtil.formatFileSize(size)
return HtmlBuilder()
.append(PyBundle.message("python.sdk.executable.not.found.header"))
.append(tag("ul").children(
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.specify.path", text("...").bold(), "python.exe"))),
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.download.and.install",
text(defaultButtonName).bold(), fileSize)))
)).toString()
}
override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
try {
val project = module?.project
return ProgressManager.getInstance().run(
object : Task.WithResult<PyDetectedSdk?, Exception>(project, PyBundle.message("python.sdk.installing", name), true) {
override fun compute(indicator: ProgressIndicator): PyDetectedSdk? = install(project, systemWideSdksDetector, indicator)
}
)
}
catch (e: IOException) {
handleIOException(e)
}
catch (e: PyInstallationExecutionException) {
handleExecutionException(e)
}
catch (e: PyInstallationException) {
handleInstallationException(e)
}
return null
}
private fun install(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>, indicator: ProgressIndicator): PyDetectedSdk? {
val targetFile = File(PathManager.getTempPath(), targetFileName)
try {
indicator.text = PyBundle.message("python.sdk.downloading", targetFileName)
if (indicator.isCanceled) {
logSdkDownload(project, version, DownloadResult.CANCELLED)
return null
}
downloadInstaller(project, targetFile, indicator)
if (indicator.isCanceled) {
logSdkDownload(project, version, DownloadResult.CANCELLED)
return null
}
checkInstallerConsistency(project, targetFile)
logSdkDownload(project, version, DownloadResult.OK)
indicator.text = PyBundle.message("python.sdk.running", targetFileName)
indicator.text2 = PyBundle.message("python.sdk.installing.windows.warning")
indicator.isIndeterminate = true
if (indicator.isCanceled) {
logSdkInstallation(project, version, InstallationResult.CANCELLED)
return null
}
runInstaller(project, targetFile, indicator)
logSdkInstallation(project, version, InstallationResult.OK)
return findInstalledSdk(project, systemWideSdksDetector)
}
finally {
FileUtil.delete(targetFile)
}
}
private fun downloadInstaller(project: Project?, targetFile: File, indicator: ProgressIndicator) {
LOGGER.info("Downloading $url to $targetFile")
return try {
HttpRequests.request(url).saveToFile(targetFile, indicator)
}
catch (e: IOException) {
logSdkDownload(project, version, DownloadResult.EXCEPTION)
throw IOException("Failed to download $url to $targetFile.", e)
}
catch (e: ProcessCanceledException) {
logSdkDownload(project, version, DownloadResult.CANCELLED)
throw e
}
}
private fun checkInstallerConsistency(project: Project?, installer: File) {
LOGGER.debug("Checking installer size")
val sizeDiff = installer.length() - size
if (sizeDiff != 0L) {
logSdkDownload(project, version, DownloadResult.SIZE)
throw IOException("Downloaded $installer has incorrect size, difference is ${sizeDiff.absoluteValue} bytes.")
}
LOGGER.debug("Checking installer checksum")
val actualHashCode = Files.asByteSource(installer).hash(hashFunction).toString()
if (!actualHashCode.equals(hash, ignoreCase = true)) {
logSdkDownload(project, version, DownloadResult.CHECKSUM)
throw IOException("Checksums for $installer does not match. Actual value is $actualHashCode, expected $hash.")
}
}
private fun handleIOException(e: IOException) {
LOGGER.info(e)
e.message?.let {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
it,
null,
e.cause?.message,
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun runInstaller(project: Project?, installer: File, indicator: ProgressIndicator) {
val commandLine = GeneralCommandLine(installer.absolutePath, "/quiet")
LOGGER.info("Running ${commandLine.commandLineString}")
val output = runInstaller(project, commandLine, indicator)
if (output.isCancelled) logSdkInstallation(project, version, InstallationResult.CANCELLED)
if (output.exitCode != 0) logSdkInstallation(project, version, InstallationResult.EXIT_CODE)
if (output.isTimeout) logSdkInstallation(project, version, InstallationResult.TIMEOUT)
if (output.exitCode != 0 || output.isTimeout) throw PyInstallationException(commandLine, output)
}
private fun handleInstallationException(e: PyInstallationException) {
val processOutput = e.output
processOutput.checkSuccess(LOGGER)
if (processOutput.isCancelled) {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.installation.has.been.cancelled.title", name),
PackageManagementService.ErrorDescription(
PyBundle.message("python.sdk.some.installed.python.components.might.get.inconsistent.after.cancellation"),
e.commandLine.commandLineString,
listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() },
PyBundle.message("python.sdk.consider.installing.python.manually")
)
)
}
else {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
if (processOutput.isTimeout) PyBundle.message("python.sdk.failed.to.install.timed.out")
else PyBundle.message("python.sdk.failed.to.install.exit.code", processOutput.exitCode),
e.commandLine.commandLineString,
listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() },
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun runInstaller(project: Project?, commandLine: GeneralCommandLine, indicator: ProgressIndicator): ProcessOutput {
try {
return CapturingProcessHandler(commandLine).runProcessWithProgressIndicator(indicator)
}
catch (e: ExecutionException) {
logSdkInstallation(project, version, InstallationResult.EXCEPTION)
throw PyInstallationExecutionException(commandLine, e)
}
}
private fun handleExecutionException(e: PyInstallationExecutionException) {
LOGGER.info(e)
e.cause.message?.let {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
it,
e.commandLine.commandLineString,
null,
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun findInstalledSdk(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
LOGGER.debug("Resetting system-wide sdks detectors")
resetSystemWideSdksDetectors()
return systemWideSdksDetector()
.also { sdks ->
LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } }
}
.also {
PySdkToInstallCollector.logSdkLookup(
project,
version,
if (it.isEmpty()) LookupResult.NOT_FOUND else LookupResult.FOUND
)
}
.singleOrNull()
}
private class PyInstallationException(val commandLine: GeneralCommandLine, val output: ProcessOutput) : Exception()
private class PyInstallationExecutionException(val commandLine: GeneralCommandLine, override val cause: ExecutionException) : Exception()
}
private class PySdkToInstallViaXCodeSelect : PySdkToInstall("Python", "") {
override fun renderInList(renderer: PySdkListCellRenderer) {
renderer.append(name)
renderer.append(" ")
renderer.append(PyBundle.message("python.cldt.installing.suggestion"), SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
@NlsContexts.DialogMessage
override fun getInstallationWarning(defaultButtonName: String): String {
val commandChunk = text(MacPythonSdkFlavor.getXCodeSelectInstallCommand().commandLineString)
return HtmlBuilder()
.append(PyBundle.message("python.sdk.executable.not.found.header"))
.append(tag("ul").children(
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.specify.path", text("...").bold(), "python"))),
tag("li").children(raw(
PyBundle.message("python.sdk.executable.not.found.option.install.with.cldt", text(defaultButtonName).bold(), commandChunk.code())
)),
tag("li").children(text(PyBundle.message("python.sdk.executable.not.found.option.install.or.brew")))
)).toString()
}
override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
val project = module?.project
return ProgressManager.getInstance().run(
object : Task.WithResult<PyDetectedSdk?, Exception>(project, PyBundle.message("python.cldt.installing.title"), true) {
override fun compute(indicator: ProgressIndicator): PyDetectedSdk? {
@Suppress("DialogTitleCapitalization")
indicator.text = PyBundle.message("python.cldt.installing.indicator")
indicator.text2 = PyBundle.message("python.cldt.installing.skip")
runXCodeSelectInstall()
while (!MacPythonSdkFlavor.areCommandLineDeveloperToolsAvailable() && isInstallCommandLineDeveloperToolsAppRunning()) {
Thread.sleep(TimeUnit.SECONDS.toMillis(5))
}
LOGGER.debug("Resetting system-wide sdks detectors")
resetSystemWideSdksDetectors()
return systemWideSdksDetector()
.also { sdks ->
LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } }
}
.singleOrNull()
}
}
.also {
it.cancelText = IdeBundle.message("button.skip")
it.cancelTooltipText = IdeBundle.message("button.skip")
}
)
}
private fun runXCodeSelectInstall() {
val commandLine = MacPythonSdkFlavor.getXCodeSelectInstallCommand()
try {
execAndGetOutput(commandLine)
.also {
if (LOGGER.isDebugEnabled) {
LOGGER.debug("Result of '${commandLine.commandLineString}':\n$it")
}
}
}
catch (e: ExecutionException) {
LOGGER.warn("Exception during '${commandLine.commandLineString}'", e)
}
}
private fun isInstallCommandLineDeveloperToolsAppRunning(): Boolean {
val appName = "Install Command Line Developer Tools.app"
return OSProcessUtil
.getProcessList()
.any { it.commandLine.contains(appName) }
.also {
if (LOGGER.isDebugEnabled) {
LOGGER.debug("'$appName' is${if (it) "" else " not"} running")
}
}
}
}
| apache-2.0 | d96ce5638be27eb639458d8d2555637a | 38.8487 | 140 | 0.717727 | 4.462801 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialogUiSpec.kt | 13 | 701 | // 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.util.ui.cloneDialog
import com.intellij.util.ui.JBValue
/**
* Contains a lot of UI related constants for clone dialog that can be helpful for external implementations.
*/
object VcsCloneDialogUiSpec {
object ExtensionsList {
val iconSize = JBValue.UIInteger("VcsCloneDialog.iconSize", 22)
const val iconTitleGap = 6
const val topBottomInsets = 8
const val leftRightInsets = 10
}
object Components {
const val innerHorizontalGap = 10
const val avatarSize = 24
const val popupMenuAvatarSize = 40
}
}
| apache-2.0 | 4028a78b1d7c2fd9960c3169df4bdee2 | 30.863636 | 140 | 0.743224 | 4.222892 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/BookmarkListProvider.kt | 9 | 2613 | // 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.ide.bookmark.ui.tree
import com.intellij.ide.bookmark.BookmarkBundle.message
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.ide.bookmark.BookmarksListProvider
import com.intellij.ide.bookmark.FileBookmark
import com.intellij.ide.bookmark.LineBookmark
import com.intellij.ide.bookmark.providers.FileBookmarkImpl
import com.intellij.ide.bookmark.providers.LineBookmarkImpl
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import javax.swing.JComponent
internal class BookmarkListProvider(private val project: Project) : BookmarksListProvider {
override fun getWeight() = Int.MAX_VALUE
override fun getProject() = project
override fun createNode(): AbstractTreeNode<*>? = null
override fun getDescriptor(node: AbstractTreeNode<*>) = when (val value = node.equalityObject) {
is LineBookmarkImpl -> value.descriptor
is FileBookmarkImpl -> value.descriptor
is LineBookmark -> OpenFileDescriptor(project, value.file, value.line)
is FileBookmark -> OpenFileDescriptor(project, value.file)
else -> null
}
override fun getEditActionText() = message("bookmark.edit.action.text")
override fun canEdit(selection: Any) = selection is BookmarkNode<*>
override fun performEdit(selection: Any, parent: JComponent) {
val node = selection as? BookmarkNode<*> ?: return
val bookmark = node.value ?: return
val group = node.bookmarkGroup ?: return
val description = group.getDescription(bookmark)
Messages.showInputDialog(parent,
message("action.bookmark.edit.description.dialog.message"),
message("action.bookmark.edit.description.dialog.title"),
null,
description,
null
)?.let {
if (description != null) group.setDescription(bookmark, it)
else group.add(bookmark, BookmarkType.DEFAULT, it)
}
}
override fun getDeleteActionText() = message("bookmark.delete.action.text")
override fun canDelete(selection: List<*>) = selection.all { it is BookmarkNode<*> }
override fun performDelete(selection: List<*>, parent: JComponent) = selection.forEach { performDelete(it) }
private fun performDelete(node: Any?) {
if (node is FileNode) node.children.forEach { performDelete(it) }
if (node is BookmarkNode<*>) node.value?.let { node.bookmarkGroup?.remove(it) }
}
}
| apache-2.0 | d6946b9cc8cd556ccb749384261b14eb | 45.660714 | 158 | 0.758515 | 4.347754 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/utils/WebBrowser.kt | 1 | 1274 | package com.cognifide.gradle.aem.common.utils
import com.cognifide.gradle.aem.AemException
import com.cognifide.gradle.aem.AemExtension
import org.buildobjects.process.ProcBuilder
import org.gradle.internal.os.OperatingSystem
import java.util.concurrent.TimeUnit
class WebBrowser(private val aem: AemExtension) {
private var options: ProcBuilder.() -> Unit = {}
fun options(options: ProcBuilder.() -> Unit) {
this.options = options
}
@Suppress("TooGenericExceptionCaught", "MagicNumber")
fun open(url: String, options: ProcBuilder.() -> Unit = {}) {
try {
val os = OperatingSystem.current()
val command = when {
os.isWindows -> "explorer"
os.isMacOsX -> "open"
else -> "sensible-browser"
}
ProcBuilder(command, url)
.withWorkingDirectory(aem.project.projectDir)
.withTimeoutMillis(TimeUnit.SECONDS.toMillis(30))
.ignoreExitStatus()
.apply(this.options)
.apply(options)
.run()
} catch (e: Exception) {
throw AemException("Browser opening command failed! Cause: ${e.message}", e)
}
}
}
| apache-2.0 | 1e16d589c7dba418887ce0c0e42caa7e | 32.526316 | 88 | 0.589482 | 4.632727 | false | false | false | false |
StuStirling/ribot-viewer | app/src/main/java/com/stustirling/ribotviewer/ui/allribot/AllRibotViewModel.kt | 1 | 2657 | package com.stustirling.ribotviewer.ui.allribot
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.stustirling.ribotviewer.BaseViewModel
import com.stustirling.ribotviewer.domain.RefreshTrigger
import com.stustirling.ribotviewer.domain.RibotRepository
import com.stustirling.ribotviewer.model.RibotModel
import com.stustirling.ribotviewer.model.toRibotModel
import com.stustirling.ribotviewer.shared.extensions.onlyResourceError
import com.stustirling.ribotviewer.shared.extensions.onlyResourceLoading
import com.stustirling.ribotviewer.shared.extensions.onlyResourceSuccess
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
/**
* Created by Stu Stirling on 23/09/2017.
*/
class AllRibotViewModel(ribotRepository: RibotRepository) : BaseViewModel() {
private val networkRefresh = RefreshTrigger()
val ribots = MutableLiveData<List<RibotModel>>()
val retrievalError = MutableLiveData<Throwable>()
val loading = MutableLiveData<Boolean>().apply {value = false }
init {
val connectableRepoCall = ribotRepository.getRibots(networkRefresh)
.subscribeOn(Schedulers.io())
.publish()
val success = connectableRepoCall
.onlyResourceSuccess()
.map { it.map { it.toRibotModel() } }
.observeOn(AndroidSchedulers.mainThread())
val error = connectableRepoCall
.onlyResourceError()
.map { it.second }
.observeOn(AndroidSchedulers.mainThread())
val loadingFlowable = connectableRepoCall
.onlyResourceLoading()
.observeOn(AndroidSchedulers.mainThread())
compositeDisposable.addAll(
error.subscribe {
retrievalError.value = it
loading.value = false
},
success.subscribe {
retrievalError.value = null
ribots.value = it
loading.value = false},
loadingFlowable.subscribe { loading.value = true },
connectableRepoCall.connect()
)
}
fun triggerRefresh() = networkRefresh.refresh()
class Factory @Inject constructor(val ribotRepository: RibotRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>?): T {
@Suppress("UNCHECKED_CAST")
return AllRibotViewModel(ribotRepository) as T
}
}
} | apache-2.0 | a372c19d89822d320a1bb71a0fb68d1b | 36.43662 | 105 | 0.674821 | 4.84854 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/explore/depictions/DepictsClientTest.kt | 3 | 2524 | package fr.free.nrw.commons.explore.depictions
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import depictSearchItem
import fr.free.nrw.commons.mwapi.Binding
import fr.free.nrw.commons.mwapi.Result
import fr.free.nrw.commons.mwapi.SparqlResponse
import fr.free.nrw.commons.upload.depicts.DepictsInterface
import fr.free.nrw.commons.wikidata.model.DepictSearchResponse
import io.reactivex.Single
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.wikipedia.wikidata.Entities
class DepictsClientTest {
@Mock
private lateinit var depictsInterface: DepictsInterface
private lateinit var depictsClient: DepictsClient
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
depictsClient = DepictsClient(depictsInterface)
}
@Test
fun searchForDepictions() {
val depictSearchResponse = mock<DepictSearchResponse>()
whenever(depictsInterface.searchForDepicts("query", "1", "en", "en", "0"))
.thenReturn(Single.just(depictSearchResponse))
whenever(depictSearchResponse.search).thenReturn(listOf(depictSearchItem("1"),depictSearchItem("2")))
val entities = mock<Entities>()
whenever(depictsInterface.getEntities("1|2")).thenReturn(Single.just(entities))
whenever(entities.entities()).thenReturn(emptyMap())
depictsClient.searchForDepictions("query", 1, 0)
.test()
.assertValue(emptyList())
}
@Test
fun getEntities() {
val entities = mock<Entities>()
whenever(depictsInterface.getEntities("ids")).thenReturn(Single.just(entities))
depictsClient.getEntities("ids").test().assertValue(entities)
}
@Test
fun toDepictions() {
val sparqlResponse = mock<SparqlResponse>()
val result = mock<Result>()
whenever(sparqlResponse.results).thenReturn(result)
val binding1 = mock<Binding>()
val binding2 = mock<Binding>()
whenever(result.bindings).thenReturn(listOf(binding1, binding2))
whenever(binding1.id).thenReturn("1")
whenever(binding2.id).thenReturn("2")
val entities = mock<Entities>()
whenever(depictsInterface.getEntities("1|2")).thenReturn(Single.just(entities))
whenever(entities.entities()).thenReturn(emptyMap())
depictsClient.toDepictions(Single.just(sparqlResponse))
.test()
.assertValue(emptyList())
}
}
| apache-2.0 | 099d57f6d91a5b26233bbaba07547259 | 35.57971 | 109 | 0.705626 | 4.397213 | false | true | false | false |
nicolas-raoul/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/UploadMediaDetail.kt | 1 | 1176 | package fr.free.nrw.commons.upload
import fr.free.nrw.commons.nearby.Place
/**
* Holds a description of an item being uploaded by [UploadActivity]
*/
data class UploadMediaDetail constructor(
/**
* @return The language code ie. "en" or "fr"
*/
/**
* @param languageCode The language code ie. "en" or "fr"
*/
var languageCode: String? = null,
var descriptionText: String = "",
var captionText: String = ""
) {
fun javaCopy() = copy()
constructor(place: Place) : this(
place.language,
place.longDescription,
place.name
)
/**
* @return the index of the language selected in a spinner with [SpinnerLanguagesAdapter]
*/
/**
* @param selectedLanguageIndex the index of the language selected in a spinner with [SpinnerLanguagesAdapter]
*/
var selectedLanguageIndex: Int = -1
/**
* returns if the description was added manually (by the user, or we have added it programaticallly)
* @return
*/
/**
* sets to true if the description was manually added by the user
* @param manuallyAdded
*/
var isManuallyAdded: Boolean = false
}
| apache-2.0 | fef6be22992bdd5e15d4e7e2383a414c | 26.348837 | 114 | 0.636905 | 4.155477 | false | false | false | false |
pinkjersey/mtlshipback | src/main/kotlin/com/ipmus/filter/AuthFilter.kt | 1 | 1922 | package com.ipmus.filter
import com.ipmus.JerseyApp
import com.ipmus.util.MTLKeyGenerator
import io.jsonwebtoken.Jwts
import org.slf4j.LoggerFactory
import java.security.Key
import java.util.logging.Logger
import javax.annotation.Priority
import javax.ws.rs.NotAuthorizedException
import javax.ws.rs.Priorities
import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerRequestFilter
import javax.ws.rs.core.HttpHeaders
import javax.ws.rs.ext.Provider
import javax.crypto.KeyGenerator
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
import javax.ws.rs.core.Response
@Provider
@TokenNeeded
@Priority(Priorities.AUTHENTICATION)
class AuthFilter() : ContainerRequestFilter {
private val logger = LoggerFactory.getLogger(AuthFilter::class.java)
override fun filter(requestContext: ContainerRequestContext?) {
if (requestContext != null) {
val authHeader: String = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
?: throw NotAuthorizedException("Invalid auth header")
if (authHeader.startsWith("Bearer ")) {
logger.info(authHeader)
val token = authHeader.substring("Bearer".length).trim();
try {
val key = MTLKeyGenerator.generateKey()
Jwts.parser().setSigningKey(key).parseClaimsJws(token);
logger.debug("#### valid token : " + token);
}
catch (e: Exception) {
logger.error("#### invalid token : " + token);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
} else {
throw NotAuthorizedException("Invalid auth header")
}
} else {
throw IllegalStateException("Something not set with the filter")
}
}
} | mit | 9af7e7f9488536855f8fab1fda07ff4d | 35.980769 | 100 | 0.664932 | 4.699267 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/variables/VariablesViewModel.kt | 1 | 9430 | package ch.rmy.android.http_shortcuts.activities.variables
import android.app.Application
import androidx.lifecycle.viewModelScope
import ch.rmy.android.framework.extensions.tryOrLog
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.framework.utils.localization.StringResLocalizable
import ch.rmy.android.framework.viewmodel.BaseViewModel
import ch.rmy.android.framework.viewmodel.WithDialog
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.variables.editor.VariableEditorActivity
import ch.rmy.android.http_shortcuts.activities.variables.editor.usecases.GetContextMenuDialogUseCase
import ch.rmy.android.http_shortcuts.activities.variables.editor.usecases.GetDeletionDialogUseCase
import ch.rmy.android.http_shortcuts.activities.variables.usecases.GetCreationDialogUseCase
import ch.rmy.android.http_shortcuts.activities.variables.usecases.GetUsedVariableIdsUseCase
import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.enums.VariableType
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.usecases.KeepVariablePlaceholderProviderUpdatedUseCase
import ch.rmy.android.http_shortcuts.utils.ExternalURLs
import ch.rmy.android.http_shortcuts.variables.VariableManager
import ch.rmy.android.http_shortcuts.variables.VariableResolver
import ch.rmy.android.http_shortcuts.variables.Variables.KEY_MAX_LENGTH
import kotlinx.coroutines.launch
import javax.inject.Inject
class VariablesViewModel(application: Application) : BaseViewModel<Unit, VariablesViewState>(application), WithDialog {
@Inject
lateinit var variableRepository: VariableRepository
@Inject
lateinit var shortcutRepository: ShortcutRepository
@Inject
lateinit var getDeletionDialog: GetDeletionDialogUseCase
@Inject
lateinit var getContextMenuDialog: GetContextMenuDialogUseCase
@Inject
lateinit var getCreationDialog: GetCreationDialogUseCase
@Inject
lateinit var getUsedVariableIdsUseCase: GetUsedVariableIdsUseCase
@Inject
lateinit var keepVariablePlaceholderProviderUpdated: KeepVariablePlaceholderProviderUpdatedUseCase
init {
getApplicationComponent().inject(this)
}
private var variablesInitialized = false
private var variables: List<VariableModel> = emptyList()
set(value) {
field = value
variablesInitialized = true
}
private var usedVariableIds: Set<VariableId>? = null
set(value) {
if (field != value) {
field = value
if (variablesInitialized) {
recomputeVariablesInViewState()
}
}
}
override var dialogState: DialogState?
get() = currentViewState?.dialogState
set(value) {
updateViewState {
copy(dialogState = value)
}
}
override fun onInitializationStarted(data: Unit) {
finalizeInitialization(silent = true)
}
override fun initViewState() = VariablesViewState()
override fun onInitialized() {
viewModelScope.launch {
variableRepository.getObservableVariables()
.collect { variables ->
[email protected] = variables
recomputeVariablesInViewState()
}
}
viewModelScope.launch {
keepVariablePlaceholderProviderUpdated()
}
}
private fun recomputeVariablesInViewState() {
updateViewState {
copy(variables = mapVariables([email protected]))
}
}
private fun mapVariables(variables: List<VariableModel>): List<VariableListItem> =
variables.map { variable ->
VariableListItem.Variable(
id = variable.id,
key = variable.key,
type = StringResLocalizable(VariableTypeMappings.getTypeName(variable.variableType)),
isUnused = usedVariableIds?.contains(variable.id) == false,
)
}
.ifEmpty {
listOf(VariableListItem.EmptyState)
}
fun onVariableMoved(variableId1: VariableId, variableId2: VariableId) {
launchWithProgressTracking {
variableRepository.moveVariable(variableId1, variableId2)
}
}
fun onCreateButtonClicked() {
dialogState = getCreationDialog(this)
}
fun onHelpButtonClicked() {
openURL(ExternalURLs.VARIABLES_DOCUMENTATION)
}
fun onVariableClicked(variableId: VariableId) {
val variable = getVariable(variableId) ?: return
dialogState = getContextMenuDialog(variableId, StringResLocalizable(VariableTypeMappings.getTypeName(variable.variableType)), this)
}
private fun getVariable(variableId: VariableId) =
variables.firstOrNull { it.id == variableId }
fun onCreationDialogVariableTypeSelected(variableType: VariableType) {
openActivity(
VariableEditorActivity.IntentBuilder(variableType)
)
}
fun onEditOptionSelected(variableId: VariableId) {
val variable = getVariable(variableId) ?: return
openActivity(
VariableEditorActivity.IntentBuilder(variable.variableType)
.variableId(variableId)
)
}
fun onDuplicateOptionSelected(variableId: VariableId) {
val variable = getVariable(variableId) ?: return
launchWithProgressTracking {
val newKey = generateNewKey(variable.key)
variableRepository.duplicateVariable(variableId, newKey)
showSnackbar(StringResLocalizable(R.string.message_variable_duplicated, variable.key))
}
}
private fun generateNewKey(oldKey: String): VariableKey {
val base = oldKey.take(KEY_MAX_LENGTH - 1)
for (i in 2..9) {
val newKey = "$base$i"
if (!isVariableKeyInUse(newKey)) {
return newKey
}
}
throw RuntimeException("Failed to generate new key for variable duplication")
}
private fun isVariableKeyInUse(key: String): Boolean =
variables.any { it.key == key }
fun onDeletionOptionSelected(variableId: VariableId) {
val variable = getVariable(variableId) ?: return
viewModelScope.launch {
val shortcutNames = getShortcutNamesWhereVariableIsInUse(variableId)
dialogState = getDeletionDialog(
variableId = variableId,
title = variable.key,
message = getDeletionMessage(shortcutNames),
viewModel = this@VariablesViewModel,
)
}
}
private suspend fun getShortcutNamesWhereVariableIsInUse(variableId: VariableId): List<String> {
val variableLookup = VariableManager(variables)
// TODO: Also check if the variable is used inside another variable
return shortcutRepository.getShortcuts()
.filter { shortcut ->
VariableResolver.extractVariableIds(shortcut, variableLookup)
.contains(variableId)
}
.map { shortcut ->
shortcut.name
}
.distinct()
}
private fun getDeletionMessage(shortcutNames: List<String>): Localizable =
if (shortcutNames.isEmpty()) {
StringResLocalizable(R.string.confirm_delete_variable_message)
} else {
Localizable.create { context ->
context.getString(R.string.confirm_delete_variable_message)
.plus("\n\n")
.plus(
context.resources.getQuantityString(
R.plurals.warning_variable_still_in_use_in_shortcuts,
shortcutNames.size,
shortcutNames.joinToString(),
shortcutNames.size,
)
)
}
}
fun onDeletionConfirmed(variableId: VariableId) {
val variable = getVariable(variableId) ?: return
launchWithProgressTracking {
variableRepository.deleteVariable(variableId)
showSnackbar(StringResLocalizable(R.string.variable_deleted, variable.key))
recomputeUsedVariableIds()
}
}
fun onBackPressed() {
viewModelScope.launch {
waitForOperationsToFinish()
finish()
}
}
fun onStart() {
viewModelScope.launch {
recomputeUsedVariableIds()
}
}
private suspend fun recomputeUsedVariableIds() {
tryOrLog {
usedVariableIds = getUsedVariableIdsUseCase()
}
}
fun onSortButtonClicked() {
launchWithProgressTracking {
variableRepository.sortVariablesAlphabetically()
showSnackbar(R.string.message_variables_sorted)
}
}
}
| mit | afdf740534bba3afe26685ce0675a124 | 35.269231 | 139 | 0.667126 | 5.07262 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/internal/javaInternalUastUtils.kt | 3 | 3852 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.openapi.util.Key
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastBinaryOperator
import java.lang.ref.WeakReference
internal val JAVA_CACHED_UELEMENT_KEY = Key.create<WeakReference<UElement>>("cached-java-uelement")
internal fun IElementType.getOperatorType() = when (this) {
JavaTokenType.EQ -> UastBinaryOperator.ASSIGN
JavaTokenType.PLUS -> UastBinaryOperator.PLUS
JavaTokenType.MINUS -> UastBinaryOperator.MINUS
JavaTokenType.ASTERISK -> UastBinaryOperator.MULTIPLY
JavaTokenType.DIV -> UastBinaryOperator.DIV
JavaTokenType.PERC -> UastBinaryOperator.MOD
JavaTokenType.ANDAND -> UastBinaryOperator.LOGICAL_AND
JavaTokenType.OROR -> UastBinaryOperator.LOGICAL_OR
JavaTokenType.OR -> UastBinaryOperator.BITWISE_OR
JavaTokenType.AND -> UastBinaryOperator.BITWISE_AND
JavaTokenType.XOR -> UastBinaryOperator.BITWISE_XOR
JavaTokenType.EQEQ -> UastBinaryOperator.IDENTITY_EQUALS
JavaTokenType.NE -> UastBinaryOperator.IDENTITY_NOT_EQUALS
JavaTokenType.GT -> UastBinaryOperator.GREATER
JavaTokenType.GE -> UastBinaryOperator.GREATER_OR_EQUALS
JavaTokenType.LT -> UastBinaryOperator.LESS
JavaTokenType.LE -> UastBinaryOperator.LESS_OR_EQUALS
JavaTokenType.LTLT -> UastBinaryOperator.SHIFT_LEFT
JavaTokenType.GTGT -> UastBinaryOperator.SHIFT_RIGHT
JavaTokenType.GTGTGT -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT
JavaTokenType.PLUSEQ -> UastBinaryOperator.PLUS_ASSIGN
JavaTokenType.MINUSEQ -> UastBinaryOperator.MINUS_ASSIGN
JavaTokenType.ASTERISKEQ -> UastBinaryOperator.MULTIPLY_ASSIGN
JavaTokenType.DIVEQ -> UastBinaryOperator.DIVIDE_ASSIGN
JavaTokenType.PERCEQ -> UastBinaryOperator.REMAINDER_ASSIGN
JavaTokenType.ANDEQ -> UastBinaryOperator.AND_ASSIGN
JavaTokenType.XOREQ -> UastBinaryOperator.XOR_ASSIGN
JavaTokenType.OREQ -> UastBinaryOperator.OR_ASSIGN
JavaTokenType.LTLTEQ -> UastBinaryOperator.SHIFT_LEFT_ASSIGN
JavaTokenType.GTGTEQ -> UastBinaryOperator.SHIFT_RIGHT_ASSIGN
JavaTokenType.GTGTGTEQ -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN
else -> UastBinaryOperator.OTHER
}
internal fun <T> singletonListOrEmpty(element: T?) = if (element != null) listOf(element) else emptyList<T>()
@Suppress("NOTHING_TO_INLINE")
internal inline fun String?.orAnonymous(kind: String = ""): String {
return this ?: "<anonymous" + (if (kind.isNotBlank()) " $kind" else "") + ">"
}
internal fun <T> lz(initializer: () -> T) = lazy(LazyThreadSafetyMode.SYNCHRONIZED, initializer)
val PsiModifierListOwner.annotations: Array<PsiAnnotation>
get() = modifierList?.annotations ?: emptyArray()
internal inline fun <reified T : UDeclaration, reified P : PsiElement> unwrap(element: P): P {
val unwrapped = if (element is T) element.psi else element
assert(unwrapped !is UElement)
return unwrapped as P
}
internal fun PsiElement.getChildByRole(role: Int) = (this as? CompositeElement)?.findChildByRoleAsPsiElement(role) | apache-2.0 | 037e4ef452e5babe07f0b2b4877b072f | 44.329412 | 114 | 0.791537 | 4.531765 | false | false | false | false |
vivchar/RendererRecyclerViewAdapter | example/src/main/java/com/github/vivchar/example/UIRouter.kt | 1 | 1177 | package com.github.vivchar.example
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.github.vivchar.example.pages.github.GithubFragment
import com.github.vivchar.example.pages.simple.*
/**
* Created by Vivchar Vitaly on 12/28/17.
*/
class UIRouter(context: AppCompatActivity) {
private val fragmentManager: FragmentManager = context.supportFragmentManager
private fun showFragment(fragment: BaseScreenFragment) {
try {
fragmentManager.beginTransaction()
.replace(R.id.screen_container, fragment, fragment::class.simpleName)
.commitAllowingStateLoss()
} catch (ignored: IllegalStateException) {
}
}
fun openViewRendererPage() = showFragment(ViewRendererFragment())
fun openCompositeViewRendererPage() = showFragment(CompositeViewRendererFragment())
fun openViewStatePage() = showFragment(ViewStateFragment())
fun openDiffUtilPage() = showFragment(DiffUtilFragment())
fun openPayloadPage() = showFragment(PayloadFragment())
fun openLoadMorePage() = showFragment(LoadMoreFragment())
fun openInputsPage() = showFragment(InputsFragment())
fun openGithubPage() = showFragment(GithubFragment())
} | apache-2.0 | f37d6be3f4de30503ca76a819a37548f | 37 | 84 | 0.797791 | 4.218638 | false | false | false | false |
h0tk3y/better-parse | src/commonMain/kotlin/generated/andFunctions.kt | 1 | 12417 | @file:Suppress(
"NO_EXPLICIT_RETURN_TYPE_IN_API_MODE", // fixme: bug in Kotlin 1.4.21, fixed in 1.4.30
"MoveLambdaOutsideParentheses",
"PackageDirectoryMismatch"
)
package com.github.h0tk3y.betterParse.combinators
import com.github.h0tk3y.betterParse.utils.*
import com.github.h0tk3y.betterParse.parser.*
import kotlin.jvm.JvmName
@JvmName("and2") public inline infix fun <reified T1, reified T2, reified T3>
AndCombinator<Tuple2<T1, T2>>.and(p3: Parser<T3>)
// : AndCombinator<Tuple3<T1, T2, T3>> =
= AndCombinator(consumersImpl + p3, {
Tuple3(it[0] as T1, it[1] as T2, it[2] as T3)
})
@JvmName("and2Operator") public inline operator fun <reified T1, reified T2, reified T3>
AndCombinator<Tuple2<T1, T2>>.times(p3: Parser<T3>)
// : AndCombinator<Tuple3<T1, T2, T3>> =
= this and p3
@JvmName("and3") public inline infix fun <reified T1, reified T2, reified T3, reified T4>
AndCombinator<Tuple3<T1, T2, T3>>.and(p4: Parser<T4>)
// : AndCombinator<Tuple4<T1, T2, T3, T4>> =
= AndCombinator(consumersImpl + p4, {
Tuple4(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4)
})
@JvmName("and3Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4>
AndCombinator<Tuple3<T1, T2, T3>>.times(p4: Parser<T4>)
// : AndCombinator<Tuple4<T1, T2, T3, T4>> =
= this and p4
@JvmName("and4") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5>
AndCombinator<Tuple4<T1, T2, T3, T4>>.and(p5: Parser<T5>)
// : AndCombinator<Tuple5<T1, T2, T3, T4, T5>> =
= AndCombinator(consumersImpl + p5, {
Tuple5(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5)
})
@JvmName("and4Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5>
AndCombinator<Tuple4<T1, T2, T3, T4>>.times(p5: Parser<T5>)
// : AndCombinator<Tuple5<T1, T2, T3, T4, T5>> =
= this and p5
@JvmName("and5") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6>
AndCombinator<Tuple5<T1, T2, T3, T4, T5>>.and(p6: Parser<T6>)
// : AndCombinator<Tuple6<T1, T2, T3, T4, T5, T6>> =
= AndCombinator(consumersImpl + p6, {
Tuple6(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6)
})
@JvmName("and5Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6>
AndCombinator<Tuple5<T1, T2, T3, T4, T5>>.times(p6: Parser<T6>)
// : AndCombinator<Tuple6<T1, T2, T3, T4, T5, T6>> =
= this and p6
@JvmName("and6") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7>
AndCombinator<Tuple6<T1, T2, T3, T4, T5, T6>>.and(p7: Parser<T7>)
// : AndCombinator<Tuple7<T1, T2, T3, T4, T5, T6, T7>> =
= AndCombinator(consumersImpl + p7, {
Tuple7(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7)
})
@JvmName("and6Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7>
AndCombinator<Tuple6<T1, T2, T3, T4, T5, T6>>.times(p7: Parser<T7>)
// : AndCombinator<Tuple7<T1, T2, T3, T4, T5, T6, T7>> =
= this and p7
@JvmName("and7") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8>
AndCombinator<Tuple7<T1, T2, T3, T4, T5, T6, T7>>.and(p8: Parser<T8>)
// : AndCombinator<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>> =
= AndCombinator(consumersImpl + p8, {
Tuple8(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8)
})
@JvmName("and7Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8>
AndCombinator<Tuple7<T1, T2, T3, T4, T5, T6, T7>>.times(p8: Parser<T8>)
// : AndCombinator<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>> =
= this and p8
@JvmName("and8") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9>
AndCombinator<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>>.and(p9: Parser<T9>)
// : AndCombinator<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>> =
= AndCombinator(consumersImpl + p9, {
Tuple9(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9)
})
@JvmName("and8Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9>
AndCombinator<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>>.times(p9: Parser<T9>)
// : AndCombinator<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>> =
= this and p9
@JvmName("and9") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10>
AndCombinator<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.and(p10: Parser<T10>)
// : AndCombinator<Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>> =
= AndCombinator(consumersImpl + p10, {
Tuple10(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10)
})
@JvmName("and9Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10>
AndCombinator<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.times(p10: Parser<T10>)
// : AndCombinator<Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>> =
= this and p10
@JvmName("and10") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11>
AndCombinator<Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.and(p11: Parser<T11>)
// : AndCombinator<Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>> =
= AndCombinator(consumersImpl + p11, {
Tuple11(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11)
})
@JvmName("and10Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11>
AndCombinator<Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.times(p11: Parser<T11>)
// : AndCombinator<Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>> =
= this and p11
@JvmName("and11") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12>
AndCombinator<Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.and(p12: Parser<T12>)
// : AndCombinator<Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> =
= AndCombinator(consumersImpl + p12, {
Tuple12(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11, it[11] as T12)
})
@JvmName("and11Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12>
AndCombinator<Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.times(p12: Parser<T12>)
// : AndCombinator<Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> =
= this and p12
@JvmName("and12") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13>
AndCombinator<Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.and(p13: Parser<T13>)
// : AndCombinator<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>> =
= AndCombinator(consumersImpl + p13, {
Tuple13(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11, it[11] as T12, it[12] as T13)
})
@JvmName("and12Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13>
AndCombinator<Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.times(p13: Parser<T13>)
// : AndCombinator<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>> =
= this and p13
@JvmName("and13") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14>
AndCombinator<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>>.and(p14: Parser<T14>)
// : AndCombinator<Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>> =
= AndCombinator(consumersImpl + p14, {
Tuple14(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11, it[11] as T12, it[12] as T13, it[13] as T14)
})
@JvmName("and13Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14>
AndCombinator<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>>.times(p14: Parser<T14>)
// : AndCombinator<Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>> =
= this and p14
@JvmName("and14") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15>
AndCombinator<Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>>.and(p15: Parser<T15>)
// : AndCombinator<Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>> =
= AndCombinator(consumersImpl + p15, {
Tuple15(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11, it[11] as T12, it[12] as T13, it[13] as T14, it[14] as T15)
})
@JvmName("and14Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15>
AndCombinator<Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>>.times(p15: Parser<T15>)
// : AndCombinator<Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>> =
= this and p15
@JvmName("and15") public inline infix fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16>
AndCombinator<Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>>.and(p16: Parser<T16>)
// : AndCombinator<Tuple16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>> =
= AndCombinator(consumersImpl + p16, {
Tuple16(it[0] as T1, it[1] as T2, it[2] as T3, it[3] as T4, it[4] as T5, it[5] as T6, it[6] as T7, it[7] as T8, it[8] as T9, it[9] as T10, it[10] as T11, it[11] as T12, it[12] as T13, it[13] as T14, it[14] as T15, it[15] as T16)
})
@JvmName("and15Operator") public inline operator fun <reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16>
AndCombinator<Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>>.times(p16: Parser<T16>)
// : AndCombinator<Tuple16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>> =
= this and p16
| apache-2.0 | a0368bc1f1bfdcff0b4f755a6a1a01bc | 63.336788 | 252 | 0.641701 | 2.379647 | false | false | false | false |
intrigus/jtransc | jtransc-core/src/com/jtransc/ast/ast_transform.kt | 2 | 694 | package com.jtransc.ast
fun AstMethod.transformInplace(transform: BuilderBase.(AstElement) -> AstElement) {
if (this.body != null) {
val base = BuilderBase(this.types)
object : AstVisitor() {
override fun visit(stm: AstStm?) {
super.visit(stm)
if (stm != null) {
val transformedStm = base.transform(stm)
if (stm != transformedStm) {
stm.replaceWith(transformedStm as AstStm)
}
}
}
override fun visit(expr: AstExpr?) {
super.visit(expr)
if (expr != null) {
val transformedExpr = base.transform(expr)
if (expr != transformedExpr) {
expr.replaceWith(transformedExpr as AstExpr)
}
}
}
}.visit(this.body!!)
}
}
| apache-2.0 | 45538c82db90754e3dcbfe32126dae03 | 23.785714 | 83 | 0.632565 | 3.242991 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/tools/util/BRDateUtil.kt | 1 | 2315 | /**
* BreadWallet
*
* Created by Mihail Gutan on <[email protected]> 6/8/17.
* Copyright (c) 2017 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.util
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
object BRDateUtil {
private val timeFormat
get() = SimpleDateFormat("h:mm a", Locale.getDefault())
private val shortDateFormat
get() = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
private val fullDateTimeFormat
get() = SimpleDateFormat("MMMM dd, yyyy, hh:mm a", Locale.getDefault())
fun getTime(timestamp: Long): String {
val calendar = Calendar.getInstance(Locale.getDefault())
calendar.timeInMillis = timestamp
return timeFormat.format(calendar.timeInMillis)
}
fun getShortDate(timestamp: Long): String {
val calendar = Calendar.getInstance(Locale.getDefault())
calendar.timeInMillis = timestamp
return shortDateFormat.format(calendar.timeInMillis)
}
fun getFullDate(timestamp: Long): String {
val calendar = Calendar.getInstance(Locale.getDefault())
calendar.timeInMillis = timestamp
return fullDateTimeFormat.format(calendar.timeInMillis)
}
} | mit | cb645a33aaf9fba3bb4b9e83984979e8 | 38.931034 | 80 | 0.732181 | 4.657948 | false | false | false | false |
timakden/advent-of-code | src/main/kotlin/ru/timakden/aoc/year2016/day04/Puzzle.kt | 1 | 2134 | package ru.timakden.aoc.year2016.day04
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solvePartOne(input)}")
println("Part Two: ${solvePartTwo(input)}")
}
}
fun solvePartOne(input: List<String>): Int {
val realRooms = input.filter(isRealRoom)
return realRooms.fold(0) { acc, s ->
val id = s.substring(s.lastIndexOf('-') + 1, s.indexOf('[')).toInt()
acc + id
}
}
fun solvePartTwo(input: List<String>): Int {
val realRooms = input.filter(isRealRoom)
realRooms.forEach {
val encryptedName = it.substringBeforeLast('-')
val id = it.substring(it.lastIndexOf('-') + 1, it.indexOf('[')).toInt()
val decryptedName = decryptRoomName(encryptedName, id)
if (decryptedName == "northpole object storage") return id
}
return 0
}
private val isRealRoom: (String) -> Boolean = {
val encryptedName = it.substringBeforeLast('-').replace("-", "")
val checksum = it.substring(it.indexOf('[') + 1, it.indexOf(']'))
calculateChecksum(encryptedName) == checksum
}
private fun calculateChecksum(encryptedName: String): String {
val map = sortedMapOf<Char, Int>()
encryptedName.forEach {
var count = map[it] ?: 0
map[it] = ++count
}
val newMap = mutableMapOf<Char, Int>()
for (i in 0..4) {
val entry = map.maxByOrNull { it.value }
entry?.let {
newMap[it.key] = it.value
map.remove(it.key)
}
}
var checksum = ""
newMap.forEach { checksum += it.key.toString() }
return checksum
}
private fun decryptRoomName(encryptedName: String, id: Int): String {
var decryptedName = ""
encryptedName.forEach {
var nextLetter = it
repeat((1..id).count()) { nextLetter = getNextLetter(nextLetter) }
decryptedName += nextLetter.toString()
}
return decryptedName
}
private fun getNextLetter(char: Char): Char {
return when (char) {
' ' -> ' '
'-' -> ' '
'z' -> 'a'
else -> char + 1
}
}
| apache-2.0 | 3b7cdd714fa6d96aeda6069fa927fb2f | 25.675 | 79 | 0.603093 | 3.824373 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/core/src/main/java/okhttp3/internal/publicsuffix/PublicSuffix.kt | 1 | 13967 | /*
* Copyright (C) 2017 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 okhttp3.internal.publicsuffix
import okhttp3.internal.and
import okhttp3.internal.platform.Platform
import okio.GzipSource
import okio.buffer
import okio.source
import java.io.IOException
import java.io.InterruptedIOException
import java.net.IDN
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
/**
* A database of public suffixes provided by [publicsuffix.org][publicsuffix_org].
*
* [publicsuffix_org]: https://publicsuffix.org/
*/
class PublicSuffix {
/** True after we've attempted to read the list for the first time. */
private val listRead = AtomicBoolean(false)
/** Used for concurrent threads reading the list for the first time. */
private val readCompleteLatch = CountDownLatch(1)
// The lists are held as a large array of UTF-8 bytes. This is to avoid allocating lots of strings
// that will likely never be used. Each rule is separated by '\n'. Please see the
// PublicSuffixListGenerator class for how these lists are generated.
// Guarded by this.
private lateinit var publicSuffixListBytes: ByteArray
private lateinit var publicSuffixExceptionListBytes: ByteArray
/**
* Returns the effective top-level domain plus one (eTLD+1) by referencing the public suffix list.
* Returns null if the domain is a public suffix or a private address.
*
* Here are some examples:
*
* ```
* assertEquals("google.com", getEffectiveTldPlusOne("google.com"));
* assertEquals("google.com", getEffectiveTldPlusOne("www.google.com"));
* assertNull(getEffectiveTldPlusOne("com"));
* assertNull(getEffectiveTldPlusOne("localhost"));
* assertNull(getEffectiveTldPlusOne("mymacbook"));
* ```
*
* @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode
* encoded.
*/
fun getEffectiveTldPlusOne(domain: String): String? {
if (domain.isEmpty()) return null
// We use UTF-8 in the list so we need to convert to Unicode.
val unicodeDomain = IDN.toUnicode(domain)
val domainLabels = splitDomain(unicodeDomain)
if (domainLabels.size < 2 || domainLabels.contains("")) return null
val rule = findMatchingRule(domainLabels)
if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {
return null // The domain is a public suffix.
}
val firstLabelOffset = if (rule[0][0] == EXCEPTION_MARKER) {
// Exception rules hold the effective TLD plus one.
domainLabels.size - rule.size
} else {
// Otherwise the rule is for a public suffix, so we must take one more label.
domainLabels.size - (rule.size + 1)
}
return splitDomain(domain).asSequence().drop(firstLabelOffset).joinToString(".")
}
fun isIncludeSuffix(domain: String): Boolean {
val unicodeDomain = IDN.toUnicode(domain)
val domainLabels = splitDomain(unicodeDomain)
val rule = findMatchingRule(domainLabels)
if (rule.size == 1 && rule[0] == "*") {
return false
}
if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {
return false // The domain is a public suffix.
}
return true
}
private fun splitDomain(domain: String): List<String> {
val domainLabels = domain.split('.')
if (domainLabels.last() == "") {
// allow for domain name trailing dot
return domainLabels.dropLast(1)
}
return domainLabels
}
private fun findMatchingRule(domainLabels: List<String>): List<String> {
if (!listRead.get() && listRead.compareAndSet(false, true)) {
readTheListUninterruptibly()
} else {
try {
readCompleteLatch.await()
} catch (_: InterruptedException) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
check(::publicSuffixListBytes.isInitialized) {
"Unable to load $PUBLIC_SUFFIX_RESOURCE resource from the classpath."
}
// Break apart the domain into UTF-8 labels, i.e. foo.bar.com turns into [foo, bar, com].
val domainLabelsUtf8Bytes =
Array(domainLabels.size) { i -> domainLabels[i].toByteArray(UTF_8) }
// Start by looking for exact matches. We start at the leftmost label. For example, foo.bar.com
// will look like: [foo, bar, com], [bar, com], [com]. The longest matching rule wins.
var exactMatch: String? = null
for (i in domainLabelsUtf8Bytes.indices) {
val rule = publicSuffixListBytes.binarySearch(domainLabelsUtf8Bytes, i)
if (rule != null) {
exactMatch = rule
break
}
}
// In theory, wildcard rules are not restricted to having the wildcard in the leftmost position.
// In practice, wildcards are always in the leftmost position. For now, this implementation
// cheats and does not attempt every possible permutation. Instead, it only considers wildcards
// in the leftmost position. We assert this fact when we generate the public suffix file. If
// this assertion ever fails we'll need to refactor this implementation.
var wildcardMatch: String? = null
if (domainLabelsUtf8Bytes.size > 1) {
val labelsWithWildcard = domainLabelsUtf8Bytes.clone()
for (labelIndex in 0 until labelsWithWildcard.size - 1) {
labelsWithWildcard[labelIndex] = WILDCARD_LABEL
val rule = publicSuffixListBytes.binarySearch(labelsWithWildcard, labelIndex)
if (rule != null) {
wildcardMatch = rule
break
}
}
}
// Exception rules only apply to wildcard rules, so only try it if we matched a wildcard.
var exception: String? = null
if (wildcardMatch != null) {
for (labelIndex in 0 until domainLabelsUtf8Bytes.size - 1) {
val rule = publicSuffixExceptionListBytes.binarySearch(
domainLabelsUtf8Bytes, labelIndex
)
if (rule != null) {
exception = rule
break
}
}
}
if (exception != null) {
// Signal we've identified an exception rule.
exception = "!$exception"
return exception.split('.')
} else if (exactMatch == null && wildcardMatch == null) {
return PREVAILING_RULE
}
val exactRuleLabels = exactMatch?.split('.') ?: listOf()
val wildcardRuleLabels = wildcardMatch?.split('.') ?: listOf()
return if (exactRuleLabels.size > wildcardRuleLabels.size) {
exactRuleLabels
} else {
wildcardRuleLabels
}
}
/**
* Reads the public suffix list treating the operation as uninterruptible. We always want to read
* the list otherwise we'll be left in a bad state. If the thread was interrupted prior to this
* operation, it will be re-interrupted after the list is read.
*/
private fun readTheListUninterruptibly() {
var interrupted = false
try {
while (true) {
try {
readTheList()
return
} catch (_: InterruptedIOException) {
Thread.interrupted() // Temporarily clear the interrupted state.
interrupted = true
} catch (e: IOException) {
Platform.get().log("Failed to read public suffix list", Platform.WARN, e)
return
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
}
@Throws(IOException::class)
private fun readTheList() {
var publicSuffixListBytes: ByteArray?
var publicSuffixExceptionListBytes: ByteArray?
val resource =
PublicSuffix::class.java.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE) ?: return
GzipSource(resource.source()).buffer().use { bufferedSource ->
val totalBytes = bufferedSource.readInt()
publicSuffixListBytes = bufferedSource.readByteArray(totalBytes.toLong())
val totalExceptionBytes = bufferedSource.readInt()
publicSuffixExceptionListBytes =
bufferedSource.readByteArray(totalExceptionBytes.toLong())
}
synchronized(this) {
this.publicSuffixListBytes = publicSuffixListBytes!!
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes!!
}
readCompleteLatch.countDown()
}
/** Visible for testing. */
fun setListBytes(
publicSuffixListBytes: ByteArray,
publicSuffixExceptionListBytes: ByteArray
) {
this.publicSuffixListBytes = publicSuffixListBytes
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes
listRead.set(true)
readCompleteLatch.countDown()
}
companion object {
const val PUBLIC_SUFFIX_RESOURCE = "/okhttp3/internal/publicsuffix/publicsuffixes.gz"
private val WILDCARD_LABEL = byteArrayOf('*'.toByte())
private val PREVAILING_RULE = listOf("*")
private const val EXCEPTION_MARKER = '!'
private val instance = PublicSuffix()
fun get(): PublicSuffix {
return instance
}
private fun ByteArray.binarySearch(
labels: Array<ByteArray>,
labelIndex: Int
): String? {
var low = 0
var high = size
var match: String? = null
while (low < high) {
var mid = (low + high) / 2
// Search for a '\n' that marks the start of a value. Don't go back past the start of the
// array.
while (mid > -1 && this[mid] != '\n'.toByte()) {
mid--
}
mid++
// Now look for the ending '\n'.
var end = 1
while (this[mid + end] != '\n'.toByte()) {
end++
}
val publicSuffixLength = mid + end - mid
// Compare the bytes. Note that the file stores UTF-8 encoded bytes, so we must compare the
// unsigned bytes.
var compareResult: Int
var currentLabelIndex = labelIndex
var currentLabelByteIndex = 0
var publicSuffixByteIndex = 0
var expectDot = false
while (true) {
val byte0: Int
if (expectDot) {
byte0 = '.'.toInt()
expectDot = false
} else {
byte0 = labels[currentLabelIndex][currentLabelByteIndex] and 0xff
}
val byte1 = this[mid + publicSuffixByteIndex] and 0xff
compareResult = byte0 - byte1
if (compareResult != 0) break
publicSuffixByteIndex++
currentLabelByteIndex++
if (publicSuffixByteIndex == publicSuffixLength) break
if (labels[currentLabelIndex].size == currentLabelByteIndex) {
// We've exhausted our current label. Either there are more labels to compare, in which
// case we expect a dot as the next character. Otherwise, we've checked all our labels.
if (currentLabelIndex == labels.size - 1) {
break
} else {
currentLabelIndex++
currentLabelByteIndex = -1
expectDot = true
}
}
}
if (compareResult < 0) {
high = mid - 1
} else if (compareResult > 0) {
low = mid + end + 1
} else {
// We found a match, but are the lengths equal?
val publicSuffixBytesLeft = publicSuffixLength - publicSuffixByteIndex
var labelBytesLeft = labels[currentLabelIndex].size - currentLabelByteIndex
for (i in currentLabelIndex + 1 until labels.size) {
labelBytesLeft += labels[i].size
}
if (labelBytesLeft < publicSuffixBytesLeft) {
high = mid - 1
} else if (labelBytesLeft > publicSuffixBytesLeft) {
low = mid + end + 1
} else {
// Found a match.
match = String(this, mid, publicSuffixLength, UTF_8)
break
}
}
}
return match
}
}
}
| apache-2.0 | 26e5a7d3b03899f39ccc5247b80eef88 | 37.476584 | 111 | 0.573781 | 5.29053 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlBoxGeneTest.kt | 1 | 590 | package org.evomaster.core.search.gene.sql.geometric
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class SqlBoxGeneTest {
val rand = Randomness().apply { updateSeed(42) }
@Test
fun testGetValueAsPrintableString() {
val gene = SqlBoxGene("box")
gene.doInitialize(rand)
gene.p.x.value=0f
gene.p.y.value=1f
gene.q.x.value=2f
gene.q.y.value=3f
assertEquals("\"((0.0, 1.0), (2.0, 3.0))\"",gene.getValueAsPrintableString())
}
} | lgpl-3.0 | 430d2c18143e5f5e716b02f12c1701e9 | 27.142857 | 85 | 0.667797 | 3.450292 | false | true | false | false |
windchopper/process-browser | src/main/kotlin/com/github/windchopper/tools/process/browser/Application.kt | 1 | 2984 | package com.github.windchopper.tools.process.browser
import com.github.windchopper.common.fx.cdi.ResourceBundleLoad
import com.github.windchopper.common.fx.cdi.form.StageFormLoad
import com.github.windchopper.common.preferences.PreferencesEntryFlatCollectionType
import com.github.windchopper.common.preferences.entries.BufferedEntry
import com.github.windchopper.common.preferences.entries.StandardEntry
import com.github.windchopper.common.preferences.storages.PlatformStorage
import com.github.windchopper.common.preferences.types.*
import com.github.windchopper.common.util.ClassPathResource
import jakarta.enterprise.inject.spi.CDI
import javafx.stage.Stage
import org.jboss.weld.environment.se.Weld
import java.time.Duration
import java.util.*
import java.util.prefs.Preferences
class Application: javafx.application.Application() {
companion object {
const val FXML__PROCESS_LIST = "com/github/windchopper/tools/process/browser/processListStage.fxml"
const val FXML__SELECTION = "com/github/windchopper/tools/process/browser/selectionStage.fxml"
const val FXML__RUN = "com/github/windchopper/tools/process/browser/runStage.fxml"
private val resourceBundle = ResourceBundle.getBundle("com.github.windchopper.tools.process.browser.i18n.messages")
val messages = resourceBundle.keySet().associateWith(resourceBundle::getString)
private val preferencesBufferLifetime = Duration.ofMinutes(1)
private val preferencesStorage = PlatformStorage(Preferences.userRoot().node("com/github/windchopper/tools/process/browser"))
val filterTextPreferencesEntry = BufferedEntry(preferencesBufferLifetime, StandardEntry(preferencesStorage, "filterText", StringType()))
val browseInitialDirectoryPreferencesEntry = BufferedEntry(preferencesBufferLifetime, StandardEntry(preferencesStorage, "browseInitialDirectory", FileType()))
val autoRefreshPreferencesEntry = BufferedEntry(preferencesBufferLifetime, StandardEntry(preferencesStorage, "autoRefresh", BooleanType()))
val autoRefreshTimeoutPreferencesEntry = BufferedEntry(preferencesBufferLifetime, StandardEntry(preferencesStorage, "autoRefreshTimeout", DurationType()))
val recentProcessList = BufferedEntry(preferencesBufferLifetime, StandardEntry(preferencesStorage, "recentProcessList", PreferencesEntryFlatCollectionType(::ArrayList, PathType())))
}
private lateinit var weld: Weld
override fun init() {
weld = Weld().let {
it.initialize()
it
}
}
override fun stop() {
weld.shutdown()
}
override fun start(primaryStage: Stage) {
with (CDI.current().beanManager) {
fireEvent(ResourceBundleLoad(resourceBundle))
fireEvent(StageFormLoad(ClassPathResource(FXML__PROCESS_LIST)) { primaryStage })
}
}
}
fun main(vararg args: String) {
javafx.application.Application.launch(Application::class.java, *args)
} | apache-2.0 | 0d96f79307ffac1a7343e6fa027de2eb | 44.923077 | 189 | 0.771448 | 4.597843 | false | false | false | false |
JimSeker/saveData | sqliteDBViewModelDemo_kt/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo_kt/myAdapter.kt | 1 | 2837 | package edu.cs4730.sqlitedbviewmodeldemo_kt
import androidx.recyclerview.widget.RecyclerView
import android.widget.TextView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.view.View
import edu.cs4730.sqlitedbdemo_kt.db.mySQLiteHelper
import android.widget.Toast
/**
* this adapter is very similar to the adapters used for listview, except a ViewHolder is required
* see http://developer.android.com/training/improving-layouts/smooth-scrolling.html
* except instead having to implement a ViewHolder, it is implemented within
* the adapter.
*/
class myAdapter //constructor
(private var mCursor: Cursor?, private val rowLayout: Int, private val mContext: Context) :
RecyclerView.Adapter<myAdapter.ViewHolder>() {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var myName: TextView
var myScore: TextView
init {
myName = itemView.findViewById(R.id.name)
myScore = itemView.findViewById(R.id.score)
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(rowLayout, viewGroup, false)
return ViewHolder(v)
}
// Replace the contents of a view (invoked by the layout manager)
@SuppressLint("Range")
override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
//this assumes it's not called with a null mCursor, since i means there is a data.
mCursor!!.moveToPosition(i)
viewHolder.myName.text =
mCursor!!.getString(mCursor!!.getColumnIndex(mySQLiteHelper.KEY_NAME))
viewHolder.myScore.text =
mCursor!!.getInt(mCursor!!.getColumnIndex(mySQLiteHelper.KEY_SCORE)).toString()
//itemView is the whole cardview, so it easy to a click listener.
viewHolder.itemView.setOnClickListener { v ->
val tv =
v.findViewById<TextView>(R.id.name) //view in this case is the itemView, which had other pieces in it.
Toast.makeText(mContext, tv.text, Toast.LENGTH_SHORT).show()
}
}
// Return the size of your data set (invoked by the layout manager)
override fun getItemCount(): Int {
return if (mCursor == null) 0 else mCursor!!.count
}
//change the cursor as needed and have the system redraw the data.
fun setCursor(c: Cursor?) {
mCursor = c
notifyDataSetChanged()
}
} | apache-2.0 | bf06fcc59932b4af65abe5d7bd65a348 | 40.130435 | 118 | 0.700035 | 4.453689 | false | false | false | false |
Ufkoku/AndroidMVPHelper | app/src/main/kotlin/com/ufkoku/demo_app/ui/activity/static_list/StaticListActivity.kt | 1 | 4595 | package com.ufkoku.demo_app.ui.activity.static_list
import android.content.Context
import android.content.Intent
import android.widget.Toast
import com.ufkoku.demo_app.R
import com.ufkoku.demo_app.entity.AwesomeEntity
import com.ufkoku.demo_app.ui.common.presenter.StaticListPresenter
import com.ufkoku.demo_app.ui.common.view_state.StaticListViewState
import com.ufkoku.demo_app.ui.lifecycle_listeners.ActivityLifecycleObserver
import com.ufkoku.demo_app.ui.view.DataView
import com.ufkoku.mvp.BaseMvpActivity
import kotlinx.android.synthetic.main.view_data.*
import java.util.*
class StaticListActivity : BaseMvpActivity<IStaticListActivityWrap, StaticListPresenter<IStaticListActivityWrap>, StaticListViewState>(), IStaticListActivity {
companion object {
protected val ARG_RETAIN = "com.ufkoku.demo_app.ui.activity.static_list.StaticListActivity.ARG_RETAIN"
}
private val wrap = IStaticListActivityWrap(this)
private val observer = ActivityLifecycleObserver()
init {
subscribe(observer)
}
//------------------------------------------------------------------------------------//
override fun retainPresenter(): Boolean {
//don't do it in real life, return constant value
val intent = intent
return intent != null && intent.getBooleanExtra(ARG_RETAIN, false)
}
override fun retainViewState(): Boolean {
//don't do it in real life, return constant value
val intent = intent
return intent != null && intent.getBooleanExtra(ARG_RETAIN, false)
}
override fun createView() {
//set view
setContentView(R.layout.view_data)
//init view fields
dataView!!.setListener(object : DataView.ViewListener {
override fun onItemClicked(entity: AwesomeEntity) {
presenter?.processItem(entity)
}
override fun onRetainableClicked() {
startActivity(Builder(true).build(this@StaticListActivity))
}
override fun onSavableClicked() {
startActivity(Builder(false).build(this@StaticListActivity))
}
})
//set title
this.title = if (retainPresenter()) "Retainable" else "Savable"
}
override fun getMvpView(): IStaticListActivityWrap = wrap
override fun createViewState(): StaticListViewState = StaticListViewState()
override fun createPresenter(): StaticListPresenter<IStaticListActivityWrap> = StaticListPresenter()
override fun onInitialized(presenter: StaticListPresenter<IStaticListActivityWrap>, viewState: StaticListViewState) {
//no entities in view state
if (viewState.entities == null) {
//load task not running
if (!presenter.isTaskRunning(StaticListPresenter.TASK_FETCH_DATA)) {
//load data from presenter
presenter.fetchData()
}
}
//invalidate progress visibility anyway
updateProgressVisibility()
}
//------------------------------------------------------------------------------------//
override fun onDataLoaded(data: ArrayList<AwesomeEntity>) {
val state = viewState
if (state != null) {
state.entities = data
}
populateData(data)
}
override fun getViewWidth(): Int = dataView!!.width
override fun onItemProcessed(result: Int) {
Toast.makeText(this,
"Item processed, result is $result",
Toast.LENGTH_LONG).show()
}
override fun populateData(entities: List<AwesomeEntity>) {
dataView?.populateData(entities)
}
override fun onTaskStatusChanged(taskId: Int, status: Int) {
updateProgressVisibility()
}
//---------------------------------------------------------------------------------//
fun updateProgressVisibility() {
val presenter = presenter
if (presenter != null) {
dataView?.setWaitViewVisible(presenter.isTaskRunning(StaticListPresenter.TASK_FETCH_DATA))
}
}
//---------------------------------------------------------------------------------//
class Builder() {
var isRetainElements = false
constructor(retainElements: Boolean) : this() {
this.isRetainElements = retainElements
}
fun build(context: Context): Intent {
val intent = Intent(context, StaticListActivity::class.java)
intent.putExtra(ARG_RETAIN, isRetainElements)
return intent
}
}
} | apache-2.0 | 59699ea2eb1aaddb48ffffcfdda24011 | 31.828571 | 159 | 0.608705 | 5.016376 | false | false | false | false |
Jire/Acelta | src/main/kotlin/com/acelta/world/Position.kt | 1 | 779 | package com.acelta.world
class Position {
companion object {
const val DEFAULT_X = 3222
const val DEFAULT_Y = 3222
const val DEFAULT_Z = 0
}
var x: Int = DEFAULT_X
set(value) {
field = value
regionX = value shr 6
chunkX = (regionX shl 3) + 6
baseX = (chunkX - 6) shl 3
localX = value - baseX
}
var y: Int = DEFAULT_Y
set(value) {
field = value
regionY = value shr 6
chunkY = (regionY shl 3) + 6
baseY = (chunkY - 6) shl 3
localY = value - baseY
}
var z: Int = DEFAULT_Z
var centerX: Int = 0
var centerY: Int = 0
var regionX: Int = 0
var regionY: Int = 0
var chunkX: Int = 0
var chunkY: Int = 0
var baseX: Int = 0
var baseY: Int = 0
var localX: Int = 0
var localY: Int = 0
init {
this.x = x
this.y = y
}
} | gpl-3.0 | ce13a1b5836561a145e051a97d70f173 | 14.918367 | 31 | 0.599487 | 2.605351 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/business/test/adapter/EnvDelegate.kt | 1 | 2257 | package com.binlly.fastpeak.business.test.adapter
import android.content.Context
import android.graphics.Color
import android.support.v7.app.AlertDialog
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.widget.ImageView
import android.widget.TextView
import com.binlly.fastpeak.Build
import com.binlly.fastpeak.R
import com.binlly.fastpeak.base.adapter.BaseDelegate
import com.binlly.fastpeak.business.test.model.TestModel
import com.binlly.fastpeak.service.Services
import com.chad.library.adapter.base.BaseViewHolder
/**
* Created by binlly on 2017/5/13.
*/
class EnvDelegate(context: Context): BaseDelegate<TestModel>(context) {
private var dialog: AlertDialog? = null
override val layoutResId: Int
get() = R.layout.test_item_switch_env
override fun childConvert(holder: BaseViewHolder, item: TestModel) {
val text = holder.getView<TextView>(R.id.env_name)
val icon = holder.getView<ImageView>(R.id.env_selected)
text.text = item.env.value
icon.isSelected = item.env.isSelected
if (item.env.isSelected) {
text.setTextColor(Color.parseColor("#e2001e"))
} else {
text.setTextColor(Color.parseColor("#222222"))
}
holder.itemView.setOnClickListener { showDialog(item.env) }
}
private fun showDialog(env: TestModel.EnvModel) {
if (dialog == null) {
val pre = "切换到"
val suf = "需要杀掉进程重启"
val msgBuilder = SpannableStringBuilder(pre + env.value + suf)
msgBuilder.setSpan(ForegroundColorSpan(Color.parseColor("#e2001e")), pre.length,
pre.length + env.value.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val builder = AlertDialog.Builder(context)
builder.setMessage(msgBuilder.toString())
builder.setPositiveButton("重启") { _, _ ->
Build.env = env.key
Services.app.restartApp(context)
dialog?.dismiss()
}
builder.setNegativeButton("取消") { _, _ -> dialog?.dismiss() }
dialog = builder.create()
}
dialog?.show()
}
}
| mit | e55f881dcc4ff21ed3a5ff641a61b2ab | 34.349206 | 92 | 0.66502 | 4.193974 | false | true | false | false |
AlekseyZhelo/LBM | SimpleGUIApp/src/main/kotlin/com/alekseyzhelo/lbm/gui/simple/util/LauncherUtil.kt | 1 | 2157 | package com.alekseyzhelo.lbm.gui.simple.util
import com.alekseyzhelo.lbm.cli.CLISettings
import com.alekseyzhelo.lbm.core.lattice.LatticeD2Q9
import com.alekseyzhelo.lbm.gui.simple.algs4.FasterStdDraw
import com.alekseyzhelo.lbm.gui.simple.algs4.drawDensityTable
import com.alekseyzhelo.lbm.gui.simple.algs4.drawVelocityNormTable
import com.alekseyzhelo.lbm.gui.simple.algs4.drawVelocityVectorTable
import com.alekseyzhelo.lbm.util.maxDensity
import com.alekseyzhelo.lbm.util.maxVelocityNorm
import com.alekseyzhelo.lbm.util.minDensity
import java.awt.Color
fun setupVisualizer(cli: CLISettings, lattice: LatticeD2Q9, delay: Int = 25): () -> Unit {
return when (cli.headless) {
false -> { ->
val maxVelocityNorm = lattice.maxVelocityNorm()
val minDensity = lattice.minDensity()
val maxDensity = lattice.maxDensity()
val velocityMax = if (cli.noRescale) { -> maxVelocityNorm } else { -> lattice.maxVelocityNorm() }
val densityMin = if (cli.noRescale) { -> minDensity } else { -> lattice.minDensity() }
val densityMax = if (cli.noRescale) { -> maxDensity } else { -> lattice.maxDensity() }
val drawVelocities = cli.drawVelocities
val vectorField = cli.vectorField
{
FasterStdDraw.clear(Color.BLACK)
when (drawVelocities) {
true -> {
when (vectorField) {
true -> lattice.drawVelocityVectorTable(0.0, velocityMax())
false -> lattice.drawVelocityNormTable(0.0, velocityMax())
}
}
false -> lattice.drawDensityTable(densityMin(), densityMax())
}
FasterStdDraw.show(delay);
}
}
true -> { -> { } }
}()
}
fun initGraphicsWindow(cli: CLISettings, width: Int = 750, height: Int = 750) {
if (!cli.headless) {
FasterStdDraw.setCanvasSize(width, height)
FasterStdDraw.setXscale(0.0, cli.lx.toDouble());
FasterStdDraw.setYscale(0.0, cli.ly.toDouble());
}
} | apache-2.0 | b929bff6e4014be5a1df40d83ffc07bb | 41.313725 | 109 | 0.618915 | 4.046904 | false | false | false | false |
roamingthings/dev-workbench | dev-workbench-backend/src/main/kotlin/de/roamingthings/devworkbench/category/domain/Category.kt | 1 | 1813 | package de.roamingthings.devworkbench.category.domain
import de.roamingthings.devworkbench.link.api.CategoryDto
import de.roamingthings.devworkbench.link.api.CreateCategoryDto
import de.roamingthings.devworkbench.link.api.UpdateCategoryDto
import de.roamingthings.devworkbench.link.domain.Link
import javax.persistence.*
/**
*
*
* @author Alexander Sparkowsky [[email protected]]
* @version 2017/07/06
*/
@Entity @Table(name = "category")
internal data class Category(
@Id @GeneratedValue val id: Long? = null,
val code: String,
val linkPattern: String? = null,
val title: String? = null,
@OneToMany(mappedBy = "category", cascade = arrayOf(CascadeType.REMOVE), orphanRemoval = true)
var links: MutableList<Link>? = null
) {
/*
@Suppress("unused")
private constructor() : this(code = "")
*/
fun toDto(): CategoryDto = CategoryDto(
id = this.id!!,
code = this.code,
linkPattern = this.linkPattern,
title = this.title,
linkCount = if (this.links != null) this.links!!.size else 0
)
fun updateFromDto(dto: UpdateCategoryDto) = Category(
id = id!!,
code = dto.code.getOrDefault(code),
linkPattern = dto.linkPattern.getOrNullOrDefault(linkPattern),
title = dto.title.getOrNullOrDefault(title))
companion object {
fun fromDto(dto: CategoryDto) = Category(
id = dto.id,
code = dto.code,
linkPattern = dto.linkPattern,
title = dto.title)
fun fromDto(dto: CreateCategoryDto) = Category(
id = null,
code = dto.code,
linkPattern = dto.linkPattern,
title = dto.title)
}
} | apache-2.0 | c244369850c289eebf89e826ec892c1c | 29.745763 | 102 | 0.610039 | 4.206497 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/physics/TickleMouseJoint.kt | 1 | 3541 | /*
Tickle
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.tickle.physics
import org.jbox2d.dynamics.joints.MouseJoint
import org.jbox2d.dynamics.joints.MouseJointDef
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.Actor
/**
* Attracts an actor towards a point (which is usually the mouse pointer's position).
*
* Each frame, you can update the target position. See [target].
*
* For example, from a Role's tick method, you could use this Kotlin snippet :
*
* actor.stage?.firstView()?.mousePosition()?.let { it }
*
* or in Groovy :
*
* mouseJoint.target( actor.stage.firstView().mousePosition() )
*
* Note. [actorA] and [pointA] are never used (as there's only one actor involved
* with this type of joint).
*
* @param actorB The actor that is affected by this joint
*
* @param target The initial target point (the same as given to the [target] method).
*
* @param maxForce A low value will give a very elastic feel, a high value may cause actorA to be accelerated
* too much. The force should be in proportion to the mass of the actor's body.
*
* @param actorA JBox2D is weird. A mouse joint is unlike the others, in that it only affects
* one body. However, we cannot leave bodyA or bodyB as null (it throws)
* It seems that the "correct" thing to do, is to send in a dummy body as bodyA. Very annoying.
* This joint will have NO affect on actorA, and is here only to keep JBox2D happy!
* However, if you like a dangerous life, you can use the same actor for actorA and actorB.
* It works, but there is an assert in JBox2D's Joint class which would throw if asserts were enabled!
*/
class TickleMouseJoint(
actorB: Actor,
target: Vector2d,
val maxForce: Double,
actorA: Actor = actorB)
: TickleJoint<MouseJoint, MouseJointDef>(actorA, actorB, Vector2d(), target) {
init {
actorB.body?.jBox2DBody?.isAwake = true
create()
}
override fun createDef(): MouseJointDef {
val jointDef = MouseJointDef()
// Hmm Have I got something wrong here? A mouse joint is unlike the others, in that it only affects
// one body. However, we cannot leave bodyA or bodyB as null (it throws), which is why I've set both
// to the same.
// However, Joint's constructor has an assert( bodyA != bodyB ).
// So this only works, because asserts aren't enabled.
// It seems that the "correct" thing to do, is to send in a dummy body as bodyA. Annoying.
jointDef.bodyA = actorB.body!!.jBox2DBody
jointDef.bodyB = actorB.body!!.jBox2DBody
jointDef.maxForce = maxForce.toFloat()
tickleWorld.pixelsToWorld(jointDef.target, pointB)
return jointDef
}
fun target(point: Vector2d) {
jBox2dJoint?.let {
tickleWorld.pixelsToWorld(it.target, point)
}
}
}
| gpl-3.0 | 007af4b0bbb9c4278a6c82793dd47d37 | 38.786517 | 109 | 0.695566 | 3.828108 | false | false | false | false |
t-yoshi/peca-android | core/src/main/java/org/peercast/core/upnp/UpnpWorker.kt | 1 | 2707 | package org.peercast.core.upnp
import android.content.Context
import android.os.Build
import androidx.work.*
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.peercast.core.common.upnp.UpnpManager
import timber.log.Timber
import java.io.IOException
class UpnpWorker(appContext: Context, params: WorkerParameters) :
CoroutineWorker(appContext, params), KoinComponent {
private val upnpManager by inject<UpnpManager>()
override suspend fun doWork(): Result {
val port = inputData.getInt(PARAM_PORT, 7144)
if (port !in 1025..65532) {
Timber.e("invalid port: %d", port)
return Result.failure()
}
val f = when (inputData.getInt(PARAM_OPERATION, -1)) {
OPERATION_OPEN -> upnpManager::addPort
OPERATION_CLOSE -> upnpManager::removePort
else -> throw IllegalArgumentException()
}
try {
f(port)
return Result.success()
} catch (e: IOException) {
Timber.d(e)
} catch (t: Throwable) {
//NOTE: 例外が起きても[androidx.work.impl.WorkerWrapper]内で
//キャッチされるだけ。補足しにくいので注意。
Timber.e(t, "An exception happened in UpnpWorker.")
}
return Result.failure()
}
companion object {
/* open | close*/
private const val PARAM_OPERATION = "operation"
private const val OPERATION_OPEN = 1
private const val OPERATION_CLOSE = 2
private const val PARAM_PORT = "port"
private const val TAG_WORKER = "UpnpWorker"
fun openPort(c: Context, port: Int) {
enqueueOneTimeWorkRequest(c, OPERATION_OPEN, port)
}
fun closePort(c: Context, port: Int) {
enqueueOneTimeWorkRequest(c, OPERATION_CLOSE, port)
}
private fun enqueueOneTimeWorkRequest(c: Context, operation: Int, port: Int) {
val req = OneTimeWorkRequest.Builder(UpnpWorker::class.java)
.addTag(TAG_WORKER)
.setInputData(
Data.Builder()
.putInt(PARAM_OPERATION, operation)
.putInt(PARAM_PORT, port)
.build()
)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
WorkManager.getInstance(c).run {
cancelAllWorkByTag(TAG_WORKER)
enqueue(req)
}
}
}
} | gpl-3.0 | 1179ddaef903fba09e36590e7448316a | 30.52381 | 86 | 0.568946 | 4.486441 | false | false | false | false |
waicool20/SikuliCef | src/main/kotlin/com/waicool20/sikulicef/input/CefMouse.kt | 1 | 3418 | /*
* GPLv3 License
* Copyright (c) SikuliCef by waicool20
*
* 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
*
* 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.waicool20.sikulicef.input
import org.sikuli.basics.Settings
import org.sikuli.script.Location
import org.sikuli.script.Mouse
class CefMouse(val robot: CefRobot) {
@Synchronized
fun click(location: Location, buttons: Int, modifiers: Int) = synchronized(this) {
moveTo(location)
val pause = if (Settings.ClickDelay > 1) 1 else (Settings.ClickDelay * 1000).toInt()
robot.pressModifiers(modifiers)
robot.mouseDown(buttons)
robot.delay(pause)
robot.mouseUp(buttons)
robot.releaseModifiers(modifiers)
Settings.ClickDelay = 0.0
}
@Synchronized
fun doubleClick(location: Location, buttons: Int, modifiers: Int) = synchronized(this) {
repeat(2) {
click(location, buttons, modifiers)
}
}
@Synchronized
fun moveTo(location: Location) = synchronized(this) { robot.smoothMove(location) }
/* Low level actions */
@Synchronized
fun mouseDown(buttons: Int) = synchronized(this) { robot.mouseDown(buttons) }
@Synchronized
fun mouseUp(buttons: Int = 0): Int = synchronized(this) { robot.mouseUp(buttons) }
@Synchronized
fun spinWheel(location: Location, direction: Int, steps: Int, stepDelay: Int) = synchronized(this) {
moveTo(location)
repeat(steps) {
robot.mouseWheel(if (direction < 0) -1 else 1)
robot.delay(stepDelay)
}
}
@Synchronized
fun drag(location: Location, resetDelays: Boolean = true) = synchronized(this) {
moveTo(location)
robot.delay((Settings.DelayBeforeMouseDown * 1000).toInt())
mouseDown(Mouse.LEFT)
robot.delay((if (Settings.DelayBeforeDrag < 0) Settings.DelayAfterDrag else Settings.DelayBeforeDrag).toInt() * 1000)
if (resetDelays) resetDragDelays()
1
}
@Synchronized
fun dropAt(location: Location, resetDelays: Boolean = true) = synchronized(this) {
moveTo(location)
robot.delay((Settings.DelayBeforeDrop * 1000).toInt())
mouseUp(Mouse.LEFT)
if (resetDelays) resetDragDelays()
1
}
@Synchronized
fun dragDrop(loc1: Location, loc2: Location) = synchronized(this) {
drag(loc1, false)
dropAt(loc2)
1
}
@Synchronized
private fun resetDragDelays() {
Settings.DelayBeforeMouseDown = Settings.DelayValue
Settings.DelayAfterDrag = Settings.DelayValue
Settings.DelayBeforeDrag = -Settings.DelayValue
Settings.DelayBeforeDrop = Settings.DelayValue
}
@Synchronized inline fun <T> atomicAction(action: () -> T): T = synchronized(this) { action() }
fun getCurrentMouseLocation() = robot.getCurrentMouseLocation()
}
| gpl-3.0 | 0218fd6812562c6d9eafde3c8ffdd976 | 31.865385 | 125 | 0.674078 | 4.138015 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/DrawerLayoutProperty.kt | 1 | 991 | package com.github.kittinunf.reactiveandroid.support.v4.widget
import android.graphics.drawable.Drawable
import android.support.v4.widget.DrawerLayout
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Properties
//================================================================================
val DrawerLayout.rx_drawerElevation: MutableProperty<Float>
get() {
val getter = { drawerElevation }
val setter: (Float) -> Unit = { drawerElevation = it }
return createMainThreadMutableProperty(getter, setter)
}
val DrawerLayout.rx_statusBarBackground: MutableProperty<Drawable>
get() {
val getter = { statusBarBackgroundDrawable }
val setter: (Drawable) -> Unit = { setStatusBarBackground(it) }
return createMainThreadMutableProperty(getter, setter)
}
| mit | 96711cc2847a77b9324ae60da4f0e815 | 37.115385 | 82 | 0.62664 | 5.695402 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/correios/CorreiosPackageInfoUpdater.kt | 1 | 8685 | package net.perfectdreams.loritta.cinnamon.discord.utils.correios
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.*
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.utils.RunnableCoroutine
import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.CorreiosFoundObjeto
import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.CorreiosUnknownObjeto
import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.EventType
import net.perfectdreams.loritta.cinnamon.pudding.tables.PendingImportantNotifications
import net.perfectdreams.loritta.cinnamon.pudding.tables.TrackedCorreiosPackages
import net.perfectdreams.loritta.cinnamon.pudding.tables.TrackedCorreiosPackagesEvents
import net.perfectdreams.loritta.cinnamon.pudding.tables.UsersFollowingCorreiosPackages
import net.perfectdreams.loritta.cinnamon.pudding.tables.notifications.CorreiosPackageUpdateUserNotifications
import net.perfectdreams.loritta.cinnamon.pudding.tables.notifications.UserNotifications
import net.perfectdreams.loritta.common.utils.PendingImportantNotificationState
import org.jetbrains.exposed.sql.*
import java.time.Instant
import java.time.LocalDateTime
class CorreiosPackageInfoUpdater(val m: LorittaBot) : RunnableCoroutine {
companion object {
private val logger = KotlinLogging.logger {}
val KTX_DATETIME_CORREIOS_OFFSET = UtcOffset(-3)
private val JAVA_TIME_CORREIOS_OFFSET = KTX_DATETIME_CORREIOS_OFFSET.toJavaZoneOffset()
}
override suspend fun run() {
logger.info { "Updating packages information..." }
try {
m.pudding.transaction {
val trackedPackages = TrackedCorreiosPackages.select { TrackedCorreiosPackages.delivered eq false and (TrackedCorreiosPackages.unknownPackage eq false ) }
.map { it[TrackedCorreiosPackages.trackingId] }
if (trackedPackages.isEmpty()) {
logger.info { "No packages need to be tracked, skipping..." }
return@transaction
}
logger.info { "Querying information about packages $trackedPackages" }
val packageInformations = runBlocking {
m.correiosClient.getPackageInfo(
*trackedPackages.toTypedArray()
)
}
val now = Instant.now()
packageInformations.objeto.forEach { correiosPackage ->
when (correiosPackage) {
is CorreiosFoundObjeto -> {
// Check when last event was received
val lastEventReceivedAt = TrackedCorreiosPackagesEvents.select {
TrackedCorreiosPackagesEvents.trackingId eq correiosPackage.numero
}.orderBy(TrackedCorreiosPackagesEvents.triggeredAt, SortOrder.DESC)
.limit(1)
.firstOrNull()
?.getOrNull(TrackedCorreiosPackagesEvents.triggeredAt)
// If this is false, then we won't need to notify the user about package updates, because we are filling our db with all the current events
val hasNeverReceivedAnyEventsBefore = lastEventReceivedAt == null
correiosPackage.events
.let {
if (lastEventReceivedAt != null) // I wanted to use hasNeverReceivedAnyEventsBefore here but Kotlin isn't smart enough to know that it is non null
it.filter {
it.criacao > LocalDateTime.ofEpochSecond(
lastEventReceivedAt.epochSecond,
0,
JAVA_TIME_CORREIOS_OFFSET
)
.toKotlinLocalDateTime()
}
else
it
}
.sortedBy { it.criacao } // the order doesn't really matter because we sort when querying the database, but at least it looks prettier when querying the database without a sort
.forEach { event ->
val packageEventId = TrackedCorreiosPackagesEvents.insertAndGetId {
it[TrackedCorreiosPackagesEvents.trackingId] = correiosPackage.numero
it[TrackedCorreiosPackagesEvents.triggeredAt] = event.criacao.toInstant(KTX_DATETIME_CORREIOS_OFFSET)
.toJavaInstant()
it[TrackedCorreiosPackagesEvents.event] = Json.encodeToString(event)
}
val whoIsTrackingThisPackage = UsersFollowingCorreiosPackages.innerJoin(
TrackedCorreiosPackages
).select {
TrackedCorreiosPackages.trackingId eq correiosPackage.numero
}.map { it[UsersFollowingCorreiosPackages.user] }
if (!hasNeverReceivedAnyEventsBefore) {
for (user in whoIsTrackingThisPackage) {
val userNotificationId = UserNotifications.insertAndGetId {
it[UserNotifications.timestamp] = now
it[UserNotifications.user] = user.value
}
CorreiosPackageUpdateUserNotifications.insert {
it[CorreiosPackageUpdateUserNotifications.timestampLog] = userNotificationId
it[CorreiosPackageUpdateUserNotifications.trackingId] = correiosPackage.numero
it[CorreiosPackageUpdateUserNotifications.packageEvent] = packageEventId
}
PendingImportantNotifications.insert {
it[PendingImportantNotifications.userId] = user.value
it[PendingImportantNotifications.state] = PendingImportantNotificationState.PENDING
it[PendingImportantNotifications.notification] = userNotificationId
it[PendingImportantNotifications.submittedAt] = Instant.now()
}
}
}
if (event.type == EventType.PackageDeliveredToRecipient) {
// If it is delivered, update the status with "delivered"
logger.info { "Package ${correiosPackage.numero} has been delivered! Updating its status in our database..." }
TrackedCorreiosPackages.update({ TrackedCorreiosPackages.trackingId eq correiosPackage.numero }) {
it[TrackedCorreiosPackages.delivered] = true
}
}
}
}
is CorreiosUnknownObjeto -> {
logger.info { "Package ${correiosPackage.numero} is unknown! Updating its status in our database..." }
TrackedCorreiosPackages.update({ TrackedCorreiosPackages.trackingId eq correiosPackage.numero }) {
it[TrackedCorreiosPackages.unknownPackage] = true
}
}
}
}
}
} catch (e: Exception) {
logger.warn(e) { "Something went wrong while updating packages information!" }
}
}
} | agpl-3.0 | 514f02d6be626d174f63c90fed9a0390 | 61.042857 | 208 | 0.5346 | 6.559668 | false | false | false | false |
fare1990/telegram-bot-bumblebee | telegram-bot-api/src/main/kotlin/com/github/telegram/domain/KeyboardReplyMarkup.kt | 2 | 2133 | package com.github.telegram.domain
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
/**
* This object represents a custom keyboard with reply options.
*
* Example: A user requests to change the bot‘s language, bot replies to the request with a keyboard to select the new language.
* Other users in the group don’t see the keyboard.
*
* @property keyboard List of button rows, each represented by an List of KeyboardButton objects
* @property resizeKeyboard Requests clients to resize the keyboard vertically for optimal fit
* (e.g., make the keyboard smaller if there are just two rows of buttons).
* Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
* @property oneTimeKeyboard Requests clients to hide the keyboard as soon as it's been used.
* The keyboard will still be available, but clients will automatically display the usual
* letter-keyboard in the chat – the user can press a special button in the input field
* to see the custom keyboard again. Defaults to false.
* @property selective Use this parameter if you want to show the keyboard to specific users only. Targets:
* 1) users that are @mentioned in the text of the Message object;
* 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
*/
data class KeyboardReplyMarkup(
val keyboard: List<List<String>>,
@SerializedName("resize_keyboard") val resizeKeyboard: Boolean = false,
@SerializedName("one_time_keyboard") val oneTimeKeyboard: Boolean = false,
val selective: Boolean? = null
) : ReplyMarkup {
constructor(
vararg keyboard: String,
resizeKeyboard: Boolean = false,
oneTimeKeyboard: Boolean = false,
selective: Boolean? = null
) : this(listOf(keyboard.toList()), resizeKeyboard, oneTimeKeyboard, selective)
private companion object {
val GSON = Gson()
}
override fun toString(): String = GSON.toJson(this)
} | mit | f9f9501b7cf60b2b3007939929ed6d93 | 49.666667 | 129 | 0.700047 | 4.574194 | false | false | false | false |
toastkidjp/Jitte | article/src/main/java/jp/toastkid/article_viewer/article/detail/ContentLoaderUseCase.kt | 1 | 1981 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.detail
import android.widget.TextView
import io.noties.markwon.Markwon
import jp.toastkid.article_viewer.article.ArticleRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* @author toastkidjp
*/
class ContentLoaderUseCase(
private val repository: ArticleRepository,
private val markwon: Markwon,
private val contentView: TextView,
private val subheads: MutableList<String>,
private val linkGeneratorService: LinkGeneratorService = LinkGeneratorService(),
private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
operator fun invoke(title: String) {
CoroutineScope(mainDispatcher).launch {
val content = withContext(ioDispatcher) { repository.findContentByTitle(title) }
?: return@launch
markwon.setMarkdown(contentView, content)
linkGeneratorService.invoke(contentView)
withContext(defaultDispatcher) {
appendSubheads(content)
}
}
}
private fun appendSubheads(content: String) {
content.split(LINE_SEPARATOR)
.filter { it.startsWith(PREFIX) }
.forEach { subheads.add(it) }
}
companion object {
private const val PREFIX = "#"
private val LINE_SEPARATOR = System.lineSeparator()
}
} | epl-1.0 | 0940acd9929872209cb0a7af50a7a9f5 | 31.491803 | 92 | 0.716305 | 4.989924 | false | false | false | false |
nasahapps/Material-Design-Toolbox | app/src/main/java/com/nasahapps/mdt/example/ui/style/ColorFragment.kt | 1 | 2776 | package com.nasahapps.mdt.example.ui.style
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nasahapps.mdt.Utils
import com.nasahapps.mdt.example.R
import com.nasahapps.mdt.example.ui.BaseFragment
import kotlinx.android.synthetic.main.fragment_color.*
class ColorFragment : BaseFragment() {
companion object {
private val EXTRA_ARRAY = "array"
private val EXTRA_TITLE = "title"
fun newInstance(array: IntArray, title: String): ColorFragment {
val args = Bundle()
args.putIntArray(EXTRA_ARRAY, array)
args.putString(EXTRA_TITLE, title)
val fragment = ColorFragment()
fragment.arguments = args
return fragment
}
}
override fun getLayoutId() = R.layout.fragment_color
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView?.layoutManager = LinearLayoutManager(activity)
recyclerView?.adapter = ColorListAdapter(arguments.getIntArray(EXTRA_ARRAY), arguments.getString(EXTRA_TITLE))
}
class ColorListAdapter(val colorArray: IntArray, val colorName: String) : RecyclerView.Adapter<ColorListAdapter.ViewHolder>() {
override fun getItemCount() = colorArray.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val color = ContextCompat.getColor(holder.itemView.context, colorArray[position])
holder.itemView?.setBackgroundColor(color)
(holder.itemView as? TextView)?.text = "$colorName ${getColorNumber(position)}"
(holder.itemView as? TextView)?.setTextColor(if (Utils.shouldUseWhiteText(color)) Color.WHITE else Color.BLACK)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent?.context)?.inflate(android.R.layout.simple_list_item_1, parent, false)
return ViewHolder(v)
}
inner class ViewHolder(v: View?) : RecyclerView.ViewHolder(v)
private fun getColorNumber(position: Int) = when (position) {
1 -> "100"
2 -> "200"
3 -> "300"
4 -> "400"
5 -> "500"
6 -> "600"
7 -> "700"
8 -> "800"
9 -> "900"
10 -> "A100"
11 -> "A200"
12 -> "A400"
13 -> "A700"
else -> "50"
}
}
} | apache-2.0 | 07a1998532fa2bd2583df0051c307050 | 34.602564 | 131 | 0.646254 | 4.4416 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/offsets/offsets/ClientOffsets.kt | 1 | 5075 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.offsets.offsets
import com.github.jonatino.misc.Strings
import org.xena.offsets.OffsetManager.clientModule
import org.xena.offsets.misc.PatternScanner
import org.xena.offsets.misc.PatternScanner.byPattern
import java.io.IOException
import java.lang.reflect.Field
import java.nio.file.Files
import java.nio.file.Paths
/**
* Created by Jonathan on 11/13/2015.
*/
object ClientOffsets {
/**
* Client.dll offsets
*/
@JvmField var dwRadarBase: Int = 0
@JvmField var dwWeaponTable: Int = 0
@JvmField var dwWeaponTableIndex: Int = 0
@JvmField var dwInput: Int = 0
@JvmField var dwGlowObject: Int = 0
@JvmField var dwForceJump: Int = 0
@JvmField var dwForceAttack: Int = 0
@JvmField var dwViewMatrix: Int = 0
@JvmField var dwEntityList: Int = 0
@JvmField var dwLocalPlayer: Int = 0
@JvmField var bDormant: Int = 0
@JvmField var dwGameRulesProxy: Int = 0
@JvmField var dwMouseEnable: Int = 0
@JvmField var dwMouseEnablePtr: Int = 0
@JvmStatic
fun load() {
dwRadarBase = byPattern(clientModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x0C, 0xB0, 0x8B, 0x01, 0xFF, 0x50, 0x00, 0x46, 0x3B, 0x35, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xEA, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00)
dwWeaponTable = byPattern(clientModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0x39, 0x86, 0x00, 0x00, 0x00, 0x00, 0x74, 0x06, 0x89, 0x86, 0x0, 0x0, 0x0, 0x0, 0x8B, 0x86)
dwWeaponTableIndex = byPattern(clientModule(), 0x2, 0x0, PatternScanner.READ, 0x39, 0x86, 0x00, 0x00, 0x00, 0x00, 0x74, 0x06, 0x89, 0x86, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x86)
dwInput = byPattern(clientModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xB9, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x04, 0x24, 0xFF, 0x50, 0x10)
dwGlowObject = byPattern(clientModule(), 0x1, 0x4, PatternScanner.READ or PatternScanner.SUBTRACT, 0xA1, 0x00, 0x00, 0x00, 0x00, 0xa8, 0x01, 0x75, 0x00, 0x0f, 0x57, 0xc0, 0xc7, 0x05)
dwForceJump = byPattern(clientModule(), 0x2, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0x89, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x8B, 0xF2, 0x8B, 0xC1, 0x83, 0xCE, 0x08)
dwForceAttack = byPattern(clientModule(), 0x2, 0xC, PatternScanner.READ or PatternScanner.SUBTRACT, 0x89, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x8B, 0xF2, 0x8B, 0xC1, 0x83, 0xCE, 0x04)
dwViewMatrix = byPattern(clientModule(), 0x3, 0xb0, PatternScanner.READ or PatternScanner.SUBTRACT, 0x0F, 0x10, 0x05, 0x00, 0x00, 0x00, 0x00, 0x8D, 0x85, 0x00, 0x00, 0x00, 0x00, 0xB9)
dwEntityList = byPattern(clientModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xBB, 0x00, 0x00, 0x00, 0x00, 0x83, 0xFF, 0x01, 0x0F, 0x8C, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xF8)
dwLocalPlayer = byPattern(clientModule(), 3, 4, PatternScanner.READ or PatternScanner.SUBTRACT, 0x8D, 0x34, 0x85, 0x0, 0x0, 0x0, 0x0, 0x89, 0x15, 0x0, 0x0, 0x0, 0x0, 0x8B, 0x41, 0x08, 0x8B, 0x48, 0x04, 0x83, 0xF9, 0xFF)
bDormant = byPattern(clientModule(), 0x2, 0x0, PatternScanner.READ, 0x88, 0x9E, 0x0, 0x0, 0x0, 0x0, 0xE8, 0x0, 0x0, 0x0, 0x0, 0x53, 0x8D, 0x8E, 0x0, 0x0, 0x0, 0x0, 0xE8, 0x0, 0x0, 0x0, 0x0, 0x8B, 0x06, 0x8B, 0xCE, 0x53, 0xFF, 0x90, 0x0, 0x0, 0x0, 0x0, 0x8B, 0x46, 0x64, 0x0F, 0xB6, 0xCB, 0x5E, 0x5B, 0x66, 0x89, 0x0C, 0xC5, 0x0, 0x0, 0x0, 0x0, 0x5D, 0xC2, 0x04, 0x00)
dwGameRulesProxy = byPattern(clientModule(), 1, 0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xA1, 0x0, 0x0, 0x0, 0x0, 0x85, 0xC0, 0x0F, 0x84, 0x0, 0x0, 0x0, 0x0, 0x80, 0xB8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x74, 0x7A)
dwMouseEnable = byPattern(clientModule(), 1, 48, PatternScanner.READ or PatternScanner.SUBTRACT, 0xB9, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x50, 0x34, 0x85, 0xC0, 0x75, 0x10)
dwMouseEnablePtr = byPattern(clientModule(), 1, 0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xB9, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x50, 0x34, 0x85, 0xC0, 0x75, 0x10)
bDormant = 0xEDL.toInt()
}
@JvmStatic
fun dump() {
val text = ClientOffsets::class.java.fields.map { it.name + " -> " + Strings.hex(getValue(it)) }
try {
Files.write(Paths.get("ClientOffsets.txt"), text)
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun getValue(field: Field): Int {
try {
return field.get(ClientOffsets::class.java) as? Int ?: -1
} catch (t: Throwable) {
println(field)
t.printStackTrace()
}
return -1
}
}
| apache-2.0 | 2d1d731fe240ef9190e42b9ca7fb5e5f | 52.989362 | 369 | 0.713498 | 2.381511 | false | false | false | false |
google/horologist | media-ui/src/main/java/com/google/android/horologist/media/ui/components/controls/PlayButton.kt | 1 | 1853 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.ui.components.controls
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.ButtonColors
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.R
@ExperimentalHorologistMediaUiApi
@Composable
public fun PlayButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors,
iconSize: Dp = 30.dp,
tapTargetSize: DpSize = DpSize(60.dp, 60.dp)
) {
MediaButton(
onClick = onClick,
icon = Icons.Default.PlayArrow,
contentDescription = stringResource(id = R.string.horologist_play_button_content_description),
modifier = modifier,
enabled = enabled,
colors = colors,
iconSize = iconSize,
tapTargetSize = tapTargetSize
)
}
| apache-2.0 | 0817e4a32645a48cbb961e06c355d1a8 | 35.333333 | 102 | 0.752294 | 4.230594 | false | false | false | false |
SUPERCILEX/Robot-Scouter | app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/utils/Database.kt | 1 | 2138 | package com.supercilex.robotscouter.server.utils
import com.supercilex.robotscouter.common.FIRESTORE_NAME
import com.supercilex.robotscouter.common.FIRESTORE_NUMBER
import com.supercilex.robotscouter.server.utils.types.CollectionReference
import com.supercilex.robotscouter.server.utils.types.DocumentSnapshot
import com.supercilex.robotscouter.server.utils.types.FieldPaths
import com.supercilex.robotscouter.server.utils.types.Firestore
import com.supercilex.robotscouter.server.utils.types.Query
import com.supercilex.robotscouter.server.utils.types.WriteBatch
import kotlinx.coroutines.async
import kotlinx.coroutines.await
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlin.js.Json
fun DocumentSnapshot.toTeamString() =
"${data()[FIRESTORE_NUMBER]} - ${data()[FIRESTORE_NAME]}: $id"
fun DocumentSnapshot.toTemplateString() = "${data()[FIRESTORE_NAME]}: $id"
fun <T> DocumentSnapshot.getAsMap(fieldPath: String): Map<String, T> = get<Json>(fieldPath).toMap()
suspend fun Firestore.batch(transaction: WriteBatch.() -> Unit) = batch().run {
transaction()
commit().await()
}
suspend fun Query.processInBatches(
batchSize: Int = 100,
action: suspend (DocumentSnapshot) -> Unit
) = coroutineScope {
processInBatches(this@processInBatches, batchSize) {
it.map { async { action(it) } }.awaitAll()
}
}
suspend fun CollectionReference.delete(
batchSize: Int = 100,
middleMan: suspend (DocumentSnapshot) -> Unit = {}
) = coroutineScope {
processInBatches(orderBy(FieldPaths.documentId()), batchSize) { snapshots ->
snapshots.map { async { middleMan(it) } }.awaitAll()
firestore.batch {
snapshots.forEach { delete(it.ref) }
}
}
}
private suspend fun processInBatches(
query: Query,
batchSize: Int,
action: suspend (List<DocumentSnapshot>) -> Unit
) {
val snapshot = query.limit(batchSize).get().await()
if (snapshot.docs.isEmpty()) return
action(snapshot.docs.toList())
processInBatches(query.startAfter(snapshot.docs.last()), batchSize, action)
}
| gpl-3.0 | 2c295722ff833b6c2ffdeb3784a394fd | 34.04918 | 99 | 0.729186 | 4.111538 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/utils/recycler/SimpleItemTouchHelperCallback.kt | 1 | 4297 | /*
* Copyright (C) 2015 Paul Burke
*
* 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.fred.taskgame.utils.recycler
import android.graphics.Canvas
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
/**
* An implementation of [ItemTouchHelper.Callback] that enables basic drag & drop and
* swipe-to-dismiss. Drag events are automatically started by an item long-press.<br></br>
*
* Expects the `RecyclerView.Adapter` to listen for [ ] callbacks and the `RecyclerView.ViewHolder` to implement
* [ItemActionViewHolder].
* @author Paul Burke (ipaulpro)
*/
class SimpleItemTouchHelperCallback(private val adapter: ItemActionAdapter) : ItemTouchHelper.Callback() {
private var startMove: Boolean = false
override fun isLongPressDragEnabled(): Boolean {
return true
}
override fun isItemViewSwipeEnabled(): Boolean {
return true
}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
// Set movement flags based on the layout manager
if (recyclerView.layoutManager is GridLayoutManager) {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
val swipeFlags = 0
return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
} else {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END
return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
}
}
override fun onMove(recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
if (source.itemViewType != target.itemViewType) {
return false
}
// Notify the adapter of the move
adapter.onItemMove(source.adapterPosition, target.adapterPosition)
startMove = true
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {
// Notify the adapter of the swipe
adapter.onItemSwiped(viewHolder.adapterPosition)
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Fade out the view as it is swiped out of the parent's bounds
val alpha = ALPHA_FULL - Math.abs(dX) / viewHolder.itemView.width.toFloat()
viewHolder.itemView.alpha = alpha
viewHolder.itemView.translationX = dX
} else {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
// We only want the active item to change
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
// Let the view holder know that this item is being moved or dragged
val itemViewHolder = viewHolder as ItemActionViewHolder?
itemViewHolder!!.onItemSelected()
adapter.onItemSelected(viewHolder!!.adapterPosition)
}
super.onSelectedChanged(viewHolder, actionState)
}
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
if (startMove) {
adapter.onItemMoveFinished()
startMove = false
}
}
companion object {
val ALPHA_FULL = 1.0f
}
}
| gpl-3.0 | ee2d8cad86e25b23df8ec092ce48929d | 38.063636 | 174 | 0.698627 | 4.97338 | false | false | false | false |
notion/Plumb | compiler/src/main/kotlin/rxjoin/internal/codegen/writer/JoinerMapImplWriter.kt | 2 | 3233 | package rxjoin.internal.codegen.writer
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.JavaFile.Builder
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.TypeVariableName
import rxjoin.Joiner
import rxjoin.JoinerMap
import rxjoin.internal.codegen.Model
import rxjoin.internal.codegen.Model.JoinerModel
import java.util.HashMap
import javax.lang.model.element.Modifier.PRIVATE
import javax.lang.model.element.Modifier.PUBLIC
object JoinerMapImplWriter : AbsWriter<Model>() {
val CLASS_NAME = "JoinerMapImpl"
override fun _write(model: Model): Builder {
val joinerMapImpl = TypeSpec.classBuilder(
CLASS_NAME)
.addSuperinterface(JoinerMap::class.java)
.addModifiers(PUBLIC)
.addField(mapDeclaration())
.addMethod(constructor(
model.joinerModels))
.addMethod(joinerForMethod())
.build();
return JavaFile.builder(PKG_NAME, joinerMapImpl)
}
private fun mapDeclaration(): FieldSpec {
val mapClzName = ClassName.get(Map::class.java)
val classClzName = ClassName.get(Class::class.java)
val joinerClzName = ClassName.get(Joiner::class.java)
val hashMapClzName = ClassName.get(HashMap::class.java)
val parameterizedMap = ParameterizedTypeName.get(mapClzName, classClzName, joinerClzName)
val parameterizedHashMap = ParameterizedTypeName.get(hashMapClzName, classClzName,
joinerClzName)
return FieldSpec.builder(parameterizedMap, "joinerMap")
.addModifiers(PRIVATE)
.initializer("new \$T()", parameterizedHashMap)
.build()
}
private fun constructor(joinerModels: List<JoinerModel>): MethodSpec {
val constructorBuilder = MethodSpec.constructorBuilder()
.addModifiers(PUBLIC)
joinerModels.sortedBy { it.enclosing.simpleName.toString() }.forEach { joiner ->
constructorBuilder.addStatement(
"joinerMap.put(\$T.class, new ${joiner.enclosing.simpleName}_Joiner())",
joiner.enclosing)
}
return constructorBuilder.build()
}
private fun joinerForMethod(): MethodSpec {
val genericT = TypeVariableName.get("T")
val genericR = TypeVariableName.get("R")
val joinerForReturns = ParameterizedTypeName.get(ClassName.get(Joiner::class.java),
genericT, genericR)
val parameterSpec = ParameterSpec.builder(genericT, "t").build()
return MethodSpec.methodBuilder("joinerFor")
.addModifiers(PUBLIC)
.addTypeVariable(genericT)
.addTypeVariable(genericR)
.returns(joinerForReturns)
.addAnnotation(Override::class.java)
.addParameter(parameterSpec)
.addStatement("return joinerMap.get(t.getClass())")
.build()
}
}
| apache-2.0 | 0dc41da924750e5b072a70ac679b5387 | 37.488095 | 97 | 0.664708 | 4.77548 | false | false | false | false |
toastkidjp/Yobidashi_kt | todo/src/main/java/jp/toastkid/todo/view/addition/TaskAdditionBottomSheet.kt | 1 | 7837 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.todo.view.addition
import android.widget.DatePicker
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.RadioButton
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import jp.toastkid.lib.preference.ColorPair
import jp.toastkid.todo.R
import jp.toastkid.todo.model.TodoTask
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.GregorianCalendar
@OptIn(ExperimentalMaterialApi::class)
@Composable
internal fun TaskEditorUi(
screenContent: @Composable () -> Unit,
taskAdditionDialogFragmentViewModel: TaskAdditionDialogFragmentViewModel?,
bottomSheetScaffoldState: ModalBottomSheetState,
onTapAdd: (TodoTask) -> Unit,
colorPair: ColorPair
) {
val task = taskAdditionDialogFragmentViewModel?.task?.observeAsState()?.value
var descriptionInput by remember { mutableStateOf(task?.description ?: "") }
var chosenColor by remember { mutableStateOf(Color.Transparent.value.toInt()) }
task?.let {
descriptionInput = it.description
chosenColor = it.color
}
val coroutineScope = rememberCoroutineScope()
val colors = setOf(
0xffe53935, 0xfff8bbd0, 0xff2196f3, 0xff4caf50, 0xffffeb3b, 0xff3e2723, 0xffffffff
)
ModalBottomSheetLayout(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
sheetContent = {
Row {
TextField(
value = descriptionInput,
onValueChange = {
descriptionInput = it
task?.description = descriptionInput
},
label = { stringResource(id = R.string.description) },
singleLine = true,
keyboardActions = KeyboardActions {
save(task, onTapAdd)
coroutineScope.launch {
bottomSheetScaffoldState.hide()
}
},
colors = TextFieldDefaults.textFieldColors(
textColor = MaterialTheme.colors.onSurface,
backgroundColor = MaterialTheme.colors.surface,
cursorColor = MaterialTheme.colors.onSurface
),
trailingIcon = {
Icon(
Icons.Filled.Clear,
tint = Color(colorPair.fontColor()),
contentDescription = "clear text",
modifier = Modifier
.offset(x = 8.dp)
.clickable {
descriptionInput = ""
}
)
}
)
Button(
onClick = {
save(task, onTapAdd)
coroutineScope.launch {
bottomSheetScaffoldState.hide()
}
},
colors = ButtonDefaults.textButtonColors(
backgroundColor = MaterialTheme.colors.primary,
contentColor = MaterialTheme.colors.onPrimary,
disabledContentColor = Color.LightGray)
) {
Text(text = stringResource(id = R.string.add), textAlign = TextAlign.Center)
}
}
Text(
text = stringResource(id = R.string.color),
fontSize = 16.sp,
modifier = Modifier.fillMaxWidth()
)
Row(modifier = Modifier
.fillMaxWidth()
.height(44.dp)) {
colors.forEach { color ->
RadioButton(
selected = chosenColor == color.toInt(),
onClick = {
task?.color = color.toInt()
chosenColor = color.toInt()
},
modifier = Modifier
.width(44.dp)
.height(44.dp)
.background(Color(color))
)
}
}
Text(
text = "Date",
fontSize = 16.sp,
modifier = Modifier.fillMaxWidth()
)
AndroidView(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
factory = { context ->
val today = Calendar.getInstance()
task?.let {
today.timeInMillis = it.dueDate
}
val datePicker = DatePicker(context)
datePicker.init(
today.get(Calendar.YEAR),
today.get(Calendar.MONTH),
today.get(Calendar.DAY_OF_MONTH)
) { _, year, monthOfYear, dayOfMonth ->
task?.dueDate = GregorianCalendar(
year,
monthOfYear,
dayOfMonth
).timeInMillis
}
datePicker
}
)
},
sheetState = bottomSheetScaffoldState
) {
screenContent()
}
}
@OptIn(ExperimentalMaterialApi::class)
private fun save(
task: TodoTask?,
onTapAdd: (TodoTask) -> Unit
) {
task?.let {
updateTask(it)
onTapAdd(it)
}
}
private fun updateTask(task: TodoTask?) {
if (task?.created == 0L) {
task.created = System.currentTimeMillis()
}
task?.lastModified = System.currentTimeMillis()
}
| epl-1.0 | 196422ce5abcabcf60b7bd36e80c5bbf | 36.319048 | 96 | 0.567054 | 5.634076 | false | false | false | false |
abdodaoud/Merlin | app/src/main/java/com/abdodaoud/merlin/ui/adapters/FactListAdapter.kt | 1 | 3305 | package com.abdodaoud.merlin.ui.adapters
import android.content.Intent
import android.net.Uri
import android.support.customtabs.CustomTabsIntent
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.abdodaoud.merlin.R
import com.abdodaoud.merlin.domain.model.Fact
import com.abdodaoud.merlin.domain.model.FactList
import com.abdodaoud.merlin.extensions.ctx
import com.abdodaoud.merlin.extensions.parseMessage
import com.abdodaoud.merlin.extensions.toDateString
import kotlinx.android.synthetic.item_fact.view.*
import org.jetbrains.anko.layoutInflater
import org.jetbrains.anko.onClick
import org.jetbrains.anko.onLongClick
class FactListAdapter(val facts: FactList) :
RecyclerView.Adapter<FactListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? {
val view = parent.ctx.layoutInflater.inflate(R.layout.item_fact, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindForecast(facts[position])
}
override fun getItemCount() = facts.size()
fun getItemAtPosition(position: Int) = facts.get(position)
class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val mContext = view.context
fun bindForecast(fact: Fact) {
with(fact) {
itemView.title.text = fact.title
itemView.date.text = fact.created.toDateString()
itemView.onClick { itemClick(fact) }
itemView.onLongClick { itemLongClick(fact) }
}
}
private fun itemLongClick(fact: Fact): Boolean {
val builderSingle = AlertDialog.Builder(mContext)
val arrayAdapter = ArrayAdapter<String>(mContext, android.R.layout.select_dialog_item)
arrayAdapter.add(mContext.getString(R.string.action_view_source))
arrayAdapter.add(mContext.getString(R.string.action_share))
builderSingle.setAdapter(arrayAdapter) { dialog, which ->
when(which) {
0 -> CustomTabsIntent.Builder().setShowTitle(true)
.setToolbarColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setStartAnimations(mContext, R.anim.slide_in_right,
R.anim.slide_out_left)
.setExitAnimations(mContext, android.R.anim.slide_in_left,
android.R.anim.slide_out_right).build()
.launchUrl(mContext as AppCompatActivity, Uri.parse(fact.url))
1 -> mContext.startActivity(Intent(Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, fact.title.parseMessage())
.setType("text/plain")))
}
}
builderSingle.show()
return true
}
private fun itemClick(fact: Fact) {
// TODO: Add favourite feature
}
}
} | mit | f1b63fbdbb04362079d2e1eec1c8c4ee | 40.325 | 100 | 0.65295 | 4.496599 | false | false | false | false |
TheFallOfRapture/Morph | src/main/kotlin/com/morph/engine/script/ConsoleScript.kt | 2 | 1360 | package com.morph.engine.script
import com.morph.engine.core.Game
import com.morph.engine.entities.Component
import com.morph.engine.entities.Entity
import com.morph.engine.script.debug.Console
import com.morph.engine.util.EntityGenUtils
abstract class ConsoleScript : Runnable {
private var console: Console? = null
fun setConsole(console: Console) {
this.console = console
}
protected fun echo(message: Any) = Console.out.println(message)
protected fun getVersion() {
echo("Morph ${Game.VERSION_STRING}")
}
protected fun addEntity(name: String, vararg components: Component) {
val e = EntityGenUtils.createEntity(name, *components)
console?.getGame()?.world?.addEntity(e)
echo("Created new entity $name (ID #${e.id})")
}
protected fun addEntityRectangle(name: String, width: Float, height: Float, isTrigger: Boolean, vararg components: Component) {
val e = EntityGenUtils.createEntityRectangle(name, width, height, isTrigger, *components)
console?.getGame()?.world?.addEntity(e)
echo("Created new entity $name (ID #${e.id})")
}
protected fun getEntity(name: String): Entity? {
return console?.getGame()?.world?.getEntityByName(name)
}
protected fun clear() {
console?.clear()
}
abstract override fun run()
}
| mit | fe00491b2a8fddd239f04347b59104b5 | 30.627907 | 131 | 0.683824 | 4.146341 | false | false | false | false |
venator85/log | log/src/main/java/eu/alessiobianchi/log/loggers.kt | 1 | 1864 | package eu.alessiobianchi.log
import android.os.Build
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.math.min
interface ILogger {
fun doLog(lock: ReentrantLock, level: Int, msg: String, tag: String)
}
open class NoOpLogger : ILogger {
override fun doLog(lock: ReentrantLock, level: Int, msg: String, tag: String) {
}
}
open class AndroidLogcat : ILogger {
companion object {
protected const val MAXIMUM_LINE_LENGTH = 4000
}
private val minLevel by lazy { findMinLevel() }
protected open fun findMinLevel() = when (Build.MANUFACTURER.lowercase(Locale.US)) {
"sony" -> android.util.Log.INFO
"zte" -> android.util.Log.DEBUG
else -> 0
}
override fun doLog(lock: ReentrantLock, level: Int, msg: String, tag: String) {
val adjLevel = level.coerceAtLeast(minLevel)
val msgLen = msg.length
if (msgLen > MAXIMUM_LINE_LENGTH) {
lock.withLock {
var i = 0
while (i < msgLen) {
var newline = msg.indexOf('\n', i)
newline = if (newline != -1) newline else msgLen
do {
val end = min(newline, i + MAXIMUM_LINE_LENGTH)
val part = msg.substring(i, end)
android.util.Log.println(adjLevel, tag, part)
i = end
} while (i < newline)
i++
}
}
} else {
android.util.Log.println(adjLevel, tag, msg)
}
}
}
open class ConsoleLogger : ILogger {
override fun doLog(lock: ReentrantLock, level: Int, msg: String, tag: String) {
val sLevel = Log.logLevelToString(level)
println("$sLevel/$tag: $msg")
}
}
| apache-2.0 | 17efe779e45900108a77e03a013a6e24 | 29.557377 | 88 | 0.564378 | 4.105727 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/authorization/DbCredentialService.kt | 1 | 4595 | /*
* Copyright (C) 2020. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.authorization
import com.google.common.base.MoreObjects
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.map.IMap
import com.openlattice.assembler.ORGANIZATION_PREFIX
import com.openlattice.directory.MaterializedViewAccount
import com.openlattice.hazelcast.HazelcastMap
import com.openlattice.ids.HazelcastLongIdService
import org.slf4j.LoggerFactory
import java.security.SecureRandom
const val USER_PREFIX = "user"
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class DbCredentialService(
hazelcastInstance: HazelcastInstance,
val longIdService: HazelcastLongIdService
) {
companion object {
private val logger = LoggerFactory.getLogger(
DbCredentialService::class.java
)
const val scope = "DB_USER_IDS"
private const val upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
private const val digits = "0123456789"
private const val special = ""//"!@#$%^&*()"
private val lower = upper.toLowerCase()
private val source = upper + lower + digits + special
private val srcBuf = source.toCharArray()
private const val CREDENTIAL_LENGTH = 29
private val r = SecureRandom()
private fun generateCredential(): String {
val cred = CharArray(CREDENTIAL_LENGTH)
for (i in 0 until CREDENTIAL_LENGTH) {
cred[i] = srcBuf[r.nextInt(srcBuf.size)]
}
return String(cred)
}
private fun buildPostgresUsername(securablePrincipal: SecurablePrincipal): String {
return "ol-internal|user|${securablePrincipal.id}"
}
}
private val dbCreds: IMap<String, MaterializedViewAccount> = HazelcastMap.DB_CREDS.getMap(hazelcastInstance)
fun getDbCredential(user: SecurablePrincipal): MaterializedViewAccount? = dbCreds[buildPostgresUsername(user)]
fun getDbCredential(userId: String): MaterializedViewAccount? = dbCreds[userId]
fun getDbUsername(user: SecurablePrincipal): String = dbCreds.getValue(buildPostgresUsername(user)).username
fun getDbUsername(userId: String): String = dbCreds.getValue(userId).username
fun getOrCreateUserCredentials(user: SecurablePrincipal): MaterializedViewAccount {
return getOrCreateUserCredentials(buildPostgresUsername(user))
}
fun getOrCreateUserCredentials(userId: String): MaterializedViewAccount {
return if (dbCreds.containsKey(userId)) {
getDbCredential(userId)!!
} else {
logger.info("Generating credentials for user id {}", userId)
val cred: String = generateCredential()
val id = longIdService.getId(scope)
val unpaddedLength = (USER_PREFIX.length + id.toString().length)
val username = if (userId.startsWith(ORGANIZATION_PREFIX)) {
userId
} else {
if (unpaddedLength < 8) {
"user" + ("0".repeat(8 - unpaddedLength)) + id
} else {
"user$id"
}
}
val account = MaterializedViewAccount(username, cred)
logger.info("Generated credentials for user id {} with username {}", userId, username)
return MoreObjects.firstNonNull(dbCreds.putIfAbsent(userId, account), account)
}
}
fun deleteUserCredential(user: SecurablePrincipal) {
dbCreds.delete(buildPostgresUsername(user))
}
fun deleteUserCredential(userId: String) {
dbCreds.delete(userId)
}
fun rollUserCredential(userId: String): String {
val cred: String = generateCredential()
dbCreds.set(userId, MaterializedViewAccount(dbCreds.getValue(userId).username, cred))
return cred
}
}
| gpl-3.0 | 807aaeee0ae610c70c50e2d719292885 | 35.181102 | 114 | 0.678781 | 4.487305 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/components/ProgressAlertDialog.kt | 1 | 2327 | package com.crossbowffs.quotelock.components
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.crossbowffs.quotelock.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder
/**
* @author Yubyf
*/
@SuppressLint("InflateParams")
class ProgressAlertDialog(
private val context: Context,
message: String? = "",
cancelable: Boolean = true,
canceledOnTouchOutside: Boolean = true,
) {
private var dialog: AlertDialog? = null
private var view: View? = null
var message = message
set(value) {
field = value ?: ""
view?.findViewById<TextView>(R.id.tv_message)?.text = field
}
var cancelable = cancelable
set(value) {
field = value
dialog?.setCancelable(field)
}
var canceledOnTouchOutside = canceledOnTouchOutside
set(value) {
field = value
dialog?.setCanceledOnTouchOutside(field)
}
init {
dialog = MaterialAlertDialogBuilder(context)
.setView(LayoutInflater.from(context).inflate(R.layout.dialog_progress, null).apply {
view = this
findViewById<TextView>(R.id.tv_message).text = message
})
.setCancelable(cancelable)
.create().apply {
setCanceledOnTouchOutside(canceledOnTouchOutside)
}
}
@SuppressLint("InflateParams")
fun create(): ProgressAlertDialog {
dialog = MaterialAlertDialogBuilder(context)
.setView(LayoutInflater.from(context).inflate(R.layout.dialog_progress, null).apply {
view = this
findViewById<TextView>(R.id.tv_message).text = message
})
.setCancelable(cancelable)
.create().apply {
setCanceledOnTouchOutside(canceledOnTouchOutside)
}
return this
}
fun show() {
dialog?.let {
if (!it.isShowing) {
it.show()
}
}
}
fun dismiss() {
dialog?.let {
if (it.isShowing) {
it.dismiss()
}
}
}
} | mit | 5bc81d32b0a51801ed817809c8621214 | 27.390244 | 97 | 0.594327 | 5.015086 | false | false | false | false |
Ingwersaft/James | src/main/kotlin/com/mkring/james/mapping/Mapping.kt | 1 | 3861 | package com.mkring.james.mapping
import com.mkring.james.Chat
import com.mkring.james.JamesPool
import com.mkring.james.chatbackend.OutgoingPayload
import com.mkring.james.chatbackend.UniqueChatTarget
import com.mkring.james.lg
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import java.util.concurrent.TimeUnit
import kotlin.coroutines.CoroutineContext
data class MappingPattern(val pattern: String, val info: String)
/**
* use map dsl function inside james
*/
class Mapping internal constructor(
private val commandText: String,
/**
* uniq chat identifier; content depends on the used backend
*/
val uniqueChatTarget: UniqueChatTarget,
/**
* if available the username will be provided
*/
val username: String?,
private val mappingPrefix: String,
private val parentChat: Chat
) : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + JamesPool
/**
* pattern will be present too, but not james name!
*
* james test arg1 arg2 -> [test,arg1,arg2]
* test arg1 arg2 -> [test,arg1,arg2]
*/
val arguments by lazy {
lg("commandText=$commandText username=$username")
commandText.removePrefix(mappingPrefix).trim().split(Regex("\\s+")).filterNot { it.isEmpty() }.toList()
}
/**
* default timeout when asking
*/
var askTimeout = 120
/**
* default timeout timeunit when asking
*/
var timeUnit = TimeUnit.SECONDS
/**
* If you ask with retries, this will be printed when the predicate is false
*/
var wrongAnswerText = "incompatible answer!"
/**
* If you ask with retries, this will be printed when a timeout happens
*/
var timeoutText = "timeout!"
/**
* If you ask with retries and all failed, this will be printed
*/
var askWithRetryFailedText = "well, nevermind then"
/**
* Send some text to the chat counterpart
*/
fun send(text: String, options: Map<String, String> = emptyMap()) {
parentChat.send(OutgoingPayload(uniqueChatTarget, text, options))
}
/**
* Ask something using the mapping timeout
* @param text the quesion to be asked
* @param options chat specific options -> see James README
*/
fun ask(text: String, options: Map<String, String> = emptyMap()): Ask<String> =
parentChat.ask(text, options, askTimeout, timeUnit, uniqueChatTarget)
/**
* Ask something and retry X times if timeout OR [predicate] false
* @param retries number of [retries] after the first failure. retries = 2 will ask a total of 3
* @param predicate this will determine if the answer is valid
* @param text the question to be asked
* @param options chat specific options -> see James README
*/
fun askWithRetry(
retries: Int, text: String, options: Map<String, String> = emptyMap(),
predicate: (String) -> Boolean
): Ask<String> {
//sequence is lazy eval!
val firstOrNull = IntRange(0, retries).asSequence().map {
ask(text, options)
}.filter {
when (it) {
is Ask.Timeout -> {
send(timeoutText)
false
}
is Ask.Answer -> {
when (predicate(it.value)) {
true -> true
else -> {
send(wrongAnswerText)
false
}
}
}
}
}.firstOrNull()
return when (firstOrNull) {
null -> {
send(askWithRetryFailedText)
Ask.Timeout
}
else -> firstOrNull
}
}
}
| gpl-3.0 | 34c0090db975d5c95e232ed5ebdf3dda | 29.888 | 111 | 0.594665 | 4.521077 | false | false | false | false |
rock3r/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/RedundantExplicitType.kt | 1 | 3714 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.AbbreviatedType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.types.typeUtil.isChar
import org.jetbrains.kotlin.types.typeUtil.isDouble
import org.jetbrains.kotlin.types.typeUtil.isFloat
import org.jetbrains.kotlin.types.typeUtil.isInt
import org.jetbrains.kotlin.types.typeUtil.isLong
/**
* Local properties do not need their type to be explicitly provided when the inferred type matches the explicit type.
*
* <noncompliant>
* fun function() {
* val x: String = "string"
* }
* </noncompliant>
*
* <compliant>
* fun function() {
* val x = "string"
* }
* </compliant>
*
* Based on code from Kotlin compiler:
* https://github.com/JetBrains/kotlin/blob/v1.3.50/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantExplicitTypeInspection.kt
*/
class RedundantExplicitType(config: Config) : Rule(config) {
override val issue = Issue(
"RedundantExplicitType", Severity.Style,
"Type does not need to be stated explicitly and can be removed.",
Debt.FIVE_MINS
)
@Suppress("ReturnCount", "ComplexMethod")
override fun visitProperty(property: KtProperty) {
if (bindingContext == BindingContext.EMPTY) return
if (!property.isLocal) return
val typeReference = property.typeReference ?: return
val type =
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptor)?.type ?: return
if (type is AbbreviatedType) return
when (val initializer = property.initializer) {
is KtConstantExpression -> if (!initializer.typeIsSameAs(type)) return
is KtStringTemplateExpression -> if (!KotlinBuiltIns.isString(type)) return
is KtNameReferenceExpression -> if (typeReference.text != initializer.getReferencedName()) return
is KtCallExpression -> if (typeReference.text != initializer.calleeExpression?.text) return
else -> return
}
report(CodeSmell(issue, Entity.from(property), issue.description))
super.visitProperty(property)
}
private fun KtConstantExpression.typeIsSameAs(type: KotlinType) =
when (node.elementType) {
KtNodeTypes.BOOLEAN_CONSTANT -> type.isBoolean()
KtNodeTypes.CHARACTER_CONSTANT -> type.isChar()
KtNodeTypes.INTEGER_CONSTANT -> {
if (text.endsWith("L")) {
type.isLong()
} else {
type.isInt()
}
}
KtNodeTypes.FLOAT_CONSTANT -> {
if (text.endsWith("f") || text.endsWith("F")) {
type.isFloat()
} else {
type.isDouble()
}
}
else -> false
}
}
| apache-2.0 | d6186ef1501aab4af4b7c3517ef5a604 | 38.510638 | 133 | 0.692515 | 4.568266 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RTime.kt | 1 | 2864 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.content.Context
import android.text.format.DateUtils
import pyxis.uzuki.live.richutilskt.R
/**
* convert time (in millis) into Relative Time
*
* @param receiver Target Time
* @param context Context object
*/
fun Long.convertToRelativeTime(context: Context): String {
return getRelativeTimeSpanString(context)
}
private fun Long.getRelativeTimeSpanString(context: Context, now: Long = System.currentTimeMillis(),
minResolution: Long = DateUtils.SECOND_IN_MILLIS,
flags: Int = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR): String {
val r = context.resources
val past = now >= this
val duration = Math.abs(now - this)
val resId: Int
val count: Long
if (duration < DateUtils.MINUTE_IN_MILLIS && minResolution < DateUtils.MINUTE_IN_MILLIS) {
count = duration / DateUtils.SECOND_IN_MILLIS
resId = compareWithPredicate(R.plurals.num_seconds_ago, R.plurals.in_num_seconds, { past })
} else if (duration < DateUtils.HOUR_IN_MILLIS && minResolution < DateUtils.HOUR_IN_MILLIS) {
count = duration / DateUtils.MINUTE_IN_MILLIS
resId = compareWithPredicate(R.plurals.num_minutes_ago, R.plurals.in_num_minutes, { past })
} else if (duration < DateUtils.DAY_IN_MILLIS && minResolution < DateUtils.DAY_IN_MILLIS) {
count = duration / DateUtils.HOUR_IN_MILLIS
resId = compareWithPredicate(R.plurals.num_hours_ago, R.plurals.in_num_hours, { past })
} else if (duration < DateUtils.WEEK_IN_MILLIS && minResolution < DateUtils.WEEK_IN_MILLIS) {
return getRelativeDayString(context, this, now)
} else {
return DateUtils.formatDateRange(null, this, this, flags)
}
val format = r.getQuantityString(resId, count.toInt())
return String.format(format, count)
}
private fun getRelativeDayString(context: Context, day: Long, today: Long): String {
val past = today > day
val r = context.resources
val days = getRelativeDay(day, today)
if (days == 1) {
return r.getString(compareWithPredicate(R.string.rtime_yesterday, R.string.rtime_tomorrow, { past }))
} else if (days == 0) {
return r.getString(R.string.rtime_today)
}
val resId: Int = compareWithPredicate(R.plurals.num_days_ago, R.plurals.in_num_days, { past })
val format = r.getQuantityString(resId, days)
return String.format(format, days)
}
private fun getRelativeDay(day: Long, today: Long): Int {
val startDay = day.normalizeDate()
val currentDay = today.normalizeDate()
return Math.abs(currentDay - startDay).toInt()
}
private fun <T> compareWithPredicate(A: T, B: T, predicate: () -> Boolean) = if (predicate()) A else B | apache-2.0 | 765696a1f6274f77d0bbc2d7a4b69ee0 | 38.791667 | 123 | 0.682263 | 3.865047 | false | false | false | false |
davidwhitman/changelogs | playstoreapi/src/main/kotlin/com/thunderclouddev/playstoreapi/legacyMarketApi/LegacyApiClientWrapper.kt | 1 | 1952 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.playstoreapi.legacyMarketApi
import android.content.Context
import com.thunderclouddev.playstoreapi.ApiClientWrapper
import com.thunderclouddev.playstoreapi.AuthenticationProvider
import com.thunderclouddev.playstoreapi.AuthorizationRequiredDelegate
import com.thunderclouddev.playstoreapi.RxOkHttpClient
import okhttp3.OkHttpClient
import java.util.*
/**
* Created by david on 4/17/17.
*/
class LegacyApiClientWrapper(context: Context,
private val gsfId: String,
authorizationRequiredDelegate: AuthorizationRequiredDelegate) {
private val apiClientWrapper = object : ApiClientWrapper<MarketApiClient, MarketRequest<*>>(context, authorizationRequiredDelegate, "market_token") {
override fun createClient(client: OkHttpClient, locale: Locale, authToken: String) =
MarketApiClient(
RxOkHttpClient(client),
authToken,
gsfId,
locale)
}
/**
* Execute a request, automatically handling missing client or token and retrying.
*/
fun <T> rxecute(request: MarketRequest<T>) = apiClientWrapper.rxecute<T>(request)
/**
* Build an authenticated api client that can service api calls.
* Retries on-hold api calls and attempts to deliver the results to the original requesters.
*/
fun build(authenticationProvider: AuthenticationProvider) = apiClientWrapper.build(authenticationProvider)
/**
* Call when the user cancels the auth token creation process, so that on-hold requests can be cleared.
*/
fun notifyAuthCanceled() = apiClientWrapper.notifyAuthCanceled()
} | gpl-3.0 | 8502790cc9f2d6fa14a09c3cf4970af9 | 38.06 | 153 | 0.701844 | 4.772616 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/ToStringHelper.kt | 1 | 1525 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core
import debop4k.core.utils.asString
import java.io.Serializable
import java.util.*
/**
* 객체의 속성 정보를 문자열로 표현하기 위한 Helper class 입니다.
* @author debop [email protected]
*/
class ToStringHelper(val className: String) : Serializable {
constructor (obj: Any) : this(obj.javaClass.simpleName)
private val map = HashMap<String, Any?>()
fun add(name: String, value: Any?): ToStringHelper {
map.put(name, value.asString())
return this
}
override fun toString(): String {
val properties = map.entries.joinToString(separator = ",") { entry ->
"${entry.key}=${entry.value}"
}
return "$className{$properties}"
}
companion object {
@JvmStatic fun of(className: String): ToStringHelper = ToStringHelper(className)
@JvmStatic fun of(obj: Any): ToStringHelper = ToStringHelper(obj)
}
} | apache-2.0 | 12777017083685f94901991b8df36395 | 29.285714 | 84 | 0.709373 | 3.892388 | false | false | false | false |
Kushki/kushki-android | kushki/src/main/java/com/kushkipagos/models/SiftScienceObject.kt | 1 | 827 | package com.kushkipagos.models
import org.json.JSONException
import org.json.JSONObject
class SiftScienceObject(responseBody:String) {
var userId: String =""
var sessionId:String=""
var code: String = ""
var message: String = ""
val jsonResponse: JSONObject=JSONObject(responseBody)
init{
try{
userId=jsonResponse.getString("userId")
sessionId=jsonResponse.getString("sessionId")
}catch (jsonException: JSONException){
code = try {
jsonResponse.getString("code")
} catch (jsonException: JSONException) {
""
}
message = try {
jsonResponse.getString("message")
} catch (jsonException: JSONException) {
""
}
}
}
} | mit | 4f2346aa640a0648656018db288250cd | 26.6 | 57 | 0.564692 | 5.07362 | false | false | false | false |
t-ray/malbec | src/main/kotlin/malbec/core/data/DaoFuncs.kt | 1 | 1281 | package malbec.core.data
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.core.namedparam.SqlParameterSource
import org.springframework.jdbc.support.GeneratedKeyHolder
val DEFAULT_ID_COLUMN_NAME = "id"
/**
* Function that will map values from the given object into named parameters
*/
typealias ParameterMapper<T> = (T) -> SqlParameterSource
typealias IntIdProvider<T> = (T) -> Int
/**
* Inserts a new row and returns the generated key
*/
fun NamedParameterJdbcTemplate.insertAndGenerateKey(sql: String, params: SqlParameterSource): Number {
val keyHolder = GeneratedKeyHolder()
this.update(sql, params, keyHolder)
return keyHolder.key
} //END insertAndGenerateKey
/**
* Inserts a new row and returns the generated key as an Int
*/
fun NamedParameterJdbcTemplate.insertAndGenerateIntKey(sql: String, params: SqlParameterSource): Int =
this.insertAndGenerateKey(sql, params).toInt()
/**
* Produces a MapSqlParameterSource with a single argument - the provided row id
*/
fun mapIntIdParameter(id: Int, columnName: String = DEFAULT_ID_COLUMN_NAME): SqlParameterSource = MapSqlParameterSource()
.addValue(columnName, id) | mit | 3e563f452f8d797bcd6e9574c68ac401 | 32.736842 | 121 | 0.783763 | 4.028302 | false | false | false | false |
clappr/clappr-android | app/src/main/kotlin/io/clappr/player/app/plugin/PlaybackStatusPlugin.kt | 1 | 2346 | package io.clappr.player.app.plugin
import android.view.LayoutInflater
import android.widget.RelativeLayout
import android.widget.TextView
import io.clappr.player.app.R
import io.clappr.player.base.Event
import io.clappr.player.base.EventHandler
import io.clappr.player.base.InternalEvent
import io.clappr.player.base.NamedType
import io.clappr.player.components.Container
import io.clappr.player.plugin.PluginEntry
import io.clappr.player.plugin.container.UIContainerPlugin
class PlaybackStatusPlugin(container: Container) : UIContainerPlugin(container, name = name) {
companion object : NamedType {
override val name = "playbackStatus"
val entry = PluginEntry.Container(name = name, factory = { container-> PlaybackStatusPlugin(container) })
}
override val view by lazy {
LayoutInflater.from(applicationContext).inflate(R.layout.playback_status_plugin, null) as RelativeLayout
}
private val status by lazy { view.findViewById(R.id.status) as TextView }
private val playbackListenerIds = mutableListOf<String>()
init {
bindContainerEvents()
}
private fun bindContainerEvents() {
listenTo(container, InternalEvent.DID_CHANGE_PLAYBACK.value) {
hide()
bindPlaybackEvents()
}
}
private fun bindPlaybackEvents() {
stopPlaybackListeners()
container.playback?.let {
playbackListenerIds.add(listenTo(it, Event.STALLING.value, updateLabel(Event.STALLING.value)))
playbackListenerIds.add(listenTo(it, Event.PLAYING.value, updateLabel(Event.PLAYING.value)))
playbackListenerIds.add(listenTo(it, Event.DID_PAUSE.value, updateLabel(Event.DID_PAUSE.value)))
playbackListenerIds.add(listenTo(it, Event.DID_STOP.value, updateLabel(Event.DID_STOP.value)))
playbackListenerIds.add(listenTo(it, Event.DID_COMPLETE.value, updateLabel(Event.DID_COMPLETE.value)))
playbackListenerIds.add(listenTo(it, Event.ERROR.value, updateLabel(Event.ERROR.value)))
}
}
private fun updateLabel(text: String): EventHandler {
return {
status.text = text
show()
}
}
private fun stopPlaybackListeners() {
playbackListenerIds.forEach(::stopListening)
playbackListenerIds.clear()
}
} | bsd-3-clause | 536139ef8429b65a46f9944a15edc304 | 34.029851 | 114 | 0.708014 | 4.477099 | false | false | false | false |
googlesamples/mlkit | android/codescanner/app/src/main/java/com/google/mlkit/samples/codescanner/kotlin/MainActivity.kt | 1 | 3645 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.samples.codescanner.kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import com.google.mlkit.common.MlKitException
import com.google.mlkit.samples.codescanner.R
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions
import com.google.mlkit.vision.codescanner.GmsBarcodeScanning
import java.util.Locale
/** Demonstrates the code scanner powered by Google Play Services. */
class MainActivity : AppCompatActivity() {
private var allowManualInput = false
private var barcodeResultView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
barcodeResultView = findViewById(R.id.barcode_result_view)
}
fun onAllowManualInputCheckboxClicked(view: View) {
allowManualInput = (view as CheckBox).isChecked
}
fun onScanButtonClicked(view: View) {
val optionsBuilder = GmsBarcodeScannerOptions.Builder()
if (allowManualInput) {
optionsBuilder.allowManualInput()
}
val gmsBarcodeScanner = GmsBarcodeScanning.getClient(this, optionsBuilder.build())
gmsBarcodeScanner
.startScan()
.addOnSuccessListener { barcode: Barcode ->
barcodeResultView!!.text = getSuccessfulMessage(barcode)
}
.addOnFailureListener { e: Exception -> barcodeResultView!!.text = getErrorMessage(e) }
.addOnCanceledListener {
barcodeResultView!!.text = getString(R.string.error_scanner_cancelled)
}
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
savedInstanceState.putBoolean(KEY_ALLOW_MANUAL_INPUT, allowManualInput)
super.onSaveInstanceState(savedInstanceState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
allowManualInput = savedInstanceState.getBoolean(KEY_ALLOW_MANUAL_INPUT)
}
private fun getSuccessfulMessage(barcode: Barcode): String {
val barcodeValue =
String.format(
Locale.US,
"Display Value: %s\nRaw Value: %s\nFormat: %s\nValue Type: %s",
barcode.displayValue,
barcode.rawValue,
barcode.format,
barcode.valueType
)
return getString(R.string.barcode_result, barcodeValue)
}
private fun getErrorMessage(e: Exception): String? {
return if (e is MlKitException) {
when (e.errorCode) {
MlKitException.CODE_SCANNER_CAMERA_PERMISSION_NOT_GRANTED ->
getString(R.string.error_camera_permission_not_granted)
MlKitException.CODE_SCANNER_APP_NAME_UNAVAILABLE ->
getString(R.string.error_app_name_unavailable)
else -> getString(R.string.error_default_message, e)
}
} else {
e.message
}
}
companion object {
private const val KEY_ALLOW_MANUAL_INPUT = "allow_manual_input"
}
}
| apache-2.0 | 87f818be371fd52e3df6f59927f60365 | 34.048077 | 93 | 0.736351 | 4.288235 | false | false | false | false |
FHannes/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/synch/impl.kt | 16 | 2741 | /*
* 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 org.jetbrains.plugins.groovy.transformations.impl.synch
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.*
import com.intellij.psi.PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns
val ANNO_FQN = "groovy.transform.Synchronized"
val LOCK_NAME = "\$lock"
val STATIC_LOCK_NAME = "\$LOCK"
internal val PATTERN: ElementPattern<out GrLiteral> = GroovyPatterns.stringLiteral().annotationParam(
StandardPatterns.string().equalTo(ANNO_FQN), DEFAULT_REFERENCED_METHOD_NAME
)
fun getImplicitLockUsages(field: GrField): Sequence<PsiAnnotation> {
val static = when (field.name) {
LOCK_NAME -> false
STATIC_LOCK_NAME -> true
else -> return emptySequence()
}
val clazz = field.containingClass ?: return emptySequence()
return getImplicitLockUsages(clazz, static)
}
private fun getImplicitLockUsages(clazz: PsiClass, static: Boolean) = clazz.methods.asSequence().filter { method ->
static == method.isStatic()
}.mapNotNull { method ->
AnnotationUtil.findAnnotation(method, ANNO_FQN)
}.filter { anno ->
anno.findDeclaredAttributeValue(null) == null
}
internal fun getMethodsReferencingLock(field: GrField): Sequence<PsiMethod> = field.containingClass?.let {
getMethodsReferencingLock(it, field.name)
} ?: emptySequence()
private fun getMethodsReferencingLock(clazz: PsiClass, requiredLockName: String) = clazz.methods.asSequence().filter(
fun(method: PsiMethod): Boolean {
val annotation = AnnotationUtil.findAnnotation(method, ANNO_FQN) ?: return false
val referencedLock = AnnotationUtil.getDeclaredStringAttributeValue(
annotation, null
) ?: if (method.isStatic()) STATIC_LOCK_NAME else LOCK_NAME
return requiredLockName == referencedLock
}
)
internal fun PsiModifierListOwner.isStatic() = hasModifierProperty(PsiModifier.STATIC) | apache-2.0 | eb372190c37ebc7851de73d73e93d7ee | 39.925373 | 117 | 0.769792 | 4.289515 | false | false | false | false |
m4gr3d/GAST | core/src/xrapp/java/org.godotengine.plugin.gast.xrapp/GastActivity.kt | 1 | 9802 | package org.godotengine.plugin.gast.xrapp
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout.LayoutParams
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import org.godotengine.godot.Godot
import org.godotengine.godot.GodotHost
import org.godotengine.godot.plugin.GodotPlugin
import org.godotengine.godot.plugin.GodotPluginRegistry
import org.godotengine.godot.xr.XRMode
import org.godotengine.plugin.gast.GastManager
import org.godotengine.plugin.gast.GastNode
import org.godotengine.plugin.gast.R
import org.godotengine.plugin.gast.input.action.GastActionListener
import org.godotengine.plugin.gast.projectionmesh.RectangularProjectionMesh
import org.godotengine.plugin.gast.view.GastFrameLayout
import org.godotengine.plugin.vr.openxr.OpenXRPlugin
import java.util.*
import kotlin.system.exitProcess
/**
* Container activity.
*
* Host and provide Gast related functionality for the driving app.
*/
abstract class GastActivity :
AppCompatActivity(),
GodotHost,
OpenXRPlugin.EventListener,
GastActionListener {
companion object {
private val TAG = GastActivity::class.java.simpleName
private const val BACK_BUTTON_ACTION = "back_button_action"
private const val MENU_BUTTON_ACTION = "menu_button_action"
}
private val enableXR = isXREnabled()
private val appPlugin = GastAppPlugin(enableXR)
private var godotFragment: Godot? = null
private var gastFrameLayout: GastFrameLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (enableXR) {
super.setContentView(R.layout.godot_app_layout)
val currentFragment =
supportFragmentManager.findFragmentById(R.id.godot_fragment_container)
if (currentFragment is Godot) {
Log.v(TAG, "Reusing existing Godot fragment instance.")
godotFragment = currentFragment
} else {
Log.v(TAG, "Creating new Godot fragment instance.")
godotFragment = Godot()
supportFragmentManager
.beginTransaction()
.replace(R.id.godot_fragment_container, godotFragment!!)
.setPrimaryNavigationFragment(godotFragment)
.commitNowAllowingStateLoss()
}
getOpenXRPlugin().registerEventListener(this)
getGastManager().registerGastActionListener(this)
}
}
override fun onDestroy() {
if (enableXR) {
getGastManager().unregisterGastActionListener(this)
getOpenXRPlugin().unregisterEventListener(this)
}
super.onDestroy()
onGodotForceQuit(godotFragment)
}
override fun onGodotForceQuit(instance: Godot?) {
if (!enableXR) {
return
}
if (instance === godotFragment) {
exitProcess(0)
}
}
private fun getGastContainerView(): ViewGroup? {
if (!enableXR) {
return null
}
if (godotFragment == null) {
throw IllegalStateException("This must be called after super.onCreate(...)")
}
// Add this point, Godot::onCreate(...) should have already been called giving us access
// the registered plugins.
val gastPlugin = getGastManager()
return gastPlugin.rootView
}
override fun <T : View?> findViewById(@IdRes id: Int): T {
if (!enableXR) {
return super.findViewById(id)
}
val container = gastFrameLayout ?: return super.findViewById(id)
return container.findViewById(id) ?: super.findViewById(id)
}
override fun setContentView(@LayoutRes layoutResID: Int) {
if (!enableXR || godotFragment == null) {
super.setContentView(layoutResID)
return
}
setContentView(layoutInflater.inflate(layoutResID, getGastContainerView(), false))
}
override fun setContentView(view: View) {
if (!enableXR || godotFragment == null) {
super.setContentView(view)
return
}
if (view.parent != null) {
(view.parent as ViewGroup).removeView(view)
}
// Setup the layout params for the container view
val viewLayoutParams = view.layoutParams
val containerLayoutParams =
LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER)
if (viewLayoutParams == null || viewLayoutParams.width == LayoutParams.MATCH_PARENT) {
containerLayoutParams.width =
resources.getDimensionPixelSize(R.dimen.default_container_width)
}
if (viewLayoutParams == null || viewLayoutParams.height == LayoutParams.MATCH_PARENT) {
containerLayoutParams.height =
resources.getDimensionPixelSize(R.dimen.default_container_height)
}
val containerView = getGastContainerView()
if (gastFrameLayout != null) {
containerView?.removeView(gastFrameLayout)
}
// Any view we want to render in VR needs to be added as a child to the containerView in
// order to be hooked to the view lifecycle events.
gastFrameLayout = if (view is GastFrameLayout) {
view
} else {
// Wrap the content view in a GastFrameLayout view.
GastFrameLayout(this).apply {
addView(view)
}
}
containerView?.addView(gastFrameLayout, 0, containerLayoutParams)
}
@CallSuper
override fun onGodotSetupCompleted() {
super.onGodotSetupCompleted()
GodotPlugin.registerPluginWithGodotNative(appPlugin, appPlugin)
}
@CallSuper
override fun onGodotMainLoopStarted() {
// Complete setup and initializing of the GastFrameLayout
super.onGodotMainLoopStarted()
val gastNode = GastNode(getGastManager(), "GastActivityContainer")
val projectionMesh = gastNode.getProjectionMesh()
if (projectionMesh is RectangularProjectionMesh) {
projectionMesh.setCurved(false)
}
runOnUiThread {
gastFrameLayout?.initialize(getGastManager(), gastNode)
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
godotFragment?.onNewIntent(intent)
}
@CallSuper
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
godotFragment?.onActivityResult(requestCode, resultCode, data)
}
@CallSuper
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String?>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
godotFragment?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onBackPressed() {
godotFragment?.onBackPressed() ?: super.onBackPressed()
}
private fun getGastManager(): GastManager {
val gastPlugin = GodotPluginRegistry.getPluginRegistry().getPlugin("gast-core")
if (gastPlugin !is GastManager) {
throw IllegalStateException("Unable to retrieve the Gast plugin.")
}
return gastPlugin
}
private fun getOpenXRPlugin(): OpenXRPlugin {
val openxrPlugin = GodotPluginRegistry.getPluginRegistry().getPlugin("OpenXR")
if (openxrPlugin !is OpenXRPlugin) {
throw IllegalStateException("Unable to retrieve the OpenXR plugin.")
}
return openxrPlugin
}
/**
* Override the engine starting parameters to indicate we want VR mode.
*/
override fun getCommandLine(): List<String> {
return if (enableXR)
Collections.singletonList(XRMode.OVR.cmdLineArg)
else
Collections.emptyList()
}
protected open fun isXREnabled() = false
/**
* Enables back button presses via the B/Y buttons for controllers or middle finger pinch for
* tracked hands.
*/
protected open fun isBackButtonEnabled() = false
/**
* Enable passthrough
*/
fun startPassthrough() {
if (enableXR) {
appPlugin.startPassthrough(godotFragment)
}
}
/**
* Disable passthrough
*/
fun stopPassthrough() {
if (enableXR) {
appPlugin.stopPassthrough(godotFragment)
}
}
@CallSuper
override fun onFocusGained() {
}
@CallSuper
override fun onFocusLost() {
}
@CallSuper
override fun onHeadsetMounted() {
}
@CallSuper
override fun onHeadsetUnmounted() {
}
@CallSuper
override fun onSessionBegun() {
}
@CallSuper
override fun onSessionEnding() {
}
override fun getInputActionsToMonitor() = setOf(BACK_BUTTON_ACTION, MENU_BUTTON_ACTION)
override fun onMainInputAction(
action: String,
pressState: GastActionListener.InputPressState,
strength: Float
) {
if (action == BACK_BUTTON_ACTION
&& pressState == GastActionListener.InputPressState.JUST_RELEASED
&& isBackButtonEnabled()
) {
onBackPressed()
} else if (action == MENU_BUTTON_ACTION
&& pressState == GastActionListener.InputPressState.JUST_RELEASED
) {
openOptionsMenu()
}
}
}
| mit | 1d38f4d50bb8e86a76572ed3c26a33f1 | 29.823899 | 97 | 0.650173 | 4.864516 | false | false | false | false |
pgutkowski/KGraphQL | src/main/kotlin/com/github/pgutkowski/kgraphql/schema/structure2/SchemaCompilation.kt | 1 | 13806 | package com.github.pgutkowski.kgraphql.schema.structure2
import com.github.pgutkowski.kgraphql.Context
import com.github.pgutkowski.kgraphql.configuration.SchemaConfiguration
import com.github.pgutkowski.kgraphql.defaultKQLTypeName
import com.github.pgutkowski.kgraphql.getIterableElementType
import com.github.pgutkowski.kgraphql.isIterable
import com.github.pgutkowski.kgraphql.schema.DefaultSchema
import com.github.pgutkowski.kgraphql.schema.SchemaException
import com.github.pgutkowski.kgraphql.schema.directive.Directive
import com.github.pgutkowski.kgraphql.schema.introspection.SchemaProxy
import com.github.pgutkowski.kgraphql.schema.introspection.TypeKind
import com.github.pgutkowski.kgraphql.schema.introspection.__Schema
import com.github.pgutkowski.kgraphql.schema.model.BaseOperationDef
import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper
import com.github.pgutkowski.kgraphql.schema.model.InputValueDef
import com.github.pgutkowski.kgraphql.schema.model.PropertyDef
import com.github.pgutkowski.kgraphql.schema.model.QueryDef
import com.github.pgutkowski.kgraphql.schema.model.SchemaDefinition
import com.github.pgutkowski.kgraphql.schema.model.Transformation
import com.github.pgutkowski.kgraphql.schema.model.TypeDef
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.KType
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.isSuperclassOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.jvmErasure
@Suppress("UNCHECKED_CAST")
class SchemaCompilation(
val configuration : SchemaConfiguration,
val definition : SchemaDefinition
){
private val queryTypeProxies = mutableMapOf<KClass<*>, TypeProxy>()
private val inputTypeProxies = mutableMapOf<KClass<*>, TypeProxy>()
private val unions = mutableListOf<Type.Union>()
private val enums = definition.enums.associate { enum -> enum.kClass to enum.toEnumType() }
private val scalars = definition.scalars.associate { scalar -> scalar.kClass to scalar.toScalarType() }
private val schemaProxy = SchemaProxy()
private val contextType = Type._Context()
private enum class TypeCategory {
INPUT, QUERY
}
fun perform(): DefaultSchema {
val queryType = handleQueries()
val mutationType = handleMutations()
definition.objects.forEach { handleObjectType(it.kClass) }
definition.inputObjects.forEach { handleInputType(it.kClass) }
queryTypeProxies.forEach { (kClass, typeProxy) ->
introspectPossibleTypes(kClass, typeProxy)
introspectInterfaces(kClass, typeProxy)
}
val model = SchemaModel (
query = queryType,
mutation = mutationType,
enums = enums,
scalars = scalars,
unions = unions,
queryTypes = queryTypeProxies + enums + scalars,
inputTypes = inputTypeProxies + enums + scalars,
allTypes = queryTypeProxies + inputTypeProxies + enums + scalars,
directives = definition.directives.map { handlePartialDirective(it) }
)
val schema = DefaultSchema(configuration, model)
schemaProxy.proxiedSchema = schema
return schema
}
private fun introspectPossibleTypes(kClass: KClass<*>, typeProxy: TypeProxy) {
val proxied = typeProxy.proxied
if(proxied is Type.Interface<*>){
val possibleTypes = queryTypeProxies.filter { (otherKClass, otherTypeProxy) ->
otherTypeProxy.kind == TypeKind.OBJECT && otherKClass != kClass && otherKClass.isSubclassOf(kClass)
}.values.toList()
typeProxy.proxied = proxied.withPossibleTypes(possibleTypes)
}
}
private fun introspectInterfaces(kClass: KClass<*>, typeProxy: TypeProxy) {
val proxied = typeProxy.proxied
if(proxied is Type.Object<*>){
val interfaces = queryTypeProxies.filter { (otherKClass, otherTypeProxy) ->
otherTypeProxy.kind == TypeKind.INTERFACE && otherKClass != kClass && kClass.isSubclassOf(otherKClass)
}.values.toList()
typeProxy.proxied = proxied.withInterfaces(interfaces)
}
}
private fun handlePartialDirective(directive: Directive.Partial) : Directive {
val inputValues = handleInputValues(directive.name, directive.execution, emptyList())
return directive.toDirective(inputValues)
}
private fun handleQueries() : Type {
return Type.OperationObject("Query", "Query object",
fields = definition.queries.map { handleOperation(it) } + introspectionSchemaQuery() + introspectionTypeQuery()
)
}
private fun handleMutations() : Type {
return Type.OperationObject("Mutation", "Mutation object", definition.mutations.map { handleOperation(it) })
}
private fun introspectionSchemaQuery() = handleOperation(
QueryDef("__schema", FunctionWrapper.on<__Schema> { schemaProxy as __Schema })
)
private fun introspectionTypeQuery() = handleOperation(
QueryDef("__type", FunctionWrapper.on {
name : String -> schemaProxy.findTypeByName(name)
})
)
private fun handleOperation(operation : BaseOperationDef<*, *>) : Field {
val returnType = handlePossiblyWrappedType(operation.kFunction.returnType, TypeCategory.QUERY)
val inputValues = handleInputValues(operation.name, operation, operation.inputValues)
return Field.Function(operation, returnType, inputValues)
}
private fun handleUnionProperty(unionProperty: PropertyDef.Union<*>) : Field {
val inputValues = handleInputValues(unionProperty.name, unionProperty, unionProperty.inputValues)
val type = handleUnionType(unionProperty.union)
return Field.Union(unionProperty, type, inputValues)
}
private fun handlePossiblyWrappedType(kType : KType, typeCategory: TypeCategory) : Type = when {
kType.isIterable() -> handleCollectionType(kType, typeCategory)
kType.jvmErasure == Context::class && typeCategory == TypeCategory.INPUT -> contextType
kType.jvmErasure == Context::class && typeCategory == TypeCategory.QUERY -> throw SchemaException("Context type cannot be part of schema")
kType.arguments.isNotEmpty() -> throw SchemaException("Generic types are not supported by GraphQL, found $kType")
else -> handleSimpleType(kType, typeCategory)
}
private fun handleCollectionType(kType: KType, typeCategory: TypeCategory): Type {
val type = kType.getIterableElementType()
?: throw SchemaException("Cannot handle collection without element type")
val nullableListType = Type.AList(handleSimpleType(type, typeCategory))
return applyNullability(kType, nullableListType)
}
private fun handleSimpleType(kType: KType, typeCategory: TypeCategory): Type {
val simpleType = handleRawType(kType.jvmErasure, typeCategory)
return applyNullability(kType, simpleType)
}
private fun applyNullability(kType: KType, simpleType: Type): Type {
if (!kType.isMarkedNullable) {
return Type.NonNull(simpleType)
} else {
return simpleType
}
}
private fun handleRawType(kClass: KClass<*>, typeCategory: TypeCategory) : Type {
if(kClass == Context::class) throw SchemaException("Context type cannot be part of schema")
val cachedInstances = when(typeCategory) {
TypeCategory.QUERY -> queryTypeProxies
TypeCategory.INPUT -> inputTypeProxies
}
val typeCreator = when(typeCategory){
TypeCategory.QUERY -> this::handleObjectType
TypeCategory.INPUT -> this::handleInputType
}
return cachedInstances[kClass]
?: enums[kClass]
?: scalars[kClass]
?: typeCreator (kClass)
}
private fun handleObjectType(kClass: KClass<*>) : Type {
assertValidObjectType(kClass)
val objectDefs = definition.objects.filter { it.kClass.isSuperclassOf(kClass) }
val objectDef = objectDefs.find { it.kClass == kClass } ?: TypeDef.Object(kClass.defaultKQLTypeName(), kClass)
//treat introspection types as objects -> adhere to reference implementation behaviour
val kind = if(kClass.isFinal || objectDef.name.startsWith("__")) TypeKind.OBJECT else TypeKind.INTERFACE
val objectType = if(kind == TypeKind.OBJECT) Type.Object(objectDef) else Type.Interface(objectDef)
val typeProxy = TypeProxy(objectType)
queryTypeProxies.put(kClass, typeProxy)
val allKotlinProperties = objectDefs.fold(emptyMap<String, PropertyDef.Kotlin<*, *>>(),
{ acc, def -> acc + def.kotlinProperties.mapKeys { entry -> entry.key.name } })
val allTransformations= objectDefs.fold(emptyMap<String, Transformation<*, *>>(),
{ acc, def -> acc + def.transformations.mapKeys { entry -> entry.key.name } })
val kotlinFields = kClass.memberProperties
.filterNot { field -> objectDefs.any { it.isIgnored(field.name) } }
.map { property -> handleKotlinProperty (
kProperty = property,
kqlProperty = allKotlinProperties[property.name],
transformation = allTransformations[property.name]
) }
val extensionFields = objectDefs.flatMap(TypeDef.Object<*>::extensionProperties).map { property -> handleOperation(property) }
val unionFields = objectDefs.flatMap(TypeDef.Object<*>::unionProperties).map { property -> handleUnionProperty(property) }
val typenameResolver = { value: Any ->
schemaProxy.typeByKClass(value.javaClass.kotlin)?.name ?: typeProxy.name
}
val __typenameField = handleOperation (
PropertyDef.Function<Nothing, String?> ("__typename", FunctionWrapper.on(typenameResolver, true))
)
val declaredFields = kotlinFields + extensionFields + unionFields
if(declaredFields.isEmpty()){
throw SchemaException("An Object type must define one or more fields. Found none on type ${objectDef.name}")
}
declaredFields.find { it.name.startsWith("__") }?.let { field ->
throw SchemaException("Illegal name '${field.name}'. Names starting with '__' are reserved for introspection system")
}
val allFields = declaredFields + __typenameField
typeProxy.proxied = if(kind == TypeKind.OBJECT) Type.Object(objectDef, allFields) else Type.Interface(objectDef, allFields)
return typeProxy
}
private fun handleInputType(kClass: KClass<*>) : Type {
assertValidObjectType(kClass)
val inputObjectDef = definition.inputObjects.find { it.kClass == kClass } ?: TypeDef.Input(kClass.defaultKQLTypeName(), kClass)
val objectType = Type.Input(inputObjectDef)
val typeProxy = TypeProxy(objectType)
inputTypeProxies.put(kClass, typeProxy)
val fields = kClass.memberProperties.map { property -> handleKotlinInputProperty(property) }
typeProxy.proxied = Type.Input(inputObjectDef, fields)
return typeProxy
}
private fun handleInputValues(operationName : String, operation: FunctionWrapper<*>, inputValues: List<InputValueDef<*>>) : List<InputValue<*>> {
val invalidInputValues = inputValues
.map { it.name }
.filterNot { it in operation.argumentsDescriptor.keys }
if(invalidInputValues.isNotEmpty()){
throw SchemaException("Invalid input values on $operationName: $invalidInputValues")
}
return operation.argumentsDescriptor.map { (name, kType) ->
val kqlInput = inputValues.find { it.name == name } ?: InputValueDef(kType.jvmErasure, name)
val inputType = handlePossiblyWrappedType(kType, TypeCategory.INPUT)
InputValue(kqlInput, inputType)
}
}
private fun handleUnionType(union : TypeDef.Union) : Type.Union {
val possibleTypes = union.members.map {
handleRawType(it, TypeCategory.QUERY)
}
val invalidPossibleTypes = possibleTypes.filterNot { it.kind == TypeKind.OBJECT }
if(invalidPossibleTypes.isNotEmpty()){
throw SchemaException("Invalid union type members")
}
val unionType = Type.Union(union, possibleTypes)
unions.add(unionType)
return unionType
}
private fun handleKotlinInputProperty(kProperty: KProperty1<*, *>) : InputValue<*> {
val type = handlePossiblyWrappedType(kProperty.returnType, TypeCategory.INPUT)
return InputValue(InputValueDef(kProperty.returnType.jvmErasure, kProperty.name), type)
}
private fun <T : Any, R> handleKotlinProperty (
kProperty: KProperty1<T, R>,
kqlProperty: PropertyDef.Kotlin<*, *>?,
transformation: Transformation<*, *>?
) : Field.Kotlin<*, *> {
val returnType = handlePossiblyWrappedType(kProperty.returnType, TypeCategory.QUERY)
val inputValues = if(transformation != null){
handleInputValues("$kProperty transformation", transformation.transformation, emptyList())
} else {
emptyList()
}
val actualKqlProperty = kqlProperty ?: PropertyDef.Kotlin(kProperty)
return Field.Kotlin (
kql = actualKqlProperty as PropertyDef.Kotlin<T, R>,
returnType = returnType,
arguments = inputValues,
transformation = transformation as Transformation<T, R>?
)
}
} | mit | 490bce6dc9c94a8d2d0fd19ee1ba5c7a | 42.831746 | 149 | 0.680212 | 4.832342 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-chart/src/main/java/net/nemerosa/ontrack/extension/chart/support/IntervalPeriod.kt | 1 | 1858 | package net.nemerosa.ontrack.extension.chart.support
import net.nemerosa.ontrack.model.exceptions.InputException
import java.time.Duration
import java.time.LocalDateTime
import java.time.Period
import java.time.format.DateTimeFormatter
sealed interface IntervalPeriod {
fun addTo(start: LocalDateTime): LocalDateTime
fun format(start: LocalDateTime): String
companion object
}
data class IntervalDatePeriod(
private val period: Period,
) : IntervalPeriod {
override fun addTo(start: LocalDateTime): LocalDateTime =
start.plus(period)
override fun format(start: LocalDateTime): String =
start.format(DateTimeFormatter.ISO_DATE)
}
data class IntervalTimePeriod(
private val duration: Duration,
) : IntervalPeriod {
override fun addTo(start: LocalDateTime): LocalDateTime =
start.plus(duration)
override fun format(start: LocalDateTime): String =
start.format(DateTimeFormatter.ISO_DATE_TIME)
}
fun parseIntervalPeriod(value: String): IntervalPeriod {
val fixed = "(\\d+)([hdwmy])".toRegex()
val f = fixed.matchEntire(value)
return if (f != null) {
val count = f.groupValues[1].toLong()
val type = f.groupValues[2]
when (type) {
"h" -> IntervalTimePeriod(Duration.ofHours(count))
"d" -> IntervalDatePeriod(Period.ofDays(count.toInt()))
"w" -> IntervalDatePeriod(Period.ofWeeks(count.toInt()))
"m" -> IntervalDatePeriod(Period.ofMonths(count.toInt()))
"y" -> IntervalDatePeriod(Period.ofYears(count.toInt()))
else -> throw IntervalPeriodFormatException("Unknow period type $type in $value")
}
} else {
throw IntervalPeriodFormatException("Cannot parse period: $value")
}
}
class IntervalPeriodFormatException(message: String) : InputException(message) | mit | 8695f9ab2e1a501dabacc64533c46be9 | 31.614035 | 93 | 0.696448 | 4.310905 | false | false | false | false |
d9n/intellij-rust | src/test/kotlin/org/rust/ide/intentions/SimplifyBooleanExpressionIntentionTest.kt | 1 | 5234 | package org.rust.ide.intentions
/**
* @author Moklev Vyacheslav
*/
class SimplifyBooleanExpressionIntentionTest : RsIntentionTestBase(SimplifyBooleanExpressionIntention()) {
fun testOr() = doAvailableTest("""
fn main() {
let a = true /*caret*/|| false;
}
""", """
fn main() {
let a = true;
}
""")
fun testAnd() = doAvailableTest("""
fn main() {
let a = true /*caret*/&& false;
}
""", """
fn main() {
let a = false;
}
""")
fun testXor() = doAvailableTest("""
fn main() {
let a = true /*caret*/^ false;
}
""", """
fn main() {
let a = true;
}
""")
fun testNot() = doAvailableTest("""
fn main() {
let a = !/*caret*/true;
}
""", """
fn main() {
let a = false;
}
""")
fun testParens() = doAvailableTest("""
fn main() {
let a = (/*caret*/true);
}
""", """
fn main() {
let a = true;
}
""")
fun testShortCircuitOr1() = doAvailableTest("""
fn main() {
let a = true /*caret*/|| b;
}
""", """
fn main() {
let a = true;
}
""")
fun testShortCircuitOr2() = doAvailableTest("""
fn main() {
let a = false /*caret*/|| a;
}
""", """
fn main() {
let a = a;
}
""")
fun testShortCircuitAnd1() = doAvailableTest("""
fn main() {
let a = false /*caret*/&& b;
}
""", """
fn main() {
let a = false;
}
""")
fun testShortCircuitAnd2() = doAvailableTest("""
fn main() {
let a = true /*caret*/&& a;
}
""", """
fn main() {
let a = a;
}
""")
fun testNonEquivalent1() = doAvailableTest("""
fn main() {
let a = a ||/*caret*/ true || true;
}
""", """
fn main() {
let a = true;
}
""")
fun testNonEquivalent2() = doAvailableTest("""
fn main() {
let a = a ||/*caret*/ false;
}
""", """
fn main() {
let a = a;
}
""")
fun testNonEquivalent3() = doAvailableTest("""
fn main() {
let a = a &&/*caret*/ false;
}
""", """
fn main() {
let a = false;
}
""")
fun testNonEquivalent4() = doAvailableTest("""
fn main() {
let a = a &&/*caret*/ true;
}
""", """
fn main() {
let a = a;
}
""")
fun testComplexNonEquivalent1() = doAvailableTest("""
fn main() {
let a = f() && (g() &&/*caret*/ false);
}
""", """
fn main() {
let a = f() && (false);
}
""")
fun testComplexNonEquivalent2() = doAvailableTest("""
fn main() {
let a = 1 > 2 &&/*caret*/ 2 > 3 && 3 > 4 || true;
}
""", """
fn main() {
let a = true;
}
""")
fun testComplexNonEquivalent3() = doAvailableTest("""
fn main() {
let a = 1 > 2 &&/*caret*/ 2 > 3 && 3 > 4 || false;
}
""", """
fn main() {
let a = 1 > 2 && 2 > 3 && 3 > 4;
}
""")
fun testNotAvailable3() = doUnavailableTest("""
fn main() {
let a = a /*caret*/&& b;
}
""")
fun testNotAvailable4() = doUnavailableTest("""
fn main() {
let a = true /*caret*/^ a;
}
""")
fun testNotAvailable5() = doUnavailableTest("""
fn main() {
let a = !/*caret*/a;
}
""")
fun testNotAvailable6() = doUnavailableTest("""
fn main() {
let a = /*caret*/true;
}
""")
fun testComplex1() = doAvailableTest("""
fn main() {
let a = !(false ^ false) /*caret*/|| b;
}
""", """
fn main() {
let a = true;
}
""")
fun testComplex2() = doAvailableTest("""
fn main() {
let a = !(false /*caret*/^ false) || b;
}
""", """
fn main() {
let a = true;
}
""")
fun testComplex3() = doAvailableTest("""
fn main() {
let a = ((((((((((true)))) || b && /*caret*/c && d))))));
}
""", """
fn main() {
let a = true;
}
""")
fun testComplex4() = doAvailableTest("""
fn main() {
let a = true || x >= y + z || foo(1, 2, r) == 42 || flag || (flag2 && !flag3/*caret*/);
}
""", """
fn main() {
let a = true;
}
""")
fun testFindLast() = doAvailableTest("""
fn main() {
let a = true || x > 0 ||/*caret*/ x < 0 || y > 2 || y < 2 || flag;
}
""", """
fn main() {
let a = true;
}
""")
fun `test incomplete code`() = doUnavailableTest("""
fn main() {
xs.iter()
.map(|/*caret*/)
}
""")
}
| mit | 1b4fa77712173ea7d420642f75c30efc | 20.190283 | 106 | 0.365495 | 4.244931 | false | true | false | false |
langara/MyIntent | myviews/src/main/java/pl/mareklangiewicz/myviews/MyViewDecorator.kt | 1 | 1988 | package pl.mareklangiewicz.myviews
import androidx.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
/**
* Created by Marek Langiewicz on 31.05.15.
* This class contains some static methods that allow to inject some decorations
* to selected views in view hierarchy. It is probably bad idea to mess with
* default view hierarchy generation, so... don't use this class. :-)
* We do not decorate inside already decorated view.
*/
object MyViewDecorator {
fun decorateOne(view: View, @LayoutRes decoration: Int, inflater: LayoutInflater = LayoutInflater.from(view.context)) {
val params = view.layoutParams
val parent = view.parent as ViewGroup
val idx = parent.indexOfChild(view)
parent.removeViewAt(idx)
val decorated = inflater.inflate(decoration, null)
parent.addView(decorated, idx, params)
val content = decorated.findViewById<ViewGroup>(android.R.id.content)
content.addView(view, MATCH_PARENT, MATCH_PARENT)
}
fun decorateTree(root: View, tag: String, @LayoutRes decoration: Int, inflater: LayoutInflater = LayoutInflater.from(root.context)) {
if (tag == root.tag) decorateOne(root, decoration, inflater)
else if (root is ViewGroup)
for (i in 0..root.childCount - 1)
decorateTree(root.getChildAt(i), tag, decoration, inflater)
}
fun decorateTree(root: View, decorations: Map<String, Int>, inflater: LayoutInflater = LayoutInflater.from(root.context)) {
val d = decorations[root.tag.toString()]
if (d !== null)
decorateOne(root, d, inflater)
else if (root is ViewGroup)
for (i in 0..root.childCount - 1)
decorateTree(root.getChildAt(i), decorations, inflater)
}
}
| apache-2.0 | 9eef86714f16ae9c0f03234e9e81fbf7 | 44.181818 | 141 | 0.660966 | 4.528474 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/Defaults.kt | 3 | 786 | package com.groupdocs.ui
interface Defaults {
companion object {
const val DEFAULT_LICENSE_PATH = "Licenses"
const val DEFAULT_LICENSE_EXTENSION = ".lic"
}
interface Comparison {
enum class FilesProviderType {
LOCAL
}
companion object {
const val DEFAULT_PREVIEW_PAGE_WIDTH = 768
const val DEFAULT_PREVIEW_PAGE_RATIO = 1.3f
val DEFAULT_FILES_PROVIDER_TYPE = FilesProviderType.LOCAL
val DEFAULT_TEMP_DIRECTORY: String? = System.getProperty("java.io.tmpdir")
}
}
interface Local {
companion object {
const val DEFAULT_FILES_DIRECTORY = "DocumentSamples"
const val DEFAULT_RESULT_DIRECTORY = "ResultFiles"
}
}
}
| mit | c85a5b7b1b99e443e7a528f78ab27379 | 26.103448 | 86 | 0.604326 | 4.678571 | false | false | false | false |
soywiz/korge | korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/attachments/PointAttachment.kt | 1 | 3502 | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.esotericsoftware.spine.attachments
import com.esotericsoftware.spine.utils.SpineUtils.cosDeg
import com.esotericsoftware.spine.utils.SpineUtils.radDeg
import com.esotericsoftware.spine.utils.SpineUtils.sinDeg
import com.soywiz.korim.color.RGBAf
import com.esotericsoftware.spine.utils.SpineVector2
import com.esotericsoftware.spine.Bone
/** An attachment which is a single point and a rotation. This can be used to spawn projectiles, particles, etc. A bone can be
* used in similar ways, but a PointAttachment is slightly less expensive to compute and can be hidden, shown, and placed in a
* skin.
*
*
* See [Point Attachments](http://esotericsoftware.com/spine-point-attachments) in the Spine User Guide. */
class PointAttachment(name: String) : Attachment(name) {
var x: Float = 0.toFloat()
var y: Float = 0.toFloat()
var rotation: Float = 0.toFloat()
// Nonessential.
/** The color of the point attachment as it was in Spine. Available only when nonessential data was exported. Point attachments
* are not usually rendered at runtime. */
val color = RGBAf(0.9451f, 0.9451f, 0f, 1f) // f1f100ff
fun computeWorldPosition(bone: Bone, point: SpineVector2): SpineVector2 {
point.x = x * bone.a + y * bone.b + bone.worldX
point.y = x * bone.c + y * bone.d + bone.worldY
return point
}
fun computeWorldRotation(bone: Bone): Float {
val cos = cosDeg(rotation)
val sin = sinDeg(rotation)
val x = cos * bone.a + sin * bone.b
val y = cos * bone.c + sin * bone.d
return kotlin.math.atan2(y.toDouble(), x.toDouble()).toFloat() * radDeg
}
override fun copy(): Attachment {
val copy = PointAttachment(name)
copy.x = x
copy.y = y
copy.rotation = rotation
copy.color.setTo(color)
return copy
}
}
| apache-2.0 | b41231d09393af47894cc1318ab65f5c | 43.897436 | 131 | 0.70731 | 4.174017 | false | false | false | false |
mibac138/ArgParser | core/src/main/kotlin/com/github/mibac138/argparser/parser/ArrayParser.kt | 1 | 3132 | /*
* Copyright (c) 2017 Michał Bączkowski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.mibac138.argparser.parser
import com.github.mibac138.argparser.reader.ArgumentReader
import com.github.mibac138.argparser.reader.asReader
import com.github.mibac138.argparser.reader.readUntilChar
import com.github.mibac138.argparser.syntax.SyntaxElement
import java.lang.reflect.Array
private fun parseArrayLiteral(input: ArgumentReader,
syntax: SyntaxElement,
elementParser: Parser,
separator: Char,
openingToClosingCharsMap: Map<Char, Char>): List<Any?> {
if (!input.hasNext()) return emptyList()
val start = input.next()
val end = openingToClosingCharsMap[start]
?: throw IllegalArgumentException("Unrecognized array start character: \'$start\'")
val content = input.readUntilChar(end)
val elements = content.split(separator)
return elements.map { elementParser.parse(it.asReader(), syntax) }
}
class ArrayParser(private val elementParser: Parser,
private val separator: Char = ',',
private val openingToClosingCharsMap: Map<Char, Char> = mapOf('[' to ']')) : Parser {
override val supportedTypes: Set<Class<*>> = elementParser.supportedTypes.map {
Array.newInstance(it, 0)::class.java // Class<T> -> Class<T[]>
}.toSet()
override fun parse(input: ArgumentReader, syntax: SyntaxElement)
= parseArrayLiteral(input, syntax, elementParser, separator, openingToClosingCharsMap).toTypedArray()
}
class ListParser(private val elementParser: Parser,
private val separator: Char = ',',
private val openingToClosingCharsMap: Map<Char, Char> = mapOf('[' to ']')) : Parser {
override val supportedTypes: Set<Class<*>> = setOf(List::class.java)
override fun parse(input: ArgumentReader, syntax: SyntaxElement): List<Any?>
= parseArrayLiteral(input, syntax, elementParser, separator, openingToClosingCharsMap)
} | mit | c3604e210935a8b0b5dd33f180c09e94 | 46.439394 | 113 | 0.704473 | 4.510086 | false | false | false | false |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/fragment/BaseListFragment.kt | 1 | 8314 | package de.cineaste.android.fragment
import android.app.Activity
import android.app.ActivityOptions.makeSceneTransitionAnimation
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Pair
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import de.cineaste.android.R
import de.cineaste.android.adapter.BaseListAdapter
import de.cineaste.android.database.dbHelper.UserDbHelper
import de.cineaste.android.listener.ItemClickListener
import de.cineaste.android.util.CustomRecyclerView
abstract class BaseListFragment : Fragment(), ItemClickListener, BaseListAdapter.DisplayMessage {
lateinit var watchState: WatchState
lateinit var customRecyclerView: CustomRecyclerView
internal lateinit var layoutManager: LinearLayoutManager
private lateinit var emptyListTextView: TextView
private lateinit var userDbHelper: UserDbHelper
lateinit var progressbar: RelativeLayout
private set
protected abstract val subtitle: String
protected abstract val layout: Int
protected abstract val dataSetSize: Int
protected abstract val emptyListMessageByState: Int
protected abstract val correctCallBack: ItemTouchHelper.Callback
val recyclerView: View
get() = customRecyclerView
abstract fun updateAdapter()
protected abstract fun initAdapter(activity: Activity)
protected abstract fun initRecyclerView()
protected abstract fun initFab(activity: Activity, view: View)
protected abstract fun filterOnQueryTextChange(newText: String)
protected abstract fun reorderEntries(filterType: FilterType)
protected abstract fun createIntent(itemId: Long, state: Int, activity: Activity): Intent
protected enum class FilterType {
ALPHABETICAL, RELEASE_DATE, RUNTIME
}
override fun setArguments(args: Bundle?) {
super.setArguments(args)
args?.let {
watchState = getWatchState(
args.getString(
WatchState.WATCH_STATE_TYPE.name,
WatchState.WATCH_STATE.name
)
)
}
}
private fun getWatchState(watchStateString: String): WatchState {
return if (watchStateString == WatchState.WATCH_STATE.name)
WatchState.WATCH_STATE
else
WatchState.WATCHED_STATE
}
override fun onResume() {
updateAdapter()
super.onResume()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val activity = activity
val watchlistView = initViews(inflater, container)
if (activity != null) {
initAdapter(activity)
showMessageIfEmptyList()
initRecyclerView()
initFab(activity, watchlistView)
initSwipe()
if (watchState == WatchState.WATCH_STATE) {
activity.setTitle(R.string.watchList)
} else {
activity.setTitle(R.string.history)
}
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.subtitle = subtitle
}
return watchlistView
}
private fun initViews(inflater: LayoutInflater, container: ViewGroup?): View {
val watchlistView = inflater.inflate(layout, container, false)
progressbar = watchlistView.findViewById(R.id.progressBar)
progressbar.visibility = View.GONE
emptyListTextView = watchlistView.findViewById(R.id.info_text)
customRecyclerView = watchlistView.findViewById(R.id.recycler_view)
layoutManager = LinearLayoutManager(activity)
customRecyclerView.setHasFixedSize(true)
return watchlistView
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(WatchState.WATCH_STATE_TYPE.name, watchState.name)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
if (savedInstanceState != null) {
val currentState =
savedInstanceState.getString(
WatchState.WATCH_STATE_TYPE.name,
WatchState.WATCH_STATE.name
)
this.watchState = getWatchState(currentState)
}
activity?.let {
userDbHelper = UserDbHelper.getInstance(it)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val searchViewMenuItem = menu.findItem(R.id.action_search)
val mSearchView = searchViewMenuItem.actionView as SearchView
val v = mSearchView.findViewById<ImageView>(R.id.search_button)
v.setImageResource(R.drawable.ic_filter)
super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
activity?.let {
it.menuInflater.inflate(R.menu.filter_menu, menu)
menu.findItem(R.id.action_search)?.let { searchItem ->
val searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
filterOnQueryTextChange(newText)
return false
}
})
}
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.filterAlphabetical -> reorderLists(FilterType.ALPHABETICAL)
R.id.filterReleaseDate -> reorderLists(FilterType.RELEASE_DATE)
R.id.filterRunTime -> reorderLists(FilterType.RUNTIME)
}
return super.onOptionsItemSelected(item)
}
private fun reorderLists(filterType: FilterType) {
progressbar.visibility = View.VISIBLE
customRecyclerView.enableScrolling(false)
reorderEntries(filterType)
progressbar.visibility = View.GONE
customRecyclerView.enableScrolling(true)
}
override fun showMessageIfEmptyList() {
if (dataSetSize == 0) {
customRecyclerView.visibility = View.GONE
emptyListTextView.visibility = View.VISIBLE
emptyListTextView.setText(emptyListMessageByState)
} else {
customRecyclerView.visibility = View.VISIBLE
emptyListTextView.visibility = View.GONE
}
}
override fun onItemClickListener(itemId: Long, views: Array<View>) {
if (!customRecyclerView.isScrollingEnabled) {
return
}
val state: Int = if (watchState == WatchState.WATCH_STATE) {
R.string.watchlistState
} else {
R.string.historyState
}
val activity = activity ?: return
val intent = createIntent(itemId, state, activity)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val options = makeSceneTransitionAnimation(
activity,
Pair.create(views[0], "card"),
Pair.create(views[1], "poster")
)
activity.startActivity(intent, options.toBundle())
} else {
activity.startActivity(intent)
// getActivity().overridePendingTransition( R.anim.fade_out, R.anim.fade_in );
}
}
private fun initSwipe() {
val itemTouchHelper = ItemTouchHelper(correctCallBack)
itemTouchHelper.attachToRecyclerView(customRecyclerView)
}
}
| gpl-3.0 | e810722efad0b88e6ba6a0c26dd54e91 | 33.355372 | 97 | 0.664181 | 5.288804 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/adapter/AdapterRightDish.kt | 1 | 7043 | package com.tamsiree.rxdemo.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.interfaces.ShopCartInterface
import com.tamsiree.rxdemo.model.ModelDish
import com.tamsiree.rxdemo.model.ModelDishMenu
import com.tamsiree.rxdemo.model.ModelShopCart
import java.util.*
/**
* @author tamsiree
* @date 16-11-10
*/
class AdapterRightDish(private val mContext: Context, private val mMenuList: ArrayList<ModelDishMenu>, modelShopCart: ModelShopCart) : RecyclerView.Adapter<RecyclerView.ViewHolder?>() {
private val MENU_TYPE = 0
private val DISH_TYPE = 1
private val HEAD_TYPE = 2
private var mItemCount: Int
private val mModelShopCart: ModelShopCart
var shopCartInterface: ShopCartInterface? = null
override fun getItemViewType(position: Int): Int {
var sum = 0
for (menu in mMenuList) {
if (position == sum) {
return MENU_TYPE
}
sum += menu.modelDishList!!.size + 1
}
return DISH_TYPE
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == MENU_TYPE) {
val view = LayoutInflater.from(parent.context).inflate(R.layout.right_menu_item, parent, false)
MenuViewHolder(view)
} else {
val view = LayoutInflater.from(parent.context).inflate(R.layout.right_dish_item1, parent, false)
DishViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (getItemViewType(position) == MENU_TYPE) {
val menuholder = holder as MenuViewHolder?
if (menuholder != null) {
menuholder.right_menu_title.text = getMenuByPosition(position)!!.menuName
menuholder.right_menu_layout.contentDescription = position.toString() + ""
}
} else {
val dishholder = holder as DishViewHolder?
if (dishholder != null) {
val modelDish = getDishByPosition(position)
dishholder.right_dish_name_tv.text = modelDish!!.dishName
dishholder.right_dish_price_tv.text = modelDish.dishPrice.toString() + ""
dishholder.right_dish_layout.contentDescription = position.toString() + ""
var count = 0
if (mModelShopCart.shoppingSingleMap.containsKey(modelDish)) {
count = mModelShopCart.shoppingSingleMap[modelDish]!!
}
if (count <= 0) {
dishholder.right_dish_remove_iv.visibility = View.GONE
dishholder.right_dish_account_tv.visibility = View.GONE
} else {
dishholder.right_dish_remove_iv.visibility = View.VISIBLE
dishholder.right_dish_account_tv.visibility = View.VISIBLE
dishholder.right_dish_account_tv.text = count.toString() + ""
}
dishholder.right_dish_add_iv.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
if (mModelShopCart.addShoppingSingle(modelDish)) {
notifyItemChanged(position)
if (shopCartInterface != null) {
shopCartInterface!!.add(view, position)
}
}
}
})
dishholder.right_dish_remove_iv.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
if (mModelShopCart.subShoppingSingle(modelDish)) {
notifyItemChanged(position)
if (shopCartInterface != null) {
shopCartInterface!!.remove(view, position)
}
}
}
})
}
}
}
fun getMenuByPosition(position: Int): ModelDishMenu? {
var sum = 0
for (menu in mMenuList) {
if (position == sum) {
return menu
}
sum += menu.modelDishList!!.size + 1
}
return null
}
fun getDishByPosition(position: Int): ModelDish? {
var position = position
for (menu in mMenuList) {
position -= if (position > 0 && position <= menu.modelDishList!!.size) {
return menu.modelDishList!![position - 1]
} else {
menu.modelDishList!!.size + 1
}
}
return null
}
fun getMenuOfMenuByPosition(position: Int): ModelDishMenu? {
var position = position
for (menu in mMenuList) {
if (position == 0) {
return menu
}
position -= if (position > 0 && position <= menu.modelDishList!!.size) {
return menu
} else {
menu.modelDishList!!.size + 1
}
}
return null
}
override fun getItemCount(): Int {
return mItemCount
}
private inner class MenuViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val right_menu_layout: LinearLayout
val right_menu_title: TextView
init {
right_menu_layout = itemView.findViewById<View>(R.id.right_menu_item) as LinearLayout
right_menu_title = itemView.findViewById<View>(R.id.right_menu_tv) as TextView
}
}
private inner class DishViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val right_dish_name_tv: TextView
val right_dish_price_tv: TextView
val right_dish_layout: LinearLayout
val right_dish_remove_iv: ImageView
val right_dish_add_iv: ImageView
val right_dish_account_tv: TextView
init {
right_dish_name_tv = itemView.findViewById<View>(R.id.right_dish_name) as TextView
right_dish_price_tv = itemView.findViewById<View>(R.id.right_dish_price) as TextView
right_dish_layout = itemView.findViewById<View>(R.id.right_dish_item) as LinearLayout
right_dish_remove_iv = itemView.findViewById<View>(R.id.right_dish_remove) as ImageView
right_dish_add_iv = itemView.findViewById<View>(R.id.right_dish_add) as ImageView
right_dish_account_tv = itemView.findViewById<View>(R.id.right_dish_account) as TextView
}
}
init {
mItemCount = mMenuList.size
mModelShopCart = modelShopCart
for (menu in mMenuList) {
mItemCount += menu.modelDishList!!.size
}
}
} | apache-2.0 | 11f23be0431872f5344da4b04f77bd0c | 38.351955 | 185 | 0.585688 | 4.371819 | false | false | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/fetch/AppIconUriFetcher.kt | 1 | 3951 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.fetch
import androidx.annotation.WorkerThread
import androidx.core.net.toUri
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.datasource.DataFrom
import com.github.panpf.sketch.datasource.DataFrom.LOCAL
import com.github.panpf.sketch.datasource.UnavailableDataSource
import com.github.panpf.sketch.fetch.AppIconUriFetcher.Companion.SCHEME
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.request.UriInvalidException
import com.github.panpf.sketch.util.ifOrNull
import java.io.IOException
import java.io.InputStream
/**
* Sample: 'app.icon://com.github.panpf.sketch.sample/1120'
*/
fun newAppIconUri(packageName: String, versionCode: Int): String =
"$SCHEME://$packageName/$versionCode"
/**
* Extract the icon of the installed app
*
* Support 'app.icon://com.github.panpf.sketch.sample/1120' uri
*/
class AppIconUriFetcher(
val sketch: Sketch,
val request: ImageRequest,
val packageName: String,
val versionCode: Int,
) : Fetcher {
companion object {
const val SCHEME = "app.icon"
const val MIME_TYPE = "application/vnd.android.app-icon"
}
@WorkerThread
override suspend fun fetch(): FetchResult = FetchResult(
AppIconDataSource(sketch, request, LOCAL, packageName, versionCode),
MIME_TYPE
)
class Factory : Fetcher.Factory {
override fun create(sketch: Sketch, request: ImageRequest): AppIconUriFetcher? {
val uri = request.uriString.toUri()
return ifOrNull(SCHEME.equals(uri.scheme, ignoreCase = true)) {
val packageName = uri.authority
?.takeIf { it.isNotEmpty() && it.isNotBlank() }
?: throw UriInvalidException("App icon uri 'packageName' part invalid: ${request.uriString}")
val versionCode = uri.lastPathSegment
?.takeIf { it.isNotEmpty() && it.isNotBlank() }
?.toIntOrNull()
?: throw UriInvalidException("App icon uri 'versionCode' part invalid: ${request.uriString}")
AppIconUriFetcher(sketch, request, packageName, versionCode)
}
}
override fun toString(): String = "AppIconUriFetcher"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return true
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class AppIconDataSource(
override val sketch: Sketch,
override val request: ImageRequest,
override val dataFrom: DataFrom,
val packageName: String,
val versionCode: Int,
) : UnavailableDataSource {
@WorkerThread
@Throws(IOException::class)
override fun length(): Long =
throw UnsupportedOperationException("Please configure AppIconBitmapDecoder")
@WorkerThread
@Throws(IOException::class)
override fun newInputStream(): InputStream =
throw UnsupportedOperationException("Please configure AppIconBitmapDecoder")
override fun toString(): String =
"AppIconDataSource(packageName='$packageName',versionCode=$versionCode)"
}
} | apache-2.0 | cc1813974990bde441bbd7c6657844a6 | 34.927273 | 113 | 0.675525 | 4.714797 | false | false | false | false |
usmansaleem/kt-vertx | src/main/kotlin/info/usmans/blog/vertx/RoutingContextHandlers.kt | 1 | 9335 | package info.usmans.blog.vertx
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.module.kotlin.readValue
import info.usmans.blog.model.BlogItem
import info.usmans.blog.model.BlogItemUtil
import info.usmans.blog.model.Category
import info.usmans.blog.model.Message
import io.vertx.core.Handler
import io.vertx.core.Vertx
import io.vertx.core.http.HttpHeaders
import io.vertx.core.json.DecodeException
import io.vertx.core.json.Json
import io.vertx.ext.auth.oauth2.AccessToken
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.impl.Utils
import io.vertx.ext.web.templ.TemplateEngine
import java.io.File
fun blogItemListFromJson(dataJson: String): List<BlogItem>? {
return try {
Json.mapper.readValue(dataJson)
} catch (e: JsonParseException) {
println(e.message)
null
}
}
fun highestPageHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc -> rc.response().sendPlain(blogItemUtil.getHighestPage().toString()) }
fun blogCountHandlerGet(blogItemMapUtil: BlogItemUtil) = Handler<RoutingContext> { rc -> rc.response().sendPlain(blogItemMapUtil.getBlogCount().toString()) }
fun pageNumberHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc ->
val pageNumber = rc.request().getParam("pageNumber").toLongOrNull() ?: 0
if (pageNumber >= 1) {
val pagedBlogItemsList = blogItemUtil.getBlogItemListForPage(pageNumber)
if (pagedBlogItemsList.isNotEmpty()) {
rc.response().sendJsonWithCacheControl(Json.encode(pagedBlogItemsList))
} else {
rc.response().endWithErrorJson("Bad Request - Invalid Page Number $pageNumber")
}
} else {
rc.response().endWithErrorJson("Bad Request - Invalid Page Number $pageNumber")
}
}
fun blogItemsHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc ->
rc.response().sendJsonWithCacheControl(Json.encodePrettily(blogItemUtil.getBlogItemList()))
}
fun blogItemByIdHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc ->
val blogItemId = rc.request().getParam("id").toLongOrNull() ?: 0
val blogItem = blogItemUtil.getBlogItemForId(blogItemId)
if (blogItem == null) {
rc.response().endWithErrorJson("Bad Request - Invalid Id: $blogItemId")
} else {
rc.response().sendJsonWithCacheControl(Json.encode(blogItem))
}
}
fun siteMapHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc ->
rc.response().putHeader("Content-Type", "text; charset=utf-8").end(blogItemUtil.getBlogItemUrlList().joinToString("\n") {
"${rc.request().getOAuthRedirectURI("/usmansaleem/blog/")}$it"
})
}
fun blogByFriendlyUrlGet(blogItemUtil: BlogItemUtil, templateEngine: TemplateEngine) = Handler<RoutingContext> { rc ->
val friendlyUrl = rc.request().getParam("url")
val blogItem = blogItemUtil.getBlogItemForUrl(friendlyUrl)
if (blogItem != null) {
//pass blogItem to the template
rc.put("blogItem", blogItem)
templateEngine.render(rc, "templates", Utils.normalizePath("blog.hbs"), { res ->
if (res.succeeded()) {
rc.response().apply {
putHeader(HttpHeaders.CONTENT_TYPE, "text/html")
putHeader(HttpHeaders.CACHE_CONTROL, "max-age=1800, must-revalidate")
end(res.result())
}
} else {
rc.fail(res.cause())
}
})
} else {
rc.response().endWithErrorJson("Invalid Blog Request")
}
}
fun redirectToFriendlyUrlHandlerGet(blogItemUtil: BlogItemUtil) = Handler<RoutingContext> { rc ->
val blogItemId = rc.request().getParam("id").toLongOrNull() ?: 0
val blogItem = blogItemUtil.getBlogItemForId(blogItemId)
if(blogItem == null) {
rc.response().endWithErrorJson("Invalid Request for Blog")
} else {
rc.request().redirectToSecure(blogItem.urlFriendlyId)
}
}
fun protectedPageByTemplateHandlerGet(blogItemList: BlogItemUtil, templateEngine: TemplateEngine) = Handler<RoutingContext> { rc ->
rc.put("blogItems", blogItemList.getBlogItemList())
val accessToken: AccessToken? = rc.user() as AccessToken
rc.put("accessToken", accessToken?.principal()?.encodePrettily())
templateEngine.render(rc, "templates", io.vertx.ext.web.impl.Utils.normalizePath("protected/protected.hbs"), { res ->
if (res.succeeded()) {
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html").end(res.result())
} else {
rc.fail(res.cause())
}
})
}
fun blogEditHandlerGet(blogItemUtil: BlogItemUtil, templateEngine: TemplateEngine) = Handler<RoutingContext> { rc ->
val blogItemId = rc.request().getParam("id").toLongOrNull() ?: 0
val blogItem = blogItemUtil.getBlogItemForId(blogItemId)
if (blogItem != null) {
//pass blogItem to the template
rc.put("blogItem", blogItem)
templateEngine.render(rc, "templates", io.vertx.ext.web.impl.Utils.normalizePath("protected/blogedit.hbs"), { res ->
if (res.succeeded()) {
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html").end(res.result())
} else {
rc.fail(res.cause())
}
})
} else {
rc.response().endWithErrorJson("Invalid Blog Request for id $blogItemId")
}
}
fun blogEditHandlerPost(blogItemUtil: BlogItemUtil, checkoutDir: File) = Handler<RoutingContext> { rc ->
val blogItemId = rc.request().getParam("blogId").toLongOrNull() ?: 0
val existingBlogItem = blogItemUtil.getBlogItemForId(blogItemId)
if (existingBlogItem != null) {
val modifiedBlogItem = getNewBlogItemFromSubmittedForm(rc, blogItemId).copy(createdOn = existingBlogItem.createdOn,
createDay = existingBlogItem.createDay, createMonth = existingBlogItem.createMonth,
createYear = existingBlogItem.createYear)
blogItemUtil.putBlogItemForId(blogItemId, modifiedBlogItem)
blogItemUtil.initPagedBlogItems()
//update data.json in local repo
File(checkoutDir, "data.json").writeText(Json.encodePrettily(blogItemUtil.getBlogItemList()))
commitGist(checkoutDir, "Updating blog $blogItemId from jgit")
pushGist(checkoutDir)
rc.response().sendJson(Json.encode(Message("Blog Successfully updated")))
} else {
rc.response().endWithErrorJson("Invalid Blog Request for id $blogItemId")
}
}
fun blogNewGetHandler(blogItemUtil: BlogItemUtil, templateEngine: TemplateEngine) = Handler<RoutingContext> { rc ->
rc.put("blogItem", BlogItem(blogItemUtil.getNextBlogItemId(), "url_friendly", "Title...", "Description...", "Body...", "Main"))
templateEngine.render(rc, "templates", io.vertx.ext.web.impl.Utils.normalizePath("protected/blogedit.hbs"), { res ->
if (res.succeeded()) {
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html").end(res.result())
} else {
rc.fail(res.cause())
}
})
}
fun blogNewPostHandler(blogItemUtil: BlogItemUtil, checkoutDir: File) = Handler<RoutingContext> { rc ->
val blogItemId = blogItemUtil.getNextBlogItemId()
val modifiedBlogItem = getNewBlogItemFromSubmittedForm(rc, blogItemId)
blogItemUtil.putBlogItemForId(blogItemId, modifiedBlogItem)
blogItemUtil.initPagedBlogItems()
//update data.json in local repo
File(checkoutDir, "data.json").writeText(Json.encodePrettily(blogItemUtil.getBlogItemList()))
commitGist(checkoutDir, "Updating blog $blogItemId from jgit")
pushGist(checkoutDir)
rc.response().sendJson(Json.encode(Message("Blog id $blogItemId Successfully created")))
}
fun iftttWebHookPostHandler(vertx: Vertx) = Handler<RoutingContext> { rc ->
try {
val body = rc.bodyAsJson
if(body != null) {
val challenge = body.getString("challenge")
if(challenge != null && ENV_BLOG_CUSTOM_NET_PASSWORD == challenge) {
val action = body.getString("action") //not used at the moment
//success code
vertx.eventBus().publish("action-feed", action ?: "Got Action from ifttt")
rc.response().sendPlain("ok")
} else {
rc.response().endWithErrorPlain("Invalid Challenge")
}
} else {
rc.response().endWithErrorPlain("Invalid Json")
}
} catch (de: DecodeException) {
rc.response().endWithErrorPlain("Invalid Json")
}
}
private fun getNewBlogItemFromSubmittedForm(rc: RoutingContext, id: Long): BlogItem {
//obtain submitted values ...
val urlFriendlyId = rc.request().getFormAttribute("urlFriendlyId")
val title = rc.request().getFormAttribute("title")
val description = rc.request().getFormAttribute("description")
val body = rc.request().getFormAttribute("body")
val categories = rc.request().getFormAttribute("categories")
val categoryList = if (categories.isNullOrBlank())
emptyList()
else
categories.split(",").mapIndexed { i, s ->
Category(i, s.trim())
}
return BlogItem(id = id, urlFriendlyId = urlFriendlyId, title = title, description = description, body = body, categories = categoryList)
}
| mit | efd1f3e51dcbc719993c9f0d3bed8e31 | 41.04955 | 157 | 0.680236 | 4.011603 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.