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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HTWDD/HTWDresden
|
app/src/main/java/de/htwdd/htwdresden/ui/views/fragments/TimetableFragment.kt
|
1
|
6147
|
package de.htwdd.htwdresden.ui.views.fragments
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView.SmoothScroller
import de.htwdd.htwdresden.R
import de.htwdd.htwdresden.adapter.TimetableItemAdapter
import de.htwdd.htwdresden.adapter.Timetables
import de.htwdd.htwdresden.ui.models.TimetableHeaderItem
import de.htwdd.htwdresden.ui.viewmodels.fragments.TimetableViewModel
import de.htwdd.htwdresden.utils.extensions.*
import de.htwdd.htwdresden.utils.holders.CryptoSharedPreferencesHolder
import kotlinx.android.synthetic.main.fragment_timetable.*
import kotlinx.android.synthetic.main.layout_empty_view.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.properties.Delegates
class TimetableFragment: Fragment(R.layout.fragment_timetable) {
private val defaultPattern = "dd.MM.yyyy"
private val viewModel by lazy { getViewModel<TimetableViewModel>() }
private lateinit var adapter: TimetableItemAdapter
private val items: Timetables = ArrayList()
private var isRefreshing: Boolean by Delegates.observable(true) { _, _, new ->
weak { self -> self.swipeRefreshLayout.isRefreshing = new }
}
private val cph by lazy { CryptoSharedPreferencesHolder.instance }
private val smoothScroller: SmoothScroller by lazy {
object : LinearSmoothScroller(context) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setup()
request()
}
override fun onResume() {
super.onResume()
cph.onChanged()
.runInUiThread()
.subscribe {
when (it) {
is CryptoSharedPreferencesHolder.SubscribeType.StudyToken -> {
weak { self ->
self.request()
}
}
}
}
.addTo(disposeBag)
}
private fun setup() {
swipeRefreshLayout.setOnRefreshListener { request() }
adapter = TimetableItemAdapter(items)
adapter.onItemsLoaded { goToToday(smooth = false) }
timetableRecycler.adapter = adapter
adapter.onEmpty {
weak { self ->
self.includeEmptyLayout.toggle(it)
self.tvIcon.text = getString(R.string.exams_no_results_icon)
self.tvTitle.text = getString(R.string.timetable_no_results_title)
self.tvMessage.text = getString(R.string.timetable_no_results_message)
}
}
}
private fun request() {
viewModel.request()
.runInUiThread()
.doOnSubscribe { isRefreshing = true }
.doOnTerminate { isRefreshing = false }
.doOnComplete { isRefreshing = false }
.doOnDispose { isRefreshing = false }
.subscribe({ timetables ->
weak { self ->
if (timetables.isNotEmpty()) {
self.adapter.update(timetables)
}
}
}, {
error(it)
weak { self ->
self.includeEmptyLayout.show()
self.tvIcon.text = getString(R.string.exams_no_results_icon)
self.tvTitle.text = getString(R.string.exams_no_credentials_title)
self.tvMessage.text = getString(R.string.timetable_no_credentials_message)
self.btnEmptyAction.apply {
show()
text = getString(R.string.general_add)
click {
self.findNavController().navigate(R.id.action_to_study_group_page_fragment)
}
}
}
})
.addTo(disposeBag)
}
private fun goToToday(smooth: Boolean = false) {
if (items.isNotEmpty()) {
val todayPosition = findTodayPosition()
val targetPosition = if (todayPosition == 0) todayPosition else (todayPosition - 1) % items.size
if (!smooth) {
Handler().post {
(timetableRecycler.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(targetPosition, 0)
}
} else {
Handler().postDelayed({
smoothScroller.targetPosition = targetPosition
timetableRecycler.layoutManager?.startSmoothScroll(smoothScroller)
}, 25)
}
}
}
private fun findTodayPosition(): Int {
val first = items.firstOrNull().guard { return 0 }
(first as? TimetableHeaderItem)?.let {
if (Date() < it.subheader()) {
return 0
}
}
var position = 0
val currentDate = Date()
items.forEach {
position += 1
if (it is TimetableHeaderItem) {
if (it.subheader().format(defaultPattern) == currentDate.format(defaultPattern) || it.subheader().after(currentDate)) {
return position
}
}
}
return items.size
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_today -> {
goToToday(smooth = true)
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.timetable, menu)
return super.onCreateOptionsMenu(menu, inflater)
}
}
|
mit
|
4c06f4449d9613361813d6728d7e3a73
| 36.036145 | 135 | 0.592647 | 5.013866 | false | false | false | false |
kivensolo/UiUsingListView
|
module-Home/src/main/java/com/zeke/home/api/RecomDataServiceImpl.kt
|
1
|
5091
|
package com.zeke.home.api
import android.content.Context
import android.os.AsyncTask
import android.util.JsonReader
import android.widget.Toast
import com.zeke.home.entity.PageContent
import com.zeke.home.entity.TemplatePageData
import com.zeke.kangaroo.utils.ZLog
import com.zeke.network.response.IRequestResponse
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
/**
* author:KingZ
* date:2020/2/21
* description:首页推荐数据实现类
*/
class RecomDataServiceImpl : DataApiService<MutableList<TemplatePageData>> {
companion object {
private val TAG = RecomDataServiceImpl::class.java.simpleName
private lateinit var mCallBack: IRequestResponse<MutableList<TemplatePageData>>
}
override fun requestData(context: Context,
callback: IRequestResponse<MutableList<TemplatePageData>>) {
mCallBack = callback
val assetManager = context.assets
val uris: Array<String>
val uriList = ArrayList<String>()
try {
for (asset in assetManager.list("")) {
if (asset.endsWith("_data.json")) {
uriList.add(asset)
}
}
} catch (e: IOException) {
Toast.makeText(context, "No home_data.json file to load !!!",
Toast.LENGTH_LONG).show()
}
uris = uriList.toTypedArray()
uris.sort()
// 异步加载本地数据,模拟网络请求
HomeDataLoader(context).execute(uris[0])
}
class HomeDataLoader(var ctx: Context)
: AsyncTask<String, Void, MutableList<TemplatePageData>>() {
private var sawError: Boolean = false
override fun doInBackground(vararg parms: String?): MutableList<TemplatePageData> {
val homeRecomData = ArrayList<TemplatePageData>()
for (uri in parms) {
try {
val inputStream = ctx.assets.open(uri)
praseLocalJsonData(JsonReader(
InputStreamReader(inputStream, "UTF-8")),
homeRecomData)
} catch (e: Exception) {
ZLog.e(TAG, "Error loading sample list: $uri", e)
sawError = true
}
}
return homeRecomData
}
// 等同于Java的 throws IOException
@Throws(IOException::class)
private fun praseLocalJsonData(
reader: JsonReader,
pages: MutableList<TemplatePageData>) {
reader.beginArray()
while (reader.hasNext()) {
parsePage(reader, pages)
}
reader.endArray()
}
@Throws(IOException::class)
private fun parsePage(
reader: JsonReader,
pages: MutableList<TemplatePageData>) {
var pageId = ""
var pageName = ""
var pageType = ""
var pageContent: MutableList<PageContent>? = null
val pageLIst = ArrayList<TemplatePageData>()
reader.beginObject()
while (reader.hasNext()) {
val node = reader.nextName()
// switch-case
when (node) {
"id" -> pageId = reader.nextString()
"name" -> pageName = reader.nextString()
"type" -> pageType = reader.nextString()
"page_content" -> {
reader.beginArray()
while (reader.hasNext()) {
pageContent = readPageContent(reader)
}
reader.endArray()
}
else -> reader.nextString()
}
}
reader.endObject()
pageLIst.add(TemplatePageData(pageId, pageName, pageType, pageContent))
pages.addAll(pageLIst)
}
@Throws(IOException::class)
private fun readPageContent(reader: JsonReader): MutableList<PageContent> {
var content_id: String? = ""
var type: String? = ""
var content_name: String? = ""
var pageContentList = ArrayList<PageContent>()
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (name) {
"id" -> content_id = reader.nextString()
"type" -> type = reader.nextString()
"name" -> content_name = reader.nextString()
else -> reader.nextString()
}
pageContentList.add(PageContent(content_id!!, type!!))
}
reader.endObject()
return pageContentList
}
override fun onPostExecute(result: MutableList<TemplatePageData>) {
super.onPostExecute(result)
//TODO 处理完毕返回数据
mCallBack.onSuccess(result)
}
}
}
|
gpl-2.0
|
134a072606a40f97e06e4c4dd12579e1
| 33.102041 | 91 | 0.534411 | 5.063636 | false | false | false | false |
feelfreelinux/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/tag/TagRepository.kt
|
1
|
3244
|
package io.github.feelfreelinux.wykopmobilny.api.tag
import io.github.feelfreelinux.wykopmobilny.api.UserTokenRefresher
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandler
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandlerTransformer
import io.github.feelfreelinux.wykopmobilny.api.filters.OWMContentFilter
import io.github.feelfreelinux.wykopmobilny.api.patrons.PatronsApi
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.TagEntriesMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.TagLinksMapper
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.ObserveStateResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.ObservedTagResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses.TagEntriesResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses.TagLinksResponse
import io.github.feelfreelinux.wykopmobilny.utils.preferences.BlacklistPreferencesApi
import io.reactivex.Single
import retrofit2.Retrofit
class TagRepository(
retrofit: Retrofit,
val userTokenRefresher: UserTokenRefresher,
val owmContentFilter: OWMContentFilter,
private val blacklistPreferencesApi: BlacklistPreferencesApi) : TagApi {
private val tagApi by lazy { retrofit.create(TagRetrofitApi::class.java) }
override fun getTagEntries(tag: String, page: Int) = tagApi.getTagEntries(tag, page)
.retryWhen(userTokenRefresher)
.flatMap(ErrorHandler<TagEntriesResponse>())
.map { TagEntriesMapper.map(it, owmContentFilter) }
override fun getTagLinks(tag: String, page: Int) = tagApi.getTagLinks(tag, page)
.retryWhen(userTokenRefresher)
.flatMap(ErrorHandler<TagLinksResponse>())
.map { TagLinksMapper.map(it, owmContentFilter) }
override fun getObservedTags(): Single<List<ObservedTagResponse>> =
tagApi.getObservedTags()
.retryWhen(userTokenRefresher)
.compose<List<ObservedTagResponse>>(ErrorHandlerTransformer())
override fun observe(tag: String) = tagApi.observe(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
override fun unobserve(tag: String) = tagApi.unobserve(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
override fun block(tag: String) = tagApi.block(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
.doOnSuccess {
if (!blacklistPreferencesApi.blockedTags.contains(tag.removePrefix("#"))) {
blacklistPreferencesApi.blockedTags = blacklistPreferencesApi.blockedTags.plus(tag.removePrefix("#"))
}
}
override fun unblock(tag: String) = tagApi.unblock(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
.doOnSuccess {
if (blacklistPreferencesApi.blockedTags.contains(tag.removePrefix("#"))) {
blacklistPreferencesApi.blockedTags = blacklistPreferencesApi.blockedTags.minus(tag.removePrefix("#"))
}
}
}
|
mit
|
284d2137f859ae845b5c49da727d35d6
| 48.166667 | 118 | 0.761406 | 4.575458 | false | false | false | false |
siosio/intellij-community
|
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/PluginSignatureChecker.kt
|
1
|
8517
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins.marketplace
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.certificates.PluginCertificateStore
import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector
import com.intellij.ide.plugins.marketplace.statistics.enums.DialogAcceptanceResultEnum
import com.intellij.ide.plugins.marketplace.statistics.enums.SignatureVerificationResult
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.ui.Messages
import com.intellij.util.io.HttpRequests
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.zip.signer.signer.CertificateUtils
import org.jetbrains.zip.signer.verifier.*
import java.io.File
import java.security.cert.Certificate
import java.security.cert.CertificateFactory
import java.security.cert.X509CRL
import java.security.cert.X509Certificate
import java.util.*
import java.util.concurrent.TimeUnit
@ApiStatus.Internal
internal object PluginSignatureChecker {
private val LOG = logger<PluginSignatureChecker>()
private val jetBrainsCertificateRevokedCache = Caffeine
.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build<String, Optional<Boolean>>()
private val jetbrainsCertificate: Certificate? by lazy {
val cert = PluginSignatureChecker.javaClass.classLoader.getResourceAsStream("ca.crt")
if (cert == null) {
LOG.warn(IdeBundle.message("jetbrains.certificate.not.found"))
null
}
else {
CertificateFactory.getInstance("X.509").generateCertificate(cert)
}
}
@JvmStatic
fun verify(descriptor: IdeaPluginDescriptor, pluginFile: File, showAcceptDialog: Boolean = true): Boolean {
val certificates = PluginCertificateStore.customTrustManager.certificates.orEmpty() + PluginCertificateStore.managedTrustedCertificates
return if (showAcceptDialog) {
isSignedInWithAcceptDialog(descriptor, pluginFile, certificates)
}
else {
isSignedInBackground(descriptor, pluginFile, certificates)
}
}
private fun isSignedInBackground(
descriptor: IdeaPluginDescriptor,
pluginFile: File,
certificates: List<Certificate> = emptyList()
): Boolean {
val jbCert = jetbrainsCertificate ?: return false
val isRevoked = runCatching { isJetBrainsCertificateRevoked() }.getOrNull() ?: return false
if (isRevoked) {
LOG.info("Plugin ${pluginFile.name} has revoked JetBrains certificate")
return false
}
val allCerts = certificates + jbCert
return isSignedBy(descriptor, pluginFile, showAcceptDialog = false, *allCerts.toTypedArray())
}
private fun isSignedInWithAcceptDialog(
descriptor: IdeaPluginDescriptor,
pluginFile: File,
certificates: List<Certificate> = emptyList()
): Boolean {
val jbCert = jetbrainsCertificate
?: return processSignatureCheckerVerdict(descriptor, IdeBundle.message("jetbrains.certificate.not.found"))
val isRevoked = try {
isJetBrainsCertificateRevoked()
}
catch (e: IllegalArgumentException) {
val message = e.message ?: IdeBundle.message("jetbrains.certificate.invalid")
return processSignatureCheckerVerdict(descriptor, message)
}
if (isRevoked) {
LOG.info("Plugin ${pluginFile.name} has revoked JetBrains certificate")
val message = IdeBundle.message("plugin.signature.checker.revoked.cert", descriptor.name)
return processSignatureCheckerVerdict(descriptor, message)
}
val allCerts = certificates + jbCert
return isSignedBy(descriptor, pluginFile, showAcceptDialog = true, *allCerts.toTypedArray())
}
private fun isJetBrainsCertificateRevoked(): Boolean {
val isRevokedCached = jetBrainsCertificateRevokedCache.getIfPresent(this.javaClass.name)?.get()
if (isRevokedCached != null) return isRevokedCached
val cert509Lists = listOfNotNull(jetbrainsCertificate as? X509Certificate)
val lists = getRevocationLists(cert509Lists)
val revokedCertificates = CertificateUtils.findRevokedCertificate(cert509Lists, lists)
val isRevoked = revokedCertificates != null
jetBrainsCertificateRevokedCache.put(this.javaClass.name, Optional.of(isRevoked))
return isRevoked
}
private fun getRevocationLists(certs: List<X509Certificate>): List<X509CRL> {
val certsExceptCA = certs.subList(0, certs.size - 1)
return certsExceptCA.mapNotNull { certificate ->
val crlUris = CertificateUtils.getCrlUris(certificate)
if (crlUris.isEmpty()) {
LOG.error("CRL not found for certificate")
throw IllegalArgumentException("CRL not found for certificate")
}
if (crlUris.size > 1) {
LOG.error("Multiple CRL URI found in certificate")
throw IllegalArgumentException("Multiple CRL URI found in certificate")
}
val crlURI = crlUris.first()
val certificateFactory = CertificateFactory.getInstance("X.509")
val inputStream = HttpRequests.request(crlURI.toURL().toExternalForm())
.throwStatusCodeException(false)
.productNameAsUserAgent()
.connect { it.inputStream }
certificateFactory.generateCRL(inputStream) as? X509CRL
}
}
private fun isSignedBy(
descriptor: IdeaPluginDescriptor,
pluginFile: File,
showAcceptDialog: Boolean = true,
vararg certificate: Certificate,
): Boolean {
val errorMessage = verifyPluginAndGetErrorMessage(descriptor, pluginFile, *certificate)
if (errorMessage != null && showAcceptDialog) {
return processSignatureCheckerVerdict(descriptor, errorMessage)
}
if (errorMessage != null) {
return false
}
return true
}
private fun verifyPluginAndGetErrorMessage(descriptor: IdeaPluginDescriptor, file: File, vararg certificates: Certificate): String? {
return when (val verificationResult = ZipVerifier.verify(file)) {
is InvalidSignatureResult -> {
PluginManagerUsageCollector.signatureCheckResult(descriptor, SignatureVerificationResult.INVALID_SIGNATURE)
IdeBundle.message("plugin.invalid.signature.result", descriptor.name, verificationResult.errorMessage)
}
is MissingSignatureResult -> {
PluginManagerUsageCollector.signatureCheckResult(descriptor, SignatureVerificationResult.MISSING_SIGNATURE)
getSignatureWarningMessage(descriptor)
}
is SuccessfulVerificationResult -> {
val isSigned = certificates.any { certificate ->
certificate is X509Certificate && verificationResult.isSignedBy(certificate)
}
if (!isSigned) {
PluginManagerUsageCollector.signatureCheckResult(descriptor, SignatureVerificationResult.WRONG_SIGNATURE)
getSignatureWarningMessage(descriptor)
}
else {
PluginManagerUsageCollector.signatureCheckResult(descriptor, SignatureVerificationResult.SUCCESSFUL)
null
}
}
}
}
private fun getSignatureWarningMessage(descriptor: IdeaPluginDescriptor): String {
val vendor = if (descriptor.organization.isNullOrBlank()) descriptor.vendor else descriptor.organization
val vendorMessage = if (vendor.isNullOrBlank()) vendor else IdeBundle.message("jetbrains.certificate.vendor", vendor)
return IdeBundle.message(
"plugin.signature.not.signed",
descriptor.name,
descriptor.pluginId.idString,
descriptor.version,
vendorMessage
)
}
private fun processSignatureCheckerVerdict(descriptor: IdeaPluginDescriptor, @Nls message: String): Boolean {
val title = IdeBundle.message("plugin.signature.checker.title")
val yesText = IdeBundle.message("plugin.signature.checker.yes")
val noText = IdeBundle.message("plugin.signature.checker.no")
var result: Int = -1
ApplicationManager.getApplication().invokeAndWait(
{ result = Messages.showYesNoDialog(message, title, yesText, noText, Messages.getWarningIcon()) },
ModalityState.any()
)
PluginManagerUsageCollector.signatureWarningShown(
descriptor,
if (result == Messages.YES) DialogAcceptanceResultEnum.ACCEPTED else DialogAcceptanceResultEnum.DECLINED
)
return result == Messages.YES
}
}
|
apache-2.0
|
595b39d23a298d2b4b9dd47a81a856c2
| 41.59 | 140 | 0.751321 | 4.76076 | false | false | false | false |
siosio/intellij-community
|
platform/util-ex/src/com/intellij/util/containers/util.kt
|
1
|
9210
|
// 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.util.containers
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.SmartList
import com.intellij.util.lang.CompoundRuntimeException
import java.util.*
import java.util.stream.Stream
import kotlin.collections.ArrayDeque
import kotlin.collections.HashSet
fun <K, V> MutableMap<K, MutableList<V>>.remove(key: K, value: V) {
val list = get(key)
if (list != null && list.remove(value) && list.isEmpty()) {
remove(key)
}
}
fun <K, V> MutableMap<K, MutableList<V>>.putValue(key: K, value: V) {
val list = get(key)
if (list == null) {
put(key, SmartList(value))
}
else {
list.add(value)
}
}
fun Collection<*>?.isNullOrEmpty(): Boolean = this == null || isEmpty()
@Deprecated("use tail()", ReplaceWith("tail()"), DeprecationLevel.ERROR)
val <T> List<T>.tail: List<T>
get() = tail()
/**
* @return all the elements of a non-empty list except the first one
*/
fun <T> List<T>.tail(): List<T> {
require(isNotEmpty())
return subList(1, size)
}
/**
* @return all the elements of a non-empty list except the first one or empty list
*/
fun <T> List<T>.tailOrEmpty(): List<T> {
if (isEmpty()) return emptyList()
return subList(1, size)
}
/**
* @return pair of the first element and the rest of a non-empty list
*/
fun <T> List<T>.headTail(): Pair<T, List<T>> = Pair(first(), tail())
/**
* @return pair of the first element and the rest of a non-empty list, or `null` if a list is empty
*/
fun <T> List<T>.headTailOrNull(): Pair<T, List<T>>? = if (isEmpty()) null else headTail()
/**
* @return all the elements of a non-empty list except the last one
*/
fun <T> List<T>.init(): List<T> {
require(isNotEmpty())
return subList(0, size - 1)
}
fun <T> List<T>?.nullize(): List<T>? = if (isNullOrEmpty()) null else this
inline fun <T> Array<out T>.forEachGuaranteed(operation: (T) -> Unit) {
return iterator().forEachGuaranteed(operation)
}
inline fun <T> Collection<T>.forEachGuaranteed(operation: (T) -> Unit) {
return iterator().forEachGuaranteed(operation)
}
inline fun <T> Iterator<T>.forEachGuaranteed(operation: (T) -> Unit) {
var errors: MutableList<Throwable>? = null
for (element in this) {
try {
operation(element)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList()
}
errors.add(e)
}
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
inline fun <T> Collection<T>.forEachLoggingErrors(logger: Logger, operation: (T) -> Unit) {
asSequence().forEach {
try {
operation(it)
}
catch (e: Throwable) {
logger.error(e)
}
}
return
}
inline fun <T, R : Any> Collection<T>.mapNotNullLoggingErrors(logger: Logger, operation: (T) -> R?): List<R> {
return mapNotNull {
try {
operation(it)
}
catch (e: Throwable) {
logger.error(e)
null
}
}
}
fun <T> Array<T>?.stream(): Stream<T> = if (this != null) Stream.of(*this) else Stream.empty()
fun <T> Stream<T>?.isEmpty(): Boolean = this == null || !this.findAny().isPresent
fun <T> Stream<T>?.notNullize(): Stream<T> = this ?: Stream.empty()
fun <T> Stream<T>?.getIfSingle(): T? {
return this?.limit(2)
?.map { Optional.ofNullable(it) }
?.reduce(Optional.empty()) { a, b -> if (a.isPresent xor b.isPresent) b else Optional.empty() }
?.orNull()
}
/**
* There probably could be some performance issues if there is lots of streams to concat. See
* http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010659.html for some details.
*
* See also [Stream.concat] documentation for other possible issues of concatenating large number of streams.
*/
fun <T> concat(vararg streams: Stream<T>): Stream<T> = Stream.of(*streams).reduce(Stream.empty()) { a, b -> Stream.concat(a, b) }
inline fun MutableList<Throwable>.catch(runnable: () -> Unit) {
try {
runnable()
}
catch (e: Throwable) {
add(e)
}
}
fun <T> MutableList<T>.addIfNotNull(e: T?) {
e?.let { add(it) }
}
fun <T> MutableList<T>.addAllIfNotNull(vararg elements: T?) {
elements.forEach { e -> e?.let { add(it) } }
}
inline fun <T, R> Array<out T>.mapSmart(transform: (T) -> R): List<R> {
return when (val size = size) {
1 -> SmartList(transform(this[0]))
0 -> SmartList()
else -> mapTo(ArrayList(size), transform)
}
}
inline fun <T, reified R> Array<out T>.map2Array(transform: (T) -> R): Array<R> = Array(this.size) { i -> transform(this[i]) }
@Suppress("UNCHECKED_CAST")
inline fun <T, reified R> Collection<T>.map2Array(transform: (T) -> R): Array<R> {
return arrayOfNulls<R>(this.size).also { array ->
this.forEachIndexed { index, t -> array[index] = transform(t) }
} as Array<R>
}
inline fun <T, R> Collection<T>.mapSmart(transform: (T) -> R): List<R> {
return when (val size = size) {
1 -> SmartList(transform(first()))
0 -> emptyList()
else -> mapTo(ArrayList(size), transform)
}
}
/**
* Not mutable set will be returned.
*/
inline fun <T, R> Collection<T>.mapSmartSet(transform: (T) -> R): Set<R> {
return when (val size = size) {
1 -> {
Collections.singleton(transform(first()))
}
0 -> emptySet()
else -> mapTo(java.util.HashSet(size), transform)
}
}
inline fun <T, R : Any> Collection<T>.mapSmartNotNull(transform: (T) -> R?): List<R> {
val size = size
return if (size == 1) {
transform(first())?.let { SmartList(it) } ?: SmartList()
}
else {
mapNotNullTo(ArrayList(size), transform)
}
}
fun <T> List<T>.toMutableSmartList(): MutableList<T> {
return when (size) {
1 -> SmartList(first())
0 -> SmartList()
else -> ArrayList(this)
}
}
inline fun <T> Collection<T>.filterSmart(predicate: (T) -> Boolean): List<T> {
val result: MutableList<T> = when (size) {
1 -> SmartList()
0 -> return emptyList()
else -> ArrayList()
}
filterTo(result, predicate)
return result
}
inline fun <T> Collection<T>.filterSmartMutable(predicate: (T) -> Boolean): MutableList<T> {
return filterTo(if (size <= 1) SmartList() else ArrayList(), predicate)
}
inline fun <reified E : Enum<E>, V> enumMapOf(): MutableMap<E, V> = EnumMap(E::class.java)
fun <E> Collection<E>.toArray(empty: Array<E>): Array<E> {
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST")
return (this as java.util.Collection<E>).toArray(empty)
}
/**
* Given a collection of elements S returns collection of minimal elements M as ordered by [comparator].
*
* Let S = M ∪ R; M ∩ R = ∅. Then:
* - ∀ m1 ∈ M, ∀ m2 ∈ M : m1 = m2;
* - ∀ m ∈ M, ∀ r ∈ R : m < r.
*/
fun <T> Collection<T>.minimalElements(comparator: Comparator<in T>): Collection<T> {
if (isEmpty() || size == 1) return this
val result = SmartList<T>()
for (item in this) {
if (result.isEmpty()) {
result.add(item)
}
else {
val comparison = comparator.compare(result[0], item)
if (comparison > 0) {
result.clear()
result.add(item)
}
else if (comparison == 0) {
result.add(item)
}
}
}
return result
}
/**
* _Example_
* The following will print `1`, `2` and `3` when executed:
* ```
* arrayOf(1, 2, 3, 4, 5)
* .iterator()
* .stopAfter { it == 3 }
* .forEach(::println)
* ```
* @return an iterator, which stops [this] Iterator after first element for which [predicate] returns `true`
*/
inline fun <T> Iterator<T>.stopAfter(crossinline predicate: (T) -> Boolean): Iterator<T> {
return iterator {
for (element in this@stopAfter) {
yield(element)
if (predicate(element)) {
break
}
}
}
}
fun <T> Optional<T>.orNull(): T? = orElse(null)
fun <T> Iterable<T>?.asJBIterable(): JBIterable<T> = JBIterable.from(this)
fun <T> Array<T>?.asJBIterable(): JBIterable<T> = if (this == null) JBIterable.empty() else JBIterable.of(*this)
/**
* Modify the elements of the array without creating a new array
*
* @return the array itself
*/
fun <T> Array<T>.mapInPlace(transform: (T) -> T): Array<T> {
for (i in this.indices) {
this[i] = transform(this[i])
}
return this
}
/**
* @return sequence of distinct nodes in breadth-first order
*/
fun <Node> generateRecursiveSequence(initialSequence: Sequence<Node>, children: (Node) -> Sequence<Node>): Sequence<Node> {
return sequence {
val initialIterator = initialSequence.iterator()
if (!initialIterator.hasNext()) {
return@sequence
}
val visited = HashSet<Node>()
val sequences = ArrayDeque<Sequence<Node>>()
sequences.addLast(initialIterator.asSequence())
while (sequences.isNotEmpty()) {
val currentSequence = sequences.removeFirst()
for (node in currentSequence) {
if (visited.add(node)) {
yield(node)
sequences.addLast(children(node))
}
}
}
}
}
/**
* Returns a new sequence either of single given element, if it is not null, or empty sequence if the element is null.
*/
fun <T : Any> sequenceOfNotNull(element: T?): Sequence<T> = if (element == null) emptySequence() else sequenceOf(element)
|
apache-2.0
|
0da71d69ef56f7eb8f28962b485d6086
| 26.927052 | 158 | 0.636047 | 3.34474 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt
|
1
|
13644
|
// 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.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.codegen.SamCodegenUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.sam.SamConversionOracle
import org.jetbrains.kotlin.resolve.sam.SamConversionResolver
import org.jetbrains.kotlin.resolve.sam.getFunctionTypeForPossibleSamType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.keysToMapExceptNulls
class RedundantSamConstructorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return callExpressionVisitor(fun(expression) {
if (expression.valueArguments.isEmpty()) return
val samConstructorCalls = samConstructorCallsToBeConverted(expression)
if (samConstructorCalls.isEmpty()) return
val single = samConstructorCalls.singleOrNull()
if (single != null) {
val calleeExpression = single.calleeExpression ?: return
val problemDescriptor = holder.manager.createProblemDescriptor(
single.getQualifiedExpressionForSelector()?.receiverExpression ?: calleeExpression,
single.typeArgumentList ?: calleeExpression,
KotlinBundle.message("redundant.sam.constructor"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
createQuickFix(single)
)
holder.registerProblem(problemDescriptor)
} else {
val problemDescriptor = holder.manager.createProblemDescriptor(
expression.valueArgumentList!!,
KotlinBundle.message("redundant.sam.constructors"),
createQuickFix(samConstructorCalls),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly
)
holder.registerProblem(problemDescriptor)
}
})
}
private fun createQuickFix(expression: KtCallExpression): LocalQuickFix {
return object : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.sam.constructor")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return
replaceSamConstructorCall(expression)
}
}
}
private fun createQuickFix(expressions: Collection<KtCallExpression>): LocalQuickFix {
return object : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.sam.constructors")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
for (callExpression in expressions) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(callExpression)) return
replaceSamConstructorCall(callExpression)
}
}
}
}
companion object {
fun replaceSamConstructorCall(callExpression: KtCallExpression): KtLambdaExpression {
val functionalArgument = callExpression.samConstructorValueArgument()?.getArgumentExpression()
?: throw AssertionError("SAM-constructor should have a FunctionLiteralExpression as single argument: ${callExpression.getElementTextWithContext()}")
return callExpression.getQualifiedExpressionForSelectorOrThis().replace(functionalArgument) as KtLambdaExpression
}
private fun canBeReplaced(
parentCall: KtCallExpression,
samConstructorCallArgumentMap: Map<KtValueArgument, KtCallExpression>
): Boolean {
val context = parentCall.analyze(BodyResolveMode.PARTIAL)
val calleeExpression = parentCall.calleeExpression ?: return false
val scope = calleeExpression.getResolutionScope(context, calleeExpression.getResolutionFacade())
val originalCall = parentCall.getResolvedCall(context) ?: return false
val dataFlow = context.getDataFlowInfoBefore(parentCall)
@OptIn(FrontendInternals::class)
val callResolver = parentCall.getResolutionFacade().frontendService<CallResolver>()
val newCall = CallWithConvertedArguments(originalCall.call, samConstructorCallArgumentMap)
val qualifiedExpression = parentCall.getQualifiedExpressionForSelectorOrThis()
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, qualifiedExpression] ?: TypeUtils.NO_EXPECTED_TYPE
val resolutionResults =
callResolver.resolveFunctionCall(BindingTraceContext(), scope, newCall, expectedType, dataFlow, false, null)
if (!resolutionResults.isSuccess) return false
val generatingAdditionalSamCandidateIsDisabled =
parentCall.languageVersionSettings.supportsFeature(LanguageFeature.SamConversionPerArgument) ||
parentCall.languageVersionSettings.supportsFeature(LanguageFeature.ProhibitVarargAsArrayAfterSamArgument)
val samAdapterOriginalDescriptor =
if (generatingAdditionalSamCandidateIsDisabled && resolutionResults.resultingCall is NewResolvedCallImpl<*>) {
resolutionResults.resultingDescriptor
} else {
SamCodegenUtil.getOriginalIfSamAdapter(resolutionResults.resultingDescriptor) ?: return false
}
return samAdapterOriginalDescriptor.original == originalCall.resultingDescriptor.original
}
private class CallWithConvertedArguments(
original: Call,
callArgumentMapToConvert: Map<KtValueArgument, KtCallExpression>,
) : DelegatingCall(original) {
private val newArguments: List<ValueArgument>
init {
val factory = KtPsiFactory(callElement)
newArguments = original.valueArguments.map { argument ->
val call = callArgumentMapToConvert[argument]
val newExpression = call?.samConstructorValueArgument()?.getArgumentExpression() ?: return@map argument
factory.createArgument(newExpression, argument.getArgumentName()?.asName, reformat = false)
}
}
override fun getValueArguments() = newArguments
}
@OptIn(FrontendInternals::class)
fun samConstructorCallsToBeConverted(functionCall: KtCallExpression): Collection<KtCallExpression> {
val valueArguments = functionCall.valueArguments
if (valueArguments.none { canBeSamConstructorCall(it) }) return emptyList()
val resolutionFacade = functionCall.getResolutionFacade()
val oracle = resolutionFacade.frontendService<SamConversionOracle>()
val resolver = resolutionFacade.frontendService<SamConversionResolver>()
val bindingContext = functionCall.analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val functionResolvedCall = functionCall.getResolvedCall(bindingContext) ?: return emptyList()
if (!functionResolvedCall.isReallySuccess()) return emptyList()
/**
* Checks that SAM conversion for [arg] and [call] in the argument position is possible
* and does not loose any information.
*
* We want to do as many cheap checks as possible before actually trying to resolve substituted call in [canBeReplaced].
*
* Several cases where we do not want the conversion:
*
* - Expected argument type is inferred from the argument; for example when the expected type is `T`, and SAM constructor
* helps to deduce it.
* - Expected argument type is a base type for the actual argument type; for example when expected type is `Any`, and removing
* SAM constructor will lead to passing object of different type.
*/
fun samConversionIsPossible(arg: KtValueArgument, call: KtCallExpression): Boolean {
val samConstructor =
call.getResolvedCall(bindingContext)?.resultingDescriptor?.original as? SamConstructorDescriptor ?: return false
// we suppose that SAM constructors return type is always not nullable
val samConstructorReturnType = samConstructor.returnType?.unwrap()?.takeUnless { it.isNullable() } ?: return false
// we take original parameter descriptor to get type parameter instead of inferred type (e.g. `T` instead of `Runnable`)
val originalParameterDescriptor = functionResolvedCall.getParameterForArgument(arg)?.original ?: return false
val expectedNotNullableType = originalParameterDescriptor.type.makeNotNullable().unwrap()
if (resolver.getFunctionTypeForPossibleSamType(expectedNotNullableType, oracle) == null) return false
return samConstructorReturnType.constructor == expectedNotNullableType.constructor
}
val argumentsWithSamConstructors = valueArguments.keysToMapExceptNulls { arg ->
arg.toCallExpression()?.takeIf { call -> samConversionIsPossible(arg, call) }
}
val haveToConvertAllArguments = !functionCall.languageVersionSettings.supportsFeature(LanguageFeature.SamConversionPerArgument)
val argumentsThatCanBeConverted = if (haveToConvertAllArguments) {
argumentsWithSamConstructors.takeIf { it.values.none(::containsLabeledReturnPreventingConversion) }.orEmpty()
} else {
argumentsWithSamConstructors.filterValues { !containsLabeledReturnPreventingConversion(it) }
}
return when {
argumentsThatCanBeConverted.isEmpty() -> emptyList()
!canBeReplaced(functionCall, argumentsThatCanBeConverted) -> emptyList()
else -> argumentsThatCanBeConverted.values
}
}
private fun canBeSamConstructorCall(argument: KtValueArgument) = argument.toCallExpression()?.samConstructorValueArgument() != null
private fun KtCallExpression.samConstructorValueArgument(): KtValueArgument? {
return valueArguments.singleOrNull()?.takeIf { it.getArgumentExpression() is KtLambdaExpression }
}
private fun ValueArgument.toCallExpression(): KtCallExpression? {
val argumentExpression = getArgumentExpression()
return (if (argumentExpression is KtDotQualifiedExpression)
argumentExpression.selectorExpression
else
argumentExpression) as? KtCallExpression
}
private fun containsLabeledReturnPreventingConversion(it: KtCallExpression): Boolean {
val samValueArgument = it.samConstructorValueArgument()
val samConstructorName = (it.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameAsName()
return samValueArgument == null ||
samConstructorName == null ||
samValueArgument.hasLabeledReturnPreventingConversion(samConstructorName)
}
private fun KtValueArgument.hasLabeledReturnPreventingConversion(samConstructorName: Name) =
anyDescendantOfType<KtReturnExpression> { it.getLabelNameAsName() == samConstructorName }
}
}
|
apache-2.0
|
53475f61db05502299c5899f0a9eed8f
| 53.358566 | 164 | 0.706098 | 6.123878 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/tests/testData/usageHighlighter/implicitReturnExpressionsFromExplicitReturnInLambdas.kt
|
4
|
373
|
fun some(a: Int, b: Int) {
run {
val i = 12
val j = 13
if (a > 50) {
if (b > 100) {
<info descr="null">i + j</info>
} else {
<info descr="null">i * j</info>
}
} else {
<info descr="null">~return@run false</info>
}
}
}
fun <T> run(a: () -> T) {}
|
apache-2.0
|
1c01bfe93d38447601c3b646e461149c
| 21 | 55 | 0.340483 | 3.300885 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt
|
1
|
16318
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.completion.handlers.BaseDeclarationInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinClassifierInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionCompositeDeclarativeInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionInsertHandler
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.core.completion.PackageLookupObject
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.highlighter.dsl.DslHighlighterExtension
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import java.awt.Font
import javax.swing.Icon
class BasicLookupElementFactory(
private val project: Project,
val insertHandlerProvider: InsertHandlerProvider
) {
companion object {
// we skip parameter names in functional types in most of the cases for shortness
val SHORT_NAMES_RENDERER = DescriptorRenderer.SHORT_NAMES_IN_TYPES.withOptions {
enhancedTypes = true
parameterNamesInFunctionalTypes = false
}
private fun getIcon(lookupObject: DeclarationLookupObject, descriptor: DeclarationDescriptor, flags: Int): Icon? {
// KotlinDescriptorIconProvider does not use declaration if it is KtElement,
// so, do not try to look up psiElement for known Kotlin descriptors as it could be a heavy deserialization (e.g. from kotlin libs)
val declaration = when (descriptor) {
is DeserializedDescriptor, is ReceiverParameterDescriptor -> null
else -> {
lookupObject.psiElement
}
}
return KotlinDescriptorIconProvider.getIcon(descriptor, declaration, flags)
}
}
fun createLookupElement(
descriptor: DeclarationDescriptor,
qualifyNestedClasses: Boolean = false,
includeClassTypeArguments: Boolean = true,
parametersAndTypeGrayed: Boolean = false
): LookupElement {
return createLookupElementUnwrappedDescriptor(
descriptor.unwrapIfFakeOverride(),
qualifyNestedClasses,
includeClassTypeArguments,
parametersAndTypeGrayed
)
}
fun createLookupElementForJavaClass(
psiClass: PsiClass,
qualifyNestedClasses: Boolean = false,
includeClassTypeArguments: Boolean = true
): LookupElement {
val lookupObject = PsiClassLookupObject(psiClass)
var element = LookupElementBuilder.create(lookupObject, psiClass.name!!).withInsertHandler(KotlinClassifierInsertHandler)
val typeParams = psiClass.typeParameters
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
element = element.appendTailText(typeParams.map { it.name }.joinToString(", ", "<", ">"), true)
}
val qualifiedName = psiClass.qualifiedName!!
var containerName = qualifiedName.substringBeforeLast('.', FqName.ROOT.toString())
if (qualifyNestedClasses) {
val nestLevel = psiClass.parents.takeWhile { it is PsiClass }.count()
if (nestLevel > 0) {
var itemText = psiClass.name
for (i in 1..nestLevel) {
val outerClassName = containerName.substringAfterLast('.')
element = element.withLookupString(outerClassName)
itemText = "$outerClassName.$itemText"
containerName = containerName.substringBeforeLast('.', FqName.ROOT.toString())
}
element = element.withPresentableText(itemText!!)
}
}
element = element.appendTailText(" ($containerName)", true)
if (lookupObject.isDeprecated) {
element = element.withStrikeoutness(true)
}
return element.withIconFromLookupObject()
}
fun createLookupElementForPackage(name: FqName): LookupElement {
var element = LookupElementBuilder.create(PackageLookupObject(name), name.shortName().asString())
element = element.withInsertHandler(BaseDeclarationInsertHandler())
if (!name.parent().isRoot) {
element = element.appendTailText(" (${name.asString()})", true)
}
return element.withIconFromLookupObject()
}
private fun createLookupElementUnwrappedDescriptor(
descriptor: DeclarationDescriptor,
qualifyNestedClasses: Boolean,
includeClassTypeArguments: Boolean,
parametersAndTypeGrayed: Boolean
): LookupElement {
if (descriptor is JavaClassDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor)
if (declaration is PsiClass && declaration !is KtLightClass) {
// for java classes we create special lookup elements
// because they must be equal to ones created in TypesCompletion
// otherwise we may have duplicates
return createLookupElementForJavaClass(declaration, qualifyNestedClasses, includeClassTypeArguments)
}
}
if (descriptor is PackageViewDescriptor) {
return createLookupElementForPackage(descriptor.fqName)
}
if (descriptor is PackageFragmentDescriptor) {
return createLookupElementForPackage(descriptor.fqName)
}
val lookupObject: DeclarationLookupObject
val name: String = when (descriptor) {
is ConstructorDescriptor -> {
// for constructor use name and icon of containing class
val classifierDescriptor = descriptor.containingDeclaration
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, classifierDescriptor) }
override fun getIcon(flags: Int): Icon? = getIcon(this, classifierDescriptor, flags)
}
classifierDescriptor.name.asString()
}
is SyntheticJavaPropertyDescriptor -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor.getMethod) }
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, null, flags)
}
descriptor.name.asString()
}
else -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy {
DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) ?: DescriptorToSourceUtilsIde.getAnyDeclaration(
project,
descriptor
)
}
override fun getIcon(flags: Int): Icon? = getIcon(this, descriptor, flags)
}
descriptor.name.asString()
}
}
var element = LookupElementBuilder.create(lookupObject, name)
val insertHandler = insertHandlerProvider.insertHandler(descriptor)
element = element.withInsertHandler(insertHandler)
when (descriptor) {
is FunctionDescriptor -> {
val returnType = descriptor.returnType
element = element.withTypeText(
if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "",
parametersAndTypeGrayed
)
val insertsLambda = when (insertHandler) {
is KotlinFunctionInsertHandler.Normal -> insertHandler.lambdaInfo != null
is KotlinFunctionCompositeDeclarativeInsertHandler -> insertHandler.isLambda
else -> false
}
if (insertsLambda) {
element = element.appendTailText(" {...} ", parametersAndTypeGrayed)
}
element = element.appendTailText(
SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor),
parametersAndTypeGrayed || insertsLambda
)
}
is VariableDescriptor -> {
element = element.withTypeText(SHORT_NAMES_RENDERER.renderType(descriptor.type), parametersAndTypeGrayed)
}
is ClassifierDescriptorWithTypeParameters -> {
val typeParams = descriptor.declaredTypeParameters
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
element = element.appendTailText(typeParams.joinToString(", ", "<", ">") { it.name.asString() }, true)
}
var container = descriptor.containingDeclaration
if (descriptor.isArtificialImportAliasedDescriptor) {
container = descriptor.original // we show original descriptor instead of container for import aliased descriptors
} else if (qualifyNestedClasses) {
element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor))
while (container is ClassDescriptor) {
val containerName = container.name
if (!containerName.isSpecial) {
element = element.withLookupString(containerName.asString())
}
container = container.containingDeclaration
}
}
if (container is PackageFragmentDescriptor || container is ClassifierDescriptor) {
element = element.appendTailText(" (" + DescriptorUtils.getFqName(container) + ")", true)
}
if (descriptor is TypeAliasDescriptor) {
// here we render with DescriptorRenderer.SHORT_NAMES_IN_TYPES to include parameter names in functional types
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.underlyingType), false)
}
}
else -> {
element = element.withTypeText(SHORT_NAMES_RENDERER.render(descriptor), parametersAndTypeGrayed)
}
}
var isMarkedAsDsl = false
if (descriptor is CallableDescriptor) {
appendContainerAndReceiverInformation(descriptor) { element = element.appendTailText(it, true) }
val dslTextAttributes = DslHighlighterExtension.dslCustomTextStyle(descriptor)?.let {
EditorColorsManager.getInstance().globalScheme.getAttributes(it)
}
if (dslTextAttributes != null) {
isMarkedAsDsl = true
element = element.withBoldness(dslTextAttributes.fontType == Font.BOLD)
dslTextAttributes.foregroundColor?.let { element = element.withItemTextForeground(it) }
}
}
if (descriptor is PropertyDescriptor) {
val getterName = JvmAbi.getterName(name)
if (getterName != name) {
element = element.withLookupString(getterName)
}
if (descriptor.isVar) {
element = element.withLookupString(JvmAbi.setterName(name))
}
}
if (lookupObject.isDeprecated) {
element = element.withStrikeoutness(true)
}
if ((insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null) {
element.putUserData(KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE, Unit)
}
val result = element.withIconFromLookupObject()
result.isDslMember = isMarkedAsDsl
return result
}
fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullOfOrNull {
it.getContainerAndReceiverInformation(descriptor)
}
if (information != null) {
appendTailText(information)
return
}
val extensionReceiver = descriptor.original.extensionReceiverParameter
if (extensionReceiver != null) {
when (descriptor) {
is SamAdapterExtensionFunctionDescriptor -> {
// no need to show them as extensions
return
}
is SyntheticJavaPropertyDescriptor -> {
var from = descriptor.getMethod.name.asString() + "()"
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.from.0", from))
return
}
else -> {
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type)
appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.for.0", receiverPresentation))
}
}
}
val containerPresentation = containerPresentation(descriptor)
if (containerPresentation != null) {
appendTailText(" ")
appendTailText(containerPresentation)
}
}
private fun containerPresentation(descriptor: DeclarationDescriptor): String? {
when {
descriptor.isArtificialImportAliasedDescriptor -> {
return "(${DescriptorUtils.getFqName(descriptor.original)})"
}
descriptor.isExtension -> {
val containerPresentation = when (val container = descriptor.containingDeclaration) {
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
is PackageFragmentDescriptor -> container.fqName.toString()
else -> return null
}
return KotlinIdeaCompletionBundle.message("presentation.tail.in.0", containerPresentation)
}
else -> {
val container = descriptor.containingDeclaration as? PackageFragmentDescriptor
// we show container only for global functions and properties
?: return null
//TODO: it would be probably better to show it also for static declarations which are not from the current class (imported)
return "(${container.fqName})"
}
}
}
// add icon in renderElement only to pass presentation.isReal()
private fun LookupElement.withIconFromLookupObject(): LookupElement = object : LookupElementDecorator<LookupElement>(this) {
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject)
}
}
}
|
apache-2.0
|
8c618f75915eb6e1bf85dd4e2eda5d17
| 44.708683 | 143 | 0.642174 | 6.001471 | false | false | false | false |
Zenika/lunchPlace
|
backend/src/main/kotlin/com/zenika/lunchPlace/restaurant/RestaurantController.kt
|
1
|
1462
|
package com.zenika.lunchPlace.restaurant
import com.zenika.lunchPlace.restaurant.category.FoodCategory
import com.zenika.lunchPlace.restaurant.category.PriceCategory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
/**
* Created by Gwennaël Buchet on 22/10/16.
*/
@RestController
@RequestMapping("/restaurants")
class RestaurantController @Autowired constructor(val repository: RestaurantRepository) {
@CrossOrigin
@GetMapping(value = "/")
fun findAll(): Iterable<Restaurant> = repository.findAll()
@CrossOrigin
@GetMapping(value = "/{id}")
fun findById(@PathVariable id: Long): Iterable<Restaurant>
= repository.findById(id)
@CrossOrigin
@PostMapping(value = "/add")
fun add(@RequestParam(value = "name") name: String): Restaurant {
val restaurant = Restaurant(
name,
/*Address(
50.636432, 3.062100,
6,
"rue Jean Roisin",
"",
"",
59000,
"Lille",
"France",
"FR"
),*/
ArrayList<FoodCategory>(),
PriceCategory.LP_PRICE_STANDARD,
"")
repository.save(restaurant)
return restaurant
}
}
|
mit
|
a697edf350d3be6c5332c5875e6c8517
| 27.115385 | 89 | 0.55989 | 4.758958 | false | false | false | false |
JetBrains/kotlin-native
|
Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt
|
1
|
6195
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.cinterop
import kotlin.native.*
import kotlin.native.internal.Intrinsic
import kotlin.native.internal.TypedIntrinsic
import kotlin.native.internal.IntrinsicType
@PublishedApi
internal inline val pointerSize: Int
get() = getPointerSize()
@PublishedApi
@TypedIntrinsic(IntrinsicType.INTEROP_GET_POINTER_SIZE)
internal external fun getPointerSize(): Int
// TODO: do not use singleton because it leads to init-check on any access.
@PublishedApi
internal object nativeMemUtils {
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getByte(mem: NativePointed): Byte
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putByte(mem: NativePointed, value: Byte)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getShort(mem: NativePointed): Short
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putShort(mem: NativePointed, value: Short)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getInt(mem: NativePointed): Int
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putInt(mem: NativePointed, value: Int)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getLong(mem: NativePointed): Long
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putLong(mem: NativePointed, value: Long)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getFloat(mem: NativePointed): Float
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putFloat(mem: NativePointed, value: Float)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getDouble(mem: NativePointed): Double
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putDouble(mem: NativePointed, value: Double)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getNativePtr(mem: NativePointed): NativePtr
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putNativePtr(mem: NativePointed, value: NativePtr)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_PRIMITIVE) external fun getVector(mem: NativePointed): Vector128
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_PRIMITIVE) external fun putVector(mem: NativePointed, value: Vector128)
// TODO: optimize
fun getByteArray(source: NativePointed, dest: ByteArray, length: Int) {
val sourceArray = source.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
dest[index] = sourceArray[index]
++index
}
}
// TODO: optimize
fun putByteArray(source: ByteArray, dest: NativePointed, length: Int) {
val destArray = dest.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
destArray[index] = source[index]
++index
}
}
// TODO: optimize
fun getCharArray(source: NativePointed, dest: CharArray, length: Int) {
val sourceArray = source.reinterpret<ShortVar>().ptr
var index = 0
while (index < length) {
dest[index] = sourceArray[index].toChar()
++index
}
}
// TODO: optimize
fun putCharArray(source: CharArray, dest: NativePointed, length: Int) {
val destArray = dest.reinterpret<ShortVar>().ptr
var index = 0
while (index < length) {
destArray[index] = source[index].toShort()
++index
}
}
// TODO: optimize
fun zeroMemory(dest: NativePointed, length: Int): Unit {
val destArray = dest.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
destArray[index] = 0
++index
}
}
// TODO: optimize
fun copyMemory(dest: NativePointed, length: Int, src: NativePointed): Unit {
val destArray = dest.reinterpret<ByteVar>().ptr
val srcArray = src.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
destArray[index] = srcArray[index]
++index
}
}
fun alloc(size: Long, align: Int): NativePointed {
return interpretOpaquePointed(allocRaw(size, align))
}
fun free(mem: NativePtr) {
freeRaw(mem)
}
internal fun allocRaw(size: Long, align: Int): NativePtr {
val ptr = malloc(size, align)
if (ptr == nativeNullPtr) {
throw OutOfMemoryError("unable to allocate native memory")
}
return ptr
}
internal fun freeRaw(mem: NativePtr) {
cfree(mem)
}
}
public fun CPointer<UShortVar>.toKStringFromUtf16(): String {
val nativeBytes = this
var length = 0
while (nativeBytes[length] != 0.toUShort()) {
++length
}
val chars = kotlin.CharArray(length)
var index = 0
while (index < length) {
chars[index] = nativeBytes[index].toShort().toChar()
++index
}
return chars.concatToString()
}
public fun CPointer<ShortVar>.toKString(): String = this.toKStringFromUtf16()
public fun CPointer<UShortVar>.toKString(): String = this.toKStringFromUtf16()
@SymbolName("Kotlin_interop_malloc")
private external fun malloc(size: Long, align: Int): NativePtr
@SymbolName("Kotlin_interop_free")
private external fun cfree(ptr: NativePtr)
@TypedIntrinsic(IntrinsicType.INTEROP_READ_BITS)
external fun readBits(ptr: NativePtr, offset: Long, size: Int, signed: Boolean): Long
@TypedIntrinsic(IntrinsicType.INTEROP_WRITE_BITS)
external fun writeBits(ptr: NativePtr, offset: Long, size: Int, value: Long)
|
apache-2.0
|
b4c00383bb0922fcceee6c6ac42e242f
| 35.441176 | 122 | 0.695238 | 4.362676 | false | false | false | false |
JetBrains/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/matchers/IrCallMatcher.kt
|
4
|
2132
|
package org.jetbrains.kotlin.backend.konan.lower.matchers
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin
internal interface IrCallMatcher : (IrCall) -> Boolean
/**
* IrCallMatcher that puts restrictions only on its callee.
*/
internal class SimpleCalleeMatcher(
restrictions: IrFunctionMatcherContainer.() -> Unit
) : IrCallMatcher {
private val calleeRestriction: IrFunctionMatcher
= createIrFunctionRestrictions(restrictions)
override fun invoke(call: IrCall) = calleeRestriction(call.symbol.owner)
}
internal class IrCallExtensionReceiverMatcher(
val restriction: (IrExpression?) -> Boolean
) : IrCallMatcher {
override fun invoke(call: IrCall) = restriction(call.extensionReceiver)
}
internal class IrCallDispatchReceiverMatcher(
val restriction: (IrExpression?) -> Boolean
) : IrCallMatcher {
override fun invoke(call: IrCall) = restriction(call.dispatchReceiver)
}
internal class IrCallOriginMatcher(
val restriction: (IrStatementOrigin?) -> Boolean
) : IrCallMatcher {
override fun invoke(call: IrCall) = restriction(call.origin)
}
internal open class IrCallMatcherContainer : IrCallMatcher {
private val matchers = mutableListOf<IrCallMatcher>()
fun add(matcher: IrCallMatcher) {
matchers += matcher
}
fun extensionReceiver(restriction: (IrExpression?) -> Boolean) =
add(IrCallExtensionReceiverMatcher(restriction))
fun origin(restriction: (IrStatementOrigin?) -> Boolean) =
add(IrCallOriginMatcher(restriction))
fun callee(restrictions: IrFunctionMatcherContainer.() -> Unit) {
add(SimpleCalleeMatcher(restrictions))
}
fun dispatchReceiver(restriction: (IrExpression?) -> Boolean) =
add(IrCallDispatchReceiverMatcher(restriction))
override fun invoke(call: IrCall) = matchers.all { it(call) }
}
internal fun createIrCallMatcher(restrictions: IrCallMatcherContainer.() -> Unit) =
IrCallMatcherContainer().apply(restrictions)
|
apache-2.0
|
a94c542f83f960805b5050137900ffbe
| 31.318182 | 83 | 0.74015 | 4.791011 | false | false | false | false |
androidx/androidx
|
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/grid/LazyGridSpanLayoutProvider.kt
|
3
|
9668
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.grid
import androidx.compose.foundation.ExperimentalFoundationApi
import kotlin.math.min
import kotlin.math.sqrt
@OptIn(ExperimentalFoundationApi::class)
internal class LazyGridSpanLayoutProvider(private val itemProvider: LazyGridItemProvider) {
class LineConfiguration(val firstItemIndex: Int, val spans: List<GridItemSpan>)
/** Caches the bucket info on lines 0, [bucketSize], 2 * [bucketSize], etc. */
private val buckets = ArrayList<Bucket>().apply { add(Bucket(0)) }
/**
* The interval at each we will store the starting element of lines. These will be then
* used to calculate the layout of arbitrary lines, by starting from the closest
* known "bucket start". The smaller the bucketSize, the smaller cost for calculating layout
* of arbitrary lines but the higher memory usage for [buckets].
*/
private val bucketSize get() = sqrt(1.0 * totalSize / slotsPerLine).toInt() + 1
/** Caches the last calculated line index, useful when scrolling in main axis direction. */
private var lastLineIndex = 0
/** Caches the starting item index on [lastLineIndex]. */
private var lastLineStartItemIndex = 0
/** Caches the span of [lastLineStartItemIndex], if this was already calculated. */
private var lastLineStartKnownSpan = 0
/**
* Caches a calculated bucket, this is useful when scrolling in reverse main axis
* direction. We cannot only keep the last element, as we would not know previous max span.
*/
private var cachedBucketIndex = -1
/**
* Caches layout of [cachedBucketIndex], this is useful when scrolling in reverse main axis
* direction. We cannot only keep the last element, as we would not know previous max span.
*/
private val cachedBucket = mutableListOf<Int>()
/**
* List of 1x1 spans if we do not have custom spans.
*/
private var previousDefaultSpans = emptyList<GridItemSpan>()
private fun getDefaultSpans(currentSlotsPerLine: Int) =
if (currentSlotsPerLine == previousDefaultSpans.size) {
previousDefaultSpans
} else {
List(currentSlotsPerLine) { GridItemSpan(1) }.also { previousDefaultSpans = it }
}
val totalSize get() = itemProvider.itemCount
/** The number of slots on one grid line e.g. the number of columns of a vertical grid. */
var slotsPerLine = 0
set(value) {
if (value != field) {
field = value
invalidateCache()
}
}
fun getLineConfiguration(lineIndex: Int): LineConfiguration {
if (!itemProvider.hasCustomSpans) {
// Quick return when all spans are 1x1 - in this case we can easily calculate positions.
val firstItemIndex = lineIndex * slotsPerLine
return LineConfiguration(
firstItemIndex,
getDefaultSpans(slotsPerLine.coerceAtMost(totalSize - firstItemIndex)
.coerceAtLeast(0))
)
}
val bucketIndex = min(lineIndex / bucketSize, buckets.size - 1)
// We can calculate the items on the line from the closest cached bucket start item.
var currentLine = bucketIndex * bucketSize
var currentItemIndex = buckets[bucketIndex].firstItemIndex
var knownCurrentItemSpan = buckets[bucketIndex].firstItemKnownSpan
// ... but try using the more localised cached values.
if (lastLineIndex in currentLine..lineIndex) {
// The last calculated value is a better start point. Common when scrolling main axis.
currentLine = lastLineIndex
currentItemIndex = lastLineStartItemIndex
knownCurrentItemSpan = lastLineStartKnownSpan
} else if (bucketIndex == cachedBucketIndex &&
lineIndex - currentLine < cachedBucket.size
) {
// It happens that the needed line start is fully cached. Common when scrolling in
// reverse main axis, as we decided to cacheThisBucket previously.
currentItemIndex = cachedBucket[lineIndex - currentLine]
currentLine = lineIndex
knownCurrentItemSpan = 0
}
val cacheThisBucket = currentLine % bucketSize == 0 &&
lineIndex - currentLine in 2 until bucketSize
if (cacheThisBucket) {
cachedBucketIndex = bucketIndex
cachedBucket.clear()
}
check(currentLine <= lineIndex)
while (currentLine < lineIndex && currentItemIndex < totalSize) {
if (cacheThisBucket) {
cachedBucket.add(currentItemIndex)
}
var spansUsed = 0
while (spansUsed < slotsPerLine && currentItemIndex < totalSize) {
val span = if (knownCurrentItemSpan == 0) {
spanOf(currentItemIndex, slotsPerLine - spansUsed)
} else {
knownCurrentItemSpan.also { knownCurrentItemSpan = 0 }
}
if (spansUsed + span > slotsPerLine) {
knownCurrentItemSpan = span
break
}
currentItemIndex++
spansUsed += span
}
++currentLine
if (currentLine % bucketSize == 0 && currentItemIndex < totalSize) {
val currentLineBucket = currentLine / bucketSize
// This should happen, as otherwise this should have been used as starting point.
check(buckets.size == currentLineBucket)
buckets.add(Bucket(currentItemIndex, knownCurrentItemSpan))
}
}
lastLineIndex = lineIndex
lastLineStartItemIndex = currentItemIndex
lastLineStartKnownSpan = knownCurrentItemSpan
val firstItemIndex = currentItemIndex
val spans = mutableListOf<GridItemSpan>()
var spansUsed = 0
while (spansUsed < slotsPerLine && currentItemIndex < totalSize) {
val span = if (knownCurrentItemSpan == 0) {
spanOf(currentItemIndex, slotsPerLine - spansUsed)
} else {
knownCurrentItemSpan.also { knownCurrentItemSpan = 0 }
}
if (spansUsed + span > slotsPerLine) break
currentItemIndex++
spans.add(GridItemSpan(span))
spansUsed += span
}
return LineConfiguration(firstItemIndex, spans)
}
/**
* Calculate the line of index [itemIndex].
*/
fun getLineIndexOfItem(itemIndex: Int): LineIndex {
if (totalSize <= 0) {
return LineIndex(0)
}
require(itemIndex < totalSize)
if (!itemProvider.hasCustomSpans) {
return LineIndex(itemIndex / slotsPerLine)
}
val lowerBoundBucket = buckets.binarySearch { it.firstItemIndex - itemIndex }.let {
if (it >= 0) it else -it - 2
}
var currentLine = lowerBoundBucket * bucketSize
var currentItemIndex = buckets[lowerBoundBucket].firstItemIndex
require(currentItemIndex <= itemIndex)
var spansUsed = 0
while (currentItemIndex < itemIndex) {
val span = spanOf(currentItemIndex++, slotsPerLine - spansUsed)
if (spansUsed + span < slotsPerLine) {
spansUsed += span
} else if (spansUsed + span == slotsPerLine) {
++currentLine
spansUsed = 0
} else {
// spansUsed + span > slotsPerLine
++currentLine
spansUsed = span
}
if (currentLine % bucketSize == 0) {
val currentLineBucket = currentLine / bucketSize
if (currentLineBucket >= buckets.size) {
buckets.add(Bucket(currentItemIndex - if (spansUsed > 0) 1 else 0))
}
}
}
if (spansUsed + spanOf(itemIndex, slotsPerLine - spansUsed) > slotsPerLine) {
++currentLine
}
return LineIndex(currentLine)
}
private fun spanOf(itemIndex: Int, maxSpan: Int) = with(itemProvider) {
with(LazyGridItemSpanScopeImpl) {
maxCurrentLineSpan = maxSpan
maxLineSpan = slotsPerLine
getSpan(itemIndex).currentLineSpan.coerceIn(1, slotsPerLine)
}
}
private fun invalidateCache() {
buckets.clear()
buckets.add(Bucket(0))
lastLineIndex = 0
lastLineStartItemIndex = 0
cachedBucketIndex = -1
cachedBucket.clear()
}
private class Bucket(
/** Index of the first item in the bucket */
val firstItemIndex: Int,
/** Known span of the first item. Not zero only if this item caused "line break". */
val firstItemKnownSpan: Int = 0
)
private object LazyGridItemSpanScopeImpl : LazyGridItemSpanScope {
override var maxCurrentLineSpan = 0
override var maxLineSpan = 0
}
}
|
apache-2.0
|
8a15420d4fc6c408ccff393cab1734d8
| 38.954545 | 100 | 0.622259 | 5.115344 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/contacts/paged/SafetyNumberRepository.kt
|
1
|
4820
|
package org.thoughtcrime.securesms.contacts.paged
import androidx.annotation.VisibleForTesting
import io.reactivex.rxjava3.core.Single
import org.signal.core.util.Stopwatch
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.concurrent.safeBlockingGet
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.crypto.storage.SignalIdentityKeyStore
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.IdentityUtil
import org.whispersystems.signalservice.api.services.ProfileService
import org.whispersystems.signalservice.internal.ServiceResponseProcessor
import org.whispersystems.signalservice.internal.push.IdentityCheckResponse
import java.util.concurrent.TimeUnit
/**
* Generic repository for interacting with safety numbers and fetch new ones.
*/
class SafetyNumberRepository(
private val profileService: ProfileService = ApplicationDependencies.getProfileService(),
private val aciIdentityStore: SignalIdentityKeyStore = ApplicationDependencies.getProtocolStore().aci().identities()
) {
private val recentlyFetched: MutableMap<RecipientId, Long> = HashMap()
fun batchSafetyNumberCheck(newSelectionEntries: List<ContactSearchKey>) {
SignalExecutors.UNBOUNDED.execute {
try {
batchSafetyNumberCheckSync(newSelectionEntries)
} catch (e: InterruptedException) {
Log.w(TAG, "Unable to fetch safety number change", e)
}
}
}
@Suppress("UNCHECKED_CAST")
@VisibleForTesting
@Throws(InterruptedException::class)
fun batchSafetyNumberCheckSync(newSelectionEntries: List<ContactSearchKey>, now: Long = System.currentTimeMillis(), batchSize: Int = MAX_BATCH_SIZE) {
val stopwatch = Stopwatch("batch-snc")
val recipientIds: Set<RecipientId> = newSelectionEntries.flattenToRecipientIds()
stopwatch.split("recipient-ids")
val recentIds = recentlyFetched.filter { (_, timestamp) -> (now - timestamp) < RECENT_TIME_WINDOW }.keys
val recipients = Recipient.resolvedList(recipientIds - recentIds).filter { it.hasServiceId() }
stopwatch.split("recipient-resolve")
if (recipients.isNotEmpty()) {
Log.i(TAG, "Checking on ${recipients.size} identities...")
val requests: List<Single<List<IdentityCheckResponse.AciIdentityPair>>> = recipients.chunked(batchSize) { it.createBatchRequestSingle() }
stopwatch.split("requests")
val aciKeyPairs: List<IdentityCheckResponse.AciIdentityPair> = Single.zip(requests) { responses ->
responses
.map { it as List<IdentityCheckResponse.AciIdentityPair> }
.flatten()
}.safeBlockingGet()
stopwatch.split("batch-fetches")
if (aciKeyPairs.isEmpty()) {
Log.d(TAG, "No identity key mismatches")
} else {
aciKeyPairs
.filter { it.aci != null && it.identityKey != null }
.forEach { IdentityUtil.saveIdentity(it.aci.toString(), it.identityKey) }
}
recentlyFetched += recipients.associate { it.id to now }
stopwatch.split("saving-identities")
}
stopwatch.stop(TAG)
}
private fun List<ContactSearchKey>.flattenToRecipientIds(): Set<RecipientId> {
return this
.map {
when (it) {
is ContactSearchKey.RecipientSearchKey.KnownRecipient -> {
val recipient = Recipient.resolved(it.recipientId)
if (recipient.isGroup) {
recipient.participantIds
} else {
listOf(it.recipientId)
}
}
is ContactSearchKey.RecipientSearchKey.Story -> Recipient.resolved(it.recipientId).participantIds
else -> throw AssertionError("Invalid contact selection $it")
}
}
.flatten()
.toMutableSet()
.apply { remove(Recipient.self().id) }
}
private fun List<Recipient>.createBatchRequestSingle(): Single<List<IdentityCheckResponse.AciIdentityPair>> {
return profileService
.performIdentityCheck(
mapNotNull { r ->
val identityRecord = aciIdentityStore.getIdentityRecord(r.id)
if (identityRecord.isPresent) {
r.requireServiceId() to identityRecord.get().identityKey
} else {
null
}
}.associate { it }
)
.map { ServiceResponseProcessor.DefaultProcessor(it).resultOrThrow.aciKeyPairs ?: emptyList() }
.onErrorReturn { t ->
Log.w(TAG, "Unable to fetch identities", t)
emptyList()
}
}
companion object {
private val TAG = Log.tag(SafetyNumberRepository::class.java)
private val RECENT_TIME_WINDOW = TimeUnit.SECONDS.toMillis(30)
private const val MAX_BATCH_SIZE = 1000
}
}
|
gpl-3.0
|
e256daec464f76b7efec8e54dced410c
| 38.508197 | 152 | 0.710166 | 4.560076 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinNullabilityUAnnotation.kt
|
2
|
2144
|
// Copyright 2000-2022 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.uast.kotlin
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
@ApiStatus.Internal
class KotlinNullabilityUAnnotation(
private val baseKotlinUastResolveProviderService: BaseKotlinUastResolveProviderService,
private val annotatedElement: PsiElement,
override val uastParent: UElement?
) : UAnnotationEx, UAnchorOwner, DelegatedMultiResolve {
override val uastAnchor: UIdentifier? = null
override val attributeValues: List<UNamedExpression>
get() = emptyList()
override val psi: PsiElement?
get() = null
override val javaPsi: PsiAnnotation?
get() = null
override val sourcePsi: PsiElement?
get() = null
private val nullability : TypeNullability? by lz {
baseKotlinUastResolveProviderService.nullability(annotatedElement)
}
override val qualifiedName: String?
get() = when (nullability) {
TypeNullability.NOT_NULL -> NotNull::class.qualifiedName
TypeNullability.NULLABLE -> Nullable::class.qualifiedName
TypeNullability.FLEXIBLE -> null
null -> null
}
override fun findAttributeValue(name: String?): UExpression? = null
override fun findDeclaredAttributeValue(name: String?): UExpression? = null
private val _resolved: PsiClass? by lz {
qualifiedName?.let {
val project = annotatedElement.project
JavaPsiFacade.getInstance(project).findClass(it, GlobalSearchScope.allScope(project))
}
}
override fun resolve(): PsiClass? = _resolved
}
|
apache-2.0
|
14d816dbc4126b9727a49a6476086a50
| 35.965517 | 158 | 0.741138 | 5.116945 | false | false | false | false |
kosiakk/Android-Books
|
app/src/main/java/com/kosenkov/androidbooks/view/BookDetailFragment.kt
|
1
|
2702
|
package com.kosenkov.androidbooks.view
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.kosenkov.androidbooks.R
import com.kosenkov.androidbooks.books.GoogleBooks
import com.kosenkov.androidbooks.booksApi
import kotlinx.android.synthetic.main.activity_book_detail.view.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
/**
* A fragment representing a single Book detail screen.
* This fragment is either contained in a [BookListActivity]
* in two-pane mode (on tablets) or a [BookDetailActivity]
* on handsets.
*
*
*/
class BookDetailFragment : Fragment() {
private lateinit var volumeId: String
private var volumeData: GoogleBooks.Volume? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!arguments.containsKey(ARG_ITEM_ID)) {
throw IllegalArgumentException("Book details were asked, but no $ARG_ITEM_ID is given")
}
volumeId = arguments.getString(ARG_ITEM_ID)!!
volumeData = arguments.getSerializable(ARG_ITEM_DETAILS) as GoogleBooks.Volume?
}
override fun onResume() {
super.onResume()
val cachedPreview = volumeData
if (cachedPreview != null) {
// This activity
applyVolume(cachedPreview, view)
}
doAsync {
val data = booksApi.details(volumeId)
val basicDetails = data.volume
uiThread {
// update
applyVolume(basicDetails, view)
}
}
}
private fun applyVolume(volume: GoogleBooks.Volume, rootView: View?) {
activity.title = volume.title
val theToolbar = rootView!!.detail_toolbar
theToolbar?.title = volume.title
val thumbnail = volume.thumbnailImageLinks
if (thumbnail != null && rootView.book_thumbnail != null) {
val glide = Glide.with(context)
glide.load(thumbnail).fitCenter().crossFade().into(rootView.book_thumbnail)
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// todo nonce
val rootView = inflater!!.inflate(R.layout.abc_screen_simple, container, false)
return rootView
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
val ARG_ITEM_ID = "volume_id"
val ARG_ITEM_DETAILS = "volume"
}
}
|
gpl-3.0
|
ea396689dcb8fea47abb3fe585ff68cc
| 29.359551 | 99 | 0.65396 | 4.458746 | false | false | false | false |
kivensolo/UiUsingListView
|
app/src/main/kotlin/com/zeke/ktx/util/RxUtils.kt
|
1
|
3049
|
package com.zeke.ktx.util
import android.util.Log
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
/**
* RxJava封装工具类
*/
object RxUtils {
/**
* 在ui线程中执行任务
*/
fun ui(onSuccess: () -> Unit, onError: ((t: Throwable) -> Unit)? = null): Disposable {
return Observable.just(0)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ onSuccess() }, {
it.printStackTrace()
if (onError != null) {
onError(it)
}
})
}
/***
* 在IO线程中执行任务
*/
fun io(onSuccess: () -> Unit, onError: ((t: Throwable) -> Unit)? = null): Disposable {
return Observable.just(0)
.observeOn(Schedulers.io())
.subscribe({ onSuccess() }, {
it.printStackTrace()
if (onError != null) {
onError(it)
}
})
}
/**
* 延迟指定时间后,在UI线程执行任务
* @param delay 延迟的毫秒数
* @onSuccess 订阅正常后需执行的操作
* @onError 订阅异常后需执行的操作
*/
fun postDelay(delay: Long,
onSuccess: () -> Unit,
onError: ((t: Throwable) -> Unit)? = null): Disposable {
return Observable.timer(delay, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({onSuccess()},{
it.printStackTrace()
if(onError != null){
onError(it)
}
})
}
fun postDelay(time: Long, action: Consumer<Long?>?): Disposable? {
return Observable.timer(time, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(action, Consumer { throwable ->
Log.e("RxUtils", "RxUtils err = $throwable")
})
}
/**
* 在UI线程定时执行任务
* 适用于播放器UI刷新检测等场景
*/
fun intervalOnUiThread(initialDelay:Long,period:Long,
onSuccess: () -> Unit,
onError: ((t: Throwable) -> Unit)? = null): Disposable{
return Observable.interval(initialDelay,period, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({onSuccess()},{
it.printStackTrace()
if(onError != null){
onError(it)
}
})
}
}
|
gpl-2.0
|
d5012c2a7d85c08e4fa01f25eebe9535
| 29.294737 | 90 | 0.499479 | 4.803005 | false | false | false | false |
loxal/FreeEthereum
|
free-ethereum-core/src/main/java/org/ethereum/net/server/WireTrafficStats.kt
|
1
|
4545
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.net.server
import com.google.common.util.concurrent.ThreadFactoryBuilder
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelDuplexHandler
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
import io.netty.channel.socket.DatagramPacket
import org.ethereum.util.Utils.sizeToStr
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import javax.annotation.PreDestroy
@Component
class WireTrafficStats : Runnable {
internal var tcp = TrafficStatHandler()
var udp = TrafficStatHandler()
private val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(ThreadFactoryBuilder().setNameFormat("WireTrafficStats-%d").build())
init {
executor.scheduleAtFixedRate(this, 10, 10, TimeUnit.SECONDS)
}
override fun run() {
logger.info("TCP: " + tcp.stats())
logger.info("UDP: " + udp.stats())
}
@PreDestroy
fun close() {
executor.shutdownNow()
}
@ChannelHandler.Sharable class TrafficStatHandler : ChannelDuplexHandler() {
val outSize = AtomicLong()
val inSize = AtomicLong()
val outPackets = AtomicLong()
val inPackets = AtomicLong()
var outSizeTot: Long = 0
var inSizeTot: Long = 0
var lastTime = System.currentTimeMillis()
fun stats(): String {
val out = outSize.getAndSet(0)
val outPac = outPackets.getAndSet(0)
val `in` = inSize.getAndSet(0)
val inPac = inPackets.getAndSet(0)
outSizeTot += out
inSizeTot += `in`
val curTime = System.currentTimeMillis()
val d = curTime - lastTime
val outSpeed = out * 1000 / d
val inSpeed = `in` * 1000 / d
lastTime = curTime
return "Speed in/out " + sizeToStr(inSpeed) + " / " + sizeToStr(outSpeed) +
"(sec), packets in/out " + inPac + "/" + outPac +
", total in/out: " + sizeToStr(inSizeTot) + " / " + sizeToStr(outSizeTot)
}
@Throws(Exception::class)
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
inPackets.incrementAndGet()
if (msg is ByteBuf) {
inSize.addAndGet(msg.readableBytes().toLong())
} else if (msg is DatagramPacket) {
inSize.addAndGet(msg.content().readableBytes().toLong())
}
super.channelRead(ctx, msg)
}
@Throws(Exception::class)
override fun write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise) {
outPackets.incrementAndGet()
if (msg is ByteBuf) {
outSize.addAndGet(msg.readableBytes().toLong())
} else if (msg is DatagramPacket) {
outSize.addAndGet(msg.content().readableBytes().toLong())
}
super.write(ctx, msg, promise)
}
}
companion object {
private val logger = LoggerFactory.getLogger("net")
}
}
|
mit
|
8a408a0262dafcab33a3de03a1984d7d
| 37.516949 | 164 | 0.666227 | 4.421206 | false | false | false | false |
jwren/intellij-community
|
plugins/git4idea/src/git4idea/merge/GitMergeDialog.kt
|
1
|
15326
|
// 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 git4idea.merge
import com.intellij.dvcs.DvcsUtil
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
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.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.MutableCollectionComboBoxModel
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.DropDownLink
import com.intellij.ui.components.JBTextArea
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import git4idea.branch.GitBranchUtil
import git4idea.branch.GitBranchUtil.equalBranches
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.config.GitExecutableManager
import git4idea.config.GitMergeSettings
import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED
import git4idea.i18n.GitBundle
import git4idea.merge.dialog.*
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.ComboBoxWithAutoCompletion
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.PropertyKey
import java.awt.BorderLayout
import java.awt.Insets
import java.awt.event.ItemEvent
import java.awt.event.KeyEvent
import java.util.Collections.synchronizedMap
import java.util.regex.Pattern
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
internal const val GIT_REF_PROTOTYPE_VALUE = "origin/long-enough-branch-name"
internal fun createRepositoryField(repositories: List<GitRepository>,
defaultRoot: VirtualFile? = null) = ComboBox(CollectionComboBoxModel(repositories)).apply {
item = repositories.find { repo -> repo.root == defaultRoot } ?: repositories.first()
renderer = SimpleListCellRenderer.create("") { DvcsUtil.getShortRepositoryName(it) }
@Suppress("UsePropertyAccessSyntax")
setUI(FlatComboBoxUI(outerInsets = Insets(BW.get(), BW.get(), BW.get(), 0)))
}
internal fun createSouthPanelWithOptionsDropDown(southPanel: JComponent, optionDropDown: DropDownLink<*>) = southPanel.apply {
(southPanel.components[0] as JPanel).apply {
(layout as BorderLayout).hgap = JBUI.scale(5)
add(optionDropDown, BorderLayout.EAST)
}
}
internal fun validateBranchExists(branchField: ComboBoxWithAutoCompletion<String>,
@PropertyKey(resourceBundle = GitBundle.BUNDLE) emptyFieldMessage: String): ValidationInfo? {
val value = branchField.getText()
if (value.isNullOrEmpty()) {
return ValidationInfo(GitBundle.message(emptyFieldMessage), branchField)
}
val items = (branchField.model as CollectionComboBoxModel).items
if (items.none { equalBranches(it, value) }) {
return ValidationInfo(GitBundle.message("merge.no.matching.branch.error"), branchField)
}
return null
}
class GitMergeDialog(private val project: Project,
private val defaultRoot: VirtualFile,
private val roots: List<VirtualFile>) : DialogWrapper(project) {
val selectedOptions = mutableSetOf<GitMergeOption>()
private val mergeSettings = project.service<GitMergeSettings>()
private val repositories = DvcsUtil.sortRepositories(GitRepositoryManager.getInstance(project).repositories)
private val allBranches = collectAllBranches()
private val unmergedBranches = synchronizedMap(HashMap<GitRepository, List<String>?>())
private val optionInfos = mutableMapOf<GitMergeOption, OptionInfo<GitMergeOption>>()
private val popupBuilder = createPopupBuilder()
private val repositoryField = createRepoField()
private val branchField = createBranchField()
private val commandPanel = createCommandPanel()
private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo)
private val commitMsgField = JBTextArea("")
private val commitMsgPanel = createCommitMsgPanel()
private val panel = createPanel()
private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project))
init {
loadUnmergedBranchesInBackground()
updateDialogTitle()
setOKButtonText(GitBundle.message("merge.action.name"))
loadSettings()
updateBranchesField()
init()
updateUi()
}
override fun createCenterPanel() = panel
override fun getPreferredFocusedComponent() = branchField
override fun doValidateAll(): List<ValidationInfo> = listOf(::validateBranchField).mapNotNull { it() }
override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown())
override fun getHelpId() = "reference.VersionControl.Git.MergeBranches"
override fun doOKAction() {
try {
saveSettings()
}
finally {
super.doOKAction()
}
}
@NlsSafe
fun getCommitMessage(): String = commitMsgField.text
fun getSelectedRoot(): VirtualFile = repositoryField.item.root
fun getSelectedBranch() = getSelectedRepository().branches.findBranchByName(branchField.getText().orEmpty())
?: error("Unable to find branch: ${branchField.getText().orEmpty()}")
fun shouldCommitAfterMerge() = !isOptionSelected(GitMergeOption.NO_COMMIT)
private fun saveSettings() {
mergeSettings.branch = branchField.getText()
mergeSettings.options = selectedOptions
}
private fun loadSettings() {
branchField.item = mergeSettings.branch
mergeSettings.options
.filter { option -> option != GitMergeOption.NO_VERIFY || isNoVerifySupported }
.forEach { option -> selectedOptions += option }
}
private fun collectAllBranches() = repositories.associateWith { repo ->
repo.branches
.let { it.localBranches + it.remoteBranches }
.map { it.name }
}
private fun loadUnmergedBranchesInBackground() {
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, GitBundle.message("merge.branch.loading.branches.progress"), true) {
override fun run(indicator: ProgressIndicator) {
val sortedRoots = LinkedHashSet<VirtualFile>(roots.size).apply {
add(defaultRoot)
addAll(roots)
}
sortedRoots.forEach { root ->
loadUnmergedBranchesForRoot(root)?.let { branches ->
unmergedBranches[getRepository(root)] = branches
}
}
}
})
}
/**
* ```
* $ git branch --all
* | master
* | feature
* |* checked-out
* |+ checked-out-by-worktree
* | remotes/origin/master
* | remotes/origin/feature
* | remotes/origin/HEAD -> origin/master
* ```
*/
@RequiresBackgroundThread
private fun loadUnmergedBranchesForRoot(root: VirtualFile): List<@NlsSafe String>? {
var result: List<String>? = null
val handler = GitLineHandler(project, root, GitCommand.BRANCH).apply {
addParameters("--no-color", "-a", "--no-merged")
}
try {
result = Git.getInstance().runCommand(handler).getOutputOrThrow()
.lines()
.filter { line -> !LINK_REF_REGEX.matcher(line).matches() }
.mapNotNull { line ->
val matcher = BRANCH_NAME_REGEX.matcher(line)
when {
matcher.matches() -> matcher.group(1)
else -> null
}
}
}
catch (e: Exception) {
LOG.warn("Failed to load unmerged branches for root: ${root}", e)
}
return result
}
private fun validateBranchField(): ValidationInfo? {
val validationInfo = validateBranchExists(branchField, GitBundle.message("merge.no.branch.selected.error"))
if (validationInfo != null) return validationInfo
val selectedBranch = branchField.getText()
if (selectedBranch.isNullOrBlank()) return null
val selectedRepository = getSelectedRepository()
val unmergedBranches = unmergedBranches[selectedRepository] ?: return null
val selectedBranchMerged = unmergedBranches.none { equalBranches(it, selectedBranch) }
if (selectedBranchMerged) {
return ValidationInfo(GitBundle.message("merge.branch.already.merged", selectedBranch), branchField)
}
return null
}
private fun updateBranchesField() {
var branchToSelect = branchField.item
val branches = splitAndSortBranches(getBranches())
val model = branchField.model as MutableCollectionComboBoxModel
model.update(branches)
if (branchToSelect == null || branchToSelect !in branches) {
val repository = getSelectedRepository()
val currentRemoteBranch = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations
branchToSelect = branches.find { branch -> branch == currentRemoteBranch } ?: branches.getOrElse(0) { "" }
}
branchField.item = branchToSelect
branchField.selectAll()
}
private fun splitAndSortBranches(branches: List<@NlsSafe String>): List<@NlsSafe String> {
val local = mutableListOf<String>()
val remote = mutableListOf<String>()
for (branch in branches) {
if (branch.startsWith(REMOTE_REF)) {
remote += branch.substring(REMOTE_REF.length)
}
else {
local += branch
}
}
return GitBranchUtil.sortBranchNames(local) + GitBranchUtil.sortBranchNames(remote)
}
private fun getBranches(): List<@NlsSafe String> {
val repository = getSelectedRepository()
return allBranches[repository] ?: emptyList()
}
private fun getRepository(root: VirtualFile) = repositories.find { repo -> repo.root == root }
?: error("Unable to find repository for root: ${root.presentableUrl}")
private fun getSelectedRepository() = getRepository(getSelectedRoot())
private fun updateDialogTitle() {
val currentBranchName = getSelectedRepository().currentBranchName
title = (if (currentBranchName.isNullOrEmpty())
GitBundle.message("merge.branch.title")
else
GitBundle.message("merge.branch.into.current.title", currentBranchName))
}
private fun createPanel() = JPanel().apply {
layout = MigLayout(LC().insets("0").hideMode(3), AC().grow())
add(commandPanel, CC().growX())
add(optionsPanel, CC().newline().width("100%").alignY("top"))
add(commitMsgPanel, CC().newline().push().grow())
}
private fun showRootField() = roots.size > 1
private fun createCommandPanel() = JPanel().apply {
val colConstraints = if (showRootField())
AC().grow(100f, 0, 2)
else
AC().grow(100f, 1)
layout = MigLayout(
LC()
.fillX()
.insets("0")
.gridGap("0", "0")
.noVisualPadding(),
colConstraints)
if (showRootField()) {
add(repositoryField,
CC()
.gapAfter("0")
.minWidth("${JBUI.scale(135)}px")
.growX())
}
add(createCmdLabel(),
CC()
.gapAfter("0")
.alignY("top")
.minWidth("${JBUI.scale(100)}px"))
add(branchField,
CC()
.alignY("top")
.minWidth("${JBUI.scale(300)}px")
.growX())
}
private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply {
addItemListener { e ->
if (e.stateChange == ItemEvent.SELECTED && e.item != null) {
updateDialogTitle()
updateBranchesField()
}
}
}
private fun createCmdLabel() = CmdLabel("git merge",
Insets(1, if (showRootField()) 0 else 1, 1, 0),
JBDimension(JBUI.scale(100), branchField.preferredSize.height, true))
private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()),
project).apply {
prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE
setPlaceholder(GitBundle.message("merge.branch.field.placeholder"))
@Suppress("UsePropertyAccessSyntax")
setUI(FlatComboBoxUI(
outerInsets = Insets(BW.get(), 0, BW.get(), BW.get()),
popupEmptyText = GitBundle.message("merge.branch.popup.empty.text")))
}
private fun createCommitMsgPanel() = JPanel().apply {
layout = MigLayout(LC().insets("0").fill())
isVisible = false
add(JLabel(GitBundle.message("merge.commit.message.label")), CC().alignY("top").wrap())
add(createScrollPane(commitMsgField,
VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED),
CC()
.alignY("top")
.grow()
.push()
.minHeight("${JBUI.scale(75)}px"))
}
private fun createPopupBuilder() = GitOptionsPopupBuilder(
project,
GitBundle.message("merge.options.modify.popup.title"),
::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen
)
private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) {
popupBuilder.createPopup()
}.apply {
mnemonic = KeyEvent.VK_M
}
private fun isOptionSelected(option: GitMergeOption) = option in selectedOptions
private fun getOptionInfo(option: GitMergeOption) = optionInfos.computeIfAbsent(option) {
OptionInfo(option, option.option, option.description)
}
private fun getOptions(): List<GitMergeOption> = GitMergeOption.values().toMutableList().apply {
if (!isNoVerifySupported) {
remove(GitMergeOption.NO_VERIFY)
}
}
private fun isOptionEnabled(option: GitMergeOption) = selectedOptions.all { it.isOptionSuitable(option) }
private fun optionChosen(option: GitMergeOption) {
if (!isOptionSelected(option)) {
selectedOptions += option
}
else {
selectedOptions -= option
}
updateUi()
}
private fun updateUi() {
optionsPanel.rerender(selectedOptions)
updateCommitMessagePanel()
rerender()
}
private fun rerender() {
window.pack()
window.revalidate()
pack()
repaint()
}
private fun updateCommitMessagePanel() {
val useCommitMsg = isOptionSelected(GitMergeOption.COMMIT_MESSAGE)
commitMsgPanel.isVisible = useCommitMsg
if (!useCommitMsg) {
commitMsgField.text = ""
}
}
companion object {
private val LOG = logger<GitMergeDialog>()
private val LINK_REF_REGEX = Pattern.compile(".+\\s->\\s.+") // aka 'symrefs'
private val BRANCH_NAME_REGEX = Pattern.compile(". (\\S+)\\s*")
@NlsSafe
private const val REMOTE_REF = "remotes/"
}
}
|
apache-2.0
|
84e01babb32a0ac49cebf730b105306f
| 33.06 | 140 | 0.699269 | 4.708449 | false | false | false | false |
vovagrechka/fucking-everything
|
1/global-menu/src/main/java/botinok-fucking-around.kt
|
1
|
6028
|
package vgrechka.botinok
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import vgrechka.*
import vgrechka.db.*
import kotlin.properties.Delegates.notNull
object BotinokFuckingAround {
@JvmStatic
fun main(args: Array<String>) {
backPlatform.springctx = AnnotationConfigApplicationContext(BotinokTestAppConfig::class.java)
DBPile.executeBunchOfSQLStatementsAndCloseConnection(BotinokGeneratedDBPile.ddl.dropCreateAllScript)
val f =
// this::fuck_txSavesShitAutomatically
// this::fuck_shitIsNotSavedAutomatically_1
// this::fuck_shitIsNotSavedAutomatically_2
// this::fuck_explicitSave
// this::fuck_bug_arenaSavedTwice
// this::fuck_bug_arenaSavedTwice
this::fuck_1
clog("====================================================")
clog(f.name)
clog("====================================================")
clog()
f()
clog("OK")
}
fun fuck_1() {
fun printArenas() {
clog(ExecuteAndFormatResultForPrinting()
.linePerRow()
.sql("select * from botinok_arenas")
.skipColumn {col->
listOf("createdAt", "updatedAt", "deleted", "screenshot")
.any {col.name.contains(it)}}
.ignite())
}
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
clog("---------- 1 -----------")
printArenas()
run {
var play by notNull<BotinokPlay>()
backPlatform.tx {
play = botinokPlayRepo.findOne(1)!!
play.arenas.size
}
var firstArena by notNull<BotinokArena>()
backPlatform.tx {
firstArena = newBotinokArena(play = play,
position = 0,
name = "Arena 1",
screenshot = byteArrayOf(),
pile = "{}")
play.arenas.add(firstArena)
play.arenas.add(newBotinokArena(play = play,
position = 1,
name = "Arena 2",
screenshot = byteArrayOf(),
pile = "{}"))
play = botinokPlayRepo.save(play)
}
clog("---------- 2 -----------")
printArenas()
backPlatform.tx {
play.arenas.remove(firstArena) // Doesn't work
// play.arenas.removeAt(firstArena) // Works
play = botinokPlayRepo.save(play)
}
clog("---------- 3 -----------")
printArenas()
}
}
fun fuck_txSavesShitAutomatically() {
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
run {
backPlatform.tx {
val play = botinokPlayRepo.findByName("The Fucking Play")!!
val arena = newBotinokArena(name = "Arena 1", screenshot = byteArrayOf(1, 2, 3), play = play, position = 0, pile = "{}")
play.arenas.add(arena)
}
}
dumpShit()
}
fun fuck_shitIsNotSavedAutomatically_1() {
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
run {
val play = botinokPlayRepo.findByName("The Fucking Play")!!
backPlatform.tx {
val arena = newBotinokArena(name = "Arena 1", screenshot = byteArrayOf(1, 2, 3), play = play, position = 0, pile = "{}")
play.arenas.add(arena)
}
}
dumpShit()
}
fun fuck_shitIsNotSavedAutomatically_2() {
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
run {
val play = botinokPlayRepo.findByName("The Fucking Play")!!
val arena = newBotinokArena(name = "Arena 1", screenshot = byteArrayOf(1, 2, 3), play = play, position = 0, pile = "{}")
play.arenas.add(arena)
}
dumpShit()
}
fun fuck_explicitSave() {
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
run {
val play = botinokPlayRepo.findByName("The Fucking Play")!!
val arena = newBotinokArena(name = "Arena 1", screenshot = byteArrayOf(1, 2, 3), play = play, position = 0, pile = "{}")
play.arenas.add(arena)
botinokPlayRepo.save(play)
}
dumpShit()
}
fun fuck_bug_arenaSavedTwice() {
run {
val play = newBotinokPlay(name = "The Fucking Play", pile = "{}")
botinokPlayRepo.save(play)
}
run {
var play = botinokPlayRepo.findByName("The Fucking Play")!!
val arena = newBotinokArena(name = "Arena 1", screenshot = byteArrayOf(1, 2, 3), play = play, position = 0, pile = "{}")
play.arenas.add(arena)
play = botinokPlayRepo.save(play)
play.name = "The Fucking Play (Amended)"
botinokPlayRepo.save(play)
}
dumpShit()
}
fun dumpShit() {
clog("Plays")
clog("-----")
clog(ExecuteAndFormatResultForPrinting().sql("select * from botinok_plays").linePerRow().ignite())
clog("Arenas")
clog("------")
clog(ExecuteAndFormatResultForPrinting().sql("select * from botinok_arenas").linePerRow().ignite())
}
}
|
apache-2.0
|
7348da3f427c82406d6eca5461b7f668
| 34.668639 | 136 | 0.487724 | 4.393586 | false | false | false | false |
jwren/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCustomCodeStyleSettings.kt
|
4
|
1799
|
// 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.intellij.plugins.markdown.lang.formatter.settings
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
import org.intellij.plugins.markdown.lang.MarkdownLanguage
@Suppress("PropertyName")
class MarkdownCustomCodeStyleSettings(settings: CodeStyleSettings) : CustomCodeStyleSettings(MarkdownLanguage.INSTANCE.id, settings) {
//BLANK LINES
// See IDEA-291443
@JvmField
//@Property(externalName = "min_lines_around_header")
var MAX_LINES_AROUND_HEADER: Int = 1
@JvmField
//@Property(externalName = "max_lines_around_header")
var MIN_LINES_AROUND_HEADER: Int = 1
@JvmField
//@Property(externalName = "min_lines_around_block_elements")
var MAX_LINES_AROUND_BLOCK_ELEMENTS: Int = 1
@JvmField
//@Property(externalName = "max_lines_around_block_elements")
var MIN_LINES_AROUND_BLOCK_ELEMENTS: Int = 1
@JvmField
//@Property(externalName = "min_lines_between_paragraphs")
var MAX_LINES_BETWEEN_PARAGRAPHS: Int = 1
@JvmField
//@Property(externalName = "max_lines_between_paragraphs")
var MIN_LINES_BETWEEN_PARAGRAPHS: Int = 1
//SPACES
@JvmField
var FORCE_ONE_SPACE_BETWEEN_WORDS: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_LIST_BULLET: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL: Boolean = true
@JvmField
var WRAP_TEXT_IF_LONG = true
@JvmField
var KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS = true
@JvmField
var WRAP_TEXT_INSIDE_BLOCKQUOTES = true
@JvmField
var INSERT_QUOTE_ARROWS_ON_WRAP = true
}
|
apache-2.0
|
cbf010a00be1268c382d7f59f4f2f85c
| 28.016129 | 158 | 0.749861 | 3.819533 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineNonBlockingContextChecker.kt
|
1
|
11040
|
// Copyright 2000-2022 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.blockingCallsDetection
import com.intellij.codeInspection.blockingCallsDetection.ContextType
import com.intellij.codeInspection.blockingCallsDetection.ContextType.*
import com.intellij.codeInspection.blockingCallsDetection.ElementContext
import com.intellij.codeInspection.blockingCallsDetection.NonBlockingContextChecker
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.util.parentsOfType
import com.intellij.util.asSafely
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.receiverValue
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.BLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_CONTEXT
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_SCOPE
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.DEFAULT_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.FLOW_PACKAGE_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.IO_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.MAIN_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.NONBLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.findFlowOnCall
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.checkers.isRestrictsSuspensionReceiver
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.types.KotlinType
class CoroutineNonBlockingContextChecker : NonBlockingContextChecker {
override fun isApplicable(file: PsiFile): Boolean {
if (file !is KtFile) return false
val languageVersionSettings = getLanguageVersionSettings(file)
return languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
}
override fun computeContextType(elementContext: ElementContext): ContextType {
val element = elementContext.element
if (element !is KtCallExpression) return Unsure
val containingLambda = element.parents
.filterIsInstance<KtLambdaExpression>()
.firstOrNull()
val containingArgument = containingLambda?.getParentOfType<KtValueArgument>(true, KtCallableDeclaration::class.java)
if (containingArgument != null) {
val callExpression = containingArgument.getStrictParentOfType<KtCallExpression>() ?: return Blocking
val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return Blocking
val blockingFriendlyDispatcherUsed = checkBlockingFriendlyDispatcherUsed(call, callExpression)
if (blockingFriendlyDispatcherUsed.isDefinitelyKnown) return blockingFriendlyDispatcherUsed
val parameterForArgument = call.getParameterForArgument(containingArgument) ?: return Blocking
val type = parameterForArgument.returnType ?: return Blocking
if (type.isBuiltinFunctionalType) {
val hasRestrictSuspensionAnnotation = type.getReceiverTypeFromFunctionType()?.isRestrictsSuspensionReceiver() ?: false
return if (!hasRestrictSuspensionAnnotation && type.isSuspendFunctionType) NonBlocking.INSTANCE else Blocking
}
}
if (containingLambda == null) {
val isInSuspendFunctionBody = element.parentsOfType<KtNamedFunction>()
.take(2)
.firstOrNull { function -> function.nameIdentifier != null }
?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false
return if (isInSuspendFunctionBody) NonBlocking.INSTANCE else Blocking
}
val containingPropertyOrFunction: KtCallableDeclaration? =
containingLambda.getParentOfTypes(true, KtProperty::class.java, KtNamedFunction::class.java)
if (containingPropertyOrFunction?.typeReference?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) return NonBlocking.INSTANCE
return if (containingPropertyOrFunction?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) NonBlocking.INSTANCE else Blocking
}
private fun checkBlockingFriendlyDispatcherUsed(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
return union(
{ checkBlockFriendlyDispatcherParameter(call) },
{ checkFunctionWithDefaultDispatcher(callExpression) },
{ checkFlowChainElementWithIODispatcher(call, callExpression) }
)
}
private fun getLanguageVersionSettings(psiElement: PsiElement): LanguageVersionSettings =
psiElement.module?.languageVersionSettings ?: psiElement.project.languageVersionSettings
private fun ResolvedCall<*>.getFirstArgument(): KtExpression? =
valueArgumentsByIndex?.firstOrNull()?.arguments?.firstOrNull()?.getArgumentExpression()
private fun KotlinType.isCoroutineContext(): Boolean =
(this.constructor.supertypes + this).any { it.fqName?.asString() == COROUTINE_CONTEXT }
private fun checkBlockFriendlyDispatcherParameter(call: ResolvedCall<*>): ContextType {
val argumentDescriptor = call.getFirstArgument()?.resolveToCall()?.resultingDescriptor ?: return Unsure
return argumentDescriptor.isBlockFriendlyDispatcher()
}
private fun checkFunctionWithDefaultDispatcher(callExpression: KtCallExpression): ContextType {
val classDescriptor =
callExpression.receiverValue().asSafely<ImplicitClassReceiver>()?.classDescriptor ?: return Unsure
if (classDescriptor.typeConstructor.supertypes.none { it.fqName?.asString() == COROUTINE_SCOPE }) return Unsure
val propertyDescriptor = classDescriptor
.unsubstitutedMemberScope
.getContributedDescriptors(DescriptorKindFilter.VARIABLES)
.filterIsInstance<PropertyDescriptor>()
.singleOrNull { it.isOverridableOrOverrides && it.type.isCoroutineContext() }
?: return Unsure
val initializer = propertyDescriptor.findPsi().asSafely<KtProperty>()?.initializer ?: return Unsure
return initializer.hasBlockFriendlyDispatcher()
}
private fun checkFlowChainElementWithIODispatcher(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
val isInsideFlow = call.resultingDescriptor.fqNameSafe.asString().startsWith(FLOW_PACKAGE_FQN)
if (!isInsideFlow) return Unsure
val flowOnCall = callExpression.findFlowOnCall() ?: return NonBlocking.INSTANCE
return checkBlockFriendlyDispatcherParameter(flowOnCall)
}
private fun KtExpression.hasBlockFriendlyDispatcher(): ContextType {
class RecursiveExpressionVisitor : PsiRecursiveElementVisitor() {
var allowsBlocking: ContextType = Unsure
override fun visitElement(element: PsiElement) {
if (element is KtExpression) {
val callableDescriptor = element.getCallableDescriptor()
val allowsBlocking = callableDescriptor.asSafely<DeclarationDescriptor>()
?.isBlockFriendlyDispatcher()
if (allowsBlocking != null && allowsBlocking != Unsure) {
this.allowsBlocking = allowsBlocking
return
}
}
super.visitElement(element)
}
}
return RecursiveExpressionVisitor().also(this::accept).allowsBlocking
}
private fun DeclarationDescriptor?.isBlockFriendlyDispatcher(): ContextType {
if (this == null) return Unsure
val returnTypeDescriptor = this.asSafely<CallableDescriptor>()?.returnType
val typeConstructor = returnTypeDescriptor?.constructor?.declarationDescriptor
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, BLOCKING_EXECUTOR_ANNOTATION)) return Blocking
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, NONBLOCKING_EXECUTOR_ANNOTATION)) return NonBlocking.INSTANCE
val fqnOrNull = fqNameOrNull()?.asString() ?: return NonBlocking.INSTANCE
return when(fqnOrNull) {
IO_DISPATCHER_FQN -> Blocking
MAIN_DISPATCHER_FQN, DEFAULT_DISPATCHER_FQN -> NonBlocking.INSTANCE
else -> Unsure
}
}
private fun isTypeOrUsageAnnotatedWith(type: KotlinType?, typeConstructor: ClassifierDescriptor?, annotationFqn: String): Boolean {
val fqName = FqName(annotationFqn)
return when {
type?.annotations?.hasAnnotation(fqName) == true -> true
typeConstructor?.annotations?.hasAnnotation(fqName) == true -> true
else -> false
}
}
private fun union(vararg checks: () -> ContextType): ContextType {
for (check in checks) {
val iterationResult = check()
if (iterationResult != Unsure) return iterationResult
}
return Unsure
}
}
|
apache-2.0
|
3d05941af39cbab6a24fb8652510f68d
| 53.389163 | 158 | 0.758514 | 5.859873 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinMigrationProjectFUSCollector.kt
|
2
|
1991
|
// 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.configuration
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import org.jetbrains.kotlin.idea.KotlinPluginUtil
class KotlinMigrationProjectFUSCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("kotlin.ide.migrationTool", 2)
private val oldLanguageVersion = EventFields.StringValidatedByRegexp("old_language_version", "version_lang_api")
private val oldApiVersion = EventFields.StringValidatedByRegexp("old_api_version", "version_lang_api")
private val oldStdlibVersion = EventFields.StringValidatedByRegexp("old_stdlib_version", "version_stdlib")
private val pluginInfo = EventFields.PluginInfo
private val notificationEvent = GROUP.registerVarargEvent(
"Notification",
oldLanguageVersion,
oldApiVersion,
oldStdlibVersion,
pluginInfo,
)
private val runEvent = GROUP.registerEvent(
"Run"
)
fun logNotification(migrationInfo: MigrationInfo) {
notificationEvent.log(
this.oldLanguageVersion.with(migrationInfo.oldLanguageVersion.versionString),
this.oldApiVersion.with(migrationInfo.oldApiVersion.versionString),
this.oldStdlibVersion.with(migrationInfo.oldStdlibVersion),
this.pluginInfo.with(getPluginInfoById(KotlinPluginUtil.KOTLIN_PLUGIN_ID))
)
}
fun logRun() {
runEvent.log()
}
}
}
|
apache-2.0
|
55fdd60d6000710275e695d1672d2ff8
| 42.304348 | 158 | 0.712205 | 5.171429 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/ifExpression/ifElseCondition.kt
|
12
|
205
|
fun a(): Int {
var a = 1
<warning descr="SSR">if (a == 1) {
a = 2
} else {
a = 3
}</warning>
if (a == 0) {
a = 2
} else {
a = 3
}
return a
}
|
apache-2.0
|
bb91753a978b133c2b7020dfc6c11325
| 12.733333 | 38 | 0.317073 | 3.059701 | false | false | false | false |
android/compose-samples
|
Jetcaster/app/src/main/java/com/example/jetcaster/data/PodcastStore.kt
|
1
|
2789
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.jetcaster.data
import com.example.jetcaster.data.room.PodcastFollowedEntryDao
import com.example.jetcaster.data.room.PodcastsDao
import com.example.jetcaster.data.room.TransactionRunner
import kotlinx.coroutines.flow.Flow
/**
* A data repository for [Podcast] instances.
*/
class PodcastStore(
private val podcastDao: PodcastsDao,
private val podcastFollowedEntryDao: PodcastFollowedEntryDao,
private val transactionRunner: TransactionRunner
) {
/**
* Return a flow containing the [Podcast] with the given [uri].
*/
fun podcastWithUri(uri: String): Flow<Podcast> {
return podcastDao.podcastWithUri(uri)
}
/**
* Returns a flow containing the entire collection of podcasts, sorted by the last episode
* publish date for each podcast.
*/
fun podcastsSortedByLastEpisode(
limit: Int = Int.MAX_VALUE
): Flow<List<PodcastWithExtraInfo>> {
return podcastDao.podcastsSortedByLastEpisode(limit)
}
/**
* Returns a flow containing a list of all followed podcasts, sorted by the their last
* episode date.
*/
fun followedPodcastsSortedByLastEpisode(
limit: Int = Int.MAX_VALUE
): Flow<List<PodcastWithExtraInfo>> {
return podcastDao.followedPodcastsSortedByLastEpisode(limit)
}
private suspend fun followPodcast(podcastUri: String) {
podcastFollowedEntryDao.insert(PodcastFollowedEntry(podcastUri = podcastUri))
}
suspend fun togglePodcastFollowed(podcastUri: String) = transactionRunner {
if (podcastFollowedEntryDao.isPodcastFollowed(podcastUri)) {
unfollowPodcast(podcastUri)
} else {
followPodcast(podcastUri)
}
}
suspend fun unfollowPodcast(podcastUri: String) {
podcastFollowedEntryDao.deleteWithPodcastUri(podcastUri)
}
/**
* Add a new [Podcast] to this store.
*
* This automatically switches to the main thread to maintain thread consistency.
*/
suspend fun addPodcast(podcast: Podcast) {
podcastDao.insert(podcast)
}
suspend fun isEmpty(): Boolean = podcastDao.count() == 0
}
|
apache-2.0
|
bdd68e81935360eca91ad1842ea5d81a
| 31.811765 | 94 | 0.708139 | 4.406003 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenTreeStructureProvider.kt
|
1
|
2936
|
// 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.idea.maven.utils
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode
import com.intellij.ide.projectView.impl.nodes.PsiFileNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.SmartList
import com.intellij.util.ui.UIUtil
import org.jetbrains.idea.maven.project.MavenProjectsManager
class MavenTreeStructureProvider : TreeStructureProvider, DumbAware {
override fun modify(parent: AbstractTreeNode<*>,
children: Collection<AbstractTreeNode<*>>,
settings: ViewSettings): Collection<AbstractTreeNode<*>> {
val project = parent.project ?: return children
val manager = MavenProjectsManager.getInstance(project)
if (!manager.isMavenizedProject) {
return children
}
if (parent is ProjectViewProjectNode || parent is PsiDirectoryNode) {
val modifiedChildren: MutableCollection<AbstractTreeNode<*>> = SmartList()
for (child in children) {
var childToAdd = child
if (child is PsiFileNode) {
if (child.virtualFile != null && MavenUtil.isPotentialPomFile(child.virtualFile!!.name)) {
val mavenProject = manager.findProject(child.virtualFile!!)
if (mavenProject != null) {
childToAdd = MavenPomFileNode(project, child.value, settings, manager.isIgnored(mavenProject))
}
}
}
modifiedChildren.add(childToAdd)
}
return modifiedChildren
}
return children
}
private inner class MavenPomFileNode(project: Project?,
value: PsiFile,
viewSettings: ViewSettings?,
val myIgnored: Boolean) : PsiFileNode(project, value, viewSettings) {
val strikeAttributes = SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, UIUtil.getInactiveTextColor())
override fun updateImpl(data: PresentationData) {
if (myIgnored) {
data.addText(value.name, strikeAttributes)
}
super.updateImpl(data)
}
@Suppress("DEPRECATION")
override fun getTestPresentation(): String? {
if (myIgnored) {
return "-MavenPomFileNode:" + super.getTestPresentation() + " (ignored)"
} else {
return "-MavenPomFileNode:" + super.getTestPresentation()
}
}
}
}
|
apache-2.0
|
b5c58c7ded10a369b8686717fbf4059b
| 41.565217 | 158 | 0.695845 | 4.885191 | false | false | false | false |
RADAR-CNS/RADAR-AndroidApplication
|
app/src/main/java/org/radarcns/detail/MainActivityViewImpl.kt
|
1
|
7082
|
/*
* Copyright 2017 The Hyve
*
* 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.radarcns.detail
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import org.radarbase.android.IRadarBinder
import org.radarbase.android.MainActivityView
import org.radarbase.android.source.SourceProvider
import org.radarbase.android.util.ChangeApplier
import org.radarbase.android.util.ChangeRunner
import org.radarbase.android.util.TimedLong
import org.slf4j.LoggerFactory
import java.text.SimpleDateFormat
import java.util.*
class MainActivityViewImpl internal constructor(private val mainActivity: MainActivityImpl) : MainActivityView {
private val connectionRows = ChangeRunner<List<SourceProvider<*>>>(emptyList())
private val actionsCells = ChangeRunner<List<SourceProvider.Action>>(emptyList())
private val timestampCache = ChangeApplier<TimedLong, String>({ numberOfRecords ->
val msg = if (numberOfRecords.value >= 0) R.string.last_upload_succeeded
else R.string.last_upload_failed
mainActivity.getString(msg, timeFormat.format(numberOfRecords.time))
}, { b -> time == b?.time })
private val serverStatusCache = ChangeRunner<String>()
// View elements
private val mServerMessage: TextView
private val mUserId: TextView
private val mSourcesTable: ViewGroup
private val mProjectId: TextView
private val mActionDivider: View
private val mActionHeader: View
private val mActionLayout: GridLayout
private val userIdCache = ChangeRunner<String>()
private val projectIdCache = ChangeRunner<String>()
private var rows: List<SourceRowView> = emptyList()
private val serverStatusMessage: String?
get() {
return mainActivity.radarService?.latestNumberOfRecordsSent?.let { numberOfRecords ->
if (numberOfRecords.time >= 0) {
timestampCache.applyIfChanged(numberOfRecords)
} else {
null
}
}
}
init {
logger.debug("Creating main activity view")
mainActivity.apply {
setContentView(R.layout.compact_overview)
setSupportActionBar(findViewById<Toolbar>(R.id.toolbar).apply {
setTitle(R.string.radar_prmt_title)
})
mServerMessage = findViewById(R.id.statusServerMessage)
mUserId = findViewById(R.id.inputUserId)
mProjectId = findViewById(R.id.inputProjectId)
mSourcesTable = findViewById(R.id.sourcesTable)
mActionHeader = findViewById(R.id.actionHeader)
mActionDivider = findViewById(R.id.actionDivider)
mActionLayout = findViewById(R.id.actionLayout)
[email protected]()
}
}
override fun onRadarServiceBound(binder: IRadarBinder) {
logger.debug("Radar service bound")
}
override fun update() {
val providers = mainActivity.radarService
?.connections
?.filter { it.isDisplayable }
?: emptyList()
val currentActions = mainActivity.radarService
?.connections
?.flatMap { it.actions }
?: emptyList()
rows.forEach(SourceRowView::update)
mainActivity.runOnUiThread {
connectionRows.applyIfChanged(providers) { p ->
val root = mSourcesTable.apply {
while (childCount > 1) {
removeView(getChildAt(1))
}
}
rows = p.map {
SourceRowView(mainActivity, it, root).apply {
update()
}
}
}
actionsCells.applyIfChanged(currentActions) { actionList ->
if (actionList.isNotEmpty()) {
mActionHeader.visibility = View.VISIBLE
mActionDivider.visibility = View.VISIBLE
mActionLayout.apply {
visibility = View.VISIBLE
removeAllViews()
actionList.forEach { action ->
addView(Button(mainActivity).apply {
text = action.name
setOnClickListener { mainActivity.apply(action.activate) }
})
}
}
} else {
mActionHeader.visibility = View.GONE
mActionDivider.visibility = View.GONE
mActionLayout.apply {
visibility = View.GONE
removeAllViews()
}
}
}
rows.forEach(SourceRowView::display)
updateServerStatus()
setUserId()
}
}
private fun updateServerStatus() {
serverStatusCache.applyIfChanged(serverStatusMessage ?: "\u2014") {
mServerMessage.text = it
}
}
private fun setUserId() {
userIdCache.applyIfChanged(mainActivity.userId ?: "") { id ->
mUserId.apply {
if (id.isEmpty()) {
visibility = View.GONE
} else {
visibility = View.VISIBLE
text = mainActivity.getString(R.string.user_id_message, id.truncate(MAX_USERNAME_LENGTH))
}
}
}
projectIdCache.applyIfChanged(mainActivity.projectId ?: "") { id ->
mProjectId.apply {
if (id.isEmpty()) {
visibility = View.GONE
} else {
visibility = View.VISIBLE
text = mainActivity.getString(R.string.study_id_message, id.truncate(MAX_USERNAME_LENGTH))
}
}
}
}
companion object {
private val logger = LoggerFactory.getLogger(MainActivityViewImpl::class.java)
private val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.US)
internal const val MAX_USERNAME_LENGTH = 20
internal fun String?.truncate(maxLength: Int): String {
return when {
this == null -> ""
length > maxLength -> substring(0, maxLength - 3) + "\u2026"
else -> this
}
}
}
}
|
apache-2.0
|
74514b4c86ba84b3e9371012876add65
| 34.949239 | 112 | 0.585851 | 5.128168 | false | false | false | false |
tomatrocho/insapp-material
|
app/src/main/java/fr/insapp/insapp/activities/SignInActivity.kt
|
2
|
3824
|
package fr.insapp.insapp.activities
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.google.gson.Gson
import fr.insapp.insapp.R
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.User
import kotlinx.android.synthetic.main.activity_sign_in.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SignInActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
setSupportActionBar(toolbar_sign_in)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
//refresh_webpage.setOnRefreshListener(this)
val cookieManager = CookieManager.getInstance()
cookieManager.removeSessionCookies { res ->
Log.d("CAS", "Cookie removed: $res")
}
webview_conditions.loadUrl(CAS_URL)
webview_conditions.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
progress_bar.visibility = View.VISIBLE
val id = url.lastIndexOf("?ticket=")
if (url.contains("?ticket=")) {
val ticket = url.substring(id + "?ticket=".length, url.length)
Log.d("CAS", "URL: $url")
Log.d("CAS", "Ticket: $ticket")
logIn(ticket)
webview_conditions.visibility = View.INVISIBLE
}
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progress_bar.visibility = View.GONE
}
}
}
fun logIn(ticket: String) {
val call = ServiceGenerator.client.logUser(ticket)
call.enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
val user = response.body()
if (response.isSuccessful && user != null) {
val userPreferences = [email protected]("User", Context.MODE_PRIVATE)
userPreferences.edit().putString("user", Gson().toJson(user)).apply()
val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this@SignInActivity)
val editor = defaultSharedPreferences.edit()
editor.putString("name", user.name)
editor.putString("description", user.description)
editor.putString("email", user.email)
editor.putString("class", user.promotion)
editor.putString("gender", user.gender)
editor.apply()
startActivity(Intent(this@SignInActivity, MainActivity::class.java))
finish()
} else {
Toast.makeText(this@SignInActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<User>, t: Throwable) {
Toast.makeText(this@SignInActivity, TAG, Toast.LENGTH_LONG).show()
}
})
}
companion object {
private const val CAS_URL = "https://cas.insa-rennes.fr/cas/login?service=https://insapp.fr/"
const val TAG = "SignInActivity"
}
}
|
mit
|
87d8fecf795c850428eb4d1da37627cb
| 36.490196 | 117 | 0.622385 | 4.94696 | false | false | false | false |
breadwallet/breadwallet-android
|
app-core/src/main/java/com/breadwallet/breadbox/CoreUtils.kt
|
1
|
7736
|
/**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 9/25/19.
* Copyright (c) 2019 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.
*/
@file:Suppress("EXPERIMENTAL_API_USAGE", "TooManyFunctions")
package com.breadwallet.breadbox
import com.breadwallet.appcore.BuildConfig
import com.breadwallet.crypto.Address
import com.breadwallet.crypto.Currency
import com.breadwallet.crypto.Network
import com.breadwallet.crypto.NetworkPeer
import com.breadwallet.crypto.Transfer
import com.breadwallet.crypto.TransferDirection
import com.breadwallet.crypto.Wallet
import com.breadwallet.crypto.WalletManager
import com.breadwallet.crypto.WalletManagerState
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.util.isBitcoin
import com.breadwallet.util.isBitcoinCash
import com.breadwallet.util.isEthereum
import com.breadwallet.util.isRipple
import com.google.common.primitives.UnsignedInteger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import java.math.BigDecimal
import java.text.DecimalFormat
import java.util.Locale
/** Default port for [NetworkPeer] */
private const val DEFAULT_PORT = 8333L
/** Returns the [Address] string removing any address prefixes. */
fun Address.toSanitizedString(): String =
toString()
.removePrefix("bitcoincash:")
.removePrefix("bchtest:")
/** Returns the [Transfer]'s hash or an empty string. */
fun Transfer.hashString(): String =
checkNotNull(hash.orNull()).toString()
.let { hash ->
val isEthHash = wallet.currency.run { isErc20() || isEthereum() }
when {
isEthHash -> hash
else -> hash.removePrefix("0x")
}
}
// TODO: Move somewhere UI related
fun BigDecimal.formatCryptoForUi(
currencyCode: String,
scale: Int = 5,
negate: Boolean = false
): String {
val amount = if (negate) negate() else this
val currencyFormat = DecimalFormat.getCurrencyInstance(Locale.getDefault()) as DecimalFormat
val decimalFormatSymbols = currencyFormat.decimalFormatSymbols
currencyFormat.isGroupingUsed = true
currencyFormat.roundingMode = BRConstants.ROUNDING_MODE
decimalFormatSymbols.currencySymbol = ""
currencyFormat.decimalFormatSymbols = decimalFormatSymbols
currencyFormat.maximumFractionDigits = scale
currencyFormat.minimumFractionDigits = 0
return "${currencyFormat.format(amount)} ${currencyCode.toUpperCase()}"
}
val Wallet.currencyId: String
get() = currency.uids
fun List<Wallet>.filterByCurrencyIds(currencyIds: List<String>) =
filter { wallet ->
currencyIds.any {
it.equals(
wallet.currencyId,
true
)
}
}
/** Returns the [Wallet] with the given [currencyId] or null. */
fun List<Wallet>.findByCurrencyId(currencyId: String) =
find { it.currencyId.equals(currencyId, true) }
/** Returns true if any of the [Wallet]s is for the given [currencyId]. */
fun List<Wallet>.containsCurrency(currencyId: String) =
findByCurrencyId(currencyId) != null
/** Returns true if the [WalletManager]'s [Network] supports the given [currencyId]. */
fun WalletManager.networkContainsCurrency(currencyId: String) =
network.containsCurrency(currencyId)
/** Returns the [Currency] if the [WalletManager]'s [Network] supports the given [currencyId], null otherwise. */
fun WalletManager.findCurrency(currencyId: String) =
network.findCurrency(currencyId)
/** Returns true if the [Network] supports the given [currencyId]. */
fun Network.containsCurrency(currencyId: String) =
findCurrency(currencyId) != null
/** Returns the [Currency] if the [Network] supports the given [currencyId], null otherwise. */
fun Network.findCurrency(currencyId: String) =
currencies.find { networkCurrency ->
networkCurrency.uids.equals(
currencyId,
true
)
}
/** Returns true if the [Network] supports the given [currencyCode]. */
fun Network.containsCurrencyCode(currencyCode: String) =
currencies.find { networkCurrency ->
networkCurrency.code.equals(
currencyCode,
true
)
} != null
/** Returns the [Currency] code if the [Transfer] is a ETH fee transfer, blank otherwise. */
fun Transfer.feeForToken(): String {
val targetAddress = target.orNull()?.toSanitizedString() ?: return ""
val issuerCode = wallet.walletManager.network.currencies.find { networkCurrency ->
networkCurrency.issuer.or("").equals(targetAddress, true)
}
return when {
!wallet.walletManager.currency.isEthereum() -> ""
issuerCode == null || issuerCode.isEthereum() -> ""
else -> issuerCode.code
}
}
fun WalletManagerState.isTracked() =
type == WalletManagerState.Type.CONNECTED ||
type == WalletManagerState.Type.SYNCING
/** Returns [Wallet] [Flow] sorted by [displayOrderCurrencyIds]. */
fun Flow<List<Wallet>>.applyDisplayOrder(displayOrderCurrencyIds: Flow<List<String>>) =
combine(displayOrderCurrencyIds) { systemWallets, currencyIds ->
currencyIds.mapNotNull {
systemWallets.findByCurrencyId(it)
}
}
/** Returns the url scheme for a payment request with this wallet. */
val Wallet.urlScheme: String?
get() = when {
currency.code.isEthereum() || currency.isErc20() -> "ethereum"
currency.code.isRipple() -> "xrp"
currency.code.isBitcoin() -> "bitcoin"
currency.code.isBitcoinCash() -> when {
walletManager.network.isMainnet -> "bitcoincash"
else -> "bchtest"
}
else -> null
}
val Wallet.urlSchemes: List<String>
get() = when {
currency.code.isRipple() -> listOf(urlScheme!!, "xrpl", "ripple")
else -> urlScheme?.run(::listOf) ?: emptyList()
}
/** Return a [NetworkPeer] pointing to the given address */
fun Network.getPeerOrNull(node: String): NetworkPeer? {
val nodeInfo = node.split(":")
if (nodeInfo.isEmpty()) return null
val address = nodeInfo[0]
val port = if (nodeInfo.size > 1) {
UnsignedInteger.valueOf(nodeInfo[1])
} else {
UnsignedInteger.valueOf(DEFAULT_PORT)
}
return createPeer(address, port, null).orNull()
}
/** True when the [Transfer] was received. */
fun Transfer.isReceived(): Boolean = direction == TransferDirection.RECEIVED
fun Transfer.getSize(): Double? {
val currencyCode = wallet.currency.code
return when {
currencyCode.isBitcoin() || currencyCode.isBitcoinCash() ->
(confirmedFeeBasis.orNull() ?: estimatedFeeBasis.orNull())?.costFactor
else -> null
}
}
|
mit
|
c8bd3085506e909a092c14b35fc8fdbd
| 36.014354 | 113 | 0.704111 | 4.380521 | false | false | false | false |
BastiaanOlij/godot
|
platform/android/java/lib/src/org/godotengine/godot/io/file/MediaStoreData.kt
|
14
|
9567
|
/*************************************************************************/
/* MediaStoreData.kt */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 org.godotengine.godot.io.file
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.nio.channels.FileChannel
/**
* Implementation of [DataAccess] which handles access and interactions with file and data
* under scoped storage via the MediaStore API.
*/
@RequiresApi(Build.VERSION_CODES.Q)
internal class MediaStoreData(context: Context, filePath: String, accessFlag: FileAccessFlags) :
DataAccess(filePath) {
private data class DataItem(
val id: Long,
val uri: Uri,
val displayName: String,
val relativePath: String,
val size: Int,
val dateModified: Int,
val mediaType: Int
)
companion object {
private val TAG = MediaStoreData::class.java.simpleName
private val COLLECTION = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
private val PROJECTION = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.RELATIVE_PATH,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.DATE_MODIFIED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
)
private const val SELECTION_BY_PATH = "${MediaStore.Files.FileColumns.DISPLAY_NAME} = ? " +
" AND ${MediaStore.Files.FileColumns.RELATIVE_PATH} = ?"
private fun getSelectionByPathArguments(path: String): Array<String> {
return arrayOf(getMediaStoreDisplayName(path), getMediaStoreRelativePath(path))
}
private const val SELECTION_BY_ID = "${MediaStore.Files.FileColumns._ID} = ? "
private fun getSelectionByIdArgument(id: Long) = arrayOf(id.toString())
private fun getMediaStoreDisplayName(path: String) = File(path).name
private fun getMediaStoreRelativePath(path: String): String {
val pathFile = File(path)
val environmentDir = Environment.getExternalStorageDirectory()
var relativePath = (pathFile.parent?.replace(environmentDir.absolutePath, "") ?: "").trim('/')
if (relativePath.isNotBlank()) {
relativePath += "/"
}
return relativePath
}
private fun queryById(context: Context, id: Long): List<DataItem> {
val query = context.contentResolver.query(
COLLECTION,
PROJECTION,
SELECTION_BY_ID,
getSelectionByIdArgument(id),
null
)
return dataItemFromCursor(query)
}
private fun queryByPath(context: Context, path: String): List<DataItem> {
val query = context.contentResolver.query(
COLLECTION,
PROJECTION,
SELECTION_BY_PATH,
getSelectionByPathArguments(path),
null
)
return dataItemFromCursor(query)
}
private fun dataItemFromCursor(query: Cursor?): List<DataItem> {
query?.use { cursor ->
cursor.count
if (cursor.count == 0) {
return emptyList()
}
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)
val displayNameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
val relativePathColumn =
cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.RELATIVE_PATH)
val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
val dateModifiedColumn =
cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED)
val mediaTypeColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MEDIA_TYPE)
val result = ArrayList<DataItem>()
while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
result.add(
DataItem(
id,
ContentUris.withAppendedId(COLLECTION, id),
cursor.getString(displayNameColumn),
cursor.getString(relativePathColumn),
cursor.getInt(sizeColumn),
cursor.getInt(dateModifiedColumn),
cursor.getInt(mediaTypeColumn)
)
)
}
return result
}
return emptyList()
}
private fun addFile(context: Context, path: String): DataItem? {
val fileDetails = ContentValues().apply {
put(MediaStore.Files.FileColumns._ID, 0)
put(MediaStore.Files.FileColumns.DISPLAY_NAME, getMediaStoreDisplayName(path))
put(MediaStore.Files.FileColumns.RELATIVE_PATH, getMediaStoreRelativePath(path))
}
context.contentResolver.insert(COLLECTION, fileDetails) ?: return null
// File was successfully added, let's retrieve its info
val infos = queryByPath(context, path)
if (infos.isEmpty()) {
return null
}
return infos[0]
}
fun delete(context: Context, path: String): Boolean {
val itemsToDelete = queryByPath(context, path)
if (itemsToDelete.isEmpty()) {
return false
}
val resolver = context.contentResolver
var itemsDeleted = 0
for (item in itemsToDelete) {
itemsDeleted += resolver.delete(item.uri, null, null)
}
return itemsDeleted > 0
}
fun fileExists(context: Context, path: String): Boolean {
return queryByPath(context, path).isNotEmpty()
}
fun fileLastModified(context: Context, path: String): Long {
val result = queryByPath(context, path)
if (result.isEmpty()) {
return 0L
}
val dataItem = result[0]
return dataItem.dateModified.toLong()
}
fun rename(context: Context, from: String, to: String): Boolean {
// Ensure the source exists.
val sources = queryByPath(context, from)
if (sources.isEmpty()) {
return false
}
// Take the first source
val source = sources[0]
// Set up the updated values
val updatedDetails = ContentValues().apply {
put(MediaStore.Files.FileColumns.DISPLAY_NAME, getMediaStoreDisplayName(to))
put(MediaStore.Files.FileColumns.RELATIVE_PATH, getMediaStoreRelativePath(to))
}
val updated = context.contentResolver.update(
source.uri,
updatedDetails,
SELECTION_BY_ID,
getSelectionByIdArgument(source.id)
)
return updated > 0
}
}
private val id: Long
private val uri: Uri
override val fileChannel: FileChannel
init {
val contentResolver = context.contentResolver
val dataItems = queryByPath(context, filePath)
val dataItem = when (accessFlag) {
FileAccessFlags.READ -> {
// The file should already exist
if (dataItems.isEmpty()) {
throw FileNotFoundException("Unable to access file $filePath")
}
val dataItem = dataItems[0]
dataItem
}
FileAccessFlags.WRITE, FileAccessFlags.READ_WRITE, FileAccessFlags.WRITE_READ -> {
// Create the file if it doesn't exist
val dataItem = if (dataItems.isEmpty()) {
addFile(context, filePath)
} else {
dataItems[0]
}
if (dataItem == null) {
throw FileNotFoundException("Unable to access file $filePath")
}
dataItem
}
}
id = dataItem.id
uri = dataItem.uri
val parcelFileDescriptor = contentResolver.openFileDescriptor(uri, accessFlag.getMode())
?: throw IllegalStateException("Unable to access file descriptor")
fileChannel = if (accessFlag == FileAccessFlags.READ) {
FileInputStream(parcelFileDescriptor.fileDescriptor).channel
} else {
FileOutputStream(parcelFileDescriptor.fileDescriptor).channel
}
if (accessFlag.shouldTruncate()) {
fileChannel.truncate(0)
}
}
}
|
mit
|
73fc605c9d005ae1435c1e9e11ae4240
| 32.68662 | 97 | 0.659559 | 4.269076 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/speeddial/view/SpeedDialSettingActivity.kt
|
1
|
8409
|
/*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.speeddial.view
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.MenuItem
import jp.hazuki.yuzubrowser.bookmark.view.BookmarkActivity
import jp.hazuki.yuzubrowser.core.utility.extensions.getBitmap
import jp.hazuki.yuzubrowser.history.presenter.BrowserHistoryActivity
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.speeddial.SpeedDial
import jp.hazuki.yuzubrowser.legacy.speeddial.WebIcon
import jp.hazuki.yuzubrowser.legacy.utils.appinfo.AppInfo
import jp.hazuki.yuzubrowser.legacy.utils.appinfo.ApplicationListFragment
import jp.hazuki.yuzubrowser.legacy.utils.appinfo.ShortCutListFragment
import jp.hazuki.yuzubrowser.legacy.utils.stack.SingleStack
import jp.hazuki.yuzubrowser.ui.app.ThemeActivity
class SpeedDialSettingActivity : ThemeActivity(), SpeedDialEditCallBack, androidx.fragment.app.FragmentManager.OnBackStackChangedListener, SpeedDialSettingActivityFragment.OnSpeedDialAddListener, SpeedDialSettingActivityEditFragment.GoBackController, ApplicationListFragment.OnAppSelectListener, ShortCutListFragment.OnShortCutSelectListener {
private val speedDialStack = object : SingleStack<SpeedDial>() {
override fun processItem(item: SpeedDial) {
goEdit(item)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_base)
supportFragmentManager.addOnBackStackChangedListener(this)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, SpeedDialSettingActivityFragment(), "main")
.commit()
if (intent != null && ACTION_ADD_SPEED_DIAL == intent.action) {
val title = intent.getStringExtra(Intent.EXTRA_TITLE)
val url = intent.getStringExtra(Intent.EXTRA_TEXT)
val icon = intent.getParcelableExtra<Bitmap>(EXTRA_ICON)
speedDialStack.addItem(SpeedDial(url, title, WebIcon.createIconOrNull(icon), true))
}
}
shouldDisplayHomeUp()
}
override fun goBack(): Boolean = supportFragmentManager.popBackStackImmediate()
override fun goEdit(speedDial: SpeedDial) {
supportFragmentManager.beginTransaction()
.addToBackStack("")
.replace(R.id.container, SpeedDialSettingActivityEditFragment.newInstance(speedDial))
.commit()
}
override fun addFromBookmark() {
val intent = Intent(this, BookmarkActivity::class.java)
.apply { action = Intent.ACTION_PICK }
startActivityForResult(intent, RESULT_REQUEST_BOOKMARK)
}
override fun addFromHistory() {
val intent = Intent(this, BrowserHistoryActivity::class.java)
.apply { action = Intent.ACTION_PICK }
startActivityForResult(intent, RESULT_REQUEST_HISTORY)
}
override fun addFromAppList() {
val target = Intent(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_LAUNCHER) }
supportFragmentManager.beginTransaction()
.addToBackStack("")
.replace(R.id.container, ApplicationListFragment.newInstance(target))
.commit()
}
override fun addFromShortCutList() {
supportFragmentManager.beginTransaction()
.addToBackStack("")
.replace(R.id.container, ShortCutListFragment())
.commit()
}
@Suppress("DEPRECATION")
override fun onShortCutSelected(data: Intent) {
goBack()
val intent = data.getParcelableExtra<Intent>(Intent.EXTRA_SHORTCUT_INTENT)!!
val name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)
var icon: Bitmap? = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON)
if (icon == null) {
val iconRes = data.getParcelableExtra<Intent.ShortcutIconResource>(Intent.EXTRA_SHORTCUT_ICON_RESOURCE)
if (iconRes != null) {
try {
val foreignResources = packageManager.getResourcesForApplication(iconRes.packageName)
val id = foreignResources.getIdentifier(iconRes.resourceName, null, null)
icon = BitmapFactory.decodeResource(foreignResources, id)
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
if (icon == null) {
try {
val component = intent.component
if (component != null) {
val drawable = packageManager.getApplicationIcon(component.packageName)
icon = drawable.getBitmap()
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
}
val webIcon = WebIcon.createIconOrNull(icon)
val speedDial = SpeedDial(intent.toUri(Intent.URI_INTENT_SCHEME), name, webIcon, false)
speedDialStack.addItem(speedDial)
}
override fun onAppSelected(type: Int, appInfo: AppInfo) {
goBack()
val intent = Intent()
intent.setClassName(appInfo.packageName, appInfo.className)
val webIcon = WebIcon.createIcon(appInfo.icon.getBitmap())
val speedDial = SpeedDial(intent.toUri(Intent.URI_INTENT_SCHEME), appInfo.appName, webIcon, false)
speedDialStack.addItem(speedDial)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
RESULT_REQUEST_BOOKMARK, RESULT_REQUEST_HISTORY -> {
if (resultCode != Activity.RESULT_OK || data == null) return
val title = data.getStringExtra(Intent.EXTRA_TITLE)
val url = data.getStringExtra(Intent.EXTRA_TEXT)
val icon = data.getByteArrayExtra(Intent.EXTRA_STREAM)
val speedDial = if (icon == null) {
SpeedDial(url, title)
} else {
SpeedDial(url, title, WebIcon(icon), true)
}
speedDialStack.addItem(speedDial)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onEdited(speedDial: SpeedDial) {
goBack()
val fragment = supportFragmentManager.findFragmentByTag("main")
if (fragment is SpeedDialEditCallBack) {
fragment.onEdited(speedDial)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun shouldDisplayHomeUp() {
val canBack = supportFragmentManager.backStackEntryCount == 0
supportActionBar?.setDisplayHomeAsUpEnabled(canBack)
}
override fun onPause() {
super.onPause()
speedDialStack.onPause()
}
override fun onResume() {
super.onResume()
speedDialStack.onResume()
}
override fun onBackStackChanged() {
shouldDisplayHomeUp()
}
companion object {
const val ACTION_ADD_SPEED_DIAL = "jp.hazuki.yuzubrowser.legacy.speeddial.view.SpeedDialSettingActivity.add_speed_dial"
const val EXTRA_ICON = ACTION_ADD_SPEED_DIAL + ".icon"
private const val RESULT_REQUEST_BOOKMARK = 100
private const val RESULT_REQUEST_HISTORY = 101
}
}
|
apache-2.0
|
a928a5e8bde790037c8d099d2d2360bc
| 37.930556 | 343 | 0.655369 | 4.906068 | false | false | false | false |
markusfisch/BinaryEye
|
app/src/main/kotlin/de/markusfisch/android/binaryeye/view/WindowInsets.kt
|
1
|
2014
|
package de.markusfisch.android.binaryeye.view
import android.graphics.Rect
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.view.ViewCompat
import android.support.v4.view.WindowInsetsCompat
import android.support.v7.widget.Toolbar
import android.view.View
private var toolbarHeight = 0
fun recordToolbarHeight(toolbar: Toolbar) {
toolbarHeight = toolbar.layoutParams.height
}
fun View.setPaddingFromWindowInsets() {
doOnApplyWindowInsets { v, insets -> v.setPadding(insets) }
}
// A slight variation of the idea from Google's Chris Banes to avoid
// adding the toolbar height for every view that needs to be inset.
// For the original post see here:
// https://medium.com/androiddevelopers/windowinsets-listeners-to-layouts-8f9ccc8fa4d1
fun View.doOnApplyWindowInsets(f: (View, Rect) -> Unit) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
f(this, insetsWithToolbar())
} else {
ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
f(v, insetsWithToolbar(insets))
insets
}
// It's important to explicitly request the insets (again) in
// case the view was created in Fragment.onCreateView() because
// setOnApplyWindowInsetsListener() won't fire when the view
// isn't attached.
requestApplyInsetsWhenAttached()
}
}
private fun insetsWithToolbar(insets: WindowInsetsCompat? = null) = Rect(
insets?.systemWindowInsetLeft ?: 0,
(insets?.systemWindowInsetTop ?: 0) + toolbarHeight,
insets?.systemWindowInsetRight ?: 0,
insets?.systemWindowInsetBottom ?: 0
)
@RequiresApi(Build.VERSION_CODES.KITKAT)
private fun View.requestApplyInsetsWhenAttached() {
if (isAttachedToWindow) {
ViewCompat.requestApplyInsets(this)
} else {
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) {
v.removeOnAttachStateChangeListener(this)
ViewCompat.requestApplyInsets(v)
}
override fun onViewDetachedFromWindow(v: View) = Unit
})
}
}
|
mit
|
cc91321207a4de941009f59f0c649a1f
| 32.016393 | 86 | 0.774081 | 3.880539 | false | false | false | false |
grote/Liberario
|
app/src/main/java/de/grobox/transportr/trips/BaseViewHolder.kt
|
1
|
3442
|
/*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.trips
import android.content.Context
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import de.grobox.transportr.R
import de.grobox.transportr.utils.DateUtils.getDelayText
import de.grobox.transportr.utils.DateUtils.getTime
import de.schildbach.pte.dto.Position
import de.schildbach.pte.dto.Stop
import java.util.*
internal abstract class BaseViewHolder(v: View) : RecyclerView.ViewHolder(v) {
protected val context: Context = v.context
protected val fromTime: TextView = v.findViewById(R.id.fromTime)
protected val toTime: TextView = v.findViewById(R.id.toTime)
protected val fromDelay: TextView = v.findViewById(R.id.fromDelay)
protected val toDelay: TextView = v.findViewById(R.id.toDelay)
fun setArrivalTimes(timeView: TextView?, delayView: TextView, stop: Stop) {
if (stop.arrivalTime == null) return
val time = Date(stop.arrivalTime.time)
if (stop.isArrivalTimePredicted && stop.arrivalDelay != null) {
val delay = stop.arrivalDelay!!
time.time = time.time - delay
delayView.text = getDelayText(delay)
if (delay <= 0)
delayView.setTextColor(ContextCompat.getColor(context, R.color.md_green_500))
else
delayView.setTextColor(ContextCompat.getColor(context, R.color.md_red_500))
delayView.visibility = VISIBLE
} else {
delayView.visibility = GONE
}
timeView?.let { it.text = getTime(context, time) }
}
fun setDepartureTimes(timeView: TextView?, delayView: TextView, stop: Stop) {
if (stop.departureTime == null) return
val time = Date(stop.departureTime.time)
if (stop.isDepartureTimePredicted && stop.departureDelay != null) {
val delay = stop.departureDelay!!
time.time = time.time - delay
delayView.text = getDelayText(delay)
if (delay <= 0)
delayView.setTextColor(ContextCompat.getColor(context, R.color.md_green_500))
else
delayView.setTextColor(ContextCompat.getColor(context, R.color.md_red_500))
delayView.visibility = VISIBLE
} else {
delayView.visibility = GONE
}
timeView?.let { it.text = getTime(context, time) }
}
protected fun TextView.addPlatform(position: Position?) {
if (position == null) return
text = "$text ${context.getString(R.string.platform, position.toString())}"
}
}
|
gpl-3.0
|
d6292e5e8fb514246f96869afe4ad8dd
| 37.674157 | 93 | 0.676641 | 4.127098 | false | false | false | false |
google/private-compute-libraries
|
java/com/google/android/libraries/pcc/chronicle/api/policy/capabilities/Capabilities.kt
|
1
|
4037
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package com.google.android.libraries.pcc.chronicle.api.policy.capabilities
import com.google.android.libraries.pcc.chronicle.api.policy.annotation.Annotation
/**
* Store capabilities containing a combination of individual [Capability]s (e.g. Persistence
* and/or Ttl and/or Queryable etc).
* If a certain capability does not appear in the combination, it is not restricted.
*/
class Capabilities(capabilities: List<Capability> = emptyList()) {
val ranges: List<Capability.Range>
constructor(capability: Capability) : this(listOf(capability))
init {
ranges = capabilities.map { it -> it.toRange() }
require(ranges.distinctBy { it.min.tag }.size == capabilities.size) {
"Capabilities must be unique $capabilities."
}
}
val persistence: Capability.Persistence?
get() = getCapability<Capability.Persistence>()
val ttl: Capability.Ttl?
get() = getCapability<Capability.Ttl>()
val isEncrypted: Boolean?
get() = getCapability<Capability.Encryption>()?.let { it.value }
val isQueryable: Boolean?
get() = getCapability<Capability.Queryable>()?.let { it.value }
val isShareable: Boolean?
get() = getCapability<Capability.Shareable>()?.let { it.value }
val isEmpty = ranges.isEmpty()
/**
* Returns true, if the given [Capability] is within the corresponding [Capability.Range]
* of same type of this.
* For example, [Capabilities] with Ttl range of 1-5 days `contains` a Ttl of 3 days.
*/
fun contains(capability: Capability): Boolean {
return ranges.find { it.isCompatible(capability) }?.contains(capability) ?: false
}
/**
* Returns true if all ranges in the given [Capabilities] are contained in this.
*/
fun containsAll(other: Capabilities): Boolean {
return other.ranges.all { otherRange -> contains(otherRange) }
}
fun isEquivalent(other: Capabilities): Boolean {
return ranges.size == other.ranges.size && other.ranges.all { hasEquivalent(it) }
}
fun hasEquivalent(capability: Capability): Boolean {
return ranges.any { it.isCompatible(capability) && it.isEquivalent(capability) }
}
override fun toString(): String = "Capabilities($ranges)"
private inline fun <reified T : Capability> getCapability(): T? {
return ranges.find { it.min is T }?.let {
require(it.min.isEquivalent(it.max)) { "Cannot get capability for a range" }
it.min as T
}
}
companion object {
fun fromAnnotations(annotations: List<Annotation>): Capabilities {
val ranges = mutableListOf<Capability.Range>()
Capability.Persistence.fromAnnotations(annotations)?.let {
ranges.add(it.toRange())
}
Capability.Encryption.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) }
Capability.Ttl.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) }
Capability.Queryable.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) }
Capability.Shareable.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) }
return Capabilities(ranges)
}
fun fromAnnotation(annotation: Annotation) = fromAnnotations(listOf(annotation))
}
}
|
apache-2.0
|
f4e1fb4fa57df245a07d460d18acfc80
| 34.412281 | 96 | 0.710181 | 4.200832 | false | false | false | false |
duftler/orca
|
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandler.kt
|
1
|
2412
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.events.TaskStarted
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.q.Queue
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
import java.time.Clock
@Component
class StartTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val contextParameterProcessor: ContextParameterProcessor,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val taskResolver: TaskResolver,
private val clock: Clock
) : OrcaMessageHandler<StartTask>, ExpressionAware {
override fun handle(message: StartTask) {
message.withTask { stage, task ->
task.status = RUNNING
task.startTime = clock.millis()
val mergedContextStage = stage.withMergedContext()
repository.storeStage(mergedContextStage)
queue.push(RunTask(message, task.id, task.type))
publisher.publishEvent(TaskStarted(this, mergedContextStage, task))
}
}
override val messageType = StartTask::class.java
@Suppress("UNCHECKED_CAST")
private val com.netflix.spinnaker.orca.pipeline.model.Task.type
get() = taskResolver.getTaskClass(implementingClass)
}
|
apache-2.0
|
d7a6f7fc29485a31bb5f0a151fb1d505
| 37.903226 | 85 | 0.794362 | 4.550943 | false | false | false | false |
nickthecoder/tickle
|
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/MainWindow.kt
|
1
|
12712
|
/*
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.editor
import javafx.application.Platform
import javafx.collections.ListChangeListener
import javafx.event.EventHandler
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.control.ButtonBar.ButtonData
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.stage.Stage
import javafx.stage.WindowEvent
import uk.co.nickthecoder.paratask.ParaTask
import uk.co.nickthecoder.paratask.gui.ShortcutHelper
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.tedi.TediArea
import uk.co.nickthecoder.tickle.*
import uk.co.nickthecoder.tickle.editor.resources.DesignJsonResources
import uk.co.nickthecoder.tickle.editor.resources.ResourceType
import uk.co.nickthecoder.tickle.editor.tabs.*
import uk.co.nickthecoder.tickle.editor.util.ImageCache
import uk.co.nickthecoder.tickle.editor.util.NewResourceTask
import uk.co.nickthecoder.tickle.events.CompoundInput
import uk.co.nickthecoder.tickle.graphics.Texture
import uk.co.nickthecoder.tickle.graphics.Window
import uk.co.nickthecoder.tickle.resources.FontResource
import uk.co.nickthecoder.tickle.resources.Layout
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.resources.SceneStub
import uk.co.nickthecoder.tickle.scripts.ScriptException
import uk.co.nickthecoder.tickle.scripts.ScriptManager
import uk.co.nickthecoder.tickle.sound.Sound
import uk.co.nickthecoder.tickle.util.ErrorHandler
class MainWindow(val stage: Stage, val glWindow: Window) : ErrorHandler {
val borderPane = BorderPane()
val toolBar = ToolBar()
val splitPane = SplitPane()
val resourcesTree = ResourcesTree()
val accordion = Accordion()
val resourcesPane = TitledPane("Resources", resourcesTree)
val tabPane = TabPane()
val scene = Scene(borderPane, resourcesTree.resources.preferences.windowWidth, resourcesTree.resources.preferences.windowHeight)
private var extraSidePanels: Collection<TitledPane> = emptyList()
private var extraButtons: Collection<Node> = emptyList()
private var extraShortcuts: ShortcutHelper? = null
private val shortcuts = ShortcutHelper("MainWindow", borderPane)
init {
stage.title = "Tickle Resources Editor"
stage.scene = scene
ParaTask.style(scene)
TediArea.style(scene)
val resource = MainWindow::class.java.getResource("tickle.css")
scene.stylesheets.add(resource.toExternalForm())
with(borderPane) {
top = toolBar
center = splitPane
}
with(splitPane) {
setDividerPositions(0.2)
items.addAll(accordion, tabPane)
}
// I like the animation, but it's too slow, and there is no API to change the speed. Turn it off. Grr.
resourcesPane.isAnimated = false
with(accordion) {
panes.addAll(resourcesPane)
expandedPane = resourcesPane
}
val toolBarPadding = HBox()
HBox.setHgrow(toolBarPadding, Priority.ALWAYS)
with(toolBar.items) {
add(EditorActions.RELOAD.createButton(shortcuts) { reload() })
add(EditorActions.NEW.createButton(shortcuts) { newResource() })
add(EditorActions.OPEN.createButton(shortcuts) { openResource() })
add(EditorActions.RUN.createButton(shortcuts) { startGame() })
add(EditorActions.TEST.createButton(shortcuts) { testGame() })
if (ScriptManager.languages().isNotEmpty()) {
add(EditorActions.RELOAD_SCRIPTS.createButton(shortcuts) { ScriptManager.reloadAll() })
}
add(toolBarPadding)
}
with(shortcuts) {
add(EditorActions.ACCORDION_ONE) { accordionPane(0) }
add(EditorActions.ACCORDION_TWO) { accordionPane(1) }
add(EditorActions.ACCORDION_THREE) { accordionPane(2) }
add(EditorActions.ACCORDION_FOUR) { accordionPane(3) }
add(EditorActions.ACCORDION_FIVE) { accordionPane(4) }
add(EditorActions.TAB_CLOSE) { onCloseTab() }
add(EditorActions.SHOW_COSTUME_PICKER) { accordionPane(1) }
}
tabPane.selectionModel.selectedItemProperty().addListener { _, _, newValue ->
onTabChanged(newValue)
}
tabPane.tabs.addListener(ListChangeListener<Tab> { c ->
while (c.next()) {
if (c.wasRemoved()) {
c.removed.filterIsInstance<EditorTab>().forEach { it.removed() }
}
}
})
if (resourcesTree.resources.preferences.isMaximized) {
stage.isMaximized = true
}
stage.show()
instance = this
stage.onCloseRequest = EventHandler<WindowEvent> { onCloseRequest(it) }
ErrorHandler.errorHandler = this
}
private fun onCloseTab() {
val selectedTab = tabPane.selectionModel.selectedItem
if (selectedTab is EditTab) {
if (selectedTab.needsSaving) {
val alert = Alert(Alert.AlertType.CONFIRMATION)
with(alert) {
headerText = "Close tab without saving?"
showAndWait()
if (result == ButtonType.OK) {
selectedTab.close()
}
}
return
}
}
(selectedTab as? EditTab)?.close()
}
private fun onCloseRequest(event: WindowEvent) {
// Check if there are tabs open, and if so, ask if they should be saved.
if (tabPane.tabs.filterIsInstance<EditTab>().filter { it.needsSaving }.isNotEmpty()) {
val alert = Alert(Alert.AlertType.CONFIRMATION)
alert.title = "Save Changes?"
alert.contentText = "Save changes before closing?"
val save = ButtonType("Save")
val ignore = ButtonType("Ignore")
val cancel = ButtonType("Cancel", ButtonData.CANCEL_CLOSE)
alert.buttonTypes.setAll(save, ignore, cancel)
when (alert.showAndWait().get()) {
save -> {
// Note. this is inefficient, as the resources are saved to disk for every opened tab.
// It is quick though, so I haven't bothered to make it save only once.
tabPane.tabs.forEach { tab ->
if (tab is EditTab) {
if (!tab.save()) {
tabPane.selectionModel.selectedItem === tab
// Tab not saved, so abort the closing of the main window.
event.consume()
return
}
}
}
}
cancel -> {
event.consume()
return
}
}
}
with(resourcesTree.resources.preferences) {
isMaximized = stage.isMaximized
if (!isMaximized) {
windowWidth = scene.width
windowHeight = scene.height
}
}
resourcesTree.resources.save()
}
private fun accordionPane(n: Int) {
if (n >= 0 && n < accordion.panes.count()) {
accordion.expandedPane = accordion.panes[n]
}
}
private fun findTab(data: Any): EditorTab? {
return tabPane.tabs.filterIsInstance<EditorTab>().firstOrNull { it.data == data }
}
private fun reload() {
saveAllTabs()
tabPane.tabs.clear()
Resources.instance.destroy()
DesignJsonResources(Resources.instance.file).loadResources()
ImageCache.clear()
resourcesTree.reload()
}
private fun newResource() {
TaskPrompter(NewResourceTask()).placeOnStage(Stage())
}
private fun openResource() {
OpenResource(stage)
}
private fun saveAllTabs() {
tabPane.tabs.forEach { tab ->
(tab as? EditTab)?.save()
}
}
private fun startGame(scenePath: String = Resources.instance.sceneFileToPath(Resources.instance.gameInfo.initialScenePath)) {
saveAllTabs()
ScriptManager.reloadAll()
stage.hide()
// Give this window the opportunity to hide before the UI hangs
Platform.runLater {
println("Game test started")
with(Resources.instance.gameInfo) {
glWindow.change(title, width, height, resizable)
}
glWindow.show()
// Clean up the old Game instance, and create a new one.
Game.instance.cleanUp()
Game(glWindow, Resources.instance).run(scenePath)
println("Game test ended")
glWindow.hide()
stage.show()
}
}
private fun testGame() {
val tab = tabPane.selectionModel.selectedItem
if (tab is SceneTab) {
startGame(Resources.instance.sceneFileToPath(tab.sceneFile))
} else {
startGame(Resources.instance.sceneFileToPath(Resources.instance.gameInfo.testScenePath))
}
}
private fun openTab(tab: EditorTab) {
tabPane.tabs.add(tab)
tabPane.selectionModel.select(tab)
}
fun openTab(dataName: String, data: Any): Tab? {
val tab = findTab(data)
if (tab == null) {
val newTab = createTab(dataName, data)
newTab?.let { openTab(it) }
return newTab
} else {
tabPane.selectionModel.select(tab)
return tab
}
}
fun openNamedTab(dataName: String, type: ResourceType): Tab? {
val data: Any = type.findResource(dataName) ?: return null
return openTab(dataName, data)
}
private fun createTab(name: String, data: Any): EditorTab? {
return when (data) {
is GameInfo -> return GameInfoTab()
is EditorPreferences -> EditorPreferencesTab()
is Texture -> TextureTab(name, data)
is Pose -> PoseTab(name, data)
is Layout -> LayoutTab(name, data)
is CompoundInput -> InputTab(name, data)
is Costume -> CostumeTab(name, data)
is CostumeGroup -> CostumeGroupTab(name, data)
is SceneStub -> SceneTab(name, data)
is FontResource -> FontTab(name, data)
is Sound -> SoundTab(name, data)
is ScriptStub -> ScriptTab(data)
is FXCoderStub -> FXCoderTab(data)
APIStub -> APITab()
else -> null
}
}
private fun onTabChanged(tab: Tab?) {
extraSidePanels.forEach {
accordion.panes.remove(it)
}
extraButtons.forEach {
toolBar.items.remove(it)
}
extraShortcuts?.disable()
if (tab is HasExtras) {
extraSidePanels = tab.extraSidePanes()
extraSidePanels.forEach {
it.isAnimated = false
accordion.panes.add(it)
}
extraButtons = tab.extraButtons()
extraButtons.forEach {
toolBar.items.add(it)
}
extraShortcuts = tab.extraShortcuts()
extraShortcuts?.enable()
}
accordion.expandedPane = resourcesPane
}
override fun handleError(e: Exception) {
if (e is ScriptException) {
e.file?.let { file ->
val tab = openTab(file.nameWithoutExtension, ScriptStub(file))
if (tab is ScriptTab) { // It should be!
tab.highlightError(e)
return
}
}
}
// TODO Handle other errors.
println("MainWindow isn't handling this well!")
e.printStackTrace()
}
companion object {
lateinit var instance: MainWindow
}
}
|
gpl-3.0
|
7bb67f1791bb4e2c7c0c075b563420f0
| 32.277487 | 132 | 0.606199 | 4.595806 | false | false | false | false |
Kotlin/anko
|
anko/library/robolectricTests/src/main/java/AndroidPropertiesTestActivity.kt
|
4
|
3945
|
package com.example.android_test
import android.app.Activity
import android.os.Bundle
import org.jetbrains.anko.*
open class AndroidPropertiesTestActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
UI {
linearLayout {
baseline
baselineAlignedChildIndex = 0
dividerPadding = 1
orientation = -1
showDividers = 0
weightSum = 2.4f
textSwitcher {}
calendarView {
date = 123456
showWeekNumber = true
}
zoomButton {}
viewSwitcher {}
digitalClock {}
multiAutoCompleteTextView {}
checkBox {
isChecked = true
}
imageButton {}
videoView {
currentPosition
}
horizontalScrollView {}
numberPicker {
displayedValues
maxValue = 3
value = 2134
}
analogClock {}
scrollView {}
textView {
compoundDrawablePadding = 23
customSelectionActionModeCallback = null
error = "error"
freezesText = false
imeOptions = 0
linksClickable = true
}
tabWidget {
tabCount
}
radioButton {}
toggleButton {
textOff = "12354"
textOn = "qwerty"
}
seekBar {}
datePicker {
calendarView
month
year
}
timePicker {
currentHour = 3
}
zoomControls {}
imageView {
baseline = 234
imageMatrix = android.graphics.Matrix()
}
autoCompleteTextView {
dropDownAnchor = 0
dropDownHeight = 0
dropDownHorizontalOffset = 2
threshold = 2
validator = null
}
switch {
textOff = "918237"
}
progressBar {
progress = 34
secondaryProgress = 9
}
space {}
listView {
checkItemIds
itemsCanFocus = true
overscrollHeader = null
}
gridView {
gravity = 68
numColumns = 3
}
spinner {}
gallery {}
imageSwitcher {}
checkedTextView {}
chronometer {
base = 9
format = "%d%Y%m"
}
button {}
editText {}
ratingBar {
numStars = 3
rating = 3.4f
stepSize = 0.7f
}
stackView {}
quickContactBadge {}
twoLineListItem {}
dialerFilter {
digits
}
tabHost {
currentTab = 2
currentTabView
}
viewAnimator {}
expandableListView {
adapter = null
selectedPosition
}
viewFlipper {}
}
}
}
}
|
apache-2.0
|
ee54f035e831c3e740d2f068623894b9
| 28.440299 | 69 | 0.358682 | 8.067485 | false | false | false | false |
UprootLabs/unplug
|
src/co/uproot/unplug/guiServices.kt
|
1
|
6145
|
package co.uproot.unplug
import javafx.beans.property.SimpleStringProperty
import javafx.concurrent.Service
import javafx.concurrent.Task
class LoginService() : Service<LoginResult>() {
val userName = SimpleStringProperty("")
val password = SimpleStringProperty("")
var baseURL: String = ""
override fun createTask(): Task<LoginResult>? {
val api = API(baseURL)
return object : Task<LoginResult>() {
override fun call(): LoginResult? {
updateMessage("Logging In")
val loginResult = api.login(userName.get(), password.get())
if (loginResult == null) {
updateMessage("Login Failed")
failed()
return null
} else {
updateMessage("Logged In Successfully")
return loginResult
}
}
}
}
}
class RoomSyncService(val loginResult: LoginResult, val roomId: String) : Service<SyncResult>() {
override fun createTask(): Task<SyncResult>? {
val api = loginResult.api
return object : Task<SyncResult>() {
override fun call(): SyncResult? {
updateMessage("Syncing")
val result = api.roomInitialSync(loginResult.accessToken, roomId)
if (result == null) {
updateMessage("Sync Failed")
failed()
return null
} else {
updateMessage("")
return result
}
}
}
}
}
class SyncService(val loginResult: LoginResult) : Service<SyncResult>() {
val userName = SimpleStringProperty("")
val password = SimpleStringProperty("")
override fun createTask(): Task<SyncResult>? {
val api = loginResult.api
return object : Task<SyncResult>() {
override fun call(): SyncResult? {
updateMessage("Syncing")
val result = api.initialSync(loginResult.accessToken)
if (result == null) {
updateMessage("Sync Failed")
failed()
return null
} else {
updateMessage("")
return result
}
}
}
}
}
class CreateRoomService(val loginResult: LoginResult, val roomname: String, val visibility: String) : Service<CreateRoomResult>() {
override fun createTask(): Task<CreateRoomResult>? {
return object : Task<CreateRoomResult>() {
override fun call(): CreateRoomResult? {
val createRoomResult = loginResult.api.createRoom(loginResult.accessToken, roomname, visibility)
if (createRoomResult == null) {
updateMessage("Failed")
failed()
return null
} else {
updateMessage("")
return createRoomResult
}
}
}
}
}
class JoinRoomService(val loginResult: LoginResult, val room: RoomIdentifier) : Service<JoinRoomResult>() {
override fun createTask(): Task<JoinRoomResult>? {
return object : Task<JoinRoomResult>() {
override fun call(): JoinRoomResult? {
val joinResult = loginResult.api.joiningRoon(loginResult.accessToken, room)
if (joinResult == null) {
updateMessage("Failed")
failed()
return null
} else {
updateMessage("")
return joinResult
}
}
}
}
}
class InviteMemberService(val loginResult: LoginResult, val room: RoomIdentifier, val memName: String) : Service<InviteMemResult>() {
override fun createTask(): Task<InviteMemResult>? {
return object : Task<InviteMemResult>() {
override fun call(): InviteMemResult? {
val inviteResult = loginResult.api.invitingMember(loginResult.accessToken, room, memName)
if (inviteResult == null) {
updateMessage("Failed")
failed()
return null
} else {
updateMessage("")
return inviteResult
}
}
}
}
}
class BanRoomService(val loginResult: LoginResult, val room: RoomIdentifier, val memId: String, val appState: AppState) : Service<BanRoomResult>() {
override fun createTask(): Task<BanRoomResult>? {
return object : Task<BanRoomResult>() {
override fun call(): BanRoomResult? {
val banRoomResult = loginResult.api.banningMember(loginResult.accessToken, room, memId, appState)
if (banRoomResult == null) {
updateMessage("Failed")
failed()
return null
} else {
updateMessage("")
return banRoomResult
}
}
}
}
}
class LeaveRoomService(val loginResult: LoginResult, val roomIdentifier: RoomIdentifier) : Service<LeaveRoomResult>() {
override fun createTask(): Task<LeaveRoomResult>? {
return object : Task<LeaveRoomResult>() {
override fun call(): LeaveRoomResult? {
val leaveResult = loginResult.api.leavingRoom(loginResult.accessToken, roomIdentifier)
if (leaveResult == null) {
updateMessage("Failed")
failed()
return null
} else {
updateMessage("")
return leaveResult
}
}
}
}
}
class EventService(val loginResult: LoginResult) : Service<EventResult>() {
private var from: String? = null
override fun createTask(): Task<EventResult>? {
return object : Task<EventResult>() {
override fun call(): EventResult? {
val eventResult = loginResult.api.getEvents(loginResult.accessToken, from)
if (eventResult == null) {
updateMessage("Events Failed")
failed()
return null
} else {
updateMessage("")
from = eventResult.end
return eventResult
}
}
}
}
}
class SendResult(eventId: String)
class SendMessageService(val loginResult: LoginResult, val roomId: String, val msg: String) : Service<SendResult>() {
override fun createTask(): Task<SendResult>? {
return object : Task<SendResult>() {
override fun call(): SendResult? {
val eventId = loginResult.api.sendMessage(loginResult.accessToken, roomId, msg)
if (eventId == null) {
updateMessage("Sending Failed")
failed()
return null
} else {
updateMessage("")
return SendResult(eventId)
}
}
}
}
}
|
gpl-3.0
|
9052641b7ca3d959582e51fa693612cd
| 27.849765 | 148 | 0.614972 | 4.770963 | false | false | false | false |
LorittaBot/Loritta
|
web/showtime/web-common/src/commonMain/kotlin/net/perfectdreams/loritta/serializable/UserIdentification.kt
|
1
|
1391
|
package net.perfectdreams.loritta.serializable
import kotlinx.serialization.Serializable
@Serializable
data class UserIdentification(
val id: Long,
val username: String,
val discriminator: String,
val avatar: String? = null,
val bot: Boolean? = false,
val mfaEnabled: Boolean? = false,
val locale: String? = null,
val verified: Boolean? = null,
val email: String? = null,
val flags: Int? = 0,
val premiumType: Int? = 0
) {
val userAvatarUrl: String
get() {
val extension = if (avatar?.startsWith("a_") == true) { // Avatares animados no Discord começam com "_a"
"gif"
} else { "png" }
return "https://cdn.discordapp.com/avatars/${id}/${avatar}.${extension}?size=256"
}
val effectiveAvatarUrl: String
get() {
return if (avatar != null) {
val extension = if (avatar.startsWith("a_")) { // Avatares animados no Discord começam com "_a"
"gif"
} else {
"png"
}
"https://cdn.discordapp.com/avatars/$id/${avatar}.${extension}?size=256"
} else {
val avatarId = id % 5
"https://cdn.discordapp.com/embed/avatars/$avatarId.png?size=256"
}
}
}
|
agpl-3.0
|
25e6d818d8ccd082bfb62814421948e9
| 30.590909 | 116 | 0.524118 | 4.354232 | false | false | false | false |
apgv/skotbuvel-portal
|
src/main/kotlin/no/skotbuvel/portal/user/UserRepository.kt
|
1
|
6362
|
package no.skotbuvel.portal.user
import no.skotbuvel.portal.helper.DbHelper
import no.skotbuvel.portal.jooq.Sequences.USER_ID_SEQ
import no.skotbuvel.portal.jooq.Sequences.USER_ROLE_ID_SEQ
import no.skotbuvel.portal.jooq.tables.Role.ROLE
import no.skotbuvel.portal.jooq.tables.User.USER
import no.skotbuvel.portal.jooq.tables.UserRole.USER_ROLE
import no.skotbuvel.portal.role.Role
import no.skotbuvel.portal.util.JavaTimeUtil
import org.jooq.Record
import org.jooq.Result
import org.jooq.TransactionalRunnable
class UserRepository(private val dbHelper: DbHelper) {
private val selectParameters = listOf(
USER.ID,
USER.FIRST_NAME,
USER.LAST_NAME,
USER.EMAIL,
USER.PHONE,
USER.CREATED_BY,
USER.CREATED_DATE,
ROLE.ID,
ROLE.NAME,
ROLE.DESCRIPTION
)
fun findAll(): List<User> {
return dbHelper.dslContext()
.select(selectParameters)
.from(USER)
.leftJoin(USER_ROLE)
.on(USER.ID.eq(USER_ROLE.USER_ID))
.and(USER_ROLE.ACTIVE.eq(true))
.leftJoin(ROLE)
.on(ROLE.ID.eq(USER_ROLE.ROLE_ID))
.fetchGroups(USER.ID)
.values
.map { mapUserWithRoles(it) }
}
fun findByEmail(email: String): User {
return dbHelper.dslContext()
.select(selectParameters)
.from(USER)
.leftJoin(USER_ROLE)
.on(USER.ID.eq(USER_ROLE.USER_ID))
.and(USER_ROLE.ACTIVE.eq(true))
.leftJoin(ROLE)
.on(ROLE.ID.eq(USER_ROLE.ROLE_ID))
.where(USER.EMAIL.eq(email))
.fetchGroups(USER.ID)
.values
.map { mapUserWithRoles(it) }
.first()
}
fun findById(id: Int): User {
return dbHelper.dslContext()
.select(selectParameters)
.from(USER)
.leftJoin(USER_ROLE)
.on(USER.ID.eq(USER_ROLE.USER_ID))
.and(USER_ROLE.ACTIVE.eq(true))
.leftJoin(ROLE)
.on(ROLE.ID.eq(USER_ROLE.ROLE_ID))
.where(USER.ID.eq(id))
.fetchGroups(USER.ID)
.values
.map { mapUserWithRoles(it) }
.first()
}
fun save(userRegistration: UserRegistration, createdBy: String) {
val dslContext = dbHelper.dslContext()
dslContext.transaction(TransactionalRunnable {
dslContext.insertInto(USER,
USER.ID,
USER.ORIGINAL_ID,
USER.ACTIVE,
USER.FIRST_NAME,
USER.LAST_NAME,
USER.EMAIL,
USER.PHONE,
USER.CREATED_BY,
USER.CREATED_DATE
).values(
dslContext.nextval(USER_ID_SEQ).toInt(),
dslContext.currval(USER_ID_SEQ).toInt(),
true,
userRegistration.firstName,
userRegistration.lastName,
userRegistration.email,
userRegistration.phone,
createdBy,
JavaTimeUtil.nowEuropeOslo()
)
.execute()
})
}
fun updateRoles(userRoleRegistration: UserRoleRegistration, createdBy: String) {
val dslContext = dbHelper.dslContext()
dslContext.transaction(TransactionalRunnable {
val existingRoleIds = dslContext
.select(USER_ROLE.ROLE_ID)
.from(USER_ROLE)
.where(USER_ROLE.USER_ID.eq(userRoleRegistration.userId))
.and(USER_ROLE.ACTIVE.eq(true))
.fetch()
.map { it.value1() }
val deletedRoleIds = existingRoleIds.filter { i -> !userRoleRegistration.roleIds.contains(i) }
if (deletedRoleIds.isNotEmpty()) {
dslContext.update(USER_ROLE)
.set(USER_ROLE.ACTIVE, false)
.set(USER_ROLE.CHANGED_BY, createdBy)
.set(USER_ROLE.CHANGED_DATE, JavaTimeUtil.nowEuropeOslo())
.where(USER_ROLE.USER_ID.eq(userRoleRegistration.userId))
.and(USER_ROLE.ROLE_ID.`in`(deletedRoleIds))
.execute()
}
val newRoleIds = userRoleRegistration.roleIds.filter { i -> !existingRoleIds.contains(i) }
newRoleIds.forEach {
dslContext.insertInto(USER_ROLE,
USER_ROLE.ID,
USER_ROLE.USER_ID,
USER_ROLE.ROLE_ID,
USER_ROLE.ACTIVE,
USER_ROLE.CREATED_BY,
USER_ROLE.CREATED_DATE
).values(
dslContext.nextval(USER_ROLE_ID_SEQ).toInt(),
userRoleRegistration.userId,
it,
true,
createdBy,
JavaTimeUtil.nowEuropeOslo()
)
.execute()
}
})
}
private fun mapUserWithRoles(result: Result<Record>): User {
val roles = mapRoles(result)
val record = result.first()
return User(
id = record[USER.ID],
firstName = record[USER.FIRST_NAME],
lastName = record[USER.LAST_NAME],
email = record[USER.EMAIL],
phone = record[USER.PHONE],
roles = roles,
createdBy = record[USER.CREATED_BY],
createdDate = record[USER.CREATED_DATE].toZonedDateTime()
)
}
private fun mapRoles(result: Result<Record>): List<Role> {
return result
.filter { it[ROLE.ID] != null }
.map {
Role(
id = it[ROLE.ID],
name = it[ROLE.NAME],
description = it[ROLE.DESCRIPTION]
)
}
}
}
|
mit
|
5a92aded0af7d742b6f73feffe43839c
| 34.35 | 106 | 0.48994 | 4.508859 | false | false | false | false |
jean79/yested_fw
|
src/jsMain/kotlin/net/yested/ext/bootstrap3/inputs.kt
|
1
|
4861
|
package net.yested.ext.bootstrap3
import net.yested.core.html.*
import net.yested.core.properties.*
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLSelectElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.HTMLTextAreaElement
import kotlin.browser.document
fun HTMLElement.text(value: ReadOnlyProperty<String>) {
val element = document.createElement("span") as HTMLSpanElement
value.onNext {
element.textContent = it
}
this.appendChild(element)
}
fun HTMLElement.textInput(
value: Property<String>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
readonly: ReadOnlyProperty<Boolean> = false.toProperty(),
id: String? = null,
inputTypeClass: String = "text",
init: (HTMLInputElement.() -> Unit)? = null): HTMLInputElement {
val element = document.createElement("input") as HTMLInputElement
id?.let { element.id = id }
element.className = "form-control $inputTypeClass"
element.type = "text"
element.bind(value)
element.setDisabled(disabled)
element.setReadOnly(readonly)
if (init != null) element.init()
this.appendChild(element)
return element
}
fun HTMLElement.textAreaInput(
value: Property<String>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
readonly: ReadOnlyProperty<Boolean> = false.toProperty(),
id: String? = null,
init: (HTMLTextAreaElement.() -> Unit)? = null): HTMLTextAreaElement {
val element = document.createElement("textarea") as HTMLTextAreaElement
id?.let { element.id = id }
element.className = "form-control"
element.bind(value)
element.setDisabled(disabled)
element.setReadOnly(readonly)
if (init != null) element.init()
this.appendChild(element)
return element
}
fun <T> HTMLElement.selectInput(
selected: Property<List<T>>,
options: Property<List<T>>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
multiple: Boolean,
size: Size = Size.Default,
render: HTMLElement.(T)->Unit): HTMLSelectElement {
val element = document.createElement("select") as HTMLSelectElement
element.className = "form-control input-${size.code}"
element.multiple = multiple
element.bindMultiselect(selected, options, render)
element.setDisabled(disabled)
this.appendChild(element)
return element
}
fun <T> HTMLElement.singleSelectInput(
selected: Property<T>,
options: ReadOnlyProperty<List<T>>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
render: HTMLElement.(T)->Unit): HTMLSelectElement {
return singleSelectInput(selected, options, disabled, { selected.set(it) }, render)
}
fun <T> HTMLElement.singleSelectInput(
selected: ReadOnlyProperty<T>,
options: ReadOnlyProperty<List<T>>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
onSelect: (T) -> Unit,
render: HTMLElement.(T)->Unit): HTMLSelectElement {
val element = document.createElement("select") as HTMLSelectElement
element.className = "form-control input-${Size.Default.code}"
element.multiple = false
element.bind(selected, options, onSelect, render)
element.setDisabled(disabled)
this.appendChild(element)
return element
}
fun <T> HTMLElement.optionalSelectInput(
selected: Property<T?>,
options: ReadOnlyProperty<List<T>>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
render: HTMLElement.(T)->Unit): HTMLSelectElement {
return optionalSelectInput(selected, options, disabled, { selected.set(it) }, render)
}
fun <T> HTMLElement.optionalSelectInput(
selected: ReadOnlyProperty<T?>,
options: ReadOnlyProperty<List<T>>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
onSelect: (T) -> Unit,
render: HTMLElement.(T)->Unit): HTMLSelectElement {
val element = document.createElement("select") as HTMLSelectElement
element.className = "form-control input-${Size.Default.code}"
element.multiple = false
element.bindOptional(selected, options, onSelect, render)
element.setDisabled(disabled)
this.appendChild(element)
return element
}
fun HTMLElement.intInput(value: Property<Int?>,
disabled: ReadOnlyProperty<Boolean> = false.toProperty(),
readonly: ReadOnlyProperty<Boolean> = false.toProperty(),
id: String? = null,
init: (HTMLInputElement.() -> Unit)? = null) {
val textValue = value.bind(
transform = { if (it == null) "" else it.toString() },
reverse = { if (!it.isEmpty()) it.toInt() else null })
textInput(textValue, disabled, readonly, id, inputTypeClass = "number int") {
type = "number"; step = "1"
if (init != null) init()
}
}
|
mit
|
768a925ad82302a0b6b03d3df1f0b548
| 34.481752 | 89 | 0.686279 | 4.340179 | false | false | false | false |
DevCharly/kotlin-ant-dsl
|
src/main/kotlin/com/devcharly/kotlin/ant/selectors/dateselector.kt
|
1
|
1918
|
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.types.selectors.DateSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IDateSelectorNested : INestedComponent {
fun date(
millis: Long? = null,
datetime: String? = null,
checkdirs: Boolean? = null,
granularity: Int? = null,
When: TimeComparison? = null,
pattern: String? = null,
error: String? = null)
{
_addDateSelector(DateSelector().apply {
component.project.setProjectReference(this);
_init(millis, datetime, checkdirs, granularity,
When, pattern, error)
})
}
fun _addDateSelector(value: DateSelector)
}
fun DateSelector._init(
millis: Long?,
datetime: String?,
checkdirs: Boolean?,
granularity: Int?,
When: TimeComparison?,
pattern: String?,
error: String?)
{
if (millis != null)
setMillis(millis)
if (datetime != null)
setDatetime(datetime)
if (checkdirs != null)
setCheckdirs(checkdirs)
if (granularity != null)
setGranularity(granularity)
if (When != null)
setWhen(org.apache.tools.ant.types.TimeComparison().apply { this.value = When.value })
if (pattern != null)
setPattern(pattern)
if (error != null)
setError(error)
}
|
apache-2.0
|
1400ceaca03c61c88d2029cd4d744fe2
| 27.205882 | 88 | 0.658498 | 3.738791 | false | false | false | false |
chRyNaN/GuitarChords
|
core/src/commonMain/kotlin/com.chrynan.chords/view/ChordViewBinder.kt
|
1
|
1702
|
package com.chrynan.chords.view
import com.chrynan.chords.model.ChordViewModel
/**
* A class that can bind a [ChordViewModel] to a [ChordView] by calling the appropriate functions
* with their related values.
*
* @property [view] The [ChordView] that will be updated with the values from the [ChordViewModel]
* in the [bind] function.
*
* @author chRyNaN
*/
class ChordViewBinder(val view: ChordView) {
/**
* Binds the [ChordViewModel] to the associated [ChordView] to this [ChordViewBinder] by
* calling the appropriate [ChordView] functions with the values from the [ChordViewModel].
* After this function is called, the [ChordView] should reflect the values from the
* [ChordViewModel]. Note that there are some properties and functions that the [ChordView] may
* have that are not present on the [ChordViewModel]. Only values present on the
* [ChordViewModel] will be applied to the [ChordView].
*
* @author chRyNaN
*/
fun bind(viewModel: ChordViewModel) {
view.fitToHeight = viewModel.fitToHeight
view.fretColor = viewModel.fretColor
view.fretLabelTextColor = viewModel.fretLabelTextColor
view.noteColor = viewModel.noteColor
view.noteLabelTextColor = viewModel.noteLabelTextColor
view.stringColor = viewModel.stringColor
view.stringLabelTextColor = viewModel.stringLabelTextColor
view.openStringText = viewModel.openStringText
view.mutedStringText = viewModel.mutedStringText
view.showFingerNumbers = viewModel.showFingerNumbers
view.showFretNumbers = viewModel.showFretNumbers
view.stringLabelState = viewModel.stringLabelState
}
}
|
apache-2.0
|
ccea691ba19c2a9041fbae4d025335c4
| 41.575 | 99 | 0.72738 | 4.714681 | false | false | false | false |
jitsi/jitsi-videobridge
|
jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/AllocationSettings.kt
|
1
|
5948
|
/*
* Copyright @ 2020 - present 8x8, Inc.
* Copyright @ 2021 - Vowel, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.cc.allocation
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.videobridge.cc.config.BitrateControllerConfig.Companion.config
import org.jitsi.videobridge.message.ReceiverVideoConstraintsMessage
import org.jitsi.videobridge.util.endpointIdToSourceName
/**
* This class encapsulates all of the client-controlled settings for bandwidth allocation.
*/
data class AllocationSettings @JvmOverloads constructor(
@Deprecated("", ReplaceWith("onStageSources"), DeprecationLevel.WARNING)
val onStageEndpoints: List<String> = emptyList(),
@Deprecated("", ReplaceWith("selectedSources"), DeprecationLevel.WARNING)
val selectedEndpoints: List<String> = emptyList(),
val onStageSources: List<String> = emptyList(),
val selectedSources: List<String> = emptyList(),
val videoConstraints: Map<String, VideoConstraints> = emptyMap(),
val lastN: Int = -1,
val defaultConstraints: VideoConstraints
) {
fun toJson() = OrderedJsonObject().apply {
put("on_stage_sources", onStageSources)
put("selected_sources", selectedSources)
put("video_constraints", videoConstraints)
put("last_n", lastN)
put("default_constraints", defaultConstraints)
}
override fun toString(): String = toJson().toJSONString()
fun getConstraints(endpointId: String) = videoConstraints.getOrDefault(endpointId, defaultConstraints)
}
/**
* Maintains an [AllocationSettings] instance and allows fields to be set individually, with an indication of whether
* the overall state changed.
*/
internal class AllocationSettingsWrapper(private val useSourceNames: Boolean) {
/**
* The last selected endpoints set signaled by the receiving endpoint.
*/
@Deprecated("", ReplaceWith("selectedSources"), DeprecationLevel.WARNING)
private var selectedEndpoints = emptyList<String>()
/**
* The last selected sources set signaled by the receiving endpoint.
*/
private var selectedSources = emptyList<String>()
internal var lastN: Int = -1
private var videoConstraints: Map<String, VideoConstraints> = emptyMap()
private var defaultConstraints: VideoConstraints = VideoConstraints(config.thumbnailMaxHeightPx())
@Deprecated("", ReplaceWith("onStageSources"), DeprecationLevel.WARNING)
private var onStageEndpoints: List<String> = emptyList()
private var onStageSources: List<String> = emptyList()
private var allocationSettings = create()
private fun create(): AllocationSettings = AllocationSettings(
onStageSources = onStageSources,
selectedSources = selectedSources,
videoConstraints = videoConstraints,
defaultConstraints = defaultConstraints,
lastN = lastN
)
fun get() = allocationSettings
fun setBandwidthAllocationSettings(message: ReceiverVideoConstraintsMessage): Boolean {
var changed = false
message.lastN?.let {
if (lastN != it) {
lastN = it
changed = true
}
}
if (useSourceNames) {
message.selectedSources?.let {
if (selectedSources != it) {
selectedSources = it
changed = true
}
}
message.onStageSources?.let {
if (onStageSources != it) {
onStageSources = it
changed = true
}
}
} else {
message.selectedEndpoints?.let {
val newSelectedSources = it.map { endpoint -> endpointIdToSourceName(endpoint) }
if (selectedSources != newSelectedSources) {
selectedSources = newSelectedSources
changed = true
}
}
message.onStageEndpoints?.let {
val newOnStageSources = it.map { endpoint -> endpointIdToSourceName(endpoint) }
if (onStageSources != newOnStageSources) {
onStageSources = newOnStageSources
changed = true
}
}
}
message.defaultConstraints?.let {
if (defaultConstraints != it) {
defaultConstraints = it
changed = true
}
}
message.constraints?.let {
var newConstraints = it
// Convert endpoint IDs to source names
if (!useSourceNames) {
newConstraints = HashMap(it.size)
it.entries.stream().forEach {
entry ->
newConstraints[endpointIdToSourceName(entry.key)] = entry.value
}
}
if (this.videoConstraints != newConstraints) {
this.videoConstraints = newConstraints
changed = true
}
}
if (changed) {
allocationSettings = create()
}
return changed
}
/**
* Return `true` iff the [AllocationSettings] state changed.
*/
fun setLastN(lastN: Int): Boolean {
if (this.lastN != lastN) {
this.lastN = lastN
allocationSettings = create()
return true
}
return false
}
}
|
apache-2.0
|
c1e53e96d3835a05be48e147f89078b3
| 34.195266 | 117 | 0.623067 | 5.20385 | false | false | false | false |
ejeinc/Meganekko
|
library/src/main/java/org/meganekkovr/KeyCode.kt
|
1
|
7173
|
package org.meganekkovr
/**
* Manually coped from VrAppFramework/Input.h enum ovrKeyCode.
*/
object KeyCode {
const val OVR_KEY_NONE = 0 // nothing
const val OVR_KEY_LCONTROL = 1
const val OVR_KEY_RCONTROL = 2
const val OVR_KEY_LSHIFT = 3
const val OVR_KEY_RSHIFT = 4
const val OVR_KEY_LALT = 5
const val OVR_KEY_RALT = 6
const val OVR_KEY_MENU = 7
const val OVR_KEY_UP = 9
const val OVR_KEY_DOWN = 10
const val OVR_KEY_LEFT = 11
const val OVR_KEY_RIGHT = 12
const val OVR_KEY_F1 = 14
const val OVR_KEY_F2 = 15
const val OVR_KEY_F3 = 16
const val OVR_KEY_F4 = 17
const val OVR_KEY_F5 = 18
const val OVR_KEY_F6 = 19
const val OVR_KEY_F7 = 20
const val OVR_KEY_F8 = 21
const val OVR_KEY_F9 = 22
const val OVR_KEY_F10 = 23
const val OVR_KEY_F11 = 24
const val OVR_KEY_F12 = 25
const val OVR_KEY_RETURN = 27 // return (not on numeric keypad)
const val OVR_KEY_SPACE = 28 // space bar
const val OVR_KEY_INSERT = 29
const val OVR_KEY_DELETE = 30
const val OVR_KEY_HOME = 31
const val OVR_KEY_END = 32
const val OVR_KEY_PAGEUP = 33
const val OVR_KEY_PAGEDOWN = 34
const val OVR_KEY_SCROLL_LOCK = 35
const val OVR_KEY_PAUSE = 36
const val OVR_KEY_PRINT_SCREEN = 37
const val OVR_KEY_NUM_LOCK = 38
const val OVR_KEY_CAPSLOCK = 39
const val OVR_KEY_ESCAPE = 40
const val OVR_KEY_BACK = OVR_KEY_ESCAPE // escape and back are synonomous
const val OVR_KEY_SYS_REQ = 41
const val OVR_KEY_BREAK = 42
const val OVR_KEY_KP_DIVIDE = 44 // / (forward slash) on numeric keypad
const val OVR_KEY_KP_MULTIPLY = 45 // * on numeric keypad
const val OVR_KEY_KP_ADD = 46 // + on numeric keypad
const val OVR_KEY_KP_SUBTRACT = 47 // - on numeric keypad
const val OVR_KEY_KP_ENTER = 48 // enter on numeric keypad
const val OVR_KEY_KP_DECIMAL = 49 // delete on numeric keypad
const val OVR_KEY_KP_0 = 50
const val OVR_KEY_KP_1 = 51
const val OVR_KEY_KP_2 = 52
const val OVR_KEY_KP_3 = 53
const val OVR_KEY_KP_4 = 54
const val OVR_KEY_KP_5 = 55
const val OVR_KEY_KP_6 = 56
const val OVR_KEY_KP_7 = 57
const val OVR_KEY_KP_8 = 58
const val OVR_KEY_KP_9 = 59
const val OVR_KEY_TAB = 61
const val OVR_KEY_COMMA = 62 // ,
const val OVR_KEY_PERIOD = 63 // .
const val OVR_KEY_LESS = 64 // <
const val OVR_KEY_GREATER = 65 // >
const val OVR_KEY_FORWARD_SLASH = 66 // /
const val OVR_KEY_BACK_SLASH = 67 /* \ */
const val OVR_KEY_QUESTION_MARK = 68 // ?
const val OVR_KEY_SEMICOLON = 69 // ;
const val OVR_KEY_COLON = 70 // :
const val OVR_KEY_APOSTROPHE = 71 // '
const val OVR_KEY_QUOTE = 72 // "
const val OVR_KEY_OPEN_BRACKET = 73 // [
const val OVR_KEY_CLOSE_BRACKET = 74 // ]
const val OVR_KEY_CLOSE_BRACE = 75 // {
const val OVR_KEY_OPEN_BRACE = 76 // }
const val OVR_KEY_BAR = 77 // |
const val OVR_KEY_TILDE = 78 // ~
const val OVR_KEY_GRAVE = 79 // `
const val OVR_KEY_1 = 81
const val OVR_KEY_2 = 82
const val OVR_KEY_3 = 83
const val OVR_KEY_4 = 84
const val OVR_KEY_5 = 85
const val OVR_KEY_6 = 86
const val OVR_KEY_7 = 87
const val OVR_KEY_8 = 88
const val OVR_KEY_9 = 89
const val OVR_KEY_0 = 90
const val OVR_KEY_EXCLAMATION = 91 // !
const val OVR_KEY_AT = 92 // @
const val OVR_KEY_POUND = 93 // #
const val OVR_KEY_DOLLAR = 94 // $
const val OVR_KEY_PERCENT = 95 // %
const val OVR_KEY_CARET = 96 // ^
const val OVR_KEY_AMPERSAND = 97 // &
const val OVR_KEY_ASTERISK = 98 // *
const val OVR_KEY_OPEN_PAREN = 99 // (
const val OVR_KEY_CLOSE_PAREN = 100 // )
const val OVR_KEY_MINUS = 101 // -
const val OVR_KEY_UNDERSCORE = 102 // _
const val OVR_KEY_PLUS = 103 // +
const val OVR_KEY_EQUALS = 104 // =
const val OVR_KEY_BACKSPACE = 105 //
const val OVR_KEY_A = 107
const val OVR_KEY_B = 108
const val OVR_KEY_C = 109
const val OVR_KEY_D = 110
const val OVR_KEY_E = 111
const val OVR_KEY_F = 112
const val OVR_KEY_G = 113
const val OVR_KEY_H = 114
const val OVR_KEY_I = 115
const val OVR_KEY_J = 116
const val OVR_KEY_K = 117
const val OVR_KEY_L = 118
const val OVR_KEY_M = 119
const val OVR_KEY_N = 120
const val OVR_KEY_O = 121
const val OVR_KEY_P = 122
const val OVR_KEY_Q = 123
const val OVR_KEY_R = 124
const val OVR_KEY_S = 125
const val OVR_KEY_T = 126
const val OVR_KEY_U = 127
const val OVR_KEY_V = 128
const val OVR_KEY_W = 129
const val OVR_KEY_X = 130
const val OVR_KEY_Y = 131
const val OVR_KEY_Z = 132
const val OVR_KEY_VOLUME_MUTE = 134
const val OVR_KEY_VOLUME_UP = 135
const val OVR_KEY_VOLUME_DOWN = 136
const val OVR_KEY_MEDIA_NEXT_TRACK = 137
const val OVR_KEY_MEDIA_PREV_TRACK = 138
const val OVR_KEY_MEDIA_STOP = 139
const val OVR_KEY_MEDIA_PLAY_PAUSE = 140
const val OVR_KEY_LAUNCH_APP1 = 141
const val OVR_KEY_LAUNCH_APP2 = 142
const val OVR_KEY_BUTTON_A = 144
const val OVR_KEY_BUTTON_B = 145
const val OVR_KEY_BUTTON_C = 146
const val OVR_KEY_BUTTON_X = 147
const val OVR_KEY_BUTTON_Y = 148
const val OVR_KEY_BUTTON_Z = 149
const val OVR_KEY_BUTTON_START = 150
const val OVR_KEY_BUTTON_SELECT = 151
const val OVR_KEY_BUTTON_MENU = 152
const val OVR_KEY_LEFT_TRIGGER = 153
const val OVR_KEY_BUTTON_L1 = OVR_KEY_LEFT_TRIGGER // FIXME: this is a poor name, but we're maintaining it for ease of conversion
const val OVR_KEY_RIGHT_TRIGGER = 154
const val OVR_KEY_BUTTON_R1 = OVR_KEY_RIGHT_TRIGGER // FIXME: this is a poor name, but we're maintaining it for eash of conversion
const val OVR_KEY_DPAD_UP = 155
const val OVR_KEY_DPAD_DOWN = 156
const val OVR_KEY_DPAD_LEFT = 157
const val OVR_KEY_DPAD_RIGHT = 158
const val OVR_KEY_LSTICK_UP = 159
const val OVR_KEY_LSTICK_DOWN = 160
const val OVR_KEY_LSTICK_LEFT = 161
const val OVR_KEY_LSTICK_RIGHT = 162
const val OVR_KEY_RSTICK_UP = 163
const val OVR_KEY_RSTICK_DOWN = 164
const val OVR_KEY_RSTICK_LEFT = 165
const val OVR_KEY_RSTICK_RIGHT = 166
const val OVR_KEY_BUTTON_LEFT_SHOULDER = 167 // the button above the left trigger on MOGA / XBox / PS joypads
const val OVR_KEY_BUTTON_L2 = OVR_KEY_BUTTON_LEFT_SHOULDER
const val OVR_KEY_BUTTON_RIGHT_SHOULDER = 168 // the button above ther right trigger on MOGA / XBox / PS joypads
const val OVR_KEY_BUTTON_R2 = OVR_KEY_BUTTON_RIGHT_SHOULDER
const val OVR_KEY_BUTTON_LEFT_THUMB = 169 // click of the left thumbstick
const val OVR_KEY_BUTTON_THUMBL = OVR_KEY_BUTTON_LEFT_THUMB
const val OVR_KEY_BUTTON_RIGHT_THUMB = 170 // click of the left thumbstick
const val OVR_KEY_BUTTON_THUMBR = OVR_KEY_BUTTON_RIGHT_THUMB
const val OVR_KEY_MAX = 172
}
|
apache-2.0
|
713b9c851b2abec50e94ee1975f93494
| 36.952381 | 137 | 0.615921 | 3.210833 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
playback/src/main/kotlin/de/ph1b/audiobook/playback/notification/NotificationChannelCreator.kt
|
1
|
1113
|
package de.ph1b.audiobook.playback.notification
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import de.ph1b.audiobook.playback.R
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
const val MUSIC_CHANNEL_ID = "musicChannel4"
@Singleton
class NotificationChannelCreator
@Inject constructor(
private val notificationManager: NotificationManager,
private val context: Context
) {
private var created = AtomicBoolean()
fun createChannel() {
if (created.getAndSet(true)) {
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.music_notification)
val channel = NotificationChannel(
MUSIC_CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_LOW
).apply {
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setShowBadge(false)
}
notificationManager.createNotificationChannel(channel)
}
}
}
|
lgpl-3.0
|
f901f43e4cb03a5487acc5201027c1c7
| 25.5 | 63 | 0.747529 | 4.452 | false | false | false | false |
ice1000/Castle-game
|
src/funcs/using/FuncMap.kt
|
1
|
782
|
package funcs.using
import castle.Game
import funcs.FuncSrc
import javax.swing.*
import java.awt.*
import java.io.File
/**
* 显示地图
* Created by asus1 on 2016/2/1.
*/
class FuncMap(game: Game) : FuncSrc(game) {
override fun DoFunc(cmd: String) {
val frame = JFrame("地图")
val panel = JPanel()
val label = JLabel()
val image = Toolkit.getDefaultToolkit().getImage(
"." + File.separator + "drawable" + File.separator + "map.png")
val icon = ImageIcon(image)
label.icon = icon
frame.setSize(icon.iconWidth, icon.iconHeight)
panel.add(label)
frame.contentPane = panel
frame.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE
frame.isVisible = true
}
}
|
lgpl-3.0
|
ebb991b5ad53c9e34adf9ae848afec25
| 24.666667 | 79 | 0.627273 | 3.811881 | false | false | false | false |
jilees/Fuel
|
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/requests/DownloadTaskRequest.kt
|
1
|
1097
|
package com.github.kittinunf.fuel.core.requests
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.util.copyTo
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
class DownloadTaskRequest(request: Request) : TaskRequest(request) {
val BUFFER_SIZE = 1024
var progressCallback: ((Long, Long) -> Unit)? = null
lateinit var destinationCallback: ((Response, URL) -> File)
lateinit var dataStream: InputStream
lateinit var fileOutputStream: FileOutputStream
override fun call(): Response {
val response = super.call()
val file = destinationCallback.invoke(response, request.url)
//file output
fileOutputStream = FileOutputStream(file)
dataStream = ByteArrayInputStream(response.data)
dataStream.copyTo(fileOutputStream, BUFFER_SIZE) { readBytes ->
progressCallback?.invoke(readBytes, response.httpContentLength)
}
return response
}
}
|
mit
|
948a00966a2e9de24adec33498331b26
| 31.294118 | 75 | 0.731996 | 4.570833 | false | false | false | false |
idanarye/nisui
|
gui/src/main/kotlin/nisui/gui/queries/PlotSettingPanel.kt
|
1
|
3415
|
package nisui.gui.queries
import javax.swing.*
import javax.swing.event.*
import java.awt.GridBagLayout
import java.awt.GridBagConstraints
import java.awt.FlowLayout
import javax.swing.KeyStroke;
import java.awt.event.ActionEvent;
import nisui.core.plotting.*
import nisui.gui.*
public class PlotSettingPanel(val parent: PlotsPanel): JPanel(GridBagLayout()) {
fun createResultsStorage() = parent.createResultsStorage()
var focusedPlotListEntry = PlotListEntry(PlotEntry.buildNew("")!!, PlotListEntry.Status.UNSYNCED)
val focusedPlot get() = focusedPlotListEntry.plot
val tablePanels: List<TablePanel<*>>
val plotsListPanel: PlotsList
init {
plotsListPanel = PlotsList(this)
add(plotsListPanel, constraints {
gridx = 0
gridy = 1
})
add(gridBagJPanel {
JButton("SAVE").let {
add(it)
it.setMnemonic('S')
it.addActionListener({savePlots()})
}
JButton("RENDER").let {
add(it)
it.setMnemonic('R')
it.addActionListener {
[email protected](focusedPlot)
}
}
}, constraints {
gridx = 0
gridy = 0
})
val tablePanels = mutableListOf<TablePanel<*>>()
fun addTablePanel(tablePanel: TablePanel<*>): TablePanel<*> {
tablePanels.add(tablePanel)
return tablePanel
}
add(addTablePanel(FiltersTable(this)), constraints {
gridx = 1
gridy = 0
gridheight = 2
})
add(addTablePanel(AxesTable(this)), constraints {
gridx = 0
gridy = 2
})
add(addTablePanel(FormulasTable(this)), constraints {
gridx = 1
gridy = 2
})
this.tablePanels = tablePanels
for (tablePanel in tablePanels) {
tablePanel.table.getModel().addTableModelListener {
plotUpdated()
}
}
}
fun changeFocusedPlot(plotListEntry: PlotListEntry) {
if (plotListEntry == focusedPlotListEntry) {
return
}
focusedPlotListEntry = plotListEntry
val oldStatus = plotListEntry.status
for (tablePanel in tablePanels) {
tablePanel.tableModel.fireTableDataChanged()
}
plotListEntry.status = oldStatus
}
fun plotUpdated() {
if (focusedPlotListEntry.status == PlotListEntry.Status.SYNCED) {
focusedPlotListEntry.status = PlotListEntry.Status.UNSYNCED
plotsListPanel.tableModel.fireTableDataChanged()
}
}
fun savePlots() {
val postActions = mutableListOf<() -> Unit>()
createResultsStorage().connect().use {con ->
con.saveStoredPlots().use {saver ->
for (plot in plotsListPanel.plots) {
when (plot.status) {
PlotListEntry.Status.UNSYNCED -> {
saver.save(plot.plot)
postActions.add({plot.status = PlotListEntry.Status.SYNCED})
}
}
}
}
}
postActions.forEach({it()})
plotsListPanel.tableModel.fireTableDataChanged()
}
}
|
mit
|
7489aa36c160657fe53eaddf32f3a3c7
| 28.695652 | 101 | 0.560469 | 4.816643 | false | false | false | false |
google/horologist
|
media-data/src/main/java/com/google/android/horologist/media/data/service/download/DownloadProgressMonitor.kt
|
1
|
3083
|
/*
* 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.data.service.download
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import androidx.media3.exoplayer.offline.DownloadManager
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
import com.google.android.horologist.media.data.database.dao.MediaDownloadDao.Companion.DOWNLOAD_PROGRESS_START
import com.google.android.horologist.media.data.datasource.MediaDownloadLocalDataSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* Monitors the progress of downloads, polling [DownloadManager] every
* [specified interval][UPDATE_INTERVAL_MILLIS] and uses [MediaDownloadLocalDataSource] to persist
* the progress.
*/
@SuppressLint("UnsafeOptInUsageError")
@ExperimentalHorologistMediaDataApi
public class DownloadProgressMonitor(
private val coroutineScope: CoroutineScope,
private val mediaDownloadLocalDataSource: MediaDownloadLocalDataSource
) {
private val handler = Handler(Looper.getMainLooper())
private var running = false
internal fun start(downloadManager: DownloadManager) {
running = true
update(downloadManager)
}
internal fun stop() {
running = false
handler.removeCallbacksAndMessages(null)
}
private fun update(downloadManager: DownloadManager) {
coroutineScope.launch {
val downloads = mediaDownloadLocalDataSource.getAllDownloading()
if (downloads.isNotEmpty()) {
downloads.forEach {
downloadManager.downloadIndex.getDownload(it.mediaId)?.let { download ->
mediaDownloadLocalDataSource.updateProgress(
mediaId = download.request.id,
progress = download.percentDownloaded
// it can return -1 (C.PERCENTAGE_UNSET)
.coerceAtLeast(DOWNLOAD_PROGRESS_START),
size = download.contentLength
)
}
}
} else {
stop()
}
}
if (running) {
handler.removeCallbacksAndMessages(null)
handler.postDelayed({ update(downloadManager) }, UPDATE_INTERVAL_MILLIS)
}
}
private companion object {
const val UPDATE_INTERVAL_MILLIS = 1000L
}
}
|
apache-2.0
|
13db93ad7bb4ef46ce7c5fa93742313a
| 35.702381 | 111 | 0.679533 | 5.216582 | false | false | false | false |
unbroken-dome/gradle-testsets-plugin
|
src/main/kotlin/org/unbrokendome/gradle/plugins/testsets/dsl/NamingConventions.kt
|
1
|
499
|
package org.unbrokendome.gradle.plugins.testsets.dsl
internal object NamingConventions {
fun sourceSetName(testSetName: String) =
testSetName
fun testTaskName(testSetName: String) =
testSetName
fun jarTaskName(testSetName: String) =
"${testSetName}Jar"
fun artifactConfigurationName(testSetName: String) =
testSetName
fun jacocoReportTaskName(testTaskName: String) =
"jacoco${testTaskName.capitalize()}Report"
}
|
mit
|
1e615f2d557d4363a8edf5900d1c3ec8
| 23.95 | 56 | 0.681363 | 4.752381 | false | true | false | false |
xfournet/intellij-community
|
plugins/devkit/testSources/build/PluginModuleCompilationTest.kt
|
1
|
4787
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.build
import com.intellij.compiler.BaseCompilerTestCase
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.util.SmartList
import com.intellij.util.io.TestFileSystemBuilder.fs
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.projectRoots.IdeaJdk
import org.jetbrains.idea.devkit.projectRoots.Sandbox
import java.io.File
import java.util.*
/**
* @author nik
*/
class PluginModuleCompilationTest : BaseCompilerTestCase() {
override fun setUpJdk() {
super.setUpJdk()
runWriteAction {
val table = ProjectJdkTable.getInstance()
val pluginSdk: Sdk = table.createSdk("IDEA plugin SDK", SdkType.findInstance(IdeaJdk::class.java))
val modificator = pluginSdk.sdkModificator
modificator.sdkAdditionalData = Sandbox(getSandboxPath(), testProjectJdk, pluginSdk)
val rootPath = FileUtil.toSystemIndependentName(PathManager.getJarPathForClass(FileUtilRt::class.java)!!)
modificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(rootPath)!!, OrderRootType.CLASSES)
modificator.commitChanges()
table.addJdk(pluginSdk, testRootDisposable)
}
}
private fun getSandboxPath() = "$projectBasePath/sandbox"
fun testMakeSimpleModule() {
val module = setupSimplePluginProject()
make(module)
BaseCompilerTestCase.assertOutput(module, fs().dir("xxx").file("MyAction.class"))
val sandbox = File(getSandboxPath())
assertThat(sandbox).isDirectory()
fs()
.dir("plugins")
.dir("pluginProject")
.dir("META-INF").file("plugin.xml").end()
.dir("classes")
.dir("xxx").file("MyAction.class")
.build().assertDirectoryEqual(sandbox)
}
fun testRebuildSimpleProject() {
setupSimplePluginProject()
val log = rebuild()
assertThat(log.warnings).`as`("Rebuild finished with warnings: ${Arrays.toString(log.warnings)}").isEmpty()
}
fun testPrepareSimpleProjectForDeployment() {
val module = setupSimplePluginProject()
rebuild()
prepareForDeployment(module)
val outputFile = File("$projectBasePath/pluginProject.jar")
assertThat(outputFile).isFile()
fs()
.archive("pluginProject.jar")
.dir("META-INF").file("plugin.xml").file("MANIFEST.MF").end()
.dir("xxx").file("MyAction.class")
.build().assertFileEqual(outputFile)
}
fun testBuildProjectWithJpsModule() {
val module = setupPluginProjectWithJpsModule()
rebuild()
prepareForDeployment(module)
val outputFile = File("$projectBasePath/pluginProject.zip")
assertThat(outputFile).isFile()
fs()
.archive("pluginProject.zip")
.dir("pluginProject")
.dir("lib")
.archive("pluginProject.jar")
.dir("META-INF").file("plugin.xml").file("MANIFEST.MF").end()
.dir("xxx").file("MyAction.class").end()
.end()
.dir("jps")
.archive("jps-plugin.jar").file("Builder.class")
.build().assertFileEqual(outputFile)
}
private fun prepareForDeployment(module: Module) {
val errorMessages = SmartList<String>()
PrepareToDeployAction.doPrepare(module, errorMessages, SmartList<String>())
assertThat(errorMessages).`as`("Building plugin zip finished with errors: $errorMessages").isEmpty()
}
private fun setupSimplePluginProject() = copyAndCreateModule("plugins/devkit/testData/build/simple")
private fun copyAndCreateModule(relativePath: String): Module {
copyToProject(relativePath)
val module = loadModule("$projectBasePath/pluginProject.iml")
assertThat(ModuleType.get(module)).isEqualTo(PluginModuleType.getInstance())
return module
}
private fun setupPluginProjectWithJpsModule(): Module {
val module = copyAndCreateModule("plugins/devkit/testData/build/withJpsModule")
val jpsModule = loadModule("$projectBasePath/jps-plugin/jps-plugin.iml")
ModuleRootModificationUtil.setModuleSdk(jpsModule, testProjectJdk)
return module
}
}
|
apache-2.0
|
876fd6412c44b154f959bbfb1d99b72d
| 37.918699 | 140 | 0.733445 | 4.453023 | false | true | false | false |
yshrsmz/monotweety
|
app/src/main/java/net/yslibrary/monotweety/base/BaseController.kt
|
1
|
2178
|
package net.yslibrary.monotweety.base
import android.os.Build
import android.widget.Toast
import androidx.annotation.StringRes
import com.bluelinelabs.conductor.rxlifecycle2.RxController
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import me.drakeet.support.toast.ToastCompat
import net.yslibrary.monotweety.analytics.Analytics
import net.yslibrary.monotweety.base.di.Names
import javax.inject.Inject
import javax.inject.Named
import kotlin.properties.Delegates
abstract class BaseController : RxController() {
@set:Inject
@setparam:Named(Names.FOR_ACTIVITY)
var activityBus by Delegates.notNull<EventBus>()
@set:Inject
var analytics by Delegates.notNull<Analytics>()
@Suppress("UNCHECKED_CAST")
fun <PROVIDER> getComponentProvider(parent: Any): PROVIDER {
return ((parent as HasComponent<Any>).component as PROVIDER)
}
fun <T> Observable<T>.bindToLifecycle(): Observable<T> =
this.compose([email protected]<T>())
fun <T> Single<T>.bindToLifecycle(): Single<T> =
this.compose([email protected]<T>())
fun <T> Completable.bindToLifecycle(): Completable =
this.compose([email protected]<T>())
fun showSnackBar(message: String) = (activity as BaseActivity).showSnackBar(message)
fun toast(message: String): Toast? = applicationContext?.let {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
ToastCompat.makeText(it, message, Toast.LENGTH_SHORT)
} else {
Toast.makeText(it, message, Toast.LENGTH_SHORT)
}
}
fun toastLong(message: String): Toast? = applicationContext?.let {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
ToastCompat.makeText(it, message, Toast.LENGTH_SHORT)
} else {
Toast.makeText(it, message, Toast.LENGTH_LONG)
}
}
fun getString(@StringRes id: Int): String = applicationContext?.getString(id) ?: ""
fun getString(@StringRes id: Int, vararg formatArgs: Any): String =
applicationContext?.getString(id, *formatArgs) ?: ""
}
|
apache-2.0
|
7b86a35adb37ef9c6e53897ac550f870
| 33.571429 | 88 | 0.708907 | 4.204633 | false | false | false | false |
clhols/zapr
|
app/src/main/java/dk/youtec/zapr/ui/adapter/ChannelsAdapter.kt
|
1
|
8167
|
package dk.youtec.zapr.ui.adapter
import android.content.Context
import android.support.annotation.LayoutRes
import android.support.annotation.MainThread
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import dk.youtec.zapr.backend.*
import dk.youtec.zapr.model.Channel
import dk.youtec.zapr.R
import dk.youtec.zapr.util.SharedPreferences
import org.jetbrains.anko.*
import java.text.SimpleDateFormat
import java.util.*
import android.support.v7.util.DiffUtil
import android.support.v7.util.ListUpdateCallback
import android.util.Log
import android.widget.ImageButton
import android.widget.ProgressBar
import dk.youtec.zapr.model.EpgDiffCallback
import dk.youtec.zapr.ui.view.AspectImageView
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
class ChannelsAdapter(val contentView: View?, var channels: List<Channel>, val listener: OnChannelClickListener) : RecyclerView.Adapter<ChannelsAdapter.ViewHolder>() {
//Toggles if description and image should be shown
var showDetails = true
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val channel = channels[position]
holder.mChannelName.text = channel.channelName
if (channel.now != null) {
holder.mChannelName.visibility = View.GONE
holder.mTitle.text = channel.now.title
holder.mNowDescription.text = channel.now.shortDescription
holder.mNowDescription.visibility = if (showDetails) View.VISIBLE else View.GONE
//Show time interval
val localDateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
val startTime = localDateFormat.format(Date(channel.now.startTime))
val endTime = localDateFormat.format(Date(channel.now.endTime))
holder.mTime.text = buildString {
append(startTime)
append(" - ")
append(endTime)
}
//Progress
val programDuration = channel.now.endTime - channel.now.startTime
val programTime = System.currentTimeMillis() - channel.now.startTime
val percentage = 100 * programTime.toFloat() / programDuration
holder.mProgress.progress = percentage.toInt()
//Genre icon
holder.mGenre.setImageResource(0)
if (channel.now.genreId == 10) {
//Sport genre
holder.mGenre.setImageResource(R.drawable.ic_genre_dot_black);
holder.mGenre.setColorFilter(holder.itemView.resources.getColor(android.R.color.holo_blue_dark))
}
//holder.mTimeLeft.text = "(" + (channel.now.endTime - System.currentTimeMillis()) / 60 + " min left)"
if (!channel.now.image.isNullOrEmpty() && showDetails) {
holder.mImage.visibility = View.VISIBLE
Glide.with(holder.mImage.context)
.load(channel.now.image)
.placeholder(R.drawable.image_placeholder)
.into(holder.mImage)
} else {
holder.mImage.visibility = View.GONE
holder.mImage.image = null
}
Glide.with(holder.mLogo.context)
.load(URL_GET_GFX.replace("[SID]", channel.sid, true).replace("[SIZE]", 60.toString()))
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.into(holder.mLogo)
} else {
holder.mChannelName.visibility = View.VISIBLE
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, position, payloads)
} else {
super.onBindViewHolder(holder, position, payloads)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.channels_item))
}
@MainThread
fun updateList(newList: List<Channel>) {
//Calculate the diff
val diffResult = DiffUtil.calculateDiff(EpgDiffCallback(channels, newList))
//Update the backing list
channels = newList
diffResult.dispatchUpdatesTo(object : ListUpdateCallback {
override fun onInserted(position: Int, count: Int) {
}
override fun onRemoved(position: Int, count: Int) {
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
}
override fun onChanged(position: Int, count: Int, payload: Any) {
if (position < newList.size) {
val (sid, channelName, now, next) = newList[position]
if (now != null && contentView != null) {
val message = now.title + " " + contentView.context.getString(R.string.on) + " " + channelName
Log.d(TAG, message)
//contentView.context.longToast(message)
}
}
}
})
//Make the adapter notify of the changes
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount(): Int {
return channels.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val TAG = ViewHolder::class.java.simpleName
var mChannelName: TextView
var mTitle: TextView
var mProgress: ProgressBar
var mNowDescription: TextView
var mImage: ImageView
var mLogo: ImageView
var mTime: TextView
var mGenre: ImageView
var mMore: ImageButton
init {
mChannelName = itemView.find<TextView>(R.id.channelName)
itemView.setOnClickListener {
if (0 <= adapterPosition && adapterPosition < channels.size) {
if (SharedPreferences.getBoolean(it.context, SharedPreferences.REMOTE_CONTROL_MODE)) {
listener.changeToChannel(channels[adapterPosition])
} else {
listener.playChannel(channels[adapterPosition])
}
}
}
itemView.setOnLongClickListener {
it.context.selector(it.context.getString(R.string.channelAction), listOf(it.context.getString(R.string.startOverAction))) { _, _ ->
if (0 <= adapterPosition && adapterPosition < channels.size) {
if (SharedPreferences.getBoolean(it.context, SharedPreferences.REMOTE_CONTROL_MODE)) {
listener.changeToChannel(channels[adapterPosition], true)
} else {
listener.playChannel(channels[adapterPosition], true)
}
}
}
true
}
mTitle = itemView.findViewById(R.id.title)
mProgress = itemView.findViewById(R.id.progress)
mNowDescription = itemView.findViewById(R.id.nowDescription)
mImage = itemView.findViewById(R.id.image)
mTime = itemView.findViewById(R.id.time)
mLogo = itemView.findViewById(R.id.logo)
mGenre = itemView.findViewById(R.id.genre)
mMore = itemView.findViewById(R.id.more)
mMore.setOnClickListener {
listener.showChannel(it.context, channels[adapterPosition])
}
(mImage as AspectImageView).setAspectRatio(292, 189)
}
}
interface OnChannelClickListener {
fun showChannel(context: Context, channel: Channel)
fun playChannel(channel: Channel, restart: Boolean = false)
fun changeToChannel(channel: Channel, restart: Boolean = false)
}
}
|
mit
|
0c80a40fa0a3d619dbc2fc4f468f0337
| 39.435644 | 167 | 0.617485 | 4.798472 | false | false | false | false |
AerisG222/maw_photos_android
|
MaWPhotos/src/main/java/us/mikeandwan/photos/domain/ActiveIdRepository.kt
|
1
|
1273
|
package us.mikeandwan.photos.domain
import kotlinx.coroutines.flow.Flow
import us.mikeandwan.photos.database.ActiveId
import us.mikeandwan.photos.database.ActiveIdDao
import us.mikeandwan.photos.database.ActiveIdType
import javax.inject.Inject
class ActiveIdRepository @Inject constructor(
private val dao: ActiveIdDao
) {
fun getActivePhotoCategoryYear(): Flow<Int?> = dao.getActiveId(ActiveIdType.PhotoCategoryYear)
fun getActivePhotoCategoryId(): Flow<Int?> = dao.getActiveId(ActiveIdType.PhotoCategory)
fun getActivePhotoId(): Flow<Int?> = dao.getActiveId(ActiveIdType.Photo)
suspend fun setActivePhotoCategoryYear(year: Int) {
val id = ActiveId(ActiveIdType.PhotoCategoryYear, year)
dao.setActiveId(id)
}
suspend fun setActivePhotoCategory(categoryId: Int) {
val id = ActiveId(ActiveIdType.PhotoCategory, categoryId)
dao.setActiveId(id)
}
suspend fun setActivePhoto(photoId: Int) {
val id = ActiveId(ActiveIdType.Photo, photoId)
dao.setActiveId(id)
}
suspend fun clearActivePhoto() {
dao.deleteActiveId(ActiveIdType.Photo)
}
suspend fun clearActiveCategory() {
clearActivePhoto()
dao.deleteActiveId(ActiveIdType.PhotoCategory)
}
}
|
mit
|
a6773040ded4a71b41ccb2270a318860
| 29.333333 | 98 | 0.732914 | 4.20132 | false | false | false | false |
vsch/idea-multimarkdown
|
src/test/java/com/vladsch/md/nav/util/TestLinkResolver_Basic_wiki_Home.kt
|
1
|
6980
|
/*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>, all rights reserved.
*
* This code is private property of the copyright holder and cannot be used without
* having obtained a license or prior written permission of the copyright holder.
*
* 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.vladsch.md.nav.util
import com.vladsch.md.nav.testUtil.TestCaseUtils.assertEqualsMessage
import com.vladsch.md.nav.testUtil.TestCaseUtils.compareOrderedLists
import com.vladsch.md.nav.testUtil.TestCaseUtils.compareUnorderedLists
import com.vladsch.md.nav.vcs.GitHubLinkResolver
import com.vladsch.plugin.util.prefixWith
import com.vladsch.plugin.util.startsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.util.*
@RunWith(value = Parameterized::class)
class TestLinkResolver_Basic_wiki_Home constructor(
val location: String
, val fullPath: String
, val linkRefType: (containingFile: FileRef, linkRef: String, anchor: String?, targetRef: FileRef?, isNormalized: Boolean) -> LinkRef
, val linkText: String
, val linkAddress: String
, val linkAnchor: String?
, val linkTitle: String?
, resolvesLocalRel: String?
, resolvesExternalRel: String?
, val linkAddressText: String?
, val remoteAddressText: String?
, val uriText: String?
, multiResolvePartial: Array<String>
, val inspectionResults: ArrayList<InspectionResult>?
, val inspectionExtResults: ArrayList<InspectionResult>?
) {
val resolvesLocal: String?
val resolvesExternal: String?
val filePathInfo = FileRef(fullPath)
val resolver = GitHubLinkResolver(MarkdownTestData, filePathInfo)
val linkRef = LinkRef.parseLinkRef(filePathInfo, linkAddress + linkAnchor.prefixWith('#'), null, linkRefType)
val linkRefNoExt = LinkRef.parseLinkRef(filePathInfo, linkRef.filePathNoExt + linkAnchor.prefixWith('#'), null, linkRefType)
val fileList = ArrayList<FileRef>(MarkdownTestData.filePaths.size)
val multiResolve: Array<String>
val localLinkRef = resolvesLocalRel
val externalLinkRef = resolvesExternalRel
val skipTest = linkRef.isExternal && !linkRef.filePath.startsWith(MarkdownTestData.mainGitHubRepo.baseUrl ?: "/", ignoreCase = true)
fun resolveRelativePath(filePath: String?): PathInfo? {
return if (filePath == null) null else if (filePath.startsWith("http://", "https://")) PathInfo(filePath) else PathInfo.appendParts(filePathInfo.path, filePath)
}
init {
resolvesLocal = resolveRelativePath(resolvesLocalRel)?.filePath
resolvesExternal = resolveRelativePath(resolvesExternalRel)?.filePath
val multiResolveAbs = ArrayList<String>()
if (multiResolvePartial.isEmpty() && resolvesLocal != null && !linkAddressText.startsWith("#")) multiResolveAbs.add(resolvesLocal)
for (path in multiResolvePartial) {
val resolvedPath = resolveRelativePath(path)?.filePath.orEmpty()
multiResolveAbs.add(resolvedPath)
}
multiResolve = multiResolveAbs.toArray(Array(0, { "" }))
for (path in MarkdownTestData.filePaths) {
fileList.add(FileRef(path))
}
}
@Test
fun test_ResolveLocal() {
if (skipTest) return
val localRef = resolver.resolve(linkRef, Want(Local.REF, Remote.REF), fileList)
assertEqualsMessage(location + "\nLocal does not match ${resolver.getMatcher(linkRef).linkAllMatch}", resolvesLocal, localRef?.filePath)
}
@Test
fun test_ResolveExternal() {
if (skipTest) return
val localRef = resolver.resolve(linkRef, Want(Local.NONE, Remote.REF, Links.NONE), fileList)
assertEqualsMessage(location + "\nExternal does not match ${resolver.getMatcher(linkRef).linkAllMatch}", resolvesExternal, localRef?.filePath)
}
@Test
fun test_LocalLinkAddress() {
if (skipTest) return
val localRef = resolver.resolve(linkRef, Want(Local.REF, Remote.REF), fileList)
val localRefAddress = if (localRef != null) resolver.linkAddress(linkRef, localRef, ((linkRef.hasExt && linkRef.ext == localRef.ext) || (linkRef.hasAnchor && linkAnchor?.contains('.') ?: false)), null, reduceToAnchor = true) else null
assertEqualsMessage(location + "\nLocal link address does not match ${resolver.getMatcher(linkRef).linkAllMatch}", this.linkAddressText, localRefAddress)
}
@Test
fun test_MultiResolve() {
if (skipTest || linkRef.filePath.isEmpty() && linkRef.anchor == null) return
val localFileRef = if (localLinkRef != null) FileRef(localLinkRef) else null
val completionMatch = localFileRef == null || localFileRef.path.isEmpty()
val localRefs = resolver.multiResolve(linkRef, Want(Local.REF, Remote.REF, if (completionMatch) Match.LOOSE else null), fileList)
val actuals = Array<String>(localRefs.size, { "" })
for (i in localRefs.indices) {
actuals[i] = localRefs[i].filePath
}
compareOrderedLists(location + "\nMultiResolve ${if (completionMatch) "completionMatch" else "exact"} does not match ${if (completionMatch) resolver.getMatcher(linkRef).linkLooseMatch else resolver.getMatcher(linkRef).linkAllMatch}", multiResolve, actuals)
}
@Test
fun test_InspectionResults() {
if (skipTest || this.inspectionResults == null) return
val looseTargetRef = resolver.resolve(linkRef, Want(Match.LOOSE), fileList) as? FileRef
val targetRef = resolver.resolve(linkRef, Want(), fileList) as? FileRef
if (targetRef != null || looseTargetRef != null) {
val inspectionResults = resolver.inspect(linkRef, targetRef ?: looseTargetRef as FileRef, location)
// if (this.inspectionResults.size < inspectionResults.size) {
// for (inspection in inspectionResults) {
// //println(inspection.toArrayOfTestString(rowId, filePathInfo.path))
// }
// }
compareUnorderedLists(location + "\nInspectionResults do not match ${resolver.getMatcher(linkRef).linkAllMatch}", this.inspectionResults, inspectionResults)
}
}
companion object {
fun resolveRelativePath(filePathInfo: PathInfo, filePath: String?): PathInfo? {
return if (filePath == null) null else PathInfo.appendParts(filePathInfo.path, filePath.splitToSequence("/"))
}
@Parameterized.Parameters(name = "{index}: filePath = {1}, linkRef = {4}, linkAnchor = {5}")
@JvmStatic
fun data(): Collection<Array<Any?>> {
return MarkdownTest__MarkdownTest_wiki__Home_md.data()
}
}
}
|
apache-2.0
|
bc8ac3ab7e7ac0e1c68747f73f2d8230
| 46.482993 | 264 | 0.704585 | 4.227741 | false | true | false | false |
lgou2w/MoonLakeLauncher
|
src/main/kotlin/com/minecraft/moonlake/launcher/skin/MuiButtonSkin.kt
|
1
|
10251
|
/*
* Copyright (C) 2017 The MoonLake Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.launcher.skin
import com.minecraft.moonlake.launcher.animation.MuiTransition
import com.minecraft.moonlake.launcher.animation.control.MuiButtonDepthTransition
import com.minecraft.moonlake.launcher.control.MuiButton
import com.minecraft.moonlake.launcher.control.MuiRippler
import com.minecraft.moonlake.launcher.layout.MuiStackPane
import com.minecraft.moonlake.launcher.util.MuiDepthUtils
import com.minecraft.moonlake.launcher.util.MuiUtils
import com.sun.javafx.scene.control.skin.ButtonSkin
import com.sun.javafx.scene.control.skin.LabeledText
import javafx.beans.binding.Bindings
import javafx.geometry.Insets
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.paint.Color
import javafx.util.Duration
import java.util.concurrent.Callable
open class MuiButtonSkin : ButtonSkin {
/**************************************************************************
*
* Private Member
*
**************************************************************************/
private val defaultRadii = CornerRadii(3.0)
private val muiButtonContainer = MuiStackPane()
private var releaseManualRippler: Runnable? = null
private var depthAnimation: MuiTransition? = null
private var muiButtonRippler: MuiRippler
private var invalidLayout = true
/**************************************************************************
*
* Constructor
*
**************************************************************************/
constructor(muiButton: MuiButton): super(muiButton) {
muiButtonRippler = object: MuiRippler(MuiStackPane()) {
override fun getMask(): Node {
val mask = MuiStackPane()
mask.shapeProperty().bind(muiButtonContainer.shapeProperty())
mask.backgroundProperty().bind(Bindings.createObjectBinding(Callable {
Background(BackgroundFill(Color.WHITE,
if(muiButtonContainer.backgroundProperty().get() != null && muiButtonContainer.background.fills.size > 0)
muiButtonContainer.background.fills[0].radii
else
defaultRadii,
if(muiButtonContainer.backgroundProperty().get() != null && muiButtonContainer.background.fills.size > 0)
muiButtonContainer.background.fills[0].insets
else
Insets.EMPTY
))
}, muiButtonContainer.backgroundProperty()))
mask.resize(muiButtonContainer.width - muiButtonContainer.snappedRightInset() - muiButtonContainer.snappedLeftInset(),
muiButtonContainer.height - muiButtonContainer.snappedBottomInset() - muiButtonContainer.snappedTopInset())
return mask
}
override fun initListeners() {
ripplerPane.setOnMousePressed { event -> run {
if(releaseManualRippler != null)
releaseManualRippler!!.run()
releaseManualRippler = null
createRipple(event.x, event.y)
}}
}
}
skinnable.armedProperty().addListener { _, _, newValue -> run {
if(newValue) {
releaseManualRippler = muiButtonRippler.createManualRipple()
} else {
if(releaseManualRippler != null)
releaseManualRippler!!.run()
}
}}
muiButtonContainer.children.add(muiButtonRippler)
muiButton.typeProperty().addListener { _, _, newValue -> updateType(newValue) }
muiButton.setOnMouseEntered {
if(depthAnimation != null) {
depthAnimation!!.rate = 1.0
depthAnimation!!.play()
}
}
muiButton.setOnMouseExited {
if(depthAnimation != null) {
depthAnimation!!.rate = -1.0
depthAnimation!!.play()
}
}
muiButton.focusedProperty().addListener { _, _, newValue -> run {
if(newValue) {
if (!skinnable.isPressed)
muiButtonRippler.showOverlay()
} else {
muiButtonRippler.hideOverlay()
}
}}
muiButton.ripplerFillProperty().addListener { _, _, newValue -> muiButtonRippler.setRipplerFill(newValue) }
muiButton.pressedProperty().addListener { _, _, _ -> muiButtonRippler.hideOverlay() }
muiButton.isPickOnBounds = false
muiButtonContainer.isPickOnBounds = false
muiButtonContainer.shapeProperty().bind(skinnable.shapeProperty())
muiButtonContainer.borderProperty().bind(skinnable.borderProperty())
muiButtonContainer.backgroundProperty().bind(Bindings.createObjectBinding(Callable {
if(muiButton.background == null || MuiUtils.isDefaultBackground(muiButton.background) || MuiUtils.isDefaultClickedBackground(muiButton.background))
updateBackground(muiButton.getType())
try {
val background = skinnable.background
if(background != null && background.fills[0].insets == Insets(-.2, -.2, -.2, -.2)) {
Background(BackgroundFill(
if(skinnable.background != null)
skinnable.background.fills[0].fill
else
Color.TRANSPARENT,
if(skinnable.background != null)
skinnable.background.fills[0].radii
else
defaultRadii,
Insets.EMPTY))
} else {
Background(BackgroundFill(
if(skinnable.background != null)
skinnable.background.fills[0].fill
else
Color.TRANSPARENT,
if(skinnable.background != null)
skinnable.background.fills[0].radii
else
defaultRadii,
Insets.EMPTY))
}
} catch (e: Exception) {
skinnable.background
}
}, skinnable.backgroundProperty()))
if(muiButton.background == null || MuiUtils.isDefaultBackground(muiButton.background))
updateBackground(muiButton.getType())
updateType(muiButton.getType())
updateChildren()
}
/**************************************************************************
*
* Override Implements
*
**************************************************************************/
final override fun updateChildren() {
super.updateChildren()
if(muiButtonContainer is MuiStackPane)
children.add(0, muiButtonContainer)
for(i in 1..children.size - 1)
children[i].isMouseTransparent = true
}
override fun layoutChildren(x: Double, y: Double, w: Double, h: Double) {
if(invalidLayout) {
if(skinnable().getRipplerFill() == null) {
(children.size - 1 downTo 1).map { children[it] }.forEach {
if(it is LabeledText) {
muiButtonRippler.setRipplerFill(it.fill)
it.fillProperty().addListener { _, _, newValue -> muiButtonRippler.setRipplerFill(newValue) }
} else if(it is Label) {
muiButtonRippler.setRipplerFill(it.textFill)
it.textFillProperty().addListener { _, _, newValue -> muiButtonRippler.setRipplerFill(newValue) }
}
}
} else {
muiButtonRippler.setRipplerFill(skinnable().getRipplerFill()!!)
}
invalidLayout = false
}
muiButtonContainer.resizeRelocate(skinnable.layoutBounds.minX - 1, skinnable.layoutBounds.minY - 1, skinnable.width + 2, skinnable.height + 2)
layoutLabelInArea(x, y, w, h)
}
/**************************************************************************
*
* Private Implements
*
**************************************************************************/
private fun skinnable(): MuiButton
= skinnable as MuiButton
private fun updateBackground(type: MuiButton.Type) {
var background: Background? = null
when(type) {
MuiButton.Type.RAISED -> background = Background(BackgroundFill(Color.WHITE, defaultRadii, null))
MuiButton.Type.FLAT -> background = Background(BackgroundFill(Color.TRANSPARENT, defaultRadii, null))
}
skinnable.background = background
}
private fun updateType(type: MuiButton.Type) {
when(type) {
MuiButton.Type.RAISED -> {
MuiDepthUtils.setNodeDepth(muiButtonContainer, 1)
depthAnimation = MuiButtonDepthTransition(muiButtonContainer, 1, 3, Duration.seconds(.1))
}
MuiButton.Type.FLAT -> {
muiButtonContainer.effect = null
}
}
}
}
|
gpl-3.0
|
f04a8a73f849bbf112b9c2c2125da245
| 43.185345 | 159 | 0.552824 | 4.904785 | false | false | false | false |
uber/RIBs
|
android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_out/LoggedOutInteractor.kt
|
1
|
2135
|
/*
* Copyright (C) 2021. Uber Technologies
*
* 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.uber.rib.compose.root.main.logged_out
import com.uber.rib.compose.root.main.AuthInfo
import com.uber.rib.compose.root.main.AuthStream
import com.uber.rib.compose.util.EventStream
import com.uber.rib.compose.util.StateStream
import com.uber.rib.core.BasicInteractor
import com.uber.rib.core.Bundle
import com.uber.rib.core.ComposePresenter
import com.uber.rib.core.coroutineScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class LoggedOutInteractor(
presenter: ComposePresenter,
private val authStream: AuthStream,
private val eventStream: EventStream<LoggedOutEvent>,
private val stateStream: StateStream<LoggedOutViewModel>
) : BasicInteractor<ComposePresenter, LoggedOutRouter>(presenter) {
override fun didBecomeActive(savedInstanceState: Bundle?) {
super.didBecomeActive(savedInstanceState)
eventStream.observe()
.onEach {
when (it) {
is LoggedOutEvent.PlayerNameChanged -> {
with(stateStream) {
dispatch(
current().copy(
playerOne = if (it.num == 1) it.name else current().playerOne,
playerTwo = if (it.num == 2) it.name else current().playerTwo
)
)
}
}
LoggedOutEvent.LogInClick -> {
val currentState = stateStream.current()
authStream.accept(AuthInfo(true, currentState.playerOne, currentState.playerTwo))
}
}
}.launchIn(coroutineScope)
}
}
|
apache-2.0
|
c6b6dcd8df0965381bac25fd99bc3ca7
| 36.45614 | 93 | 0.698829 | 4.211045 | false | true | false | false |
quarkusio/quarkus
|
extensions/panache/mongodb-panache-kotlin/runtime/src/main/kotlin/io/quarkus/mongodb/panache/kotlin/PanacheMongoRepositoryBase.kt
|
1
|
24744
|
@file:Suppress("unused")
package io.quarkus.mongodb.panache.kotlin
import com.mongodb.client.MongoCollection
import com.mongodb.client.MongoDatabase
import io.quarkus.mongodb.panache.kotlin.runtime.KotlinMongoOperations.Companion.INSTANCE
import io.quarkus.panache.common.Parameters
import io.quarkus.panache.common.Sort
import io.quarkus.panache.common.impl.GenerateBridge
import org.bson.Document
import java.util.stream.Stream
/**
* Represents a Repository for a specific type of entity [Entity], with an ID type
* of [Id]. Implementing this repository will gain you the exact same useful methods
* that are on [PanacheMongoEntityBase]. Unless you have a custom ID strategy, you should not
* implement this interface directly but implement [PanacheMongoRepository] instead.
*
* @param Entity The type of entity to operate on
* @param Id The ID type of the entity
* @see [PanacheMongoRepository]
*/
interface PanacheMongoRepositoryBase<Entity : Any, Id : Any> {
/**
* Persist the given entity in the database.
* This will set its ID field if not already set.
*
* @param entity the entity to insert.
*/
fun persist(entity: Entity) = INSTANCE.persist(entity)
/**
* Update the given entity in the database.
*
* @param entity the entity to update.
*/
fun update(entity: Entity) = INSTANCE.update(entity)
/**
* Persist the given entity in the database or update it if it already exists.
*
* @param entity the entity to update.
*/
fun persistOrUpdate(entity: Entity) = INSTANCE.persistOrUpdate(entity)
/**
* Delete the given entity from the database, if it is already persisted.
*
* @param entity the entity to delete.
* @see [deleteAll]
*/
fun delete(entity: Entity) = INSTANCE.delete(entity)
/**
* Find an entity of this type by ID.
*
* @param id the ID of the entity to find.
* @return the entity found, or `null` if not found.
*/
@GenerateBridge(targetReturnTypeErased = true)
fun findById(id: Id): Entity? = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query, with optional indexed parameters.
*
* @param query a query string
* @param params optional sequence of indexed parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, vararg params: Any?): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query and the given sort options, with optional indexed parameters.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params optional sequence of indexed parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, sort: Sort, vararg params: Any?): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query, with named parameters.
*
* @param query a query string
* @param params [Map] of named parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, params: Map<String, Any?>): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query and the given sort options, with named parameters.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Map] of indexed parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, sort: Sort, params: Map<String, Any?>): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query, with named parameters.
*
* @param query a query string
* @param params [Parameters] of named parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, params: Parameters): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a query and the given sort options, with named parameters.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Parameters] of indexed parameters
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: String, sort: Sort, params: Parameters): PanacheQuery<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query.
*
* @param query a [Document] query
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: Document): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query and a BSON sort.
*
* @param query a [Document] query
* @param sort the [Document] sort
* @return a new [PanacheQuery] instance for the given query
* @see [list]
* @see [stream]
*/
@GenerateBridge
fun find(query: Document, sort: Document): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type.
*
* @return a new [PanacheQuery] instance to find all entities of this type.
* @see [listAll]
* @see [streamAll]
*/
@GenerateBridge
fun findAll(): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type, in the given order.
*
* @param sort the sort order to use
* @return a new [PanacheQuery] instance to find all entities of this type.
* @see [listAll]
* @see [streamAll]
*/
@GenerateBridge
fun findAll(sort: Sort): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with optional indexed parameters.
* This method is a shortcut for `find(query, params).list()`.
*
* @param query a query string
* @param params optional sequence of indexed parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, vararg params: Any?): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with optional indexed parameters.
* This method is a shortcut for `find(query, sort, params).list()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params optional sequence of indexed parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, sort: Sort, vararg params: Any?): List<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with named parameters.
* This method is a shortcut for `find(query, params).list()`.
*
* @param query a query string
* @param params [Map] of named parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, params: Map<String, Any?>): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with named parameters.
* This method is a shortcut for `find(query, sort, params).list()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Map] of indexed parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, sort: Sort, params: Map<String, Any?>): List<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with named parameters.
* This method is a shortcut for `find(query, params).list()`.
*
* @param query a query string
* @param params [Parameters] of named parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, params: Parameters): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with named parameters.
* This method is a shortcut for `find(query, sort, params).list()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Parameters] of indexed parameters
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: String, sort: Sort, params: Parameters): List<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query.
* This method is a shortcut for `find(query).list()`.
*
* @param query a [Document] query
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: Document): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query and a BSON sort.
* This method is a shortcut for `find(query, sort).list()`.
*
* @param query a [Document] query
* @param sort the [Document] sort
* @return a [List] containing all results, without paging
* @see [find]
* @see [stream]
*/
@GenerateBridge
fun list(query: Document, sort: Document): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type.
* This method is a shortcut for `findAll().list()`.
*
* @return a [List] containing all results, without paging
* @see [findAll]
* @see [streamAll]
*/
@GenerateBridge
fun listAll(): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type, in the given order.
* This method is a shortcut for `findAll(sort).list()`.
*
* @param sort the sort order to use
* @return a [List] containing all results, without paging
* @see [findAll]
* @see [streamAll]
*/
@GenerateBridge
fun listAll(sort: Sort): List<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with optional indexed parameters.
* This method is a shortcut for `find(query, params).stream()`.
*
* @param query a query string
* @param params optional sequence of indexed parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, vararg params: Any?): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with optional indexed parameters.
* This method is a shortcut for `find(query, sort, params).stream()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params optional sequence of indexed parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, sort: Sort, vararg params: Any?): Stream<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with named parameters.
* This method is a shortcut for `find(query, params).stream()`.
*
* @param query a query string
* @param params [Map] of named parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, params: Map<String, Any?>): Stream<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with named parameters.
* This method is a shortcut for `find(query, sort, params).stream()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Map] of indexed parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, sort: Sort, params: Map<String, Any?>): Stream<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query, with named parameters.
* This method is a shortcut for `find(query, params).stream()`.
*
* @param query a query string
* @param params [Parameters] of named parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, params: Parameters): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities matching a query and the given sort options, with named parameters.
* This method is a shortcut for `find(query, sort, params).stream()`.
*
* @param query a query string
* @param sort the sort strategy to use
* @param params [Parameters] of indexed parameters
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: String, sort: Sort, params: Parameters): Stream<Entity> =
throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query.
* This method is a shortcut for `find(query).stream()`.
*
* @param query a [Document] query
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: Document): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find entities using a BSON query and a BSON sort.
* This method is a shortcut for `find(query, sort).stream()`.
*
* @param query a [Document] query
* @param sort the [Document] sort
* @return a [Stream] containing all results, without paging
* @see [find]
* @see [list]
*/
@GenerateBridge
fun stream(query: Document, sort: Document): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type.
* This method is a shortcut for `findAll().stream()`.
*
* @return a [Stream] containing all results, without paging
* @see [findAll]
* @see [listAll]
*/
@GenerateBridge
fun streamAll(sort: Sort): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Find all entities of this type, in the given order.
* This method is a shortcut for `findAll(sort).stream()`.
*
* @return a [Stream] containing all results, without paging
* @see [findAll]
* @see [listAll]
*/
@GenerateBridge
fun streamAll(): Stream<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Counts the number of this type of entity in the database.
*
* @return the number of this type of entity in the database.
*/
@GenerateBridge
fun count(): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Counts the number of this type of entity matching the given query, with optional indexed parameters.
*
* @param query a query string
* @param params optional sequence of indexed parameters
* @return the number of entities counted.
*/
@GenerateBridge
fun count(query: String, vararg params: Any?): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Counts the number of this type of entity matching the given query, with named parameters.
*
* @param query a query string
* @param params [Map] of named parameters
* @return the number of entities counted.
*/
@GenerateBridge
fun count(query: String, params: Map<String, Any?>): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Counts the number of this type of entity matching the given query, with named parameters.
*
* @param query a query string
* @param params [Parameters] of named parameters
* @return the number of entities counted.
*/
@GenerateBridge
fun count(query: String, params: Parameters): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Counts the number of this type of entity matching the given query
*
* @param query a [Document] query
* @return the number of entities counted.
*/
@GenerateBridge
fun count(query: Document): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Delete all entities of this type from the database.
*
* @return the number of entities deleted.
* @see [delete]
*/
@GenerateBridge
fun deleteAll(): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Delete an entity of this type by ID.
*
* @param id the ID of the entity to delete.
* @return false if the entity was not deleted (not found).
*/
@GenerateBridge
fun deleteById(id: Id): Boolean = throw INSTANCE.implementationInjectionMissing()
/**
* Delete all entities of this type matching the given query, with optional indexed parameters.
*
* @param query a query string
* @param params optional sequence of indexed parameters
* @return the number of entities deleted.
* @see [deleteAll]
*/
@GenerateBridge
fun delete(query: String, vararg params: Any?): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Delete all entities of this type matching the given query, with named parameters.
*
* @param query a query string
* @param params [Map] of named parameters
* @return the number of entities deleted.
* @see [deleteAll]
*/
@GenerateBridge
fun delete(query: String, params: Map<String, Any?>): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Delete all entities of this type matching the given query, with named parameters.
*
* @param query a query string
* @param params [Parameters] of named parameters
* @return the number of entities deleted.
* @see [deleteAll]
*/
@GenerateBridge
fun delete(query: String, params: Parameters): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Delete all entities of this type matching the given query
*
* @param query a [Document] query
* @return the number of entities counted.
*/
@GenerateBridge
fun delete(query: Document): Long = throw INSTANCE.implementationInjectionMissing()
/**
* Persist all given entities.
*
* @param entities the entities to insert
*/
fun persist(entities: Iterable<Entity>) = INSTANCE.persist(entities)
/**
* Persist all given entities.
*
* @param entities the entities to insert
*/
fun persist(entities: Stream<Entity>) = INSTANCE.persist(entities)
/**
* Persist all given entities.
*
* @param entities the entities to insert
*/
fun persist(firstEntity: Entity, vararg entities: Entity) = INSTANCE.persist(firstEntity, *entities)
/**
* Update all given entities.
*
* @param entities the entities to update
*/
fun update(entities: Iterable<Entity>) = INSTANCE.update(entities)
/**
* Update all given entities.
*
* @param entities the entities to update
*/
fun update(entities: Stream<Entity>) = INSTANCE.update(entities)
/**
* Update all given entities.
*
* @param entities the entities to update
*/
fun update(firstEntity: Entity, vararg entities: Entity) = INSTANCE.update(firstEntity, *entities)
/**
* Persist all given entities or update them if they already exist.
*
* @param entities the entities to update
*/
fun persistOrUpdate(entities: Iterable<Entity>) = INSTANCE.persistOrUpdate(entities)
/**
* Persist all given entities or update them if they already exist.
*
* @param entities the entities to update
*/
fun persistOrUpdate(entities: Stream<Entity>) = INSTANCE.persistOrUpdate(entities)
/**
* Persist all given entities or update them if they already exist.
*
* @param entities the entities to update
*/
fun persistOrUpdate(firstEntity: Entity, vararg entities: Entity) =
INSTANCE.persistOrUpdate(firstEntity, *entities)
/**
* Update all entities of this type by the given update document, with optional indexed parameters.
* The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which documents the update should be applied.
*
* @param update the update document, if it didn't contain any update operator, we add `$set`.
* It can also be expressed as a query string.
* @param params optional sequence of indexed parameters
* @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document
*/
@GenerateBridge
fun update(update: String, vararg params: Any?): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing()
/**
* Update all entities of this type by the given update document, with named parameters.
* The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which documents the update should be applied.
*
* @param update the update document, if it didn't contain any update operator, we add `$set`.
* It can also be expressed as a query string.
* @param params [Map] of named parameters
* @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document
*/
@GenerateBridge
fun update(update: String, params: Map<String, Any?>): io.quarkus.mongodb.panache.common.PanacheUpdate =
throw INSTANCE.implementationInjectionMissing()
/**
* Update all entities of this type by the given update document, with named parameters.
* The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied.
*
* @param update the update document, if it didn't contain any update operator, we add `$set`.
* It can also be expressed as a query string.
* @param params [Parameters] of named parameters
* @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document
*/
@GenerateBridge
fun update(update: String, params: Parameters): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing()
/**
* Update all entities of this type by the given update BSON document.
* The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied.
*
* @param update the update document, as a [Document].
* @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document
*/
@GenerateBridge
fun update(update: Document): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing()
/**
* Allow to access the underlying Mongo Collection
*/
@GenerateBridge
fun mongoCollection(): MongoCollection<Entity> = throw INSTANCE.implementationInjectionMissing()
/**
* Allow to access the underlying Mongo Database.
*/
@GenerateBridge
fun mongoDatabase(): MongoDatabase = throw INSTANCE.implementationInjectionMissing()
}
|
apache-2.0
|
68247737d6ff3f5236d7be453d50267f
| 35.281525 | 150 | 0.662706 | 4.413842 | false | false | false | false |
abdodaoud/Merlin
|
app/src/main/java/com/abdodaoud/merlin/data/db/FactDb.kt
|
1
|
2024
|
package com.abdodaoud.merlin.data.db
import com.abdodaoud.merlin.domain.datasource.FactDataSource
import com.abdodaoud.merlin.domain.model.Fact
import com.abdodaoud.merlin.domain.model.FactList
import com.abdodaoud.merlin.extensions.*
import org.jetbrains.anko.db.SqlOrderDirection
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.select
import java.util.*
class FactDb(val factDbHelper: FactDbHelper = FactDbHelper.instance,
val dataMapper: DbDataMapper = DbDataMapper()) : FactDataSource {
override fun requestDayFact(id: Long): Fact? = factDbHelper.use {
val fact = select(DayFactTable.NAME).byId(id).
parseOpt { DayFact(HashMap(it)) }
fact?.let { dataMapper.convertDayToDomain(it) }
}
override fun request(date: Long, currentPage: Int, lastDate: Long) = factDbHelper.use {
var maxDate = date
var minDate = date
if (currentPage == -1) {
minDate = lastDate.future()
} else {
maxDate = date.maxDate(currentPage)
minDate = date.minDate(currentPage)
}
val dailyFact = select(DayFactTable.NAME)
.where("${DayFactTable.DATE} <= " + maxDate.toString() + " AND " +
"${DayFactTable.DATE} >= " + minDate.toString())
.orderBy(DayFactTable.DATE, SqlOrderDirection.DESC)
.parseList { DayFact(HashMap(it)) }
val mainFacts = select(MainFactsTable.NAME)
.whereSimple("${MainFactsTable.ID} = ?", "-1")
.parseOpt { MainFacts(HashMap(it), dailyFact) }
mainFacts?.let { dataMapper.convertToDomain(it) }
}
fun saveFact(facts: FactList) = factDbHelper.use {
clear(MainFactsTable.NAME)
clear(DayFactTable.NAME)
with(dataMapper.convertFromDomain(facts)) {
insert(MainFactsTable.NAME, *map.toVarargArray())
dailyFact.forEach { insert(DayFactTable.NAME, *it.map.toVarargArray()) }
}
}
}
|
mit
|
a54baf94631d6ca6f514594549fb810e
| 35.160714 | 91 | 0.636858 | 3.855238 | false | false | false | false |
rei-m/android_hyakuninisshu
|
feature/corecomponent/src/main/java/me/rei_m/hyakuninisshu/feature/corecomponent/helper/bindingadapters/TextViewBindingAdapters.kt
|
1
|
1680
|
/*
* Copyright (c) 2020. Rei Matsushita
*
* 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.
*/
/* ktlint-disable package-name */
package me.rei_m.hyakuninisshu.feature.corecomponent.helper.bindingadapters
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import androidx.databinding.BindingAdapter
import com.google.android.material.textview.MaterialTextView
@BindingAdapter("textKamiNoKuKana", "kimariji")
fun setTextKamiNoKuKana(
view: MaterialTextView,
kamiNoKu: String?,
kimariji: Int?
) {
if (kamiNoKu == null || kimariji == null) {
return
}
var finallyKimariji = 0
for (i in 0 until kamiNoKu.length - 1) {
if (kamiNoKu.substring(i, i + 1) == " ") {
finallyKimariji++
} else {
if (kimariji < i) {
break
}
}
finallyKimariji++
}
val ssb = SpannableStringBuilder().append(kamiNoKu)
ssb.setSpan(
ForegroundColorSpan(Color.RED),
0,
finallyKimariji - 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
view.text = ssb
}
|
apache-2.0
|
76c3b2e10eb2fc07fea98259b2bed692
| 30.660377 | 112 | 0.686532 | 3.866359 | false | false | false | false |
k-r-g/FrameworkBenchmarks
|
frameworks/Kotlin/ktor/src/main/kotlin/org/jetbrains/ktor/benchmarks/Hello.kt
|
7
|
5291
|
package org.jetbrains.ktor.benchmarks
import com.google.gson.*
import com.mysql.jdbc.*
import com.zaxxer.hikari.*
import kotlinx.coroutines.experimental.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.content.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.util.*
import java.sql.ResultSet.*
import java.util.concurrent.*
import java.util.concurrent.atomic.*
import javax.sql.*
data class Message(val message: String = "Hello, World!")
data class World(val id: Int, var randomNumber: Int)
fun Application.main() {
val (a, b) = hex("62656e63686d61726b6462757365723a62656e63686d61726b646270617373").toString(Charsets.ISO_8859_1).split(":")
val gson = GsonBuilder().create()
val DbRows = 10000
Driver::class.java.newInstance()
val pool by lazy {
val dbHost = System.getenv("DBHOST") ?: error("DBHOST environment variable is not set")
hikari(dbHost, a, b)
}
val counter = AtomicInteger()
val databaseExecutor = Executors.newFixedThreadPool(256) { r ->
Thread(r, "db-${counter.incrementAndGet()}-thread")
}
val databaseDispatcher = databaseExecutor.asCoroutineDispatcher()
install(SamplingCallLogging) {
samplingFactor = 50000L
}
install(DefaultHeaders)
routing {
get("/plaintext") { call ->
call.respond(TextContent("Hello, World!", ContentType.Text.Plain, HttpStatusCode.OK))
}
get("/json") { call ->
call.respond(TextContent(gson.toJson(Message()), ContentType.Application.Json, HttpStatusCode.OK))
}
get("/db") { call ->
val response = run(databaseDispatcher) {
pool.connection.use { connection ->
val random = ThreadLocalRandom.current()
val queries = call.queries()
val result = mutableListOf<World>()
connection.prepareStatement("SELECT * FROM World WHERE id = ?", TYPE_FORWARD_ONLY, CONCUR_READ_ONLY).use { statement ->
for (i in 1..(queries ?: 1)) {
statement.setInt(1, random.nextInt(DbRows) + 1)
statement.executeQuery().use { rs ->
while (rs.next()) {
result += World(rs.getInt("id"), rs.getInt("randomNumber"))
}
}
}
TextContent(gson.toJson(when (queries) {
null -> result.single()
else -> result
}), ContentType.Application.Json, HttpStatusCode.OK)
}
}
}
call.respond(response)
}
get("/updates") {
val t = run(databaseDispatcher) {
pool.connection.use { connection ->
val queries = call.queries()
val random = ThreadLocalRandom.current()
val result = mutableListOf<World>()
connection.prepareStatement("SELECT * FROM World WHERE id = ?", TYPE_FORWARD_ONLY, CONCUR_READ_ONLY).use { statement ->
for (i in 1..(queries ?: 1)) {
statement.setInt(1, random.nextInt(DbRows) + 1)
statement.executeQuery().use { rs ->
while (rs.next()) {
result += World(rs.getInt("id"), rs.getInt("randomNumber"))
}
}
}
}
result.forEach { it.randomNumber = random.nextInt(DbRows) + 1 }
connection.prepareStatement("UPDATE World SET randomNumber = ? WHERE id = ?").use { updateStatement ->
for ((id, randomNumber) in result) {
updateStatement.setInt(1, randomNumber)
updateStatement.setInt(2, id)
updateStatement.executeUpdate()
}
}
TextContent(gson.toJson(when (queries) {
null -> result.single()
else -> result
}), ContentType.Application.Json, HttpStatusCode.OK)
}
}
call.respond(t)
}
}
}
fun ApplicationCall.queries() = try {
request.queryParameters["queries"]?.toInt()?.coerceIn(1, 500)
} catch (nfe: NumberFormatException) {
1
}
private fun hikari(dbHost: String, a: String, b: String): DataSource {
val config = HikariConfig()
config.jdbcUrl = "jdbc:mysql://$dbHost:3306/hello_world?useSSL=false"
config.username = a
config.password = b
config.addDataSourceProperty("cachePrepStmts", "true")
config.addDataSourceProperty("prepStmtCacheSize", "250")
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
config.driverClassName = Driver::class.java.name
config.connectionTimeout = 10000
config.maximumPoolSize = 100
return HikariDataSource(config)
}
|
bsd-3-clause
|
3042e9754e5ef1f84ec5705d767f7011
| 36.792857 | 139 | 0.544321 | 4.854128 | false | true | false | false |
Gu3pardo/PasswordSafe-AndroidClient
|
mobile/src/main/java/guepardoapps/passwordsafe/models/securityquestions/SecurityQuestion.kt
|
1
|
1543
|
package guepardoapps.passwordsafe.models.securityquestions
import guepardoapps.passwordsafe.annotations.CsvEntry
import guepardoapps.passwordsafe.enums.ModelState
internal class SecurityQuestion {
@CsvEntry(0, "Id")
lateinit var id: String
@CsvEntry(1, "UserId")
lateinit var userId: String
@CsvEntry(2, "AccountId")
lateinit var accountId: String
@CsvEntry(3, "Question")
lateinit var question: String
@CsvEntry(4, "Answer")
lateinit var answer: String
@CsvEntry(5, "ModelState")
var modelState: ModelState = ModelState.Null
fun isSameAs(securityQuestion: SecurityQuestion?): Boolean {
return securityQuestion == null
|| (this.id == securityQuestion.id
&& this.userId == securityQuestion.userId
&& this.accountId == securityQuestion.accountId
&& this.question == securityQuestion.question
&& this.answer == securityQuestion.answer)
}
companion object {
fun clone(securityQuestion: SecurityQuestion): SecurityQuestion {
return SecurityQuestion()
.apply {
id = securityQuestion.id
userId = securityQuestion.userId
accountId = securityQuestion.accountId
question = securityQuestion.question
answer = securityQuestion.answer
modelState = securityQuestion.modelState
}
}
}
}
|
mit
|
1ba46a4ed7a35b10671f10e7cabb7eb3
| 31.851064 | 73 | 0.608555 | 5.395105 | false | false | false | false |
envoyproxy/envoy
|
mobile/library/kotlin/io/envoyproxy/envoymobile/filters/Filter.kt
|
2
|
7928
|
package io.envoyproxy.envoymobile
import io.envoyproxy.envoymobile.engine.types.EnvoyFinalStreamIntel
import io.envoyproxy.envoymobile.engine.types.EnvoyHTTPFilter
import io.envoyproxy.envoymobile.engine.types.EnvoyHTTPFilterCallbacks
import io.envoyproxy.envoymobile.engine.types.EnvoyHTTPFilterFactory
import io.envoyproxy.envoymobile.engine.types.EnvoyStreamIntel
import java.nio.ByteBuffer
/*
* Interface representing a filter. See `RequestFilter` and `ResponseFilter` for more details.
*/
@Suppress("EmptyClassBlock")
interface Filter
internal class FilterFactory(
private val filterName: String,
private val factory: () -> Filter
) : EnvoyHTTPFilterFactory {
override fun getFilterName(): String {
return filterName
}
override fun create(): EnvoyHTTPFilter { return EnvoyHTTPFilterAdapter(factory()) }
}
internal class EnvoyHTTPFilterAdapter(
private val filter: Filter
) : EnvoyHTTPFilter {
override fun onRequestHeaders(headers: Map<String, List<String>>, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? RequestFilter)?.let { requestFilter ->
val result = requestFilter.onRequestHeaders(RequestHeaders(headers), endStream, StreamIntel(streamIntel))
return when (result) {
is FilterHeadersStatus.Continue -> arrayOf(result.status, result.headers.caseSensitiveHeaders())
is FilterHeadersStatus.StopIteration -> arrayOf(result.status, emptyMap<String, List<String>>())
}
}
return arrayOf(0, headers)
}
override fun onResponseHeaders(headers: Map<String, List<String>>, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? ResponseFilter)?.let { responseFilter ->
val result = responseFilter.onResponseHeaders(ResponseHeaders(headers), endStream, StreamIntel(streamIntel))
return when (result) {
is FilterHeadersStatus.Continue -> arrayOf(result.status, result.headers.caseSensitiveHeaders())
is FilterHeadersStatus.StopIteration -> arrayOf(result.status, emptyMap<String, List<String>>())
}
}
return arrayOf(0, headers)
}
override fun onRequestData(data: ByteBuffer, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? RequestFilter)?.let { requestFilter ->
val result = requestFilter.onRequestData(data, endStream, StreamIntel(streamIntel))
return when (result) {
is FilterDataStatus.Continue<*> -> arrayOf(result.status, result.data)
is FilterDataStatus.StopIterationAndBuffer<*> -> arrayOf(result.status, ByteBuffer.allocate(0))
is FilterDataStatus.StopIterationNoBuffer<*> -> arrayOf(result.status, ByteBuffer.allocate(0))
is FilterDataStatus.ResumeIteration<*> -> arrayOf(result.status, result.data, result.headers?.caseSensitiveHeaders())
}
}
return arrayOf(0, data)
}
override fun onResponseData(data: ByteBuffer, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? ResponseFilter)?.let { responseFilter ->
val result = responseFilter.onResponseData(data, endStream, StreamIntel(streamIntel))
return when (result) {
is FilterDataStatus.Continue<*> -> arrayOf(result.status, result.data)
is FilterDataStatus.StopIterationAndBuffer<*> -> arrayOf(result.status, ByteBuffer.allocate(0))
is FilterDataStatus.StopIterationNoBuffer<*> -> arrayOf(result.status, ByteBuffer.allocate(0))
is FilterDataStatus.ResumeIteration<*> -> arrayOf(result.status, result.data, result.headers?.caseSensitiveHeaders())
}
}
return arrayOf(0, data)
}
override fun onRequestTrailers(trailers: Map<String, List<String>>, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? RequestFilter)?.let { requestFilter ->
val result = requestFilter.onRequestTrailers(RequestTrailers(trailers), StreamIntel(streamIntel))
return when (result) {
is FilterTrailersStatus.Continue<*, *> -> arrayOf(result.status, result.trailers.caseSensitiveHeaders())
is FilterTrailersStatus.StopIteration<*, *> -> arrayOf(result.status, emptyMap<String, List<String>>())
is FilterTrailersStatus.ResumeIteration<*, *> -> arrayOf(result.status, result.trailers.caseSensitiveHeaders(), result.headers?.caseSensitiveHeaders(), result.data)
}
}
return arrayOf(0, trailers)
}
override fun onResponseTrailers(trailers: Map<String, List<String>>, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? ResponseFilter)?.let { responseFilter ->
val result = responseFilter.onResponseTrailers(ResponseTrailers(trailers), StreamIntel(streamIntel))
return when (result) {
is FilterTrailersStatus.Continue<*, *> -> arrayOf(result.status, result.trailers.caseSensitiveHeaders())
is FilterTrailersStatus.StopIteration<*, *> -> arrayOf(result.status, emptyMap<String, List<String>>())
is FilterTrailersStatus.ResumeIteration<*, *> -> arrayOf(result.status, result.trailers.caseSensitiveHeaders(), result.headers?.caseSensitiveHeaders(), result.data)
}
}
return arrayOf(0, trailers)
}
override fun onError(errorCode: Int, message: String, attemptCount: Int, streamIntel: EnvoyStreamIntel, finalStreamIntel: EnvoyFinalStreamIntel) {
(filter as? ResponseFilter)?.let { responseFilter ->
responseFilter.onError(EnvoyError(errorCode, message, attemptCount), FinalStreamIntel(streamIntel, finalStreamIntel))
}
}
override fun onCancel(streamIntel: EnvoyStreamIntel, finalStreamIntel: EnvoyFinalStreamIntel) {
(filter as? ResponseFilter)?.let { responseFilter ->
responseFilter.onCancel(FinalStreamIntel(streamIntel, finalStreamIntel))
}
}
override fun onComplete(streamIntel: EnvoyStreamIntel, finalStreamIntel: EnvoyFinalStreamIntel) {
(filter as? ResponseFilter)?.let { responseFilter ->
responseFilter.onComplete(FinalStreamIntel(streamIntel, finalStreamIntel))
}
}
override fun setRequestFilterCallbacks(callbacks: EnvoyHTTPFilterCallbacks) {
(filter as? AsyncRequestFilter)?.let { asyncRequestFilter ->
asyncRequestFilter.setRequestFilterCallbacks(RequestFilterCallbacksImpl(callbacks))
}
}
override fun onResumeRequest(headers: Map<String, List<String>>?, data: ByteBuffer?, trailers: Map<String, List<String>>?, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? AsyncRequestFilter)?.let { asyncRequestFilter ->
val result = asyncRequestFilter.onResumeRequest(
headers?.let(::RequestHeaders),
data,
trailers?.let(::RequestTrailers),
endStream,
StreamIntel(streamIntel)
)
return when (result) {
is FilterResumeStatus.ResumeIteration<*, *> -> arrayOf(result.status, result.headers?.caseSensitiveHeaders(), result.data, result.trailers?.caseSensitiveHeaders())
}
}
return arrayOf(-1, headers, data, trailers)
}
override fun setResponseFilterCallbacks(callbacks: EnvoyHTTPFilterCallbacks) {
(filter as? AsyncResponseFilter)?.let { asyncResponseFilter ->
asyncResponseFilter.setResponseFilterCallbacks(ResponseFilterCallbacksImpl(callbacks))
}
}
override fun onResumeResponse(headers: Map<String, List<String>>?, data: ByteBuffer?, trailers: Map<String, List<String>>?, endStream: Boolean, streamIntel: EnvoyStreamIntel): Array<Any?> {
(filter as? AsyncResponseFilter)?.let { asyncResponseFilter ->
val result = asyncResponseFilter.onResumeResponse(
headers?.let(::ResponseHeaders),
data,
trailers?.let(::ResponseTrailers),
endStream,
StreamIntel(streamIntel)
)
return when (result) {
is FilterResumeStatus.ResumeIteration<*, *> -> arrayOf(result.status, result.headers?.caseSensitiveHeaders(), result.data, result.trailers?.caseSensitiveHeaders())
}
}
return arrayOf(-1, headers, data, trailers)
}
}
|
apache-2.0
|
194d8f863a43180d10ae5638e29f61cb
| 47.341463 | 191 | 0.732719 | 4.481628 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/way_lit/WayLitForm.kt
|
1
|
1259
|
package de.westnordost.streetcomplete.quests.way_lit
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.mapdata.Way
import de.westnordost.streetcomplete.ktx.isArea
import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment
import de.westnordost.streetcomplete.quests.way_lit.WayLit.*
import de.westnordost.streetcomplete.quests.AnswerItem
class WayLitForm : AbstractQuestAnswerFragment<WayLitOrIsStepsAnswer>() {
override val buttonPanelAnswers = listOf(
AnswerItem(R.string.quest_generic_hasFeature_no) { applyAnswer(NO) },
AnswerItem(R.string.quest_generic_hasFeature_yes) { applyAnswer(YES) }
)
override val otherAnswers get() = listOfNotNull(
AnswerItem(R.string.quest_way_lit_24_7) { applyAnswer(NIGHT_AND_DAY) },
AnswerItem(R.string.quest_way_lit_automatic) { applyAnswer(AUTOMATIC) },
createConvertToStepsAnswer(),
)
private fun createConvertToStepsAnswer(): AnswerItem? {
val way = osmElement as? Way ?: return null
if (way.isArea() || way.tags["highway"] == "steps") return null
return AnswerItem(R.string.quest_generic_answer_is_actually_steps) {
applyAnswer(IsActuallyStepsAnswer)
}
}
}
|
gpl-3.0
|
4908c7d81b6a1b06e25a793de1e50963
| 39.612903 | 80 | 0.735504 | 4.114379 | false | false | false | false |
binaryfoo/emv-bertlv
|
src/main/java/io/github/binaryfoo/cmdline/Main.kt
|
1
|
1952
|
package io.github.binaryfoo.cmdline
import io.github.binaryfoo.RootDecoder
import io.github.binaryfoo.TagInfo
import io.github.binaryfoo.decoders.DecodeSession
import java.io.BufferedReader
import java.io.InputStreamReader
/**
* Command line too for parsing a few flavours of chip card data.
*/
class Main {
companion object {
@JvmStatic
fun main(args: Array<String>) {
if (args.size < 2) {
printHelp()
System.exit(1)
}
val tag = args[0]
val value = args[1]
val meta = if (args.size > 2) args[2] else "EMV"
val rootDecoder = RootDecoder()
val decodeSession = DecodeSession()
decodeSession.tagMetaData = rootDecoder.getTagMetaData(meta)
val tagInfo = RootDecoder.getTagInfo(tag)
if (tagInfo == null) {
println("Unknown tag $tag")
printHelp()
} else {
if (value == "-") {
val reader = BufferedReader(InputStreamReader(System.`in`))
while (true) {
val line = reader.readLine() ?: break
decodeValue(line, decodeSession, tagInfo)
}
} else {
decodeValue(value, decodeSession, tagInfo)
}
}
}
private fun decodeValue(value: String, decodeSession: DecodeSession, tagInfo: TagInfo) {
val decoded = tagInfo.decoder.decode(value, 0, decodeSession)
DecodedWriter(System.out).write(decoded, "")
}
private fun printHelp() {
System.out.println("Usage Main <decode-type> <value> [<tag-set>]")
System.out.println(" <decode-type> is one of")
for (tag in RootDecoder.getSupportedTags()) {
System.out.println(" " + tag.key + ": " + tag.value.shortName)
}
System.out.println(" <value> is the hex string or '-' for standard input")
System.out.println(" <tag-set> is one of " + RootDecoder.getAllTagMeta() + " defaults to EMV")
}
}
}
fun main(args: Array<String>) = Main.main(args)
|
mit
|
72cd0dd33dcbfa91f07159b0eee95f06
| 31 | 101 | 0.622951 | 3.834971 | false | false | false | false |
sbhachu/kotlin-bootstrap
|
app/src/main/kotlin/com/sbhachu/bootstrap/presentation/main/MainActivity.kt
|
1
|
2725
|
package com.sbhachu.bootstrap.presentation.main
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.MenuItem
import android.view.View
import com.sbhachu.bootstrap.R
import com.sbhachu.bootstrap.presentation.common.BaseActivity
class MainActivity : BaseActivity<MainPresenter>(), IMainViewContract, NavigationView.OnNavigationItemSelectedListener {
private val TAG: String = "MainActivity"
override var layoutId: Int = R.layout.activity_main
private var navigationView: NavigationView? = null
private var drawerLayout: DrawerLayout? = null
private var toolbar: Toolbar? = null
override fun initialisePresenter(): MainPresenter {
return MainPresenter(this)
}
override fun initialiseViews(): Unit {
Log.d(TAG, "initialiseViews()")
navigationView = findViewById(R.id.navigation_view) as NavigationView?
drawerLayout = findViewById(R.id.navigation_drawer) as DrawerLayout?
toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
supportActionBar?.setTitle(R.string.app_name)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun initialiseListeners(): Unit {
Log.d(TAG, "initialiseListeners()")
navigationView?.setNavigationItemSelectedListener(this)
}
override fun handleExtras(bundle: Bundle?): Unit {
Log.d(TAG, "handleExtras()")
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
drawerLayout?.closeDrawers()
when (item.itemId) {
R.id.screen_1 -> showSnackbar(getString(R.string.screen_1), Snackbar.LENGTH_LONG, getString(R.string.dismiss), hideSnackbar())
R.id.screen_2 -> showSnackbar(getString(R.string.screen_2), Snackbar.LENGTH_LONG, getString(R.string.dismiss), hideSnackbar())
R.id.screen_3 -> showSnackbar(getString(R.string.screen_3), Snackbar.LENGTH_LONG, getString(R.string.dismiss), hideSnackbar())
else -> return false
}
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId) {
android.R.id.home -> {
drawerLayout?.openDrawer(GravityCompat.START)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
|
apache-2.0
|
337bff1835da25e220e167d538ba9115
| 34.851351 | 138 | 0.686606 | 4.698276 | false | false | false | false |
debop/debop4k
|
debop4k-core/src/main/kotlin/debop4k/core/collections/permutations/Nil.kt
|
1
|
3111
|
/*
* 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.collections.permutations
import java.lang.IndexOutOfBoundsException
import java.util.*
/**
* Permutation 의 종료를 나타내는 클래스입니다.
* @author [email protected]
*/
class Nil<T> : Permutation<T>() {
companion object {
@JvmField val NIL: Nil<Any> = Nil<Any>()
@Suppress("UNCHECKED_CAST")
@JvmStatic fun <T> instance(): Nil<T> = NIL as Nil<T>
}
override val head: T
get() = throw NoSuchElementException("head of empty sequence")
// override val headOption: Option<T>
// get() = Option.None
override val tail: Permutation<T>
get() = throw NoSuchElementException("tail of empty sequence")
override val isTailDefined: Boolean
get() = false
override fun get(index: Int): T = throw IndexOutOfBoundsException(index.toString())
override fun <R> map(mapper: (T) -> R): Permutation<R> = instance()
override fun filter(predicate: (T) -> Boolean): Permutation<T> = instance()
override fun <R> flatMap(mapper: (T) -> Iterable<R>): Permutation<R> = instance()
override fun takeUnsafe(maxSize: Long): Permutation<T> = instance()
override fun dropUnsafe(startInclusive: Long): Permutation<T> = instance()
override fun forEach(action: (T) -> Unit) {
/* Nothing to do */
}
override fun max(comparator: Comparator<in T>): T? = null
override fun min(comparator: Comparator<in T>): T? = null
override val size: Int get() = 0
override fun anyMatch(predicate: (T) -> Boolean): Boolean = false
override fun allMatch(predicate: (T) -> Boolean): Boolean = true
override fun noneMatch(predicate: (T) -> Boolean): Boolean = true
override fun <S, R> zip(second: Permutation<S>, zipper: (T, S) -> R): Permutation<R> = instance()
override fun takeWhile(predicate: (T) -> Boolean): Permutation<T> = instance()
override fun dropWhile(predicate: (T) -> Boolean): Permutation<T> = instance()
override fun slidingUnsafe(size: Long): Permutation<List<T>> = instance()
override fun groupedUnsafe(size: Long): Permutation<List<T>> = instance()
override fun scan(initial: T, binFunc: (T, T) -> T): Permutation<T> = permutationOf(initial)
override fun distinct(): Permutation<T> = instance()
override fun startsWith(iterator: Iterator<T>): Boolean = !iterator.hasNext()
override fun force(): Permutation<T> = this
override fun equals(other: Any?): Boolean = other is Nil<*>
override fun hashCode(): Int = Nil.hashCode()
override fun isEmpty(): Boolean = true
}
|
apache-2.0
|
b4d0be7bc75817a4a57dfeff15f14d8f
| 35.282353 | 99 | 0.698021 | 3.810878 | false | false | false | false |
soniccat/android-taskmanager
|
storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/clients/CacheStatus.kt
|
1
|
755
|
package com.example.alexeyglushkov.cachemanager.clients
import com.example.alexeyglushkov.cachemanager.clients.Cache.CacheMode
/**
* Created by alexeyglushkov on 03.03.18.
*/
object CacheStatus {
fun canLoadFromCache(cache: Cache?): Boolean {
if (cache == null) {
return false
}
val cacheMode = cache.cacheMode
return cacheMode != CacheMode.IGNORE_CACHE &&
cacheMode != CacheMode.ONLY_STORE_TO_CACHE
}
fun canWriteToCache(client: Cache?): Boolean {
if (client == null) {
return false
}
val cacheMode = client.cacheMode
return cacheMode != CacheMode.IGNORE_CACHE &&
cacheMode != CacheMode.ONLY_LOAD_FROM_CACHE
}
}
|
mit
|
df9f8ee44a4887b96e036afeff33c0ae
| 26 | 70 | 0.622517 | 4.415205 | false | false | false | false |
soniccat/android-taskmanager
|
authorization/src/main/java/com/example/alexeyglushkov/authorization/OAuth/Token.kt
|
1
|
2200
|
package com.example.alexeyglushkov.authorization.OAuth
import org.junit.Assert
import java.io.Serializable
class Token @JvmOverloads constructor(token: String, secret: String, rawResponse: String? = null) : Serializable {
val token: String
val secret: String
private val rawResponse: String?
fun getRawResponse(): String {
checkNotNull(rawResponse) { "This token object was not constructed by scribe and does not have a rawResponse" }
return rawResponse
}
fun getParameter(parameter: String): String? {
var value: String? = null
for (str in getRawResponse().split("&").toTypedArray()) {
if (str.startsWith("$parameter=")) {
val part = str.split("=").toTypedArray()
if (part.size > 1) {
value = part[1].trim { it <= ' ' }
}
break
}
}
return value
}
override fun toString(): String {
return String.format("Token[%s , %s]", token, secret)
}
/**
* Returns true if the token is empty (token = "", secret = "")
*/
val isEmpty: Boolean
get() = "" == token && "" == secret
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val that = o as Token
return token == that.token && secret == that.secret
}
override fun hashCode(): Int {
return 31 * token.hashCode() + 31 * secret.hashCode()
}
companion object {
private const val serialVersionUID = 715000866082812683L
/**
* Factory method that returns an empty token (token = "", secret = "").
*
* Useful for two legged OAuth.
*/
fun empty(): Token {
return Token("", "")
}
}
/**
* Default constructor
*
* @param token token value. Can't be null.
* @param secret token secret. Can't be null.
*/
init {
Assert.assertNotNull(token)
Assert.assertNotNull(secret)
this.token = token
this.secret = secret
this.rawResponse = rawResponse
}
}
|
mit
|
18afccbe60ea82b9ece34cc5969e3049
| 27.960526 | 119 | 0.556818 | 4.592902 | false | false | false | false |
nemerosa/ontrack
|
ontrack-service/src/main/java/net/nemerosa/ontrack/service/ordering/VersionBranchOrdering.kt
|
1
|
2387
|
package net.nemerosa.ontrack.service.ordering
import net.nemerosa.ontrack.common.Version
import net.nemerosa.ontrack.common.toVersion
import net.nemerosa.ontrack.model.ordering.BranchOrdering
import net.nemerosa.ontrack.model.structure.Branch
import net.nemerosa.ontrack.model.structure.BranchDisplayNameService
import org.springframework.stereotype.Component
/**
* Branch ordering based on a [Version] extracted from the branch name or SCM path. Branches where a version
* cannot be extracted are classified alphabetically and put at the end.
*/
@Component
class VersionBranchOrdering(
val branchDisplayNameService: BranchDisplayNameService
) : BranchOrdering {
override val id: String = "version"
override fun getComparator(param: String?): Comparator<Branch> {
return if (param != null && param.isNotBlank()) {
val regex = param.toRegex()
compareByDescending { it.getVersion(regex) }
} else {
throw IllegalArgumentException("`param` argument for the version branch ordering is required.")
}
}
private fun Branch.getVersion(regex: Regex): VersionOrString {
// Path to use for the branch
val path: String = branchDisplayNameService.getBranchDisplayName(this)
// Path first, then name, then version = name
return getVersion(regex, path) ?: getVersion(regex, name) ?: VersionOrString(null)
}
private fun getVersion(regex: Regex, path: String): VersionOrString? {
val matcher = regex.matchEntire(path)
if (matcher != null && matcher.groupValues.size >= 2) {
// Getting the first group
val token = matcher.groupValues[1]
// Converting to a version
val version = token.toVersion()
// ... and using it if not null
if (version != null) {
return VersionOrString(version)
}
}
// Nothing
return null
}
private class VersionOrString(
val version: Version?
) : Comparable<VersionOrString> {
override fun compareTo(other: VersionOrString): Int {
return if (version != null && other.version != null) {
version.compareTo(other.version)
} else if (version != null) {
1
} else {
-1
}
}
}
}
|
mit
|
6cb03ef9daf5eccb77360bef3ec25149
| 35.181818 | 108 | 0.63762 | 4.726733 | false | false | false | false |
nemerosa/ontrack
|
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/service/GitServiceImpl.kt
|
1
|
46139
|
package net.nemerosa.ontrack.extension.git.service
import net.nemerosa.ontrack.common.FutureUtils
import net.nemerosa.ontrack.common.asOptional
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.extension.api.model.BuildDiffRequest
import net.nemerosa.ontrack.extension.api.model.BuildDiffRequestDifferenceProjectException
import net.nemerosa.ontrack.extension.git.GitConfigProperties
import net.nemerosa.ontrack.extension.git.branching.BranchingModelService
import net.nemerosa.ontrack.extension.git.model.*
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationProperty
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationPropertyType
import net.nemerosa.ontrack.extension.git.repository.GitRepositoryHelper
import net.nemerosa.ontrack.extension.git.support.NoGitCommitPropertyException
import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService
import net.nemerosa.ontrack.extension.issues.model.Issue
import net.nemerosa.ontrack.extension.issues.model.IssueServiceNotConfiguredException
import net.nemerosa.ontrack.extension.scm.model.SCMBuildView
import net.nemerosa.ontrack.extension.scm.model.SCMChangeLogFileChangeType
import net.nemerosa.ontrack.extension.scm.model.SCMPathInfo
import net.nemerosa.ontrack.extension.scm.service.AbstractSCMChangeLogService
import net.nemerosa.ontrack.extension.scm.service.SCMUtilsService
import net.nemerosa.ontrack.git.GitRepositoryClient
import net.nemerosa.ontrack.git.GitRepositoryClientFactory
import net.nemerosa.ontrack.git.exceptions.GitRepositorySyncException
import net.nemerosa.ontrack.git.model.*
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.security.ProjectConfig
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.model.support.*
import net.nemerosa.ontrack.tx.TransactionService
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import java.lang.String.format
import java.time.Duration
import java.util.*
import java.util.concurrent.Future
import java.util.function.BiConsumer
import java.util.stream.Stream
@Service
@Transactional
class GitServiceImpl(
structureService: StructureService,
propertyService: PropertyService,
private val jobScheduler: JobScheduler,
private val securityService: SecurityService,
private val transactionService: TransactionService,
private val applicationLogService: ApplicationLogService,
private val gitRepositoryClientFactory: GitRepositoryClientFactory,
private val buildGitCommitLinkService: BuildGitCommitLinkService,
private val gitConfigurators: Collection<GitConfigurator>,
private val scmService: SCMUtilsService,
private val gitRepositoryHelper: GitRepositoryHelper,
private val branchingModelService: BranchingModelService,
private val entityDataService: EntityDataService,
private val gitConfigProperties: GitConfigProperties,
private val gitPullRequestCache: DefaultGitPullRequestCache,
transactionManager: PlatformTransactionManager
) : AbstractSCMChangeLogService<GitConfiguration, GitBuildInfo, GitChangeLogIssue>(structureService, propertyService), GitService, JobOrchestratorSupplier {
private val logger = LoggerFactory.getLogger(GitService::class.java)
private val transactionTemplate = TransactionTemplate(transactionManager)
override fun forEachConfiguredProject(consumer: BiConsumer<Project, GitConfiguration>) {
structureService.projectList
.forEach { project ->
val configuration = getProjectConfiguration(project)
if (configuration != null) {
consumer.accept(project, configuration)
}
}
}
override fun forEachConfiguredBranch(consumer: BiConsumer<Branch, GitBranchConfiguration>) {
for (project in structureService.projectList) {
forEachConfiguredBranchInProject(project, consumer::accept)
}
}
override fun forEachConfiguredBranchInProject(project: Project, consumer: (Branch, GitBranchConfiguration) -> Unit) {
structureService.getBranchesForProject(project.id)
.forEach { branch ->
val configuration = getBranchConfiguration(branch)
if (configuration != null) {
consumer(branch, configuration)
}
}
}
override fun collectJobRegistrations(): Stream<JobRegistration> {
val jobs = ArrayList<JobRegistration>()
// Indexation of repositories, based on projects actually linked
forEachConfiguredProject(BiConsumer { project, configuration ->
if (!project.isDisabled) {
jobs.add(getGitIndexationJobRegistration(configuration))
}
})
// Synchronisation of branch builds with tags when applicable
forEachConfiguredBranch(BiConsumer { branch, branchConfiguration ->
if (!branch.isDisabled && !branch.project.isDisabled) {
// Build/tag sync job
if (branchConfiguration.buildTagInterval > 0 && branchConfiguration.buildCommitLink?.link is IndexableBuildGitCommitLink<*>) {
jobs.add(
JobRegistration.of(createBuildSyncJob(branch))
.everyMinutes(branchConfiguration.buildTagInterval.toLong())
)
}
}
})
// OK
return jobs.stream()
}
override fun isBranchConfiguredForGit(branch: Branch): Boolean {
return getBranchConfiguration(branch) != null
}
override fun launchBuildSync(branchId: ID, synchronous: Boolean): Future<*>? {
// Gets the branch
val branch = structureService.getBranch(branchId)
// Gets its configuration
val branchConfiguration = getBranchConfiguration(branch)
// If valid, launches a job
return if (branchConfiguration != null && branchConfiguration.buildCommitLink?.link is IndexableBuildGitCommitLink<*>) {
if (synchronous) {
buildSync<Any>(branch, branchConfiguration, JobRunListener.logger(logger))
null
} else {
jobScheduler.fireImmediately(getGitBranchSyncJobKey(branch)).orElse(null)
}
} else {
null
}
}
@Transactional
override fun changeLog(request: BuildDiffRequest): GitChangeLog {
transactionService.start().use { ignored ->
// Gets the two builds
var buildFrom = structureService.getBuild(request.from!!)
var buildTo = structureService.getBuild(request.to!!)
// Ordering of builds
if (buildFrom.id() > buildTo.id()) {
val t = buildFrom
buildFrom = buildTo
buildTo = t
}
// Gets the two associated projects
val project = buildFrom.branch.project
val otherProject = buildTo.branch.project
// Checks the project
if (project.id() != otherProject.id()) {
throw BuildDiffRequestDifferenceProjectException()
}
// Project Git configuration
val oProjectConfiguration = getProjectConfiguration(project)
if (oProjectConfiguration != null) {
// Forces Git sync before
var syncError: Boolean
try {
syncAndWait(oProjectConfiguration)
syncError = false
} catch (ex: GitRepositorySyncException) {
applicationLogService.log(
ApplicationLogEntry.error(
ex,
NameDescription.nd(
"git-sync",
"Git synchronisation issue"
),
oProjectConfiguration.remote
).withDetail("project", project.name)
.withDetail("git-name", oProjectConfiguration.name)
.withDetail("git-remote", oProjectConfiguration.remote)
)
syncError = true
}
// Change log computation
return GitChangeLog(
UUID.randomUUID().toString(),
project,
getSCMBuildView(buildFrom.id),
getSCMBuildView(buildTo.id),
syncError
)
} else {
throw GitProjectNotConfiguredException(project.id)
}
}
}
protected fun syncAndWait(gitConfiguration: GitConfiguration): Any? {
// Gets the sync job (might be null)
val sync = sync(gitConfiguration, GitSynchronisationRequest.SYNC)
return if (sync != null) {
FutureUtils.wait("Synchronisation for " + gitConfiguration.name, sync)
} else {
null
}
}
protected fun getRequiredProjectConfiguration(project: Project): GitConfiguration {
return getProjectConfiguration(project) ?: throw GitProjectNotConfiguredException(project.id)
}
protected fun getGitRepositoryClient(project: Project): GitRepositoryClient {
return getProjectConfiguration(project)?.gitRepository
?.let { gitRepositoryClientFactory.getClient(it) }
?: throw GitProjectNotConfiguredException(project.id)
}
override fun getChangeLogCommits(changeLog: GitChangeLog): GitChangeLogCommits {
// Gets the client
val client = getGitRepositoryClient(changeLog.project)
// Gets the build boundaries
val buildFrom = changeLog.from.build
val buildTo = changeLog.to.build
// Commit boundaries
var commitFrom = getCommitFromBuild(buildFrom)
var commitTo = getCommitFromBuild(buildTo)
// Gets the commits
var log = client.graph(commitFrom, commitTo)
// If log empty, inverts the boundaries
if (log.commits.isEmpty()) {
val t = commitFrom
commitFrom = commitTo
commitTo = t
log = client.graph(commitFrom, commitTo)
}
// Consolidation to UI
val commits = log.commits
val uiCommits = toUICommits(getRequiredProjectConfiguration(changeLog.project), commits)
return GitChangeLogCommits(
GitUILog(
log.plot,
uiCommits
)
)
}
protected fun getCommitFromBuild(build: Build): String {
return getBranchConfiguration(build.branch)
?.buildCommitLink
?.getCommitFromBuild(build)
?: throw GitBranchNotConfiguredException(build.branch.id)
}
override fun getChangeLogIssuesIds(changeLog: GitChangeLog): List<String> {
// Commits must have been loaded first
val commits: GitChangeLogCommits = changeLog.loadCommits {
getChangeLogCommits(it)
}
// In a transaction
transactionService.start().use { _ ->
// Configuration
val configuration = getRequiredProjectConfiguration(changeLog.project)
// Issue service
val configuredIssueService = configuration.configuredIssueService
?: throw IssueServiceNotConfiguredException()
// Set of issues
val issueKeys = TreeSet<String>()
// For all commits in this commit log
for (gitUICommit in commits.log.commits) {
val keys = configuredIssueService.extractIssueKeysFromMessage(gitUICommit.commit.fullMessage)
issueKeys += keys
}
// OK
return issueKeys.toList()
}
}
override fun getChangeLogIssues(changeLog: GitChangeLog): GitChangeLogIssues {
// Commits must have been loaded first
val commits: GitChangeLogCommits = changeLog.loadCommits {
getChangeLogCommits(it)
}
// In a transaction
transactionService.start().use { _ ->
// Configuration
val configuration = getRequiredProjectConfiguration(changeLog.project)
// Issue service
val configuredIssueService = configuration.configuredIssueService
?: throw IssueServiceNotConfiguredException()
// Index of issues, sorted by keys
val issues = TreeMap<String, GitChangeLogIssue>()
// For all commits in this commit log
for (gitUICommit in commits.log.commits) {
val keys = configuredIssueService.extractIssueKeysFromMessage(gitUICommit.commit.fullMessage)
for (key in keys) {
var existingIssue: GitChangeLogIssue? = issues[key]
if (existingIssue != null) {
existingIssue.add(gitUICommit)
} else {
val issue = configuredIssueService.getIssue(key)
if (issue != null) {
existingIssue = GitChangeLogIssue.of(issue, gitUICommit)
issues[key] = existingIssue
}
}
}
}
// List of issues
val issuesList = ArrayList(issues.values)
// Issues link
val issueServiceConfiguration = configuredIssueService.issueServiceConfigurationRepresentation
// OK
return GitChangeLogIssues(issueServiceConfiguration, issuesList)
}
}
override fun getChangeLogFiles(changeLog: GitChangeLog): GitChangeLogFiles {
// Gets the configuration
val configuration = getRequiredProjectConfiguration(changeLog.project)
// Gets the client for this project
val client = gitRepositoryClientFactory.getClient(configuration.gitRepository)
// Gets the build boundaries
val buildFrom = changeLog.from.build
val buildTo = changeLog.to.build
// Commit boundaries
val commitFrom = getCommitFromBuild(buildFrom)
val commitTo = getCommitFromBuild(buildTo)
// Diff
val diff = client.diff(commitFrom, commitTo)
// File change links
val fileChangeLinkFormat = configuration.fileAtCommitLink
// OK
return GitChangeLogFiles(
diff.entries.map { entry ->
toChangeLogFile(entry).withUrl(
getDiffUrl(diff, entry, fileChangeLinkFormat)
)
}
)
}
override fun isPatternFound(gitConfiguration: GitConfiguration, token: String): Boolean {
// Gets the client
val client = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
// Scanning
return client.isPatternFound(token)
}
override fun lookupCommit(configuration: GitConfiguration, id: String): GitCommit? {
// Gets the client client for this configuration
val gitClient = gitRepositoryClientFactory.getClient(configuration.gitRepository)
// Gets the commit
return gitClient.getCommitFor(id)
}
override fun forEachCommit(gitConfiguration: GitConfiguration, code: (GitCommit) -> Unit) {
// Gets the client client for this configuration
val gitClient = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
// Looping
gitClient.forEachCommit(code)
}
override fun isRepositorySynched(gitConfiguration: GitConfiguration): Boolean {
// Gets the client client for this configuration
val gitClient = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
// Test
return gitClient.isReady
}
override fun getCommitProjectInfo(projectId: ID, commit: String): OntrackGitCommitInfo {
return getOntrackGitCommitInfo(structureService.getProject(projectId), commit)
}
override fun getRemoteBranches(gitConfiguration: GitConfiguration): List<String> {
val gitClient = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
return gitClient.remoteBranches
}
override fun diff(changeLog: GitChangeLog, patterns: List<String>): String {
// Gets the client client for this configuration`
val gitClient = getGitRepositoryClient(changeLog.project)
// Path predicate
val pathFilter = scmService.getPathFilter(patterns)
// Gets the build boundaries
val buildFrom = changeLog.from.build
val buildTo = changeLog.to.build
// Commit boundaries
val commitFrom = getCommitFromBuild(buildFrom)
val commitTo = getCommitFromBuild(buildTo)
// Gets the diff
return gitClient.unifiedDiff(
commitFrom,
commitTo,
pathFilter
)
}
override fun download(branch: Branch, path: String): Optional<String> {
securityService.checkProjectFunction(branch, ProjectConfig::class.java)
return transactionService.doInTransaction {
val branchConfiguration = getRequiredBranchConfiguration(branch)
val client = gitRepositoryClientFactory.getClient(
branchConfiguration.configuration.gitRepository
)
client.download(branchConfiguration.branch, path).asOptional()
}
}
override fun download(project: Project, scmBranch: String, path: String): String? {
securityService.checkProjectFunction(project, ProjectConfig::class.java)
return transactionService.doInTransaction {
val projectConfiguration = getRequiredProjectConfiguration(project)
val client = gitRepositoryClientFactory.getClient(
projectConfiguration.gitRepository
)
client.download(scmBranch, path).asOptional()
}.getOrNull()
}
override fun projectSync(project: Project, request: GitSynchronisationRequest): Ack {
securityService.checkProjectFunction(project, ProjectConfig::class.java)
val projectConfiguration = getProjectConfiguration(project)
if (projectConfiguration != null) {
val sync = sync(projectConfiguration, request)
return Ack.validate(sync != null)
} else {
return Ack.NOK
}
}
override fun sync(gitConfiguration: GitConfiguration, request: GitSynchronisationRequest): Future<*>? {
// Reset the repository?
if (request.isReset) {
gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository).reset()
}
// Schedules the job
return jobScheduler.fireImmediately(getGitIndexationJobKey(gitConfiguration)).orElse(null)
}
override fun getProjectGitSyncInfo(project: Project): GitSynchronisationInfo {
securityService.checkProjectFunction(project, ProjectConfig::class.java)
return getProjectConfiguration(project)
?.let { getGitSynchronisationInfo(it) }
?: throw GitProjectNotConfiguredException(project.id)
}
private fun getGitSynchronisationInfo(gitConfiguration: GitConfiguration): GitSynchronisationInfo {
// Gets the client for this configuration
val client = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
// Gets the status
val status = client.synchronisationStatus
// Collects the branch info
val branches: List<GitBranchInfo> = if (status == GitSynchronisationStatus.IDLE) {
client.branches.branches
} else {
emptyList()
}
// OK
return GitSynchronisationInfo(
gitConfiguration.type,
gitConfiguration.name,
gitConfiguration.remote,
gitConfiguration.indexationInterval,
status,
branches
)
}
override fun getIssueProjectInfo(projectId: ID, key: String): OntrackGitIssueInfo? {
// Gets the project
val project = structureService.getProject(projectId)
// Gets the project configuration
val projectConfiguration = getRequiredProjectConfiguration(project)
// Issue service
val configuredIssueService: ConfiguredIssueService? = projectConfiguration.configuredIssueService
// Gets the details about the issue
val issue: Issue? = logTime("issue-object") {
configuredIssueService?.getIssue(key)
}
// If no issue, no info
if (issue == null || configuredIssueService == null) {
return null
} else {
// Gets a client for this project
val repositoryClient: GitRepositoryClient = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository)
// Regular expression for the issue
val regex = configuredIssueService.getMessageRegex(issue)
// Now, get the last commit for this issue
val commit = logTime("issue-commit") {
repositoryClient.getLastCommitForExpression(regex)
}
// If commit is found, we collect the commit info
return if (commit != null) {
val commitInfo = getOntrackGitCommitInfo(project, commit)
// We now return the commit info together with the issue
OntrackGitIssueInfo(
configuredIssueService.issueServiceConfigurationRepresentation,
issue,
commitInfo
)
}
// If not found, no commit info
else {
OntrackGitIssueInfo(
configuredIssueService.issueServiceConfigurationRepresentation,
issue,
null
)
}
}
}
private fun getOntrackGitCommitInfo(project: Project, commit: String): OntrackGitCommitInfo {
// Gets the project configuration
val projectConfiguration = getRequiredProjectConfiguration(project)
// Gets a client for this configuration
val repositoryClient = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository)
// Gets the commit
val commitObject = logTime("commit-object") {
repositoryClient.getCommitFor(commit) ?: throw GitCommitNotFoundException(commit)
}
// Gets the annotated commit
val messageAnnotators = getMessageAnnotators(projectConfiguration)
val uiCommit = toUICommit(
projectConfiguration.commitLink,
messageAnnotators,
commitObject
)
// Looks for all Git branches for this commit
val gitBranches = logTime("branches-for-commit") { repositoryClient.getBranchesForCommit(commit) }
// Sorts the branches according to the branching model
val indexedBranches = logTime("branch-index") {
branchingModelService.getBranchingModel(project)
.groupBranches(gitBranches)
.mapValues { (_, gitBranches) ->
gitBranches.mapNotNull { findBranchWithGitBranch(project, it) }
}
.filterValues { !it.isEmpty() }
}
// Logging of the index
indexedBranches.forEach { type, branches: List<Branch> ->
logger.debug("git-search-branch-index,type=$type,branches=${branches.joinToString { it.name }}")
}
// For every indexation group of branches
val branchInfos = indexedBranches.mapValues { (_, branches) ->
branches.map { branch ->
// Gets its Git configuration
val branchConfiguration = getRequiredBranchConfiguration(branch)
// Gets the earliest build on this branch that contains this commit
val firstBuildOnThisBranch = logTime("earliest-build", listOf("branch" to branch.name)) {
getEarliestBuildAfterCommit(commitObject, branch, branchConfiguration, repositoryClient)
}
// Promotions
val promotions: List<PromotionRun> = logTime("earliest-promotion", listOf("branch" to branch.name)) {
firstBuildOnThisBranch?.let { build ->
structureService.getPromotionLevelListForBranch(branch.id)
.mapNotNull { promotionLevel ->
structureService.getEarliestPromotionRunAfterBuild(promotionLevel, build).orElse(null)
}
} ?: emptyList()
}
// Complete branch info
BranchInfo(
branch,
firstBuildOnThisBranch,
promotions
)
}
}.mapValues { (_, infos) ->
infos.filter { !it.isEmpty }
}.filterValues {
!it.isEmpty()
}
// Result
return OntrackGitCommitInfo(
uiCommit,
branchInfos
)
}
internal fun getEarliestBuildAfterCommit(commit: GitCommit, branch: Branch, branchConfiguration: GitBranchConfiguration, client: GitRepositoryClient): Build? {
return gitRepositoryHelper.getEarliestBuildAfterCommit(
branch,
IndexableGitCommit(commit)
)?.let { structureService.getBuild(ID.of(it)) }
}
private fun getDiffUrl(diff: GitDiff, entry: GitDiffEntry, fileChangeLinkFormat: String): String {
return if (StringUtils.isNotBlank(fileChangeLinkFormat)) {
fileChangeLinkFormat
.replace("{commit}", entry.getReferenceId(diff.from, diff.to))
.replace("{path}", entry.referencePath)
} else {
""
}
}
private fun toChangeLogFile(entry: GitDiffEntry): GitChangeLogFile {
return when (entry.changeType) {
GitChangeType.ADD -> GitChangeLogFile.of(SCMChangeLogFileChangeType.ADDED, entry.newPath)
GitChangeType.COPY -> GitChangeLogFile.of(SCMChangeLogFileChangeType.COPIED, entry.oldPath, entry.newPath)
GitChangeType.DELETE -> GitChangeLogFile.of(SCMChangeLogFileChangeType.DELETED, entry.oldPath)
GitChangeType.MODIFY -> GitChangeLogFile.of(SCMChangeLogFileChangeType.MODIFIED, entry.oldPath)
GitChangeType.RENAME -> GitChangeLogFile.of(SCMChangeLogFileChangeType.RENAMED, entry.oldPath, entry.newPath)
else -> GitChangeLogFile.of(SCMChangeLogFileChangeType.UNDEFINED, entry.oldPath, entry.newPath)
}
}
override fun toUICommit(gitConfiguration: GitConfiguration, commit: GitCommit): GitUICommit {
return toUICommits(
gitConfiguration,
listOf(commit)
).first()
}
private fun toUICommits(gitConfiguration: GitConfiguration, commits: List<GitCommit>): List<GitUICommit> {
// Link?
val commitLink = gitConfiguration.commitLink
// Issue-based annotations
val messageAnnotators = getMessageAnnotators(gitConfiguration)
// OK
return commits.map { commit -> toUICommit(commitLink, messageAnnotators, commit) }
}
private fun toUICommit(commitLink: String, messageAnnotators: List<MessageAnnotator>, commit: GitCommit): GitUICommit {
return GitUICommit(
commit,
MessageAnnotationUtils.annotate(commit.shortMessage, messageAnnotators),
MessageAnnotationUtils.annotate(commit.fullMessage, messageAnnotators),
StringUtils.replace(commitLink, "{commit}", commit.id)
)
}
private fun getMessageAnnotators(gitConfiguration: GitConfiguration): List<MessageAnnotator> {
val configuredIssueService = gitConfiguration.configuredIssueService
return if (configuredIssueService != null) {
// Gets the message annotator
val messageAnnotator = configuredIssueService.messageAnnotator
// If present annotate the messages
messageAnnotator.map { listOf(it) }.orElseGet { emptyList<MessageAnnotator?>() }
} else {
emptyList()
}
}
private fun getSCMBuildView(buildId: ID): SCMBuildView<GitBuildInfo> {
return SCMBuildView(getBuildView(buildId), GitBuildInfo())
}
override fun getGitConfiguratorAndConfiguration(project: Project): Pair<GitConfigurator, GitConfiguration>? =
gitConfigurators.mapNotNull {
val configuration = it.getConfiguration(project)
if (configuration != null) {
it to configuration
} else {
null
}
}.firstOrNull()
override fun isProjectConfiguredForGit(project: Project): Boolean =
gitConfigurators.any { configurator ->
configurator.isProjectConfigured(project)
}
override fun getProjectConfiguration(project: Project): GitConfiguration? {
return gitConfigurators.asSequence()
.mapNotNull { c -> c.getConfiguration(project) }
.firstOrNull()
}
protected fun getRequiredBranchConfiguration(branch: Branch): GitBranchConfiguration {
return getBranchConfiguration(branch)
?: throw GitBranchNotConfiguredException(branch.id)
}
override fun getBranchAsPullRequest(branch: Branch): GitPullRequest? =
propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java).value?.let { property ->
getBranchAsPullRequest(branch, property)
}
override fun isBranchAPullRequest(branch: Branch): Boolean =
gitConfigProperties.pullRequests.enabled &&
propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java).value
?.let { property ->
getGitConfiguratorAndConfiguration(branch.project)
?.let { (configurator, _) ->
configurator.toPullRequestID(property.branch) != null
}
}
?: false
override fun getBranchAsPullRequest(branch: Branch, gitBranchConfigurationProperty: GitBranchConfigurationProperty?): GitPullRequest? =
if (gitConfigProperties.pullRequests.enabled) {
// Actual code to get the PR
fun internalPR() = gitBranchConfigurationProperty?.let {
getGitConfiguratorAndConfiguration(branch.project)
?.let { (configurator, configuration) ->
configurator.toPullRequestID(gitBranchConfigurationProperty.branch)?.let { prId ->
configurator.getPullRequest(configuration, prId)
?: GitPullRequest.invalidPR(prId, configurator.toPullRequestKey(prId))
}
}
}
// Calling the cache
gitPullRequestCache.getBranchPullRequest(branch, ::internalPR)
} else {
// Pull requests are not supported
null
}
override fun getBranchConfiguration(branch: Branch): GitBranchConfiguration? {
// Get the configuration for the project
val configuration = getProjectConfiguration(branch.project)
if (configuration != null) {
// Gets the configuration for a branch
val gitBranch: String
val buildCommitLink: ConfiguredBuildGitCommitLink<*>?
val override: Boolean
val buildTagInterval: Int
val branchConfig = propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java)
if (!branchConfig.isEmpty) {
val branchConfigurationProperty = branchConfig.value
gitBranch = branchConfigurationProperty.branch
buildCommitLink = branchConfigurationProperty.buildCommitLink?.let {
toConfiguredBuildGitCommitLink<Any>(it)
}
override = branchConfigurationProperty.isOverride
buildTagInterval = branchConfigurationProperty.buildTagInterval
// Pull request information
val gitPullRequest = getBranchAsPullRequest(branch, branchConfigurationProperty)
// OK
return GitBranchConfiguration(
configuration,
gitBranch,
gitPullRequest,
buildCommitLink,
override,
buildTagInterval
)
} else {
return null
}
} else {
return null
}
}
override fun findBranchWithGitBranch(project: Project, branchName: String): Branch? {
return gitRepositoryHelper.findBranchWithProjectAndGitBranch(project, branchName)
?.let { structureService.getBranch(ID.of(it)) }
}
private fun <T> toConfiguredBuildGitCommitLink(serviceConfiguration: ServiceConfiguration): ConfiguredBuildGitCommitLink<T> {
@Suppress("UNCHECKED_CAST")
val link = buildGitCommitLinkService.getLink(serviceConfiguration.id) as BuildGitCommitLink<T>
val linkData = link.parseData(serviceConfiguration.data)
return ConfiguredBuildGitCommitLink(
link,
linkData
)
}
private fun createBuildSyncJob(branch: Branch): Job {
val configuration = getRequiredBranchConfiguration(branch)
return object : AbstractBranchJob(structureService, branch) {
override fun getKey(): JobKey {
return getGitBranchSyncJobKey(branch)
}
override fun getTask(): JobRun {
return JobRun { listener -> buildSync<Any>(branch, configuration, listener) }
}
override fun getDescription(): String {
return format(
"Branch %s @ %s",
branch.name,
branch.project.name
)
}
override fun isDisabled(): Boolean {
return super.isDisabled() && isBranchConfiguredForGit(branch)
}
}
}
protected fun getGitBranchSyncJobKey(branch: Branch): JobKey {
return GIT_BUILD_SYNC_JOB.getKey(branch.id.toString())
}
private fun getGitIndexationJobKey(config: GitConfiguration): JobKey {
return GIT_INDEXATION_JOB.getKey(config.gitRepository.id)
}
private fun createIndexationJob(config: GitConfiguration): Job {
return object : Job {
override fun getKey(): JobKey {
return getGitIndexationJobKey(config)
}
override fun getTask(): JobRun {
return JobRun { runListener -> index(config, runListener) }
}
override fun getDescription(): String {
return format(
"%s (%s @ %s)",
config.remote,
config.name,
config.type
)
}
override fun isDisabled(): Boolean {
return false
}
override fun getTimeout() = gitConfigProperties.indexation.timeout
}
}
protected fun <T> buildSync(branch: Branch, branchConfiguration: GitBranchConfiguration, listener: JobRunListener) {
listener.message("Git build/tag sync for %s/%s", branch.project.name, branch.name)
val configuration = branchConfiguration.configuration
// Gets the branch Git client
val gitClient = gitRepositoryClientFactory.getClient(configuration.gitRepository)
// Link
@Suppress("UNCHECKED_CAST")
val link = branchConfiguration.buildCommitLink?.link as IndexableBuildGitCommitLink<T>?
@Suppress("UNCHECKED_CAST")
val linkData = branchConfiguration.buildCommitLink?.data as T?
// Check for configuration
if (link == null || linkData == null) {
listener.message("No commit link configuration on the branch - no synchronization.")
return
}
// Configuration for the sync
val confProperty = propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java)
val override = !confProperty.isEmpty && confProperty.value.isOverride
// Makes sure of synchronization
listener.message("Synchronizing before importing")
syncAndWait(configuration)
// Gets the list of tags
listener.message("Getting list of tags")
val tags = gitClient.tags
// Creates the builds
listener.message("Creating builds from tags")
for (tag in tags) {
val tagName = tag.name
// Filters the tags according to the branch tag pattern
link.getBuildNameFromTagName(tagName, linkData).ifPresent { buildNameCandidate ->
val buildName = NameDescription.escapeName(buildNameCandidate)
listener.message(format("Build %s from tag %s", buildName, tagName))
// Existing build?
val build = structureService.findBuildByName(branch.project.name, branch.name, buildName)
val createBuild: Boolean = if (build.isPresent) {
if (override) {
// Deletes the build
listener.message("Deleting existing build %s", buildName)
structureService.deleteBuild(build.get().id)
true
} else {
// Keeps the build
listener.message("Build %s already exists", buildName)
false
}
} else {
true
}
// Actual creation
if (createBuild) {
listener.message("Creating build %s from tag %s", buildName, tagName)
structureService.newBuild(
Build.of(
branch,
NameDescription(
buildName,
"Imported from Git tag $tagName"
),
securityService.currentSignature.withTime(
tag.time
)
)
)
}
}
}
}
private fun index(config: GitConfiguration, listener: JobRunListener) {
listener.message("Git sync for %s", config.name)
// Gets the client for this configuration
val client = gitRepositoryClientFactory.getClient(config.gitRepository)
// Launches the synchronisation
client.sync(listener.logger())
}
private fun getGitIndexationJobRegistration(configuration: GitConfiguration): JobRegistration {
return JobRegistration
.of(createIndexationJob(configuration))
.everyMinutes(configuration.indexationInterval.toLong())
}
override fun scheduleGitBuildSync(branch: Branch, property: GitBranchConfigurationProperty) {
if (property.buildTagInterval > 0) {
jobScheduler.schedule(
createBuildSyncJob(branch),
Schedule.everyMinutes(property.buildTagInterval.toLong())
)
} else {
unscheduleGitBuildSync(branch, property)
}
}
override fun unscheduleGitBuildSync(branch: Branch, property: GitBranchConfigurationProperty) {
jobScheduler.unschedule(getGitBranchSyncJobKey(branch))
}
override fun getSCMPathInfo(branch: Branch): Optional<SCMPathInfo> = getBranchSCMPathInfo(branch).asOptional()
override fun getBranchSCMPathInfo(branch: Branch): SCMPathInfo? =
getBranchConfiguration(branch)
?.let {
SCMPathInfo(
"git",
it.configuration.remote,
it.branch, null
)
}
override fun getCommitForBuild(build: Build): IndexableGitCommit? =
entityDataService.retrieve(
build,
"git-commit",
IndexableGitCommit::class.java
)
override fun setCommitForBuild(build: Build, commit: IndexableGitCommit) {
entityDataService.store(
build,
"git-commit",
commit
)
}
override fun collectIndexableGitCommitForBranch(branch: Branch, overrides: Boolean) {
val project = branch.project
val projectConfiguration = getProjectConfiguration(project)
if (projectConfiguration != null) {
val client = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository)
val branchConfiguration = getBranchConfiguration(branch)
if (branchConfiguration != null) {
collectIndexableGitCommitForBranch(
branch,
client,
branchConfiguration,
overrides,
JobRunListener.logger(logger)
)
}
}
}
override fun collectIndexableGitCommitForBranch(
branch: Branch,
client: GitRepositoryClient,
config: GitBranchConfiguration,
overrides: Boolean,
listener: JobRunListener
) {
val buildCommitLink = config.buildCommitLink
if (buildCommitLink != null) {
structureService.findBuild(branch.id, BuildSortDirection.FROM_NEWEST) { build ->
collectIndexableGitCommitForBuild(build, client, buildCommitLink, overrides, listener) ?: false
}
}
}
override fun collectIndexableGitCommitForBuild(build: Build) {
val project = build.project
val projectConfiguration = getProjectConfiguration(project)
if (projectConfiguration != null) {
val client = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository)
val branchConfiguration = getBranchConfiguration(build.branch)
val buildCommitLink = branchConfiguration?.buildCommitLink
if (buildCommitLink != null) {
collectIndexableGitCommitForBuild(
build,
client,
buildCommitLink,
true,
JobRunListener.logger(logger)
)
}
}
}
override fun getSCMDefaultBranch(project: Project): String? =
getProjectConfiguration(project)?.let { conf ->
val client = gitRepositoryClientFactory.getClient(conf.gitRepository)
client.defaultBranch
}
private fun collectIndexableGitCommitForBuild(
build: Build,
client: GitRepositoryClient,
buildCommitLink: ConfiguredBuildGitCommitLink<*>,
overrides: Boolean,
listener: JobRunListener
): Boolean? = transactionTemplate.execute {
val commit =
try {
buildCommitLink.getCommitFromBuild(build)
} catch (ex: NoGitCommitPropertyException) {
null
}
if (commit != null) {
listener.message("Indexing $commit for build ${build.entityDisplayName}")
// Gets the Git information for the commit
val toSet: Boolean = overrides || getCommitForBuild(build) == null
if (toSet) {
val commitFor = client.getCommitFor(commit)
if (commitFor != null) {
setCommitForBuild(build, IndexableGitCommit(commitFor))
}
}
}
// Going on
false
} ?: false
private fun <T> logTime(key: String, tags: List<Pair<String, *>> = emptyList(), code: () -> T): T {
val start = System.currentTimeMillis()
val result = code()
val end = System.currentTimeMillis()
val time = end - start
val tagsString = tags.joinToString("") {
",${it.first}=${it.second.toString()}"
}
logger.debug("git-search-time,key=$key,time-ms=$time$tagsString")
return result
}
companion object {
private val GIT_INDEXATION_JOB = GIT_JOB_CATEGORY.getType("git-indexation").withName("Git indexation")
private val GIT_BUILD_SYNC_JOB = GIT_JOB_CATEGORY.getType("git-build-sync").withName("Git build synchronisation")
}
}
|
mit
|
3767b1cd61dcd21c831df82f916cf20b
| 42.527358 | 163 | 0.613602 | 5.627394 | false | true | false | false |
olonho/carkot
|
translator/src/test/kotlin/tests/serialization_test/serialization_test.kt
|
1
|
18270
|
class DirectionResponse private constructor(var code: Int) {
//========== Properties ===========
//int32 code = 1
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo(output: CodedOutputStream) {
//int32 code = 1
if (code != 0) {
output.writeInt32(1, code)
}
}
fun mergeWith(other: DirectionResponse) {
code = other.code
this.errorCode = other.errorCode
}
fun mergeFromWithSize(input: CodedInputStream, expectedSize: Int) {
val builder = DirectionResponse.BuilderDirectionResponse(0)
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom(input: CodedInputStream) {
val builder = DirectionResponse.BuilderDirectionResponse(0)
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (code != 0) {
size += WireFormat.getInt32Size(1, code)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (code != 0) {
size += WireFormat.getInt32Size(1, code)
}
return size
}
//========== Builder ===========
class BuilderDirectionResponse constructor(var code: Int) {
//========== Properties ===========
//int32 code = 1
fun setCode(value: Int): DirectionResponse.BuilderDirectionResponse {
code = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo(output: CodedOutputStream) {
//int32 code = 1
if (code != 0) {
output.writeInt32(1, code)
}
}
//========== Mutating methods ===========
fun build(): DirectionResponse {
val res = DirectionResponse(code)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) {
return false
}
val tag = input.readInt32NoTag()
if (tag == 0) {
return false
}
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when (fieldNumber) {
1 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
code = input.readInt32NoTag()
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): DirectionResponse.BuilderDirectionResponse {
while (getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) {
errorCode = 2
}
return this
}
fun parseFrom(input: CodedInputStream): DirectionResponse.BuilderDirectionResponse {
while (parseFieldFrom(input)) {
}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (code != 0) {
size += WireFormat.getInt32Size(1, code)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (code != 0) {
size += WireFormat.getInt32Size(1, code)
}
return size
}
}
}
class RouteRequest private constructor(var distances: IntArray, var angles: IntArray) {
//========== Properties ===========
//repeated int32 distances = 1
//repeated int32 angles = 2
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo(output: CodedOutputStream) {
//repeated int32 distances = 1
if (distances.size > 0) {
output.writeTag(1, WireType.LENGTH_DELIMITED)
var arrayByteSize = 0
if (distances.size != 0) {
do {
var arraySize = 0
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
arrayByteSize += arraySize
} while (false)
}
output.writeInt32NoTag(arrayByteSize)
do {
var i = 0
while (i < distances.size) {
output.writeInt32NoTag(distances[i])
i += 1
}
} while (false)
}
//repeated int32 angles = 2
if (angles.size > 0) {
output.writeTag(2, WireType.LENGTH_DELIMITED)
var arrayByteSize = 0
if (angles.size != 0) {
do {
var arraySize = 0
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
arrayByteSize += arraySize
} while (false)
}
output.writeInt32NoTag(arrayByteSize)
do {
var i = 0
while (i < angles.size) {
output.writeInt32NoTag(angles[i])
i += 1
}
} while (false)
}
}
fun mergeWith(other: RouteRequest) {
distances = distances.plus((other.distances))
angles = angles.plus((other.angles))
this.errorCode = other.errorCode
}
fun mergeFromWithSize(input: CodedInputStream, expectedSize: Int) {
val builder = RouteRequest.BuilderRouteRequest(IntArray(0), IntArray(0))
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom(input: CodedInputStream) {
val builder = RouteRequest.BuilderRouteRequest(IntArray(0), IntArray(0))
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (distances.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED)
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
if (angles.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED)
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (distances.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED)
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
if (angles.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED)
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
return size
}
//========== Builder ===========
class BuilderRouteRequest constructor(var distances: IntArray, var angles: IntArray) {
//========== Properties ===========
//repeated int32 distances = 1
fun setDistances(value: IntArray): RouteRequest.BuilderRouteRequest {
distances = value
return this
}
fun setdistancesByIndex(index: Int, value: Int): RouteRequest.BuilderRouteRequest {
distances[index] = value
return this
}
//repeated int32 angles = 2
fun setAngles(value: IntArray): RouteRequest.BuilderRouteRequest {
angles = value
return this
}
fun setanglesByIndex(index: Int, value: Int): RouteRequest.BuilderRouteRequest {
angles[index] = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo(output: CodedOutputStream) {
//repeated int32 distances = 1
if (distances.size > 0) {
output.writeTag(1, WireType.LENGTH_DELIMITED)
var arrayByteSize = 0
if (distances.size != 0) {
do {
var arraySize = 0
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
arrayByteSize += arraySize
} while (false)
}
output.writeInt32NoTag(arrayByteSize)
do {
var i = 0
while (i < distances.size) {
output.writeInt32NoTag(distances[i])
i += 1
}
} while (false)
}
//repeated int32 angles = 2
if (angles.size > 0) {
output.writeTag(2, WireType.LENGTH_DELIMITED)
var arrayByteSize = 0
if (angles.size != 0) {
do {
var arraySize = 0
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
arrayByteSize += arraySize
} while (false)
}
output.writeInt32NoTag(arrayByteSize)
do {
var i = 0
while (i < angles.size) {
output.writeInt32NoTag(angles[i])
i += 1
}
} while (false)
}
}
//========== Mutating methods ===========
fun build(): RouteRequest {
val res = RouteRequest(distances, angles)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) {
return false
}
val tag = input.readInt32NoTag()
if (tag == 0) {
return false
}
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when (fieldNumber) {
1 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
val expectedByteSize = input.readInt32NoTag()
var newArray = IntArray(0)
var readSize = 0
do {
var i = 0
while (readSize < expectedByteSize) {
val tmp = IntArray(1)
tmp[0] = input.readInt32NoTag()
newArray = newArray.plus(tmp)
readSize += WireFormat.getInt32SizeNoTag(tmp[0])
}
distances = newArray
} while (false)
}
2 -> {
if (wireType.id != WireType.LENGTH_DELIMITED.id) {
errorCode = 1
return false
}
val expectedByteSize = input.readInt32NoTag()
var newArray = IntArray(0)
var readSize = 0
do {
var i = 0
while (readSize < expectedByteSize) {
val tmp = IntArray(1)
tmp[0] = input.readInt32NoTag()
newArray = newArray.plus(tmp)
readSize += WireFormat.getInt32SizeNoTag(tmp[0])
}
angles = newArray
} while (false)
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): RouteRequest.BuilderRouteRequest {
while (getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) {
errorCode = 2
}
return this
}
fun parseFrom(input: CodedInputStream): RouteRequest.BuilderRouteRequest {
while (parseFieldFrom(input)) {
}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (distances.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED)
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
if (angles.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED)
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (distances.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED)
var i = 0
while (i < distances.size) {
arraySize += WireFormat.getInt32SizeNoTag(distances[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
if (angles.size != 0) {
do {
var arraySize = 0
size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED)
var i = 0
while (i < angles.size) {
arraySize += WireFormat.getInt32SizeNoTag(angles[i])
i += 1
}
size += arraySize
size += WireFormat.getInt32SizeNoTag(arraySize)
} while (false)
}
return size
}
}
}
fun serialization_test1(i: Int): Int {
val msg = DirectionResponse.BuilderDirectionResponse(i).build()
val buffer = ByteArray(msg.getSizeNoTag())
val output = CodedOutputStream(buffer)
msg.writeTo(output)
val input = CodedInputStream(buffer)
val msg2 = DirectionResponse.BuilderDirectionResponse(1).parseFrom(input)
return msg2.code
}
fun serialization_test2(size: Int) {
val arr = IntArray(size)
var i = 0
while (i < size) {
arr[i] = i
i++
}
val message = RouteRequest.BuilderRouteRequest(arr, arr).build()
val buffer = ByteArray(message.getSizeNoTag())
i = 0
while (i < buffer.size) {
buffer[i] = 0
i++
}
val outputStream = CodedOutputStream(buffer)
message.writeTo(outputStream)
val inputStream = CodedInputStream(buffer)
val receivedMessage = RouteRequest.BuilderRouteRequest(IntArray(1), IntArray(1)).parseFrom(inputStream).build()
i = 0
while (i < size) {
assert(message.distances[i] == receivedMessage.distances[i])
i++
}
}
|
mit
|
2ecb1e554b0b0c28e3e0c83e5c1340d7
| 31.859712 | 119 | 0.460482 | 5.465151 | false | false | false | false |
goodwinnk/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/UastUtils.kt
|
1
|
8878
|
/*
* 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.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import java.io.File
inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict)
@JvmOverloads
fun <T : UElement> UElement.getParentOfType(parentClass: Class<out UElement>, strict: Boolean = true): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
parentClass: Class<out UElement>,
strict: Boolean = true,
vararg terminators: Class<out UElement>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (terminators.any { it.isInstance(element) }) {
return null
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
strict: Boolean = true,
firstParentClass: Class<out T>,
vararg parentClasses: Class<out T>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (firstParentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (parentClasses.any { it.isInstance(element) }) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun UElement?.getUCallExpression(): UCallExpression? = this?.withContainingElements?.mapNotNull {
when (it) {
is UCallExpression -> it
is UQualifiedReferenceExpression -> it.selector as? UCallExpression
else -> null
}
}?.firstOrNull()
@Deprecated(message = "This function is deprecated, use getContainingUFile", replaceWith = ReplaceWith("getContainingUFile()"))
fun UElement.getContainingFile(): UFile? = getContainingUFile()
fun UElement.getContainingUFile(): UFile? = getParentOfType(UFile::class.java)
fun UElement.getContainingUClass(): UClass? = getParentOfType(UClass::class.java)
fun UElement.getContainingUMethod(): UMethod? = getParentOfType(UMethod::class.java)
fun UElement.getContainingUVariable(): UVariable? = getParentOfType(UVariable::class.java)
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingMethod()?.javaPsi"))
fun UElement.getContainingMethod(): PsiMethod? = getContainingUMethod()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingUClass()?.javaPsi"))
fun UElement.getContainingClass(): PsiClass? = getContainingUClass()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingUVariable()?.javaPsi"))
fun UElement.getContainingVariable(): PsiVariable? = getContainingUVariable()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1",
replaceWith = ReplaceWith("PsiTreeUtil.getParentOfType(this, PsiClass::class.java)"))
fun PsiElement?.getContainingClass(): PsiClass? = this?.let { PsiTreeUtil.getParentOfType(it, PsiClass::class.java) }
fun PsiElement?.findContainingUClass(): UClass? = findContaining(UClass::class.java)
fun <T : UElement> PsiElement?.findContaining(clazz: Class<T>): T? {
var element = this
while (element != null && element !is PsiFileSystemItem) {
element.toUElement(clazz)?.let { return it }
element = element.parent
}
return null
}
fun UElement.isChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean {
tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean {
return when (current) {
null -> false
probablyParent -> true
else -> isChildOf(current.uastParent, probablyParent)
}
}
if (probablyParent == null) return false
return isChildOf(if (strict) this else uastParent, probablyParent)
}
/**
* Resolves the receiver element if it implements [UResolvable].
*
* @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable].
*/
fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve()
fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement
fun UElement.tryResolveUDeclaration(context: UastContext): UDeclaration? {
return (this as? UResolvable)?.resolve()?.let { context.convertElementWithParent(it, null) as? UDeclaration }
}
fun UReferenceExpression?.getQualifiedName(): String? = (this?.resolve() as? PsiClass)?.qualifiedName
/**
* Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String.
*/
fun UExpression.evaluateString(): String? = evaluate() as? String
/**
* Get a physical [File] for this file, or null if there is no such file on disk.
*/
fun UFile.getIoFile(): File? = psi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) }
tailrec fun UElement.getUastContext(): UastContext {
val psi = this.psi
if (psi != null) {
return ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext()
}
tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin {
val psi = this.psi
if (psi != null) {
val uastContext = ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
return uastContext.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin()
}
fun Collection<UElement?>.toPsiElements(): List<PsiElement> = mapNotNull { it?.psi }
/**
* A helper function for getting parents for given [PsiElement] that could be considered as identifier.
* Useful for working with gutter according to recommendations in [com.intellij.codeInsight.daemon.LineMarkerProvider].
*
* @see [getUParentForAnnotationIdentifier] for working with annotations
*/
fun getUParentForIdentifier(identifier: PsiElement): UElement? {
val uIdentifier = identifier.toUElementOfType<UIdentifier>() ?: return null
return uIdentifier.uastParent
}
/**
* @param arg expression in call arguments list of [this]
* @return parameter that corresponds to the [arg] in declaration to which [this] resolves
*/
fun UCallExpression.getParameterForArgument(arg: UExpression): PsiParameter? {
val psiMethod = resolve() ?: return null
val parameters = psiMethod.parameterList.parameters
if (this is UCallExpressionEx)
return parameters.withIndex().find { (i, p) ->
val argumentForParameter = getArgumentForParameter(i) ?: return@find false
if (argumentForParameter == arg) return@find true
if (arg is ULambdaExpression && arg.sourcePsi?.parent == argumentForParameter.sourcePsi) return@find true // workaround for KT-25297
if (p.isVarArgs && argumentForParameter is UExpressionList) return@find argumentForParameter.expressions.contains(arg)
return@find false
}?.value
// not everyone implements UCallExpressionEx, lets try to guess
val indexInArguments = valueArguments.indexOf(arg)
if (parameters.size == valueArguments.count()) {
return parameters.getOrNull(indexInArguments)
}
// probably it is a kotlin extension method
if (parameters.size - 1 == valueArguments.count()) {
val parameter = parameters.firstOrNull() ?: return null
val receiverType = receiverType ?: return null
if (!parameter.type.isAssignableFrom(receiverType)) return null
if (!parameters.drop(1).zip(valueArguments)
.all { (param, arg) -> arg.getExpressionType()?.let { param.type.isAssignableFrom(it) } == true }) return null
return parameters.getOrNull(indexInArguments + 1)
}
//named parameters are not processed
return null
}
|
apache-2.0
|
8a87301a71f39b08aef524f60f34be28
| 38.990991 | 138 | 0.733273 | 4.379872 | false | false | false | false |
nickbutcher/plaid
|
core/src/test/java/io/plaidapp/core/producthunt/data/TestData.kt
|
1
|
1681
|
/*
* Copyright 2019 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.producthunt.data
import io.plaidapp.core.producthunt.data.api.model.GetPostItemResponse
import io.plaidapp.core.producthunt.data.api.model.GetPostsResponse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Response
val errorResponseBody = "Error".toResponseBody("".toMediaTypeOrNull())
val post1 = GetPostItemResponse(
id = 345L,
url = "www.plaid.amazing",
name = "Plaid",
tagline = "amazing",
discussionUrl = "www.disc.plaid",
redirectUrl = "www.d.plaid",
commentsCount = 5,
votesCount = 100
)
val post2 = GetPostItemResponse(
id = 947L,
url = "www.plaid.team",
name = "Plaid",
tagline = "team",
discussionUrl = "www.team.plaid",
redirectUrl = "www.t.plaid",
commentsCount = 2,
votesCount = 42
)
val responseDataSuccess = GetPostsResponse(posts = listOf(post1, post2))
val responseSuccess = Response.success(responseDataSuccess)
val responseError = Response.error<GetPostsResponse>(
400,
errorResponseBody
)
|
apache-2.0
|
ac67efb2a08b545b0f3fc9e4e48623ec
| 29.563636 | 75 | 0.732302 | 3.900232 | false | false | false | false |
RedstonerServer/Parcels
|
src/main/kotlin/io/dico/parcels2/ParcelsPlugin.kt
|
1
|
5415
|
package io.dico.parcels2
import io.dico.dicore.Registrator
import io.dico.dicore.command.EOverridePolicy
import io.dico.dicore.command.ICommandDispatcher
import io.dico.parcels2.command.getParcelCommands
import io.dico.parcels2.defaultimpl.GlobalPrivilegesManagerImpl
import io.dico.parcels2.defaultimpl.ParcelProviderImpl
import io.dico.parcels2.listener.ParcelEntityTracker
import io.dico.parcels2.listener.ParcelListeners
import io.dico.parcels2.listener.WorldEditListener
import io.dico.parcels2.options.Options
import io.dico.parcels2.options.optionsMapper
import io.dico.parcels2.storage.Storage
import io.dico.parcels2.util.MainThreadDispatcher
import io.dico.parcels2.util.PluginAware
import io.dico.parcels2.util.ext.tryCreate
import io.dico.parcels2.util.isServerThread
import io.dico.parcels2.util.scheduleRepeating
import kotlinx.coroutines.CoroutineScope
import org.bukkit.Bukkit
import org.bukkit.generator.ChunkGenerator
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import kotlin.coroutines.CoroutineContext
val logger: Logger = LoggerFactory.getLogger("ParcelsPlugin")
private inline val plogger get() = logger
class ParcelsPlugin : JavaPlugin(), CoroutineScope, PluginAware {
lateinit var optionsFile: File; private set
lateinit var options: Options; private set
lateinit var parcelProvider: ParcelProvider; private set
lateinit var storage: Storage; private set
lateinit var globalPrivileges: GlobalPrivilegesManager; private set
val registrator = Registrator(this)
lateinit var entityTracker: ParcelEntityTracker; private set
private var listeners: ParcelListeners? = null
private var cmdDispatcher: ICommandDispatcher? = null
override val coroutineContext: CoroutineContext = MainThreadDispatcher(this)
override val plugin: Plugin get() = this
val jobDispatcher: JobDispatcher by lazy { BukkitJobDispatcher(this, this, options.tickJobtime) }
override fun onEnable() {
plogger.info("Is server thread: ${isServerThread()}")
plogger.info("Debug enabled: ${plogger.isDebugEnabled}")
plogger.debug(System.getProperty("user.dir"))
if (!init()) {
Bukkit.getPluginManager().disablePlugin(this)
}
}
override fun onDisable() {
val hasWorkers = jobDispatcher.jobs.isNotEmpty()
if (hasWorkers) {
plogger.warn("Parcels is attempting to complete all ${jobDispatcher.jobs.size} remaining jobs before shutdown...")
}
jobDispatcher.completeAllTasks()
if (hasWorkers) {
plogger.info("Parcels has completed the remaining jobs.")
}
cmdDispatcher?.unregisterFromCommandMap()
}
private fun init(): Boolean {
optionsFile = File(dataFolder, "options.yml")
options = Options()
parcelProvider = ParcelProviderImpl(this)
try {
if (!loadOptions()) return false
try {
storage = options.storage.newInstance()
storage.init()
} catch (ex: Exception) {
plogger.error("Failed to connect to database", ex)
return false
}
globalPrivileges = GlobalPrivilegesManagerImpl(this)
entityTracker = ParcelEntityTracker(parcelProvider)
} catch (ex: Exception) {
plogger.error("Error loading options", ex)
return false
}
registerListeners()
registerCommands()
parcelProvider.loadWorlds()
return true
}
fun loadOptions(): Boolean {
when {
optionsFile.exists() -> optionsMapper.readerForUpdating(options).readValue<Options>(optionsFile)
else -> run {
options.addWorld("parcels")
if (saveOptions()) {
plogger.warn("Created options file with a world template. Please review it before next start.")
} else {
plogger.error("Failed to save options file ${optionsFile.canonicalPath}")
}
return false
}
}
return true
}
fun saveOptions(): Boolean {
if (optionsFile.tryCreate()) {
try {
optionsMapper.writeValue(optionsFile, options)
} catch (ex: Throwable) {
optionsFile.delete()
throw ex
}
return true
}
return false
}
override fun getDefaultWorldGenerator(worldName: String, generatorId: String?): ChunkGenerator? {
return parcelProvider.getWorldGenerator(worldName)
}
private fun registerCommands() {
cmdDispatcher = getParcelCommands(this).apply {
registerToCommandMap("parcels:", EOverridePolicy.FALLBACK_ONLY)
}
}
private fun registerListeners() {
if (listeners == null) {
listeners = ParcelListeners(parcelProvider, entityTracker, storage)
registrator.registerListeners(listeners!!)
val worldEditPlugin = server.pluginManager.getPlugin("WorldEdit")
if (worldEditPlugin != null) {
WorldEditListener.register(this, worldEditPlugin)
}
}
scheduleRepeating(5, delay = 100, task = entityTracker::tick)
}
}
|
gpl-2.0
|
b53234de657a63a0bbda7681cd92a887
| 34.168831 | 126 | 0.667221 | 4.75 | false | false | false | false |
d9n/intellij-rust
|
src/main/kotlin/org/rust/cargo/runconfig/filters/RsBacktraceFilter.kt
|
1
|
5297
|
package org.rust.cargo.runconfig.filters
import com.intellij.execution.filters.Filter
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.cargo.runconfig.filters.RegexpFileLinkFilter.Companion.FILE_POSITION_RE
import org.rust.lang.core.resolve.resolveStringPath
import java.util.*
import java.util.regex.Pattern
/**
* Adds features to stack backtraces:
* - Wrap function calls into hyperlinks to source code.
* - Turn source code links into hyperlinks.
* - Dims function hash codes to reduce noise.
*/
class RsBacktraceFilter(
project: Project,
cargoProjectDir: VirtualFile,
module: Module
) : Filter {
private val sourceLinkFilter = RegexpFileLinkFilter(project, cargoProjectDir, "\\s+at ${FILE_POSITION_RE}")
private val backtraceItemFilter = RsBacktraceItemFilter(project, module)
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
return backtraceItemFilter.applyFilter(line, entireLength)
?: sourceLinkFilter.applyFilter(line, entireLength)
}
}
/**
* Adds hyperlinks to function names in backtraces
*/
private class RsBacktraceItemFilter(
val project: Project,
val module: Module
) : Filter {
private val pattern = Pattern.compile("^(\\s*\\d+:\\s+(?:0x[a-f0-9]+ - )?)(.+?)(::h[0-9a-f]+)?$")!!
private val docManager = PsiDocumentManager.getInstance(project)
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
val matcher = pattern.matcher(line)
if (!matcher.find()) return null
val header = matcher.group(1)
val funcName = matcher.group(2)
val funcHash = matcher.group(3)
val normFuncName = funcName.normalize()
val resultItems = ArrayList<Filter.ResultItem>(2)
// Add hyperlink to the function name
val funcStart = entireLength - line.length + header.length
val funcEnd = funcStart + funcName.length
if (SKIP_PREFIXES.none { normFuncName.startsWith(it) }) {
extractFnHyperlink(normFuncName, funcStart, funcEnd)?.let { resultItems.add(it) }
}
// Dim the hashcode
if (funcHash != null) {
resultItems.add(Filter.ResultItem(funcEnd, funcEnd + funcHash.length, null, DIMMED_TEXT))
}
return Filter.Result(resultItems)
}
private fun extractFnHyperlink(funcName: String, start: Int, end: Int): Filter.ResultItem? {
val (element, pkg) = resolveStringPath(funcName, module) ?: return null
val funcFile = element.containingFile
val doc = docManager.getDocument(funcFile) ?: return null
val link = OpenFileHyperlinkInfo(project, funcFile.virtualFile, doc.getLineNumber(element.textOffset))
return Filter.ResultItem(start, end, link, pkg.origin != PackageOrigin.WORKSPACE)
}
/**
* Normalizes function path:
* - Removes angle brackets from the element path, including enclosed contents when necessary.
* - Removes closure markers.
* Examples:
* - <core::option::Option<T>>::unwrap -> core::option::Option::unwrap
* - std::panicking::default_hook::{{closure}} -> std::panicking::default_hook
*/
private fun String.normalize(): String {
var str = this
while (str.endsWith("::{{closure}}")) {
str = str.substringBeforeLast("::")
}
while (true) {
val range = str.findAngleBrackets() ?: break
val idx = str.indexOf("::", range.start + 1)
if (idx < 0 || idx > range.endInclusive) {
str = str.removeRange(range)
} else {
str = str.removeRange(IntRange(range.endInclusive, range.endInclusive))
.removeRange(IntRange(range.start, range.start))
}
}
return str
}
/**
* Finds the range of the first matching angle brackets within the string.
*/
private fun String.findAngleBrackets(): IntRange? {
var start = -1
var counter = 0
loop@ for ((index, char) in this.withIndex()) {
when (char) {
'<' -> {
if (start < 0) {
start = index
}
counter += 1
}
'>' -> counter -= 1
else -> continue@loop
}
if (counter == 0) {
val range = IntRange(start, index)
return range
}
}
return null
}
private companion object {
val DIMMED_TEXT = EditorColorsManager.getInstance().globalScheme
.getAttributes(TextAttributesKey.createTextAttributesKey("org.rust.DIMMED_TEXT"))!!
val SKIP_PREFIXES = arrayOf(
"std::rt::lang_start",
"std::panicking",
"std::sys::backtrace",
"std::sys::imp::backtrace",
"core::panicking")
}
}
|
mit
|
e80813b4729345c3bd98d7934c8c8c54
| 36.567376 | 111 | 0.628469 | 4.356086 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/translations/identification/ReferenceTranslationIdentifier.kt
|
1
|
2107
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.identification
import com.intellij.codeInsight.completion.CompletionUtilCore
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiField
import com.intellij.psi.PsiLiteral
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.impl.source.PsiClassReferenceType
import com.intellij.psi.search.GlobalSearchScope
class ReferenceTranslationIdentifier : TranslationIdentifier<PsiReferenceExpression>() {
override fun identify(element: PsiReferenceExpression): TranslationInstance? {
val reference = element.resolve()
val statement = element.parent
if (reference is PsiField) {
val scope = GlobalSearchScope.allScope(element.project)
val stringClass =
JavaPsiFacade.getInstance(element.project).findClass("java.lang.String", scope) ?: return null
val isConstant =
reference.hasModifierProperty(PsiModifier.STATIC) && reference.hasModifierProperty(PsiModifier.FINAL)
val type = reference.type as? PsiClassReferenceType ?: return null
val resolved = type.resolve() ?: return null
if (isConstant && (resolved.isEquivalentTo(stringClass) || resolved.isInheritor(stringClass, true))) {
val referenceElement = reference.initializer as? PsiLiteral ?: return null
val result = identify(element.project, element, statement, referenceElement)
return result?.copy(
key = result.key.copy(
infix = result.key.infix.replace(
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED,
""
)
)
)
}
}
return null
}
override fun elementClass(): Class<PsiReferenceExpression> {
return PsiReferenceExpression::class.java
}
}
|
mit
|
0f00631ff289dd543833dc2964802739
| 36.625 | 117 | 0.655434 | 5.320707 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/insight/generation/MinecraftClassCreateAction.kt
|
1
|
5105
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight.generation
import com.demonwav.mcdev.asset.GeneralAssets
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.fabric.FabricModuleType
import com.demonwav.mcdev.platform.forge.ForgeModuleType
import com.demonwav.mcdev.util.MinecraftTemplates
import com.demonwav.mcdev.util.findModule
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil
import com.intellij.ide.actions.CreateFileFromTemplateDialog
import com.intellij.ide.actions.CreateTemplateInPackageAction
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.InputValidatorEx
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameHelper
import com.intellij.psi.util.PsiUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
class MinecraftClassCreateAction :
CreateTemplateInPackageAction<PsiClass>(
CAPTION,
"Class generation for modders",
GeneralAssets.MC_TEMPLATE,
JavaModuleSourceRootTypes.SOURCES
),
DumbAware {
override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String = CAPTION
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle(CAPTION)
builder.setValidator(ClassInputValidator(project, directory))
val module = directory.findModule()
val isForge = module?.let { MinecraftFacet.getInstance(it, ForgeModuleType) } != null
val isFabric = module?.let { MinecraftFacet.getInstance(it, FabricModuleType) } != null
if (isForge) {
val icon = PlatformAssets.FORGE_ICON
builder.addKind("Block", icon, MinecraftTemplates.FORGE_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FORGE_ITEM_TEMPLATE)
builder.addKind("Packet", icon, MinecraftTemplates.FORGE_PACKET_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FORGE_ENCHANTMENT_TEMPLATE)
}
if (isFabric) {
val icon = PlatformAssets.FABRIC_ICON
builder.addKind("Block", icon, MinecraftTemplates.FABRIC_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FABRIC_ITEM_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FABRIC_ENCHANTMENT_TEMPLATE)
}
}
override fun isAvailable(dataContext: DataContext): Boolean {
val psi = dataContext.getData(CommonDataKeys.PSI_ELEMENT)
val isModModule = psi?.findModule()?.let {
MinecraftFacet.getInstance(it, FabricModuleType, ForgeModuleType)
} != null
return isModModule && super.isAvailable(dataContext)
}
override fun checkPackageExists(directory: PsiDirectory): Boolean {
val pkg = JavaDirectoryService.getInstance().getPackage(directory) ?: return false
val name = pkg.qualifiedName
return StringUtil.isEmpty(name) || PsiNameHelper.getInstance(directory.project).isQualifiedName(name)
}
override fun getNavigationElement(createdElement: PsiClass): PsiElement? {
return createdElement.lBrace
}
override fun doCreate(dir: PsiDirectory, className: String, templateName: String): PsiClass? {
return JavaDirectoryService.getInstance().createClass(dir, className, templateName, false)
}
private class ClassInputValidator(
private val project: Project,
private val directory: PsiDirectory
) : InputValidatorEx {
override fun getErrorText(inputString: String): String? {
if (inputString.isNotEmpty() && !PsiNameHelper.getInstance(project).isQualifiedName(inputString)) {
return JavaErrorBundle.message("create.class.action.this.not.valid.java.qualified.name")
}
val shortName = StringUtil.getShortName(inputString)
val languageLevel = PsiUtil.getLanguageLevel(directory)
return if (HighlightClassUtil.isRestrictedIdentifier(shortName, languageLevel)) {
JavaErrorBundle.message("restricted.identifier", shortName)
} else {
null
}
}
override fun checkInput(inputString: String): Boolean =
inputString.isNotBlank() && getErrorText(inputString) == null
override fun canClose(inputString: String): Boolean =
checkInput(inputString)
}
private companion object {
private const val CAPTION = "Minecraft Class"
}
}
|
mit
|
973b9569d19a8331223bbf0254e5a844
| 39.515873 | 120 | 0.726543 | 4.83428 | false | false | false | false |
soywiz/korge
|
korge-dragonbones/src/commonMain/kotlin/com/soywiz/korge/dragonbones/KorgeDbArmatureDisplay.kt
|
1
|
10408
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* 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.soywiz.korge.dragonbones
import com.dragonbones.animation.*
import com.dragonbones.armature.*
import com.dragonbones.core.*
import com.dragonbones.event.*
import com.dragonbones.model.*
import com.dragonbones.util.*
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
import com.soywiz.korge.debug.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
import com.soywiz.korim.vector.*
import com.soywiz.korma.geom.vector.*
import com.soywiz.korui.*
/**
* @inheritDoc
*/
class KorgeDbArmatureDisplay : Container(), IArmatureProxy {
private val _events = FastArrayList<EventObject>()
private val _eventsReturnQueue: FastArrayList<BaseObject> = FastArrayList()
/**
* @private
*/
var debugDraw: Boolean = false
private var _debugDraw: Boolean = false
// private var _disposeProxy: boolean = false;
//private var _armature: Armature = null as any
private var _armature: Armature? = null
private var _debugDrawer: Container? = null
/**
* @inheritDoc
*/
override fun dbInit(armature: Armature) {
this._armature = armature
}
// Do not use the time from DragonBones, but the UpdateComponent
init {
addUpdater {
returnEvents()
//_armature?.advanceTimeForChildren(it.toDouble() / 1000.0)
_armature?.advanceTime(it.seconds)
dispatchQueuedEvents()
}
}
/**
* @inheritDoc
*/
override fun dbClear() {
if (this._debugDrawer !== null) {
//this._debugDrawer.destroy(true) // Note: Korge doesn't require this
}
this._armature = null
this._debugDrawer = null
//super.destroy() // Note: Korge doesn't require this
}
/**
* @inheritDoc
*/
override fun dbUpdate() {
val armature = this._armature ?: return
val drawed = DragonBones.debugDraw || this.debugDraw
if (drawed || this._debugDraw) {
this._debugDraw = drawed
if (this._debugDraw) {
if (this._debugDrawer === null) {
//this._debugDrawer = Image(Bitmaps.transparent)
this._debugDrawer = Container()
val boneDrawer = Graphics()
this._debugDrawer?.addChild(boneDrawer)
}
this.addChild(this._debugDrawer!!)
val boneDrawer = this._debugDrawer?.getChildAt(0) as Graphics
boneDrawer.clear()
val bones = armature.getBones()
//for (let i = 0, l = bones.length; i < l; ++i) {
for (i in 0 until bones.length) {
val bone = bones[i]
val boneLength = bone.boneData.length
val startX = bone.globalTransformMatrix.txf
val startY = bone.globalTransformMatrix.tyf
val endX = startX + bone.globalTransformMatrix.af * boneLength
val endY = startY + bone.globalTransformMatrix.bf * boneLength
boneDrawer.stroke(Colors.PURPLE.withAd(0.7), StrokeInfo(thickness = 2.0)) {
boneDrawer.moveTo(startX.toDouble(), startY.toDouble())
boneDrawer.lineTo(endX, endY)
}
boneDrawer.fill(Colors.PURPLE, 0.7) {
boneDrawer.circle(startX.toDouble(), startY.toDouble(), 3.0)
}
}
val slots = armature.getSlots()
//for (let i = 0, l = slots.length; i < l; ++i) {
for (i in 0 until slots.length) {
val slot = slots[i]
val boundingBoxData = slot.boundingBoxData
if (boundingBoxData != null) {
var child = this._debugDrawer?.getChildByName(slot.name) as? Graphics?
if (child == null) {
child = Graphics()
child.name = slot.name
this._debugDrawer?.addChild(child)
}
child.stroke(Colors.RED.withAd(0.7), StrokeInfo(thickness = 2.0)) {
when (boundingBoxData.type) {
BoundingBoxType.Rectangle -> {
child.rect(
-boundingBoxData.width * 0.5,
-boundingBoxData.height * 0.5,
boundingBoxData.width,
boundingBoxData.height
)
}
BoundingBoxType.Ellipse -> {
child.rect(
-boundingBoxData.width * 0.5,
-boundingBoxData.height * 0.5,
boundingBoxData.width,
boundingBoxData.height
)
}
BoundingBoxType.Polygon -> {
val vertices = (boundingBoxData as PolygonBoundingBoxData).vertices
//for (let i = 0, l = vertices.length; i < l; i += 2) {
for (i in 0 until vertices.size step 2) {
val x = vertices[i]
val y = vertices[i + 1]
if (i == 0) {
child.moveTo(x, y)
} else {
child.lineTo(x, y)
}
}
child.lineTo(vertices[0], vertices[1])
}
else -> {
}
}
}
slot.updateTransformAndMatrix()
slot.updateGlobalTransform()
val transform = slot.global
//println("SET TRANSFORM: $transform")
child.setMatrix(slot.globalTransformMatrix)
} else {
val child = this._debugDrawer?.getChildByName(slot.name)
if (child != null) {
this._debugDrawer?.removeChild(child)
}
}
}
} else if (this._debugDrawer !== null && this._debugDrawer?.parent === this) {
this.removeChild(this._debugDrawer)
}
}
}
/**
* @inheritDoc
*/
override fun dispose(disposeProxy: Boolean) {
if (this._armature != null) {
this._armature?.dispose()
this._armature = null
}
}
/**
* @inheritDoc
*/
fun destroy() {
//this.dispose() // Note: Korge doesn't require this!
}
private var eventListeners = LinkedHashMap<EventStringType, FastArrayList<(EventObject) -> Unit>>()
/**
* @private
*/
override fun dispatchDBEvent(type: EventStringType, eventObject: EventObject) {
//println("dispatchDBEvent:$type")
val listeners = eventListeners[type]
if (listeners != null) {
listeners.fastForEach { listener ->
listener(eventObject)
}
}
}
/**
* @inheritDoc
*/
override fun hasDBEventListener(type: EventStringType): Boolean {
return eventListeners.containsKey(type).apply {
//println("hasDBEventListener:$type:$this")
}
}
/**
* @inheritDoc
*/
override fun addDBEventListener(type: EventStringType, listener: (event: EventObject) -> Unit) {
//println("addDBEventListener:$type")
eventListeners.getOrPut(type) { FastArrayList() } += listener
}
/**
* @inheritDoc
*/
override fun removeDBEventListener(type: EventStringType, listener: (event: EventObject) -> Unit) {
//println("removeDBEventListener:$type")
eventListeners[type]?.remove(listener)
}
override fun queueEvent(value: EventObject) {
if (!this._events.contains(value)) {
this._events.add(value)
}
}
private fun queueReturnEvent(obj: BaseObject?) {
if (obj != null && !this._eventsReturnQueue.contains(obj)) this._eventsReturnQueue.add(obj)
}
private fun dispatchQueuedEvents() {
if (this._events.size <= 0) return
for (i in 0 until this._events.size) {
val eventObject = this._events[i]
val armature = eventObject.armature
if (armature._armatureData != null) { // May be armature disposed before advanceTime.
armature.eventDispatcher.dispatchDBEvent(eventObject.type, eventObject)
if (eventObject.type == EventObject.SOUND_EVENT) {
dispatchDBEvent(eventObject.type, eventObject)
}
}
queueReturnEvent(eventObject)
}
this._events.clear()
}
private fun returnEvents() {
if (this._eventsReturnQueue.size <= 0) return
this._eventsReturnQueue.fastForEach { obj ->
obj.returnToPool()
}
this._eventsReturnQueue.clear()
}
fun on(type: EventStringType, listener: (event: EventObject) -> Unit) {
addDBEventListener(type, listener)
}
/**
* @inheritDoc
*/
override val armature: Armature get() = this._armature!!
/**
* @inheritDoc
*/
override val animation: Animation get() = this._armature!!.animation
val animationNames get() = animation.animationNames
override fun buildDebugComponent(views: Views, container: UiContainer) {
container.uiCollapsibleSection("DragonBones") {
addChild(UiRowEditableValue(app, "animation", UiListEditableValue(app, { animationNames }, ObservableProperty(
name = "animation",
internalSet = { animationName -> animation.play(animationName) },
internalGet = { animation.lastAnimationName }
))))
}
super.buildDebugComponent(views, container)
}
}
|
apache-2.0
|
ec5142191cb900d07c3b8069da567897
| 31.322981 | 122 | 0.593966 | 4.210356 | false | false | false | false |
Andr3Carvalh0/mGBA
|
app/src/main/java/io/mgba/main/MainViewModel.kt
|
1
|
1756
|
package io.mgba.main
import android.app.Activity
import android.content.Intent
import android.view.MenuItem
import androidx.lifecycle.ViewModel
import com.mikepenz.aboutlibraries.LibsBuilder
import io.mgba.R
import io.mgba.utilities.device.ResourcesManager.getString
class MainViewModel : ViewModel() {
fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent) {
if (requestCode == SETTINGS_CODE && resultCode == Activity.RESULT_OK) {
throw UnsupportedOperationException()
}
}
fun onMenuItemSelected(item: MenuItem) {
if (item.itemId == R.id.action_about) {
/* val aboutPanel = LibsBuilder()
.withActivityTheme(R.style.AboutTheme)
.withAboutIconShown(true)
.withAboutVersionShown(true)
.withAboutDescription(getString(R.string.About_description))*/
//view.startAboutPanel(aboutPanel)
}
if (item.itemId == R.id.action_settings) {
//view.startActivityForResult(SettingsCategoriesActivity::class.java, SETTINGS_CODE)
}
}
fun onSearchTextChanged(oldQuery: String, newQuery: String) {
if (oldQuery != "" && newQuery == "") {
//view.clearSuggestions()
} else {
// view.showProgress()
// disposable.add(Library.query(newQuery)
// .subscribeOn(Schedulers.computation())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(Consumer<List<Game>> { view.showSuggestions(it) }))
}
}
companion object {
val DEFAULT_PANEL = 1
private val SETTINGS_CODE = 738
}
}
|
mpl-2.0
|
8a82938300758c955b9c44c86c06a1a7
| 33.431373 | 98 | 0.602506 | 4.72043 | false | false | false | false |
thatJavaNerd/gradle-bootstrap
|
api/src/test/kotlin/net/dean/gbs/api/test/ProjectConfigTest.kt
|
1
|
2444
|
package net.dean.gbs.api.test
import net.dean.gbs.api.models.*
import kotlin.collections.filter
import kotlin.collections.isEmpty
import kotlin.collections.setOf
import kotlin.text.toLowerCase
import org.junit.Test as test
public class ProjectConfigTest {
public @test fun testProperDirectories() {
val proj = newProject(*Language.values())
for (lang in Language.values()) {
assert("src/main/${lang.name.toLowerCase()}/com/example/app" in proj.directoriesToCreate) { "Did not find main source set for $lang" }
assert("src/test/${lang.name.toLowerCase()}/com/example/app" in proj.directoriesToCreate) { "Did not find test source set for $lang" }
}
assert("src/main/resources" in proj.directoriesToCreate) { "src/main/resources not found" }
assert("src/test/resources" in proj.directoriesToCreate) { "src/test/resources not found" }
}
public @test fun testAddFrameworks() {
val proj = newProject(Language.JAVA)
proj.build.logging = LoggingFramework.SLF4J
assert(proj.build.projectContext.deps.filter { it.name == "slf4j-api" && it.group == "org.slf4j" }.size > 0)
proj.build.logging = LoggingFramework.LOGBACK_CLASSIC
// Make sure it removed the SLF4J dependencies and added Logback's
assert(proj.build.projectContext.deps.filter { it.name == "slf4j-api" && it.group == "org.slf4j" }.size == 0)
assert(proj.build.projectContext.deps.filter { it.name == "logback-classic" && it.group == "ch.qos.logback" }.size > 0)
}
public @test fun formatDependency() {
val dep = Dependency(group = "com.mydep", name = "mydep", version = "1.0.0", extension = "jar", scope = Scope.COMPILE)
assert(dep.format() == "com.mydep:mydep:1.0.0@jar")
assert(dep.gradleFormat() == "compile 'com.mydep:mydep:1.0.0@jar'")
val dep2 = Dependency(group = "com.mydep", name = "mydep", version = "1.0.0", scope = Scope.TEST_RUNTIME)
assert(dep2.format() == "com.mydep:mydep:1.0.0")
assert(dep2.gradleFormat() == "testRuntime 'com.mydep:mydep:1.0.0'")
}
private fun newProject(vararg langs: Language): Project {
if (langs.isEmpty())
throw IllegalArgumentException("Must have more than one language")
return Project("test-proj", "com.example.app", version = "0.1", languages = setOf(*langs), gitRepo = "https://github.com/example/example")
}
}
|
mit
|
bc755023f685a40dcd2bce286baaf2c5
| 48.877551 | 146 | 0.662848 | 3.557496 | false | true | false | false |
slartus/4pdaClient-plus
|
qms/qms-impl/src/main/java/org/softeg/slartus/forpdaplus/qms/impl/screens/threads/fingerprints/QmsThreadFingerprint.kt
|
1
|
3385
|
package org.softeg.slartus.forpdaplus.qms.impl.screens.threads.fingerprints
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint
import org.softeg.slartus.forpdaplus.qms.impl.R
import org.softeg.slartus.forpdaplus.qms.impl.databinding.LayoutQmsThreadItemBinding
class QmsThreadFingerprint(
@DrawableRes
private val accentBackground: Int,
private val onClickListener: (view: View?, item: QmsThreadItem) -> Unit,
private val onLongClickListener: (view: View?, item: QmsThreadItem) -> Boolean
) :
ItemFingerprint<LayoutQmsThreadItemBinding, QmsThreadItem> {
private val diffUtil = object : DiffUtil.ItemCallback<QmsThreadItem>() {
override fun areItemsTheSame(
oldItem: QmsThreadItem,
newItem: QmsThreadItem
) = oldItem.id == newItem.id
override fun areContentsTheSame(
oldItem: QmsThreadItem,
newItem: QmsThreadItem
) = oldItem == newItem
}
override fun getLayoutId() = R.layout.layout_qms_thread_item
override fun isRelativeItem(item: Item) = item is QmsThreadItem
override fun getViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup
): BaseViewHolder<LayoutQmsThreadItemBinding, QmsThreadItem> {
val binding = LayoutQmsThreadItemBinding.inflate(layoutInflater, parent, false)
return QmsThreadViewHolder(
binding = binding,
accentBackground = accentBackground,
onClickListener = onClickListener,
onLongClickListener = onLongClickListener
)
}
override fun getDiffUtil() = diffUtil
}
class QmsThreadViewHolder(
binding: LayoutQmsThreadItemBinding,
@DrawableRes
accentBackground: Int,
private val onClickListener: (view: View?, item: QmsThreadItem) -> Unit,
private val onLongClickListener: (view: View?, item: QmsThreadItem) -> Boolean
) :
BaseViewHolder<LayoutQmsThreadItemBinding, QmsThreadItem>(binding) {
private val totalTextFormat =
itemView.context.getString(org.softeg.slartus.forpdaplus.core_res.R.string.qms_thread_total)
init {
itemView.setOnClickListener { v -> onClickListener(v, item) }
itemView.setOnLongClickListener { v -> onLongClickListener(v, item) }
binding.newMessagesCountTextView.setBackgroundResource(accentBackground)
}
override fun onBind(item: QmsThreadItem) {
super.onBind(item)
with(binding) {
titleTextView.text = item.title
messagesCountTextView.text = totalTextFormat.format(item.messagesCount)
newMessagesCountTextView.text = item.newMessagesCount.toString()
newMessagesCountTextView.isVisible = item.newMessagesCount > 0
dateTextView.text = item.lastMessageDate
}
}
}
data class QmsThreadItem(
override val id: String,
override val title: String,
override val messagesCount: Int,
override val newMessagesCount: Int,
override val lastMessageDate: String?
) : ThreadItem
|
apache-2.0
|
5bb56bbd0f994c676997063501dadb11
| 36.622222 | 100 | 0.724668 | 4.656121 | false | false | false | false |
AlexLandau/semlang
|
kotlin/refill/src/test/kotlin/recorders.kt
|
1
|
6799
|
package net.semlang.refill
import java.util.ArrayList
internal class RecordingRawInstance(val delegate: TrickleInstance): TrickleRawInstance {
override val definition: TrickleDefinition
get() = delegate.definition
// It would be nice to record these as actual objects, but that would take some effort
val records = ArrayList<String>()
@Synchronized
override fun setInputs(changes: List<TrickleInputChange>): Long {
records.add("Calling setInputs")
records.add(" changes: $changes")
val result = delegate.setInputs(changes)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> setInput(nodeName: NodeName<T>, value: T): Long {
records.add("Calling setInput")
records.add(" nodeName: $nodeName")
records.add(" value: $value")
val result = delegate.setInput(nodeName, value)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> setInput(nodeName: KeyListNodeName<T>, list: List<T>): Long {
records.add("Calling setInput")
records.add(" nodeName: $nodeName")
records.add(" list: $list")
val result = delegate.setInput(nodeName, list)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> addKeyInput(nodeName: KeyListNodeName<T>, key: T): Long {
records.add("Calling addKeyInput")
records.add(" nodeName: $nodeName")
records.add(" key: $key")
val result = delegate.addKeyInput(nodeName, key)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> removeKeyInput(nodeName: KeyListNodeName<T>, key: T): Long {
records.add("Calling removeKeyInput")
records.add(" nodeName: $nodeName")
records.add(" key: $key")
val result = delegate.removeKeyInput(nodeName, key)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, T> setKeyedInput(nodeName: KeyedNodeName<K, T>, key: K, value: T): Long {
records.add("Calling setKeyedInput")
records.add(" nodeName: $nodeName")
records.add(" key: $key")
records.add(" value: $value")
val result = delegate.setKeyedInput(nodeName, key, value)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, T> setKeyedInputs(nodeName: KeyedNodeName<K, T>, map: Map<K, T>): Long {
records.add("Calling setKeyedInputs")
records.add(" nodeName: $nodeName")
records.add(" map: $map")
val result = delegate.setKeyedInputs(nodeName, map)
records.add(" result: $result")
return result
}
@Synchronized
override fun getNextSteps(): List<TrickleStep> {
records.add("Calling getNextSteps")
val result = delegate.getNextSteps()
records.add(" result: $result")
return result
}
@Synchronized
override fun completeSynchronously() {
records.add("Calling completeSynchronously")
delegate.completeSynchronously()
records.add("Done with completeSynchronously")
}
@Synchronized
override fun reportResult(result: TrickleStepResult) {
records.add("Calling reportResult")
records.add(" result (arg): $result")
delegate.reportResult(result)
}
@Synchronized
override fun <T> getNodeValue(nodeName: NodeName<T>): T {
records.add("Calling getNodeValue")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeValue(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> getNodeValue(nodeName: KeyListNodeName<T>): List<T> {
records.add("Calling getNodeValue")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeValue(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, V> getNodeValue(nodeName: KeyedNodeName<K, V>, key: K): V {
records.add("Calling getNodeValue")
records.add(" nodeName: $nodeName")
records.add(" key: $key")
val result = delegate.getNodeValue(nodeName, key)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, V> getNodeValue(nodeName: KeyedNodeName<K, V>): List<V> {
records.add("Calling getNodeValue")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeValue(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> getNodeOutcome(nodeName: NodeName<T>): NodeOutcome<T> {
records.add("Calling getNodeOutcome")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeOutcome(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun <T> getNodeOutcome(nodeName: KeyListNodeName<T>): NodeOutcome<List<T>> {
records.add("Calling getNodeOutcome")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeOutcome(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, V> getNodeOutcome(nodeName: KeyedNodeName<K, V>, key: K): NodeOutcome<V> {
records.add("Calling getNodeOutcome")
records.add(" nodeName: $nodeName")
records.add(" key: $key")
val result = delegate.getNodeOutcome(nodeName, key)
records.add(" result: $result")
return result
}
@Synchronized
override fun <K, V> getNodeOutcome(nodeName: KeyedNodeName<K, V>): NodeOutcome<List<V>> {
records.add("Calling getNodeOutcome")
records.add(" nodeName: $nodeName")
val result = delegate.getNodeOutcome(nodeName)
records.add(" result: $result")
return result
}
@Synchronized
override fun getLastUpdateTimestamp(valueId: ValueId): Long {
records.add("Calling getLastUpdateTimestamp")
records.add(" valueId: $valueId")
val result = delegate.getLastUpdateTimestamp(valueId)
records.add(" result: $result")
return result
}
@Synchronized
override fun getLatestTimestampWithValue(valueId: ValueId): Long {
records.add("Calling getLatestTimestampWithValue")
records.add(" valueId: $valueId")
val result = delegate.getLatestTimestampWithValue(valueId)
records.add(" result: $result")
return result
}
@Synchronized
fun getRecording(): List<String> {
return records
}
}
|
apache-2.0
|
56235f68ebe35c498b03f5c1252d0833
| 33.165829 | 95 | 0.63024 | 4.319568 | false | false | false | false |
stripe/stripe-android
|
paymentsheet-example/src/androidTestDebug/java/com/stripe/android/TestLink.kt
|
1
|
3115
|
package com.stripe.android
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import com.stripe.android.test.core.AuthorizeAction
import com.stripe.android.test.core.Automatic
import com.stripe.android.test.core.Billing
import com.stripe.android.test.core.Browser
import com.stripe.android.test.core.Currency
import com.stripe.android.test.core.Customer
import com.stripe.android.test.core.DelayedPMs
import com.stripe.android.test.core.DisableAnimationsRule
import com.stripe.android.test.core.GooglePayState
import com.stripe.android.test.core.INDIVIDUAL_TEST_TIMEOUT_SECONDS
import com.stripe.android.test.core.IntentType
import com.stripe.android.test.core.LinkState
import com.stripe.android.test.core.MyScreenCaptureProcessor
import com.stripe.android.test.core.PlaygroundTestDriver
import com.stripe.android.test.core.Shipping
import com.stripe.android.test.core.TestParameters
import com.stripe.android.test.core.TestWatcher
import com.stripe.android.ui.core.forms.resources.LpmRepository
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Timeout
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TestLink {
@get:Rule
var globalTimeout: Timeout = Timeout.seconds(INDIVIDUAL_TEST_TIMEOUT_SECONDS)
@get:Rule
val composeTestRule = createEmptyComposeRule()
@get:Rule
val testWatcher = TestWatcher()
@get:Rule
val disableAnimations = DisableAnimationsRule()
private lateinit var device: UiDevice
private lateinit var testDriver: PlaygroundTestDriver
private val screenshotProcessor = MyScreenCaptureProcessor()
@Before
fun before() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
testDriver = PlaygroundTestDriver(device, composeTestRule, screenshotProcessor)
}
@After
fun after() {
}
private val linkNewUser = TestParameters(
paymentMethod = lpmRepository.fromCode("card")!!,
customer = Customer.Guest,
linkState = LinkState.On,
googlePayState = GooglePayState.On,
currency = Currency.USD,
intentType = IntentType.Pay,
billing = Billing.Off,
shipping = Shipping.Off,
delayed = DelayedPMs.Off,
automatic = Automatic.Off,
saveCheckboxValue = false,
saveForFutureUseCheckboxVisible = false,
useBrowser = Browser.Chrome,
authorizationAction = AuthorizeAction.Authorize,
merchantCountryCode = "US",
)
@Test
fun testLinkInlineCustom() {
testDriver.testLinkCustom(linkNewUser)
}
companion object {
private val lpmRepository = LpmRepository(
LpmRepository.LpmRepositoryArguments(
InstrumentationRegistry.getInstrumentation().targetContext.resources
)
).apply {
forceUpdate(this.supportedPaymentMethods, null)
}
}
}
|
mit
|
e0b28538f2e1175e328410c08a197bbb
| 32.858696 | 87 | 0.747673 | 4.33844 | false | true | false | false |
AndroidX/androidx
|
bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/AdvertisingSetCallback.kt
|
3
|
7134
|
/*
* 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.bluetooth.le.AdvertisingSetCallback as FwkAdvertisingSetCallback
import android.bluetooth.le.AdvertisingSet as FwkAdvertisingSet
@JvmDefaultWithCompatibility
/**
* Bluetooth LE advertising set callbacks, used to deliver advertising operation
* status.
*
* @hide
*/
interface AdvertisingSetCallback {
companion object {
/**
* The requested operation was successful.
*/
const val ADVERTISE_SUCCESS =
FwkAdvertisingSetCallback.ADVERTISE_SUCCESS
/**
* Failed to start advertising as the advertise data to be broadcasted is too
* large.
*/
const val ADVERTISE_FAILED_DATA_TOO_LARGE =
FwkAdvertisingSetCallback.ADVERTISE_FAILED_DATA_TOO_LARGE
/**
* Failed to start advertising because no advertising instance is available.
*/
const val ADVERTISE_FAILED_TOO_MANY_ADVERTISERS =
FwkAdvertisingSetCallback.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS
/**
* Failed to start advertising as the advertising is already started.
*/
const val ADVERTISE_FAILED_ALREADY_STARTED =
FwkAdvertisingSetCallback.ADVERTISE_FAILED_ALREADY_STARTED
/**
* Operation failed due to an internal error.
*/
const val ADVERTISE_FAILED_INTERNAL_ERROR =
FwkAdvertisingSetCallback.ADVERTISE_FAILED_INTERNAL_ERROR
/**
* This feature is not supported on this platform.
*/
const val ADVERTISE_FAILED_FEATURE_UNSUPPORTED =
FwkAdvertisingSetCallback.ADVERTISE_FAILED_FEATURE_UNSUPPORTED
}
/**
* Callback triggered in response to [BluetoothLeAdvertiser.startAdvertisingSet]
* indicating result of the operation. If status is ADVERTISE_SUCCESS, then advertisingSet
* contains the started set and it is advertising. If error occurred, advertisingSet is
* null, and status will be set to proper error code.
*
* @param advertisingSet The advertising set that was started or null if error.
* @param txPower tx power that will be used for this set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onAdvertisingSetStarted(advertisingSet: FwkAdvertisingSet, txPower: Int, status: Int) {}
/**
* Callback triggered in response to [BluetoothLeAdvertiser.stopAdvertisingSet]
* indicating advertising set is stopped.
*
* @param advertisingSet The advertising set.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onAdvertisingSetStopped(advertisingSet: FwkAdvertisingSet) {}
/**
* Callback triggered in response to [BluetoothLeAdvertiser.startAdvertisingSet]
* indicating result of the operation. If status is ADVERTISE_SUCCESS, then advertising set is
* advertising.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onAdvertisingEnabled(advertisingSet: FwkAdvertisingSet, enable: Boolean, status: Int) {}
/**
* Callback triggered in response to [AdvertisingSet.setAdvertisingData] indicating
* result of the operation. If status is ADVERTISE_SUCCESS, then data was changed.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onAdvertisingDataSet(advertisingSet: FwkAdvertisingSet, status: Int) {}
/**
* Callback triggered in response to [AdvertisingSet.setAdvertisingData] indicating
* result of the operation.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onScanResponseDataSet(advertisingSet: FwkAdvertisingSet, status: Int) {}
/**
* Callback triggered in response to [AdvertisingSet.setAdvertisingParameters]
* indicating result of the operation.
*
* @param advertisingSet The advertising set.
* @param txPower tx power that will be used for this set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onAdvertisingParametersUpdated(
advertisingSet: FwkAdvertisingSet,
txPower: Int,
status: Int
) {
}
/**
* Callback triggered in response to [AdvertisingSet.setPeriodicAdvertisingParameters]
* indicating result of the operation.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onPeriodicAdvertisingParametersUpdated(advertisingSet: FwkAdvertisingSet, status: Int) {}
/**
* Callback triggered in response to [AdvertisingSet.setPeriodicAdvertisingData]
* indicating result of the operation.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onPeriodicAdvertisingDataSet(advertisingSet: FwkAdvertisingSet, status: Int) {}
/**
* Callback triggered in response to [AdvertisingSet.setPeriodicAdvertisingEnabled]
* indicating result of the operation.
*
* @param advertisingSet The advertising set.
* @param status Status of the operation.
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onPeriodicAdvertisingEnabled(
advertisingSet: FwkAdvertisingSet,
enable: Boolean,
status: Int
) {
}
/**
* Callback triggered in response to [AdvertisingSet.getOwnAddress]
* indicating result of the operation.
*
* @param advertisingSet The advertising set.
* @param addressType type of address.
* @param address advertising set bluetooth address.
* @hide
*/
// TODO(ofy) Change FwkAdvertisingSet to core.AdvertisingSet when it is available
fun onOwnAddressRead(advertisingSet: FwkAdvertisingSet, addressType: Int, address: String?) {}
}
|
apache-2.0
|
ba9f3617f3b44a830c118f48bc72b17f
| 37.562162 | 98 | 0.702271 | 4.687254 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems
|
advanced/rest/pagination-offset/src/test/kotlin/org/tsdes/advanced/rest/pagination/PaginationRestTest.kt
|
1
|
11255
|
package org.tsdes.advanced.rest.pagination
import io.restassured.RestAssured
import io.restassured.RestAssured.given
import io.restassured.http.ContentType
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.tsdes.advanced.rest.pagination.dto.hal.PageDto
import org.tsdes.advanced.rest.pagination.dto.CommentDto
import org.tsdes.advanced.rest.pagination.dto.NewsDto
import org.tsdes.advanced.rest.pagination.dto.VoteDto
import org.tsdes.advanced.rest.pagination.entity.News
import java.util.*
@Repository
interface Rep : CrudRepository<News, Long>
@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [(PaginationApplication::class)],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PaginationRestTest {
@LocalServerPort
protected var port = 0
@Autowired
private lateinit var rep: Rep
@BeforeEach
@AfterEach
fun clean() {
// RestAssured configs shared by all the tests
RestAssured.baseURI = "http://localhost"
RestAssured.port = port
RestAssured.basePath = "/news"
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails()
rep.deleteAll()
}
@Test
fun testBaseCreateNews() {
val text = "some text"
val country = "Norway"
val location = given().body(NewsDto(null, text, country))
.contentType(ContentType.JSON)
.post()
.then()
.statusCode(201)
.extract().header("location")
given().get()
.then()
.statusCode(200)
.body("list.size()", equalTo(1))
.body("totalSize", equalTo(1))
given().basePath("")
.get(location)
.then()
.statusCode(200)
.body("text", equalTo(text))
.body("country", equalTo(country))
}
private fun createNews(text: String, country: String) {
given().body(NewsDto(null, text, country))
.contentType(ContentType.JSON)
.post()
.then()
.statusCode(201)
}
private fun createSeveralNews(n: Int): Int {
for (i in 0 until n) {
createNews("$i", "Norway")
}
return n
}
/**
* Extract the "text" fields from all the News
*/
private fun getTexts(selfDto: PageDto<*>): MutableSet<String> {
val values = HashSet<String>()
selfDto.list.stream()
.map{ (it as Map<String,String>)["text"] }
.forEach { if(it!=null){values.add(it)} }
return values
}
private fun assertContainsTheSame(a: Collection<*>, b: Collection<*>) {
assertEquals(a.size.toLong(), b.size.toLong())
a.forEach { assertTrue(b.contains(it)) }
b.forEach { assertTrue(a.contains(it)) }
}
@Test
fun testSelfLink() {
val n = createSeveralNews(30)
val limit = 10
val listDto = given()
.queryParam("limit", limit)
.get()
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
assertEquals(n, listDto.totalSize.toInt())
assertEquals(0, listDto.rangeMin)
assertEquals(limit - 1, listDto.rangeMax)
assertNull(listDto.previous)
assertNotNull(listDto.next)
assertNotNull(listDto._self)
//read again using self link
val selfDto = given()
.basePath("")
.get(listDto._self!!.href)
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
val first = getTexts(listDto)
val self = getTexts(selfDto)
assertContainsTheSame(first, self)
}
@Test
fun testNextLink() {
val n = createSeveralNews(30)
val limit = 10
var listDto: PageDto<*> = given()
.queryParam("limit", limit)
.get()
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
assertEquals(n, listDto.totalSize.toInt())
assertNotNull(listDto.next!!.href)
val values = getTexts(listDto)
var next : String? = listDto.next?.href
var counter = 0
//read pages until there is still a "next" link
while (next != null) {
counter++
val beforeNextSize = values.size
listDto = given()
.basePath("")
.get(next)
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
values.addAll(getTexts(listDto))
assertEquals(beforeNextSize + limit, values.size)
assertEquals(counter * limit, listDto.rangeMin)
assertEquals(listDto.rangeMin + limit - 1, listDto.rangeMax)
next = listDto.next?.href
}
assertEquals(n.toLong(), values.size.toLong())
}
@Test
fun testJsonIgnore() {
createSeveralNews(30)
val limit = 10
given().queryParam("limit", limit)
.get()
.then()
.statusCode(200)
.body("_links.next", notNullValue())
.body("next", nullValue())
}
@Test
fun textPreviousLink() {
val n = createSeveralNews(30)
val limit = 10
val listDto = given()
.queryParam("limit", limit)
.get()
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
val first = getTexts(listDto)
//read next page
val nextDto = given()
.basePath("")
.get(listDto.next!!.href)
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
val next = getTexts(nextDto)
// check that an element of next page was not in the first page
assertTrue(!first.contains(next.iterator().next()))
/*
The "previous" page of the "next" page should be the
first "self" page, ie
self.next.previous == self
*/
val previousDto = given()
.basePath("")
.get(nextDto.previous!!.href)
.then()
.statusCode(200)
.extract()
.`as`(PageDto::class.java)
val previous = getTexts(previousDto)
assertContainsTheSame(first, previous)
}
private fun createNewsWithCommentAndVote() {
val newsLocation = given().body(NewsDto(null, "some text", "Sweden"))
.contentType(ContentType.JSON)
.post()
.then()
.statusCode(201)
.extract().header("location")
given().basePath("")
.body(VoteDto(user = "a user"))
.contentType(ContentType.JSON)
.post("$newsLocation/votes")
.then()
.statusCode(201)
given().basePath("")
.body(CommentDto(null, "a comment"))
.contentType(ContentType.JSON)
.post("$newsLocation/comments")
.then()
.statusCode(201)
}
private fun getWithExpand(expandType: String, expectedComments: Int, expectedVotes: Int) {
given().queryParam("expand", expandType)
.get()
.then()
.statusCode(200)
.body("list.size()", equalTo(1))
.body("list[0].comments.id.size()", equalTo(expectedComments))
.body("list[0].votes.id.size()", equalTo(expectedVotes))
.body("_links.self.href", containsString("expand=$expandType"))
}
@Test
fun testExpandNone() {
createNewsWithCommentAndVote()
getWithExpand("NONE", 0, 0)
}
@Test
fun testExpandALL() {
createNewsWithCommentAndVote()
getWithExpand("ALL", 1, 1)
}
@Test
fun testExpandComments() {
createNewsWithCommentAndVote()
getWithExpand("COMMENTS", 1, 0)
}
@Test
fun testExpandVotes() {
createNewsWithCommentAndVote()
getWithExpand("VOTES", 0, 1)
}
@Test
fun testNegativeOffset() {
given().queryParam("offset", -1)
.get()
.then()
.statusCode(400)
}
@Test
fun testInvalidOffset() {
given().queryParam("offset", 0)
.get()
.then()
.statusCode(200)
given().queryParam("offset", 1)
.get()
.then()
.statusCode(400)
}
@Test
fun testInvalidLimit() {
given().queryParam("limit", 0)
.get()
.then()
.statusCode(400)
}
@Test
fun testInvalidExpand() {
/*
Slightly tricky: in the code we use "expand" as a Java
enumeration. But, in the URI request, it is just a string.
So what happens if the string does not match any valid value
in the enum? Technically, it should be a 4xx user error.
The actual code might vary depending on the server.
*/
given().queryParam("expand", "foo")
.get()
.then()
.statusCode(400)
/*
however, what if you just use a param that does not exist?
it just gets ignored...
so the behavior is actually quite inconsistent.
The main problem here is that, if you just misspell a query
parameter, it might just get ignored with no warning.
*/
given().queryParam("bar", "foo")
.get()
.then()
.statusCode(200)
/*
So, this is an issue. If we misspell an existing
query parameter (eg, note the missing "d"), by default
it will be just ignored
*/
given().queryParam("expan", "ALL")
.get()
.then()
.statusCode(200)
/*
As ignored, the check against the enum would not be done
*/
given().queryParam("expan", "foo")
.get()
.then()
.statusCode(200)
}
}
|
lgpl-3.0
|
96f98dd466f6c715cec5fa6d7aeba9e2
| 25.992806 | 94 | 0.528299 | 4.646986 | false | true | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/post/StoryPostFragment.kt
|
1
|
5249
|
package org.thoughtcrime.securesms.stories.viewer.post
import android.app.Activity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.ViewBinderDelegate
import org.thoughtcrime.securesms.components.voice.VoiceNoteMediaControllerOwner
import org.thoughtcrime.securesms.databinding.StoriesPostFragmentBinding
import org.thoughtcrime.securesms.mediapreview.VideoControlsDelegate
import org.thoughtcrime.securesms.stories.viewer.page.StoryDisplay
import org.thoughtcrime.securesms.stories.viewer.page.StoryViewerPageViewModel
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.fragments.requireListener
import org.thoughtcrime.securesms.util.visible
import org.thoughtcrime.securesms.video.VideoPlayer.PlayerCallback
/**
* Renders a given StoryPost object as a viewable story.
*/
class StoryPostFragment : Fragment(R.layout.stories_post_fragment) {
private val postViewModel: StoryPostViewModel by viewModels(factoryProducer = {
StoryPostViewModel.Factory(StoryTextPostRepository())
})
private val pageViewModel: StoryViewerPageViewModel by viewModels(ownerProducer = {
requireParentFragment()
})
private val binding by ViewBinderDelegate(StoriesPostFragmentBinding::bind) {
it.video.cleanup()
presentNone()
}
private val disposables = LifecycleDisposable()
private var storyImageLoader: StoryImageLoader? = null
private var storyTextLoader: StoryTextLoader? = null
private var storyVideoLoader: StoryVideoLoader? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initializeVideoPlayer()
disposables.bindTo(viewLifecycleOwner)
disposables += pageViewModel.postContent
.filter { it.isPresent }
.map { it.get() }
.distinctUntilChanged()
.subscribe {
postViewModel.onPostContentChanged(it)
}
disposables += postViewModel.state.distinctUntilChanged().subscribe { state ->
when (state) {
is StoryPostState.None -> presentNone()
is StoryPostState.TextPost -> presentTextPost(state)
is StoryPostState.VideoPost -> presentVideoPost(state)
is StoryPostState.ImagePost -> presentImagePost(state)
}
}
}
private fun initializeVideoPlayer() {
binding.video.setWindow(requireActivity().window)
binding.video.setPlayerPositionDiscontinuityCallback { _, r: Int ->
requireCallback().getVideoControlsDelegate()?.onPlayerPositionDiscontinuity(r)
}
binding.video.setPlayerCallback(object : PlayerCallback {
override fun onReady() {
requireCallback().onContentReady()
}
override fun onPlaying() {
val activity: Activity? = activity
if (activity is VoiceNoteMediaControllerOwner) {
(activity as VoiceNoteMediaControllerOwner).voiceNoteMediaController.pausePlayback()
}
}
override fun onStopped() {}
override fun onError() {
requireCallback().onContentNotAvailable()
}
})
}
private fun presentNone() {
storyImageLoader?.clear()
storyImageLoader = null
storyVideoLoader?.clear()
storyVideoLoader = null
storyTextLoader = null
binding.text.visible = false
binding.blur.visible = false
binding.image.visible = false
binding.video.visible = false
}
private fun presentVideoPost(state: StoryPostState.VideoPost) {
presentNone()
binding.video.visible = true
binding.blur.visible = true
val storyBlurLoader = StoryBlurLoader(
viewLifecycleOwner.lifecycle,
state.blurHash,
state.videoUri,
pageViewModel.storyCache,
StoryDisplay.getStorySize(resources),
binding.blur
)
storyVideoLoader = StoryVideoLoader(
this,
state,
binding.video,
requireCallback(),
storyBlurLoader
)
storyVideoLoader?.load()
}
private fun presentImagePost(state: StoryPostState.ImagePost) {
presentNone()
binding.image.visible = true
binding.blur.visible = true
storyImageLoader = StoryImageLoader(
this,
state,
pageViewModel.storyCache,
StoryDisplay.getStorySize(resources),
binding.image,
binding.blur,
requireCallback()
)
storyImageLoader?.load()
}
private fun presentTextPost(state: StoryPostState.TextPost) {
presentNone()
if (state.loadState == StoryPostState.LoadState.FAILED) {
requireCallback().onContentNotAvailable()
return
}
if (state.loadState == StoryPostState.LoadState.INIT) {
return
}
binding.text.visible = true
storyTextLoader = StoryTextLoader(
this,
binding.text,
state,
requireCallback()
)
storyTextLoader?.load()
}
fun requireCallback(): Callback {
return requireListener()
}
interface Callback {
fun onContentReady()
fun onContentNotAvailable()
fun setIsDisplayingLinkPreviewTooltip(isDisplayingLinkPreviewTooltip: Boolean)
fun getVideoControlsDelegate(): VideoControlsDelegate?
}
}
|
gpl-3.0
|
3c0c3e22a01023ab2d02dbfd63d6928d
| 26.920213 | 94 | 0.727186 | 4.737365 | false | false | false | false |
stoyicker/dinger
|
data/src/main/kotlin/data/tinder/recommendation/RecommendationTeaserDaoDelegate.kt
|
1
|
1265
|
package data.tinder.recommendation
import data.database.CollectibleDaoDelegate
import domain.recommendation.DomainRecommendationTeaser
internal class RecommendationTeaserDaoDelegate(
private val teaserDao: RecommendationUserTeaserDao,
private val userTeaserDao: RecommendationUser_TeaserDao)
: CollectibleDaoDelegate<String, DomainRecommendationTeaser>() {
override fun selectByPrimaryKey(primaryKey: String) =
teaserDao.selectTeaserById(primaryKey).firstOrNull()?.let {
return@let DomainRecommendationTeaser(
id = it.id,
description = it.description,
type = it.type)
} ?: DomainRecommendationTeaser.NONE
override fun insertResolved(source: DomainRecommendationTeaser) = teaserDao
.insertTeaser(RecommendationUserTeaserEntity(
id = source.id,
description = source.description,
type = source.type))
fun insertResolvedForUserId(userId: String, teasers: Iterable<DomainRecommendationTeaser>) =
teasers.forEach {
insertResolved(it)
userTeaserDao.insertUser_Teaser(RecommendationUserEntity_RecommendationUserTeaserEntity(
recommendationUserEntityId = userId,
recommendationUserTeaserEntityId = it.id))
}
}
|
mit
|
8c28a6b2f475095dfe3aa7dc8059b487
| 39.806452 | 96 | 0.739921 | 4.702602 | false | false | false | false |
mvaldez/kotlin-examples
|
src/i_introduction/_5_String_Templates/StringTemplates.kt
|
1
|
1186
|
package i_introduction._5_String_Templates
import util.TODO
import util.doc5
fun example1(a: Any, b: Any) =
"This is some text in which variables ($a, $b) appear."
fun example2(a: Any, b: Any) =
"You can write it in a Java way as well. Like this: " + a + ", " + b + "!"
fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}"
fun example4() =
"""
You can use raw strings to write multiline text.
There is no escaping here, so raw strings are useful for writing regex patterns,
you don't need to escape a backslash by a backslash.
String template entries (${42}) are allowed here.
"""
fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""
fun example() = "13.06.1992".matches(getPattern().toRegex()) //true
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
fun todoTask5(): Nothing = TODO(
"""
Task 5.
Copy the body of 'getPattern()' to the 'task5()' function
and rewrite it in such a way that it matches '13 JUN 1992'.
Use the 'month' variable.
""",
documentation = doc5(),
references = { getPattern(); month })
fun task5(): String = """\d{2}\s($month)\s\d{4}"""
|
mit
|
653895608584de58491358e3f212cbc7
| 30.210526 | 91 | 0.62226 | 3.249315 | false | false | false | false |
GDLActivity/Who-Or-What-Is-Kotlin
|
src/main/kotlin/extension/ExtensionFun.kt
|
1
|
2074
|
package extension
/**
* Created by sierisimo on 11/6/16.
*/
val cache = mutableListOf("",
" ",
" ",
" ",
" ",
" ")
fun String.leftpad(size: Int, char: String = " " /*`char` defaults to `' '`*/): String {
// `len` is the `pad`'s length now
var len: Int = size - length
if (len > 0) {
return if (char == " " && len < cache.size) {
// cache common use cases
cache[len] + this
} else if (char == " " && len > cache.size) {
// If len is not cached, put it on the cache
while (len >= cache.size) cache.add(cache[cache.size - 1] + " ")
// now a cache common use case
cache[len] + this
} else {
// `pad` starts with an empty string
var pad = ""
// mutable string
var ch = char
while (true) {
// add `ch` to `pad` if `len` is odd
if (len % 2 == 1) {
pad += ch
}
// divide `len` by 2, ditch the remainder
len /= 2
if (len > 0) {
// "double" the `ch` so this operation count grows logarithmically on `len`
// each time `ch` is "doubled", the `len` would need to be "doubled" too
// similar to finding a value in binary search tree, hence O(log(n))
ch += ch
} else break // `len` is 0, exit the loop
}
// return the new created string
pad + this
}
} else {
// doesn't need to pad
return this
}
}
fun Int.divideByTwo(): Int {
return this / 2
}
fun String.leftpad(size: Int, value: Any): String = this.leftpad(size, value.toString())
fun main(args: Array<String>) {
val word = "Perrito"
println(word.leftpad(10))
println(word.leftpad(20, "-"))
println("GDLActivity".leftpad(20))
println("GDLActivity".leftpad(30, ""))
println(5.divideByTwo())
}
|
gpl-2.0
|
02d22b8ae030553de41d5d49a972a492
| 26.653333 | 95 | 0.468177 | 3.798535 | false | false | false | false |
TUWien/DocScan
|
app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/images/ImagesAdapter.kt
|
1
|
6637
|
package at.ac.tuwien.caa.docscan.ui.docviewer.images
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.databinding.GalleryItemBinding
import at.ac.tuwien.caa.docscan.db.model.state.PostProcessingState
import at.ac.tuwien.caa.docscan.logic.FileHandler
import at.ac.tuwien.caa.docscan.logic.GlideHelper
import at.ac.tuwien.caa.docscan.logic.calculateImageResolution
import org.koin.java.KoinJavaComponent.inject
import kotlin.math.roundToInt
class ImagesAdapter(
private val onClick: (PageSelection) -> Unit,
private val onLongClick: (PageSelection) -> Unit,
screenWidth: Int,
private val columnCount: Int,
private val paddingPx: Int,
private val marginPx: Int
) : ListAdapter<PageSelection, ImagesAdapter.ImageViewHolder>(DiffPageCallback()) {
private val itemWidth = screenWidth / columnCount
private val fileHandler: FileHandler by inject(FileHandler::class.java)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
return ImageViewHolder(GalleryItemBinding.inflate(LayoutInflater.from(parent.context)))
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
holder.bind(getItem(position), position)
}
inner class ImageViewHolder(val binding: GalleryItemBinding) :
RecyclerView.ViewHolder(binding.root), View.OnClickListener, View.OnLongClickListener {
fun bind(page: PageSelection, position: Int) {
val isProcessing = page.page.postProcessingState == PostProcessingState.PROCESSING
// set click listeners
binding.root.setOnClickListener(this)
binding.root.setOnLongClickListener(this)
// TODO: Consider calling this in the viewModel on an IO thread
val aspectRatio = fileHandler.getFileByPage(page.page)?.let {
calculateImageResolution(it, page.page.rotation).aspectRatio
} ?: .0
val topView = binding.pageContainer
// set item height based on ratio
topView.layoutParams.height = if (aspectRatio != .0) {
(itemWidth / aspectRatio).roundToInt()
} else {
itemWidth
}
// set item width to the calculate width
topView.layoutParams.width = itemWidth
// set paddings
when {
(position % columnCount) == 0 -> {
topView.setPadding(0, paddingPx, paddingPx, paddingPx)
}
(position % columnCount) == (columnCount - 1) -> {
topView.setPadding(paddingPx, paddingPx, 0, paddingPx)
}
else -> {
topView.setPadding(paddingPx / 2, paddingPx, paddingPx / 2, paddingPx)
}
}
// set image view
binding.pageImageview.transitionName = page.page.id.toString()
val isCropped = page.page.postProcessingState == PostProcessingState.DONE
binding.pageProgressbar.visibility = if (isProcessing) View.VISIBLE else View.INVISIBLE
binding.pageCheckbox.isEnabled = page.isSelectionActivated
GlideHelper.loadPageIntoImageView(
page.page,
binding.pageImageview,
if (isCropped) GlideHelper.GlideStyles.IMAGE_CROPPED else GlideHelper.GlideStyles.IMAGES_UNCROPPED
)
// set checkbox
if (page.isSelectionActivated) {
binding.pageCheckbox.isChecked = page.isSelected
}
binding.pageCheckbox.visibility =
if (page.isSelectionActivated) View.VISIBLE else View.GONE
binding.pageContainer.setBackgroundColor(
ContextCompat.getColor(
itemView.context,
if (page.isSelectionActivated) R.color.colorSelectLight else R.color.white
)
)
val params = binding.pageImageview.layoutParams as RelativeLayout.LayoutParams
params.setMargins(
if (page.isSelectionActivated) marginPx else 0,
if (page.isSelectionActivated) marginPx else 0,
0,
0
)
}
override fun onClick(view: View) {
onClick(getItem(adapterPosition))
}
override fun onLongClick(view: View): Boolean {
onLongClick(getItem(adapterPosition))
return true
}
}
}
class DiffPageCallback : DiffUtil.ItemCallback<PageSelection>() {
override fun areItemsTheSame(oldItem: PageSelection, newItem: PageSelection): Boolean {
return oldItem.page.id == newItem.page.id
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(
oldItem: PageSelection,
newItem: PageSelection
): Boolean {
return isPrimaryEqual(oldItem, newItem) && isSecondaryEqual(oldItem, newItem)
}
/**
* See [at.ac.tuwien.caa.docscan.ui.docviewer.documents.DocumentAdapter] for the same function
* on why this is necessary.
*/
override fun getChangePayload(oldItem: PageSelection, newItem: PageSelection): Any? {
return when {
isPrimaryEqual(
oldItem,
newItem
) && !isSecondaryEqual(oldItem, newItem) -> Any()
else -> null
}
}
/**
* The primary equal check for which the default animation of the recyclerview is always applied
* if it's not equal.
*/
private fun isPrimaryEqual(
oldItem: PageSelection,
newItem: PageSelection
): Boolean {
return oldItem.page.fileHash == newItem.page.fileHash
}
/**
* In contrast to [isPrimaryEqual] these changes won't trigger a default animation.
*/
private fun isSecondaryEqual(
oldItem: PageSelection,
newItem: PageSelection
): Boolean {
return oldItem.isSelected == newItem.isSelected &&
oldItem.isSelectionActivated == newItem.isSelectionActivated &&
oldItem.page.singlePageBoundary == newItem.page.singlePageBoundary &&
oldItem.page.postProcessingState == newItem.page.postProcessingState
}
}
|
lgpl-3.0
|
8d2ac7c68caaeda46c4efcf072d09e1b
| 37.812865 | 114 | 0.645924 | 5.009057 | false | false | false | false |
teobaranga/T-Tasks
|
t-tasks/src/main/java/com/teo/ttasks/api/entities/TasksResponse.kt
|
1
|
809
|
package com.teo.ttasks.api.entities
import com.google.gson.annotations.Expose
import com.teo.ttasks.data.model.Task
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.Ignore
import io.realm.annotations.PrimaryKey
open class TasksResponse : RealmObject() {
companion object {
val EMPTY: TasksResponse = TasksResponse()
}
/** The task list ID */
@Expose
@PrimaryKey
var id: String? = null
@Expose
var etag: String? = null
@Expose
@Ignore
var nextPageToken: String? = null
/**
* The list of tasks associated with this task list.
*
* This list does not need to be persisted since each individual task will be persisted anyways.
* */
@Expose
@Ignore
var items: RealmList<Task>? = null
}
|
apache-2.0
|
06a07947eaff8ba65137bb0c454a30e0
| 20.864865 | 100 | 0.677379 | 4.106599 | false | false | false | false |
nurkiewicz/ts.class
|
src/main/kotlin/com/nurkiewicz/tsclass/parser/ast/Expression.kt
|
1
|
2307
|
package com.nurkiewicz.tsclass.parser.ast
sealed class Expression
data class AdditiveExpression(val left: Expression, val operator: Operator, val right: Expression): Expression() {
override fun toString(): String {
return "($left $operator $right)"
}
enum class Operator(private val s: String) {
PLUS("+"), MINUS("-");
override fun toString() = s
companion object {
fun of(s: String) = when (s) {
"+" -> PLUS
"-" -> MINUS
else -> throw IllegalArgumentException(s)
}
}
}
}
data class Identifier(val name: String) : Expression() {
override fun toString() = name
}
data class MethodCall(val name: String, val parameters: List<Expression>): Expression()
data class MultiplicativeExpression(val left: Expression, val operator: Operator, val right: Expression): Expression() {
override fun toString(): String {
return "($left $operator $right)"
}
enum class Operator(private val s: String) {
MUL("*"), DIV("/"), MOD("%");
override fun toString(): String {
return s
}
companion object {
fun of(s: String) = when (s) {
"*" -> MUL
"/" -> DIV
"%" -> MOD
else -> throw IllegalArgumentException(s)
}
}
}
}
data class Neg(val expression: Expression): Expression() {
override fun toString() = "-($expression)"
}
data class NumberLiteral(val value: Double) : Expression() {
override fun toString() = value.toString()
}
data class Relational(val left: Expression, val operator: Operator, val right: Expression) : Expression() {
override fun toString() = "($left) $operator ($right)"
enum class Operator(private val s: String) {
GT(">"), GTE(">="), LT("<"), LTE("<=");
override fun toString() = s
companion object {
fun of(s: String): Operator {
return when (s) {
">" -> GT
">=" -> GTE
"<" -> LT
"<=" -> LTE
else -> throw IllegalArgumentException("Unsupported operator $s")
}
}
}
}
}
|
apache-2.0
|
e39ad23ddd37338e9ffe9b0d162559ed
| 21.627451 | 120 | 0.52319 | 4.708163 | false | false | false | false |
Hentioe/BloggerMini
|
app/src/main/kotlin/io/bluerain/tweets/presenter/TweetPresenter.kt
|
1
|
2430
|
package io.bluerain.tweets.presenter
import io.bluerain.tweets.base.BasePresenter
import io.bluerain.tweets.data.ResultHandler
import io.bluerain.tweets.data.models.TweetJsonModel
import io.bluerain.tweets.data.models.TweetModel
import io.bluerain.tweets.data.service.TweetService
import io.bluerain.tweets.utils.ColorUtil
import io.bluerain.tweets.view.ITweetsView
class TweetPresenter : BasePresenter<ITweetsView>() {
override fun onCreate() {
super.onCreate()
}
override fun onAttachView(view: ITweetsView) {
super.onAttachView(view)
updateList()
}
fun updateList() {
TweetService.list(object : ResultHandler<List<TweetModel>>(view!!) {
override fun onSuccess(model: List<TweetModel>) {
view!!.initListView(model)
view!!.stopRefreshing()
}
override fun onFailure(code: Int, message: String) {
view!!.stopRefreshing()
}
})
}
fun updateTweetColor(id: Long, intColor: Int, content: String) {
val tweet = TweetJsonModel(id = id, color = ColorUtil.intToString(intColor), content = content)
async {
if (TweetService.update(tweet)) {
view!!.showText("编辑成功!")
updateList()
} else {
view!!.showText("编辑失败!")
}
}
}
fun publish(intColor: Int, content: String) {
val model = TweetModel(color = ColorUtil.intToString(intColor), content = content)
async {
if (TweetService.add(model)) {
view!!.showText("发布成功!")
view!!.clearContent()
updateList()
} else {
view!!.showText("发布失败!")
}
}
}
fun deleteTweet(id: Long) {
async {
if (TweetService.delete(id))
updateList()
else
view!!.showText("删除失败!")
}
}
fun hiddenTweet(id: Long) {
async {
if (TweetService.hidden(id))
updateList()
else
view!!.showText("隐藏失败!")
}
}
fun normalTweet(id: Long) {
async {
if (TweetService.normal(id))
updateList()
else
view!!.showText("恢复失败!")
}
}
}
|
gpl-3.0
|
bee86dab99898c91b441fb51600ec72d
| 25.988636 | 103 | 0.538753 | 4.521905 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/execution/ui/ConsoleViewImpl.kt
|
1
|
2778
|
/*
* Copyright (C) 2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.execution.ui
import com.intellij.execution.filters.Filter
import com.intellij.execution.filters.HyperlinkInfo
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
open class ConsoleViewImpl : JPanel(BorderLayout()), ConsoleView, DataProvider {
private var helpId: String? = null
// region ConsoleView
override fun hasDeferredOutput(): Boolean = false
override fun clear() {
}
override fun setHelpId(helpId: String) {
this.helpId = helpId
}
override fun print(text: String, contentType: ConsoleViewContentType) {
}
override fun getContentSize(): Int = 0
override fun setOutputPaused(value: Boolean) {
}
override fun createConsoleActions(): Array<AnAction> = AnAction.EMPTY_ARRAY
override fun getComponent(): JComponent = this
override fun performWhenNoDeferredOutput(runnable: Runnable) {
runnable.run()
}
override fun attachToProcess(processHandler: ProcessHandler) {
}
override fun getPreferredFocusableComponent(): JComponent = this
override fun isOutputPaused(): Boolean = false
override fun addMessageFilter(filter: Filter) {
}
override fun printHyperlink(hyperlinkText: String, info: HyperlinkInfo?) {
print(hyperlinkText, ConsoleViewContentType.NORMAL_OUTPUT)
}
override fun canPause(): Boolean = false
override fun allowHeavyFilters() {
}
override fun dispose() {
}
override fun scrollTo(offset: Int) {
}
// endregion
// region DataProvider
override fun getData(dataId: String): Any? = when (dataId) {
PlatformDataKeys.HELP_ID.name -> helpId
LangDataKeys.CONSOLE_VIEW.name -> this
else -> null
}
// endregion
}
|
apache-2.0
|
97084410df79e36bc82951259c0011de
| 27.9375 | 80 | 0.730742 | 4.614618 | false | false | false | false |
luanalbineli/popularmovies
|
app/src/main/java/com/themovielist/intheaters/InTheatersPresenter.kt
|
1
|
1861
|
package com.themovielist.intheaters
import com.themovielist.model.view.MovieImageGenreViewModel
import com.themovielist.repository.intheaters.InTheatersRepository
import com.themovielist.repository.movie.CommonRepository
import com.themovielist.util.ApiUtil
import io.reactivex.disposables.Disposable
import javax.inject.Inject
class InTheatersPresenter @Inject
internal constructor(private val mInTheatersRepository: InTheatersRepository, private val commonRepository: CommonRepository) : InTheatersContract.Presenter {
private lateinit var mView: InTheatersContract.View
private var mRequest: Disposable? = null
override fun setView(view: InTheatersContract.View) {
mView = view
}
override fun start() {
mView.showLoadingIndicator()
mRequest = mInTheatersRepository.getInTheatersMovieList(ApiUtil.INITIAL_PAGE_INDEX)
.doAfterTerminate {
mRequest = null
mView.hideLoadingIndicator()
}
.subscribe({ response ->
mView.showMainMovieDetail(response.movieWithGenreList.results.first())
val finalMovieList = response.movieWithGenreList.results.map {
val genreList = commonRepository.fillMovieGenresList(it.movieModel, response.genreListModel)
MovieImageGenreViewModel(genreList, it.movieModel, response.favoriteMovieIds.contains(it.movieModel.id))
}
mView.showMovieList(finalMovieList, response.configurationResponseModel.imageResponseModel)
}, { error ->
mView.showErrorLoadingMovies(error)
})
}
override fun onStop() {
mRequest?.let {
if (!it.isDisposed) {
it.dispose()
}
}
}
}
|
apache-2.0
|
f6bc907d79dc3532b8e926fd8c0a3761
| 39.456522 | 158 | 0.663622 | 5.198324 | false | false | false | false |
huy-vuong/streamr
|
app/src/main/java/com/huyvuong/streamr/model/view/PhotoDetail.kt
|
1
|
1231
|
package com.huyvuong.streamr.model.view
import com.huyvuong.streamr.model.mapper.ExifMapper
import com.huyvuong.streamr.model.mapper.LicenseMapper
import com.huyvuong.streamr.model.mapper.LocationMapper
import com.huyvuong.streamr.model.transport.photos.exif.GetExifResponse
import com.huyvuong.streamr.model.transport.photos.geo.GetLocationResponse
import com.huyvuong.streamr.model.transport.photos.licenses.GetLicenseInfoResponse
data class PhotoDetail(
val location: Location? = null,
val exif: Exif? = null,
val license: License? = null
) {
companion object {
fun fromResponses(
getLocationResponse: GetLocationResponse,
getExifResponse: GetExifResponse,
getLicenseInfoResponse: GetLicenseInfoResponse,
licenseId: Int
): PhotoDetail {
val location = LocationMapper.toViewModel(getLocationResponse.photo?.location)
val exifSummary = ExifMapper.toViewModel(getExifResponse.exifSummary)
val license =
LicenseMapper.toViewModel(getLicenseInfoResponse.licenses?.list?.get(licenseId))
return PhotoDetail(location, exifSummary, license)
}
}
}
|
gpl-3.0
|
e7df921ced14ab1a398331c0f4cae591
| 41.448276 | 100 | 0.711617 | 4.576208 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/binaryOp/compareBoxedChars.kt
|
5
|
372
|
fun <T> id(x: T) = x
fun box(): String {
if (id('a') > id('b')) return "fail 1"
if (id('a') >= id('b')) return "fail 2"
if (id('b') < id('a')) return "fail 3"
if (id('b') <= id('a')) return "fail 4"
val x = id('a').compareTo('b')
if (x != -1) return "fail 5"
val y = id('b').compareTo('a')
if (y != 1) return "fail 6"
return "OK"
}
|
apache-2.0
|
be58058cade7c47db94f061c113ec62c
| 22.25 | 43 | 0.454301 | 2.583333 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
common_room/src/main/java/com/vmenon/mpo/persistence/room/base/dao/BaseDao.kt
|
1
|
619
|
package com.vmenon.mpo.persistence.room.base.dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Update
import com.vmenon.mpo.persistence.room.base.entity.BaseEntity
interface BaseDao<T : BaseEntity<T>> {
@Insert
suspend fun insert(entity: T): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun update(entity: T)
suspend fun insertOrUpdate(entity: T): T =
if (entity.id() == BaseEntity.UNSAVED_ID) {
entity.copyWithNewId(newId = insert(entity))
} else {
update(entity)
entity
}
}
|
apache-2.0
|
98c2cbbbdb80518064d62e8382383b87
| 27.181818 | 61 | 0.681745 | 4.099338 | false | false | false | false |
PolymerLabs/arcs
|
javatests/arcs/android/devtools/StoreOperationMessageTest.kt
|
1
|
2781
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.devtools
import arcs.android.devtools.DevToolsMessage.Companion.ACTOR
import arcs.android.devtools.DevToolsMessage.Companion.KIND
import arcs.android.devtools.DevToolsMessage.Companion.MESSAGE
import arcs.android.devtools.DevToolsMessage.Companion.OPERATIONS
import arcs.android.devtools.DevToolsMessage.Companion.STORAGE_KEY
import arcs.android.devtools.DevToolsMessage.Companion.STORE_ID
import arcs.android.devtools.DevToolsMessage.Companion.STORE_OP_MESSAGE
import arcs.android.devtools.DevToolsMessage.Companion.STORE_TYPE
import arcs.android.devtools.DevToolsMessage.Companion.TYPE
import arcs.android.devtools.DevToolsMessage.Companion.UPDATE_TYPE
import arcs.android.devtools.DevToolsMessage.Companion.VALUE
import arcs.android.devtools.DevToolsMessage.Companion.VERSION_MAP
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtOperation
import arcs.core.crdt.CrdtSingleton
import arcs.core.crdt.VersionMap
import arcs.core.data.util.ReferencablePrimitive
import arcs.core.storage.ProxyMessage
import arcs.core.util.JsonValue
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class StoreOperationMessageTest {
@Test
fun toJson() {
val expected = JsonValue.JsonObject(
KIND to JsonValue.JsonString(STORE_OP_MESSAGE),
MESSAGE to JsonValue.JsonObject(
STORE_ID to JsonValue.JsonNumber(1.toDouble()),
STORE_TYPE to JsonValue.JsonString("Direct"),
STORAGE_KEY to JsonValue.JsonString("db://sk"),
OPERATIONS to JsonValue.JsonArray(
listOf(
JsonValue.JsonObject(
TYPE to JsonValue.JsonString(UPDATE_TYPE),
VALUE to JsonValue.JsonString("foo"),
ACTOR to JsonValue.JsonString("bar"),
VERSION_MAP to JsonValue.JsonObject(
"fooBar" to JsonValue.JsonNumber(1.toDouble())
)
)
)
)
)
)
val proxyMessage = ProxyMessage.Operations<CrdtData, CrdtOperation, Any?>(
listOf(
CrdtSingleton.Operation.Update(
value = ReferencablePrimitive(String::class, "foo"),
actor = "bar",
versionMap = VersionMap(mapOf("fooBar" to 1))
)
),
id = 1
)
val message = StoreOperationMessage(proxyMessage, "Direct", "db://sk").toJson()
assertThat(message).isEqualTo(expected.toString())
}
}
|
bsd-3-clause
|
dc391953a859a8dcafde04a30751d579
| 35.592105 | 96 | 0.727436 | 4.2983 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.