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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/base/usecase/GetUserListsUseCase.kt | 1 | 1555 | package com.arcao.geocaching4locus.base.usecase
import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider
import com.arcao.geocaching4locus.base.usecase.entity.GeocacheListEntity
import com.arcao.geocaching4locus.data.api.GeocachingApiRepository
import com.arcao.geocaching4locus.data.api.model.enums.GeocacheListType
import com.arcao.geocaching4locus.data.api.model.response.PagedArrayList
import com.arcao.geocaching4locus.data.api.model.response.PagedList
import kotlinx.coroutines.withContext
class GetUserListsUseCase(
private val repository: GeocachingApiRepository,
private val geocachingApiLogin: GeocachingApiLoginUseCase,
private val dispatcherProvider: CoroutinesDispatcherProvider
) {
@Suppress("BlockingMethodInNonBlockingContext")
suspend operator fun invoke(
referenceCode: String = "me",
types: Set<GeocacheListType> = setOf(GeocacheListType.BOOKMARK),
skip: Int = 0,
take: Int = 10
): PagedList<GeocacheListEntity> = withContext(dispatcherProvider.io) {
geocachingApiLogin()
val list = repository.userLists(
referenceCode, types, skip, take
)
list.mapTo(PagedArrayList(list.size, list.totalCount)) {
GeocacheListEntity(
it.id,
it.referenceCode,
it.name,
it.description?.takeIf(String::isNotEmpty),
it.count,
it.isShared,
it.isPublic,
it.type
)
}
}
}
| gpl-3.0 | 7a1ecd5947b0805916dd6044416129f3 | 36.02381 | 77 | 0.691318 | 4.627976 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/utils/VM.kt | 1 | 4308 | package com.androidvip.hebf.utils
import android.os.Build
import androidx.annotation.WorkerThread
import java.io.File
object VM {
private const val PATH = "/proc/sys/vm"
suspend fun getParams(): List<String> {
val params = mutableListOf<String>()
RootUtils.executeWithOutput("ls $PATH | awk '{ print \$1 }'") { line ->
params.add(line.trim())
}
if (params.isEmpty()) {
val paramsFiles = File(PATH).listFiles()
paramsFiles?.let {
it.forEach { paramFile -> params.add(paramFile.name) }
}
}
return params.filterNot {
it == "drop_caches"
|| it == "hugetlb_shm_group" || it == "legacy_va_layout" || it == "panic_on_oom" || it == "hugetlb_shm_group"
|| it == "lowmem_reserve_ratio" || it == "memory_failure_early_kill" || it == "memory_failure_recovery"
|| it == "min_slab_ratio" || it == "min_unmapped_ratio" || it == "compact_memory"
}
}
fun getValue(param: String): String {
return RootUtils.executeSync("cat $PATH/$param").trim()
}
fun setValue(param: String, value: String?) {
value?.let {
RootUtils.executeSync("echo $it > $PATH/$param")
}
}
}
object ZRAM {
private const val ZRAM = "/sys/block/zram0"
private const val BLOCK = "/dev/block/zram0"
private const val DISK_SIZE = "/sys/block/zram0/disksize"
private const val RESET = "/sys/block/zram0/reset"
private const val MAX_COMP_STREAMS = "/sys/block/zram0/max_comp_streams"
private const val COMP_ALGO = "/sys/block/zram0/comp_algorithm"
private const val PROC_MEM_INFO = "/proc/meminfo"
@WorkerThread
fun setDiskSize(valueInMbs: Long) {
RootUtils.executeSync(
"swapoff $BLOCK > /dev/null 2>&1 && sleep 0.5",
"echo 1 > $RESET",
"echo 0 > $DISK_SIZE && sleep 0.5"
)
RootUtils.finishProcess()
val size = valueInMbs * 1024 * 1024
if (size > 0L) {
RootUtils.executeSync(
"echo $size > $DISK_SIZE && sleep 0.5",
"mkswap $BLOCK > /dev/null 2>&1 && sleep 0.5",
"swapon $BLOCK > /dev/null 2>&1"
)
} else {
RootUtils.executeSync("swapoff $BLOCK > /dev/null 2>&1")
}
}
@WorkerThread
fun getDiskSize(): Int {
return try {
val value: Long = RootUtils.executeSync("cat $DISK_SIZE").toLong() / 1024 / 1024
return value.toInt()
} catch (e: Exception) {
0
}
}
fun setZRAMAlgo(value: String?) {
RootUtils.executeSync("echo $value > $COMP_ALGO")
}
private fun getAvailableZramAlgos(path: String): MutableList<String> {
val resultList = mutableListOf<String>()
val algos = RootUtils.executeSync("cat $path").split(" ")
algos.forEach {
resultList.add(it.replace("[", "").replace("]", ""))
}
return resultList
}
fun getAvailableZramAlgos(): MutableList<String> {
return getAvailableZramAlgos(COMP_ALGO)
}
private fun getZRAMAlgo(path: String): String? {
val algos = RootUtils.executeSync("cat $path").split(" ")
algos.forEach {
if (it.startsWith("[") && it.endsWith("]")) {
return it.replace("[", "").replace("]", "")
}
}
return ""
}
fun getZRAMAlgo(): String? {
return getZRAMAlgo(COMP_ALGO)
}
fun hasZRAMAlgo(): Boolean {
return RootUtils.executeSync("[ -e $COMP_ALGO ] && echo true") == "true"
}
fun supported(): Boolean {
return RootUtils.executeSync("[ -e $ZRAM ] && echo true") == "true"
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
}
fun getFreeSwap(): Long = getMemoryItem("SwapFree")
fun getTotalSwap(): Long = getMemoryItem("SwapTotal")
private fun getMemoryItem(prefix: String): Long {
val paramInfo = RootUtils.executeSync("cat $PROC_MEM_INFO | grep $prefix")
return try {
return paramInfo.split(":")[1].trim().replace("[^\\d]".toRegex(), "").toLong() / 1024L
} catch (e: Exception) {
0
}
}
} | apache-2.0 | 85ac9092f612c1d22c0320493baace60 | 30.452555 | 125 | 0.551996 | 3.846429 | false | false | false | false |
almibe/grid-builder | src/test/kotlin/org/libraryweasel/gridbuilder/demo/Demo.kt | 1 | 858 | package org.libraryweasel.gridbuilder.demo
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.control.TextArea
import javafx.scene.control.TextField
import javafx.scene.layout.FlowPane
import javafx.scene.layout.GridPane
import javafx.scene.text.Text
import javafx.stage.Stage
import org.libraryweasel.gridbuilder.Span
import org.libraryweasel.gridbuilder.gridBuilder
public fun main(args: Array<String>) {
Application.launch(javaClass<Demo>())
}
public class Demo() : Application() {
override fun start(stage: Stage) {
val text = Text("Hey")
val input = TextField("Shorter")
val input2 = TextField("Longer")
val gridBuilder = gridBuilder { +text +input +Span(input2, 3) }
val scene = Scene(FlowPane(gridBuilder))
stage.setScene(scene)
stage.show()
}
} | apache-2.0 | 2fb7bc557877c2dc75fbf28d42706cea | 27.633333 | 71 | 0.728438 | 3.990698 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt | 2 | 3777 | package eu.kanade.tachiyomi.data.preference
/**
* This class stores the keys for the preferences in the application.
*/
object PreferenceKeys {
const val theme = "pref_theme_key"
const val rotation = "pref_rotation_type_key"
const val enableTransitions = "pref_enable_transitions_key"
const val doubleTapAnimationSpeed = "pref_double_tap_anim_speed"
const val showPageNumber = "pref_show_page_number_key"
const val fullscreen = "fullscreen"
const val keepScreenOn = "pref_keep_screen_on_key"
const val customBrightness = "pref_custom_brightness_key"
const val customBrightnessValue = "custom_brightness_value"
const val colorFilter = "pref_color_filter_key"
const val colorFilterValue = "color_filter_value"
const val defaultViewer = "pref_default_viewer_key"
const val imageScaleType = "pref_image_scale_type_key"
const val imageDecoder = "image_decoder"
const val zoomStart = "pref_zoom_start_key"
const val readerTheme = "pref_reader_theme_key"
const val cropBorders = "crop_borders"
const val readWithTapping = "reader_tap"
const val readWithVolumeKeys = "reader_volume_keys"
const val readWithVolumeKeysInverted = "reader_volume_keys_inverted"
const val portraitColumns = "pref_library_columns_portrait_key"
const val landscapeColumns = "pref_library_columns_landscape_key"
const val updateOnlyNonCompleted = "pref_update_only_non_completed_key"
const val autoUpdateTrack = "pref_auto_update_manga_sync_key"
const val askUpdateTrack = "pref_ask_update_manga_sync_key"
const val lastUsedCatalogueSource = "last_catalogue_source"
const val lastUsedCategory = "last_used_category"
const val catalogueAsList = "pref_display_catalogue_as_list"
const val enabledLanguages = "source_languages"
const val backupDirectory = "backup_directory"
const val downloadsDirectory = "download_directory"
const val downloadOnlyOverWifi = "pref_download_only_over_wifi_key"
const val numberOfBackups = "backup_slots"
const val backupInterval = "backup_interval"
const val removeAfterReadSlots = "remove_after_read_slots"
const val removeAfterMarkedAsRead = "pref_remove_after_marked_as_read_key"
const val libraryUpdateInterval = "pref_library_update_interval_key"
const val libraryUpdateRestriction = "library_update_restriction"
const val libraryUpdateCategories = "library_update_categories"
const val filterDownloaded = "pref_filter_downloaded_key"
const val filterUnread = "pref_filter_unread_key"
const val filterCompleted = "pref_filter_completed_key"
const val librarySortingMode = "library_sorting_mode"
const val automaticUpdates = "automatic_updates"
const val startScreen = "start_screen"
const val downloadNew = "download_new"
const val downloadNewCategories = "download_new_categories"
const val libraryAsList = "pref_display_library_as_list"
const val lang = "app_language"
const val defaultCategory = "default_category"
const val downloadBadge = "display_download_badge"
@Deprecated("Use the preferences of the source")
fun sourceUsername(sourceId: Long) = "pref_source_username_$sourceId"
@Deprecated("Use the preferences of the source")
fun sourcePassword(sourceId: Long) = "pref_source_password_$sourceId"
fun sourceSharedPref(sourceId: Long) = "source_$sourceId"
fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId"
fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId"
fun trackToken(syncId: Int) = "track_token_$syncId"
}
| apache-2.0 | b046564d5e2318d91595720728b8f275 | 28.459677 | 78 | 0.707705 | 4.224832 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/UrlUtil.kt | 1 | 1290 | package uk.co.appsbystudio.geoshare.utils
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
/* DIRECTIONS METHODS */
/*fun getDirectionsUrl(origin: LatLng, dest: LatLng) {
val sOrigin = "origin=" + origin.latitude + "," + origin.longitude
val sDest = "destination=" + dest.latitude + "," + dest.longitude
val params = "$sOrigin&$sDest&sensor=false"
Application.getContext().getString(R.string.server_key)
}*/
/* GEOCODING METHOD */
//Reverse Geocoding
fun getReverseGeocodingUrl(lat: Double, lng: Double): String {
return "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=AIzaSyCMzZatGotT2XcOm5DOmKMBnybNZgRg1jQ"
}
//Download url result
fun downloadUrl(stringUrl: String): String {
var data = ""
val obj = URL(stringUrl)
with(obj.openConnection() as HttpURLConnection) {
requestMethod = "GET"
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
data = response.toString()
}
}
return data
}
| apache-2.0 | 224ef5bf6e761d47b7af1c32ddbb1f9f | 27.043478 | 123 | 0.662791 | 3.873874 | false | false | false | false |
daring2/fms | zabbix/core/src/main/kotlin/com/gitlab/daring/fms/zabbix/model/ItemValue.kt | 1 | 963 | package com.gitlab.daring.fms.zabbix.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import java.time.Instant
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ItemValue(
val host: String,
val key: String,
val value: String,
val state: Int = 0,
val clock: Long? = null,
val ns: Int? = null,
val lastlogsize: Long? = null,
val mtime: Long? = null
) {
val isError @JsonIgnore get() = state == 1
constructor(value: String, isError: Boolean = false, item: Item? = null): this(
item?.host ?: "",
item?.key_orig ?: "",
value,
if (isError) 1 else 0
)
fun withError(error: String): ItemValue {
return copy(value = error, state = 1)
}
fun withTime(time: Instant?): ItemValue {
return copy(clock = time?.epochSecond, ns = time?.nano)
}
} | apache-2.0 | 46808104e2ea49998439a2d02a7bc7c3 | 25.777778 | 83 | 0.595016 | 3.930612 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/data/db/DatabaseRepository.kt | 2 | 5532 | package org.fossasia.susi.ai.data.db
import io.realm.Case
import io.realm.Realm
import io.realm.RealmList
import io.realm.RealmResults
import org.fossasia.susi.ai.data.db.contract.IDatabaseRepository
import org.fossasia.susi.ai.data.model.ChatMessage
import org.fossasia.susi.ai.data.model.MapData
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.helper.PrefManager
import org.fossasia.susi.ai.rest.responses.susi.Datum
/**
* The Database repository. Does all database operations like updating database,
* deleting from database, searching from database etc
*
* Created by chiragw15 on 12/7/17.
*/
class DatabaseRepository: IDatabaseRepository {
var realm: Realm = Realm.getDefaultInstance()
override fun getMessageCount(): Long {
val temp = realm.where(ChatMessage::class.java).max(Constant.ID)
if(temp == null)
return -1
else
return temp as Long
}
override fun getAMessage(index: Long): ChatMessage {
return realm.where(ChatMessage::class.java).equalTo("id", index).findFirst()
}
override fun deleteAllMessages() {
realm.executeTransaction { realm -> realm.deleteAll() }
}
override fun getUndeliveredMessages(): RealmResults<ChatMessage> {
return realm.where(ChatMessage::class.java).equalTo(Constant.IS_DELIVERED, false).findAll().sort(Constant.ID)
}
override fun getAllMessages(): RealmResults<ChatMessage> {
return realm.where(ChatMessage::class.java).findAllSorted(Constant.ID)
}
override fun getSearchResults(query: String): RealmResults<ChatMessage> {
return realm.where(ChatMessage::class.java).contains(Constant.CONTENT,
query, Case.INSENSITIVE).findAll()
}
override fun updateDatabase(prevId: Long, message: String, isDate: Boolean, date: String,
timeStamp: String, mine: Boolean, actionType: String, mapData: MapData?,
isHavingLink: Boolean, datumList: List<Datum>?, webSearch: String, skillLocation: String,
listener: IDatabaseRepository.onDatabaseUpdateListener) {
val id = PrefManager.getLong(Constant.MESSAGE_COUNT, 0)
listener.updateMessageCount()
realm.executeTransactionAsync({ bgRealm ->
val chatMessage = bgRealm.createObject(ChatMessage::class.java, id)
chatMessage.content = message
chatMessage.date = date
chatMessage.setIsDate(isDate)
chatMessage.setIsMine(mine)
chatMessage.timeStamp = timeStamp
chatMessage.isHavingLink = isHavingLink
if (mine)
chatMessage.isDelivered = false
else {
chatMessage.actionType = actionType
chatMessage.webquery = webSearch
chatMessage.isDelivered = true
if (mapData != null) {
chatMessage.latitude = mapData.latitude
chatMessage.longitude = mapData.longitude
chatMessage.zoom = mapData.zoom
}
if (datumList != null) {
val datumRealmList = RealmList<Datum>()
for (datum in datumList) {
val realmDatum = bgRealm.createObject(Datum::class.java)
realmDatum.description = datum.description
realmDatum.link = datum.link
realmDatum.title = datum.title
datumRealmList.add(realmDatum)
}
chatMessage.datumRealmList = datumRealmList
}
chatMessage.skillLocation = skillLocation
}
}, {
if (!mine) {
val prId = prevId
realm.executeTransactionAsync { bgRealm ->
try {
val previouschatMessage = bgRealm.where(ChatMessage::class.java).equalTo("id", prId).findFirst()
if (previouschatMessage != null && previouschatMessage.isMine) {
previouschatMessage.isDelivered = true
previouschatMessage.date = date
previouschatMessage.timeStamp = timeStamp
}
} catch (e: Exception) {
e.printStackTrace()
}
try {
val previousChatMessage = bgRealm.where(ChatMessage::class.java).equalTo("id", prId - 1).findFirst()
if (previousChatMessage != null && previousChatMessage.isDate) {
previousChatMessage.date = date
previousChatMessage.timeStamp = timeStamp
val previousChatMessage2 = bgRealm.where(ChatMessage::class.java).equalTo("id", prId - 2).findFirst()
if (previousChatMessage2 != null && previousChatMessage2.date == previousChatMessage.date) {
previousChatMessage.deleteFromRealm()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
listener.onDatabaseUpdateSuccess()
}
}) { error -> error.printStackTrace() }
}
override fun closeDatabase() {
realm.close()
}
} | apache-2.0 | 3c38a793b1299e052062c6448e111b61 | 41.236641 | 129 | 0.574837 | 5.339768 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/launcher/AppWidgetProvider.kt | 1 | 1853 | package info.papdt.express.helper.ui.launcher
import android.app.Application
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.RemoteViews
import info.papdt.express.helper.R
import info.papdt.express.helper.services.AppWidgetService
import info.papdt.express.helper.ui.DetailsActivity
class AppWidgetProvider : android.appwidget.AppWidgetProvider() {
override fun onUpdate(context: Context, manager: AppWidgetManager, appWidgetIds: IntArray) {
for (appWidgetId in appWidgetIds) {
val remoteViews = updateWidgetListView(context, appWidgetId)
manager.updateAppWidget(appWidgetId, remoteViews)
}
super.onUpdate(context, manager, appWidgetIds)
}
private fun updateWidgetListView(context: Context, id: Int): RemoteViews {
val views = RemoteViews(context.packageName, R.layout.launcher_widget_layout)
val intent = Intent(context, AppWidgetService::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))
views.setRemoteAdapter(R.id.widget_list_view, intent)
views.setEmptyView(R.id.widget_list_view, R.id.empty_view)
val tempIntent = Intent(context, DetailsActivity::class.java)
tempIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
views.setPendingIntentTemplate(R.id.widget_list_view, PendingIntent.getActivity(context, 0, tempIntent, PendingIntent.FLAG_CANCEL_CURRENT))
return views
}
companion object {
fun updateManually(app: Application) {
val ids = AppWidgetManager.getInstance(app).getAppWidgetIds(ComponentName(app, AppWidgetProvider::class.java))
AppWidgetManager.getInstance(app).notifyAppWidgetViewDataChanged(ids, R.id.widget_list_view)
}
}
}
| gpl-3.0 | 314a02de19fbd1b64f8307146bdf9d01 | 34.634615 | 141 | 0.803022 | 3.925847 | false | false | false | false |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/platform/ui/layout/BaseScaffold.kt | 1 | 2378 | package com.mrebollob.loteria.android.presentation.platform.ui.layout
import android.content.res.Configuration
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.ProvideWindowInsets
import com.google.accompanist.insets.navigationBarsWithImePadding
import com.google.accompanist.insets.statusBarsPadding
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun BaseScaffold(
modifier: Modifier = Modifier,
toolbarText: String? = null,
backgroundColor: Color = MaterialTheme.colors.background,
scaffoldState: ScaffoldState = rememberScaffoldState(),
barActions: @Composable RowScope.() -> Unit = {},
snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) },
content: @Composable () -> Unit,
onBackClick: (() -> Unit)? = null
) {
ProvideWindowInsets {
Scaffold(
modifier = modifier
.statusBarsPadding()
.navigationBarsWithImePadding(),
scaffoldState = scaffoldState,
snackbarHost = snackbarHost,
backgroundColor = backgroundColor,
topBar = {
if (toolbarText != null) {
BaseTopAppBar(
toolbarText = toolbarText,
barActions = barActions,
onBackClick = onBackClick
)
}
},
content = {
content()
}
)
}
}
@Preview("BaseScaffold")
@Preview("BaseScaffold (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Preview("BaseScaffold (big font)", fontScale = 1.5f)
@Composable
fun PreviewBaseScaffold() {
MaterialTheme {
BaseScaffold(
content = {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(text = "BaseScaffold")
}
},
onBackClick = {}
)
}
}
| apache-2.0 | 76ffb758fe30cd18a795d58b180b4427 | 32.492958 | 81 | 0.62868 | 4.995798 | false | false | false | false |
kibotu/RecyclerViewPresenter | app/src/main/kotlin/net/kibotu/android/recyclerviewpresenter/app/screens/pagination/PhotoPresenter.kt | 1 | 1506 | package net.kibotu.android.recyclerviewpresenter.app.screens.pagination
import android.net.Uri
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import net.kibotu.android.recyclerviewpresenter.Presenter
import net.kibotu.android.recyclerviewpresenter.PresenterViewModel
import net.kibotu.android.recyclerviewpresenter.app.R
import net.kibotu.android.recyclerviewpresenter.app.databinding.PhotoPresenterItemBinding
import net.kibotu.android.recyclerviewpresenter.app.misc.GlideApp
class PhotoPresenter : Presenter<String, PhotoPresenterItemBinding>(
layout = R.layout.photo_presenter_item,
viewBindingAccessor = PhotoPresenterItemBinding::bind
) {
override fun bindViewHolder(
viewBinding: PhotoPresenterItemBinding,
viewHolder: RecyclerView.ViewHolder,
item: PresenterViewModel<String>,
payloads: MutableList<Any>?
) {
with(viewBinding) {
val uri = Uri.parse(item.model)
val width = uri.pathSegments.takeLast(2).first().toInt()
val height = uri.pathSegments.last().toInt()
photo.minimumWidth = width
photo.minimumHeight = height
GlideApp.with(root.context.applicationContext)
.load(uri)
.transition(withCrossFade())
.into(photo)
.clearOnDetach()
}
}
} | apache-2.0 | 962e51110937fb45f77cafc24f28a64f | 35.756098 | 89 | 0.723108 | 4.826923 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/ShopDetailHtmlSidebarEntity.kt | 1 | 428 | package cn.cloudself.model
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Entity
@Table(name = "shop_detail_html_sidebar", schema = "shop")
data class ShopDetailHtmlSidebarEntity(
@get:Id
@get:Column(name = "id", nullable = false)
var id: Int = 0,
@get:Basic
@get:Column(name = "xss_html", nullable = true, length = -1)
var xssHtml: String? = null
)
| mit | 78c7b3dc39310e3ad6004674d444d83c | 22.777778 | 68 | 0.607477 | 3.147059 | false | false | false | false |
MyDogTom/detekt | detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/IdeaExtension.kt | 1 | 2067 | package io.gitlab.arturbosch.detekt.extensions
/**
* @author Artur Bosch
*/
open class IdeaExtension(open var path: String? = null,
open var codeStyleScheme: String? = null,
open var inspectionsProfile: String? = null,
open var report: String? = null,
open var mask: String = "*.kt") {
fun formatArgs(ext: DetektExtension): Array<String> {
val input = ext.profileInputPath()
require(path != null) { IDEA_PATH_ERROR }
require(input != null) { INPUT_PATH_ERROR }
return if (codeStyleScheme != null) {
arrayOf(format(path!!), "-r", input!!, "-s", codeStyleScheme!!, "-m", mask)
} else {
arrayOf(format(path!!), "-r", input!!, "-m", mask)
}
}
fun inspectArgs(ext: DetektExtension): Array<String> {
val input = ext.profileInputPath()
require(path != null) { IDEA_PATH_ERROR }
require(input != null) { INPUT_PATH_ERROR }
require(report != null) { REPORT_PATH_ERROR }
require(inspectionsProfile != null) { INSPECTION_PROFILE_ERROR }
return arrayOf(inspect(path!!), input!!, inspectionsProfile!!, report!!)
}
private fun DetektExtension.profileInputPath() = systemOrDefaultProfile()?.input?.apply {
if (debug) println("input: $this")
}
override fun toString(): String = "IdeaExtension(path=$path, " +
"codeStyleScheme=$codeStyleScheme, inspectionsProfile=$inspectionsProfile, report=$report, mask='$mask')"
}
private val isWindows: Boolean = System.getProperty("os.name").contains("Windows")
private const val INPUT_PATH_ERROR = "Make sure the input path is specified!"
private const val IDEA_PATH_ERROR = "Make sure the idea path is specified to run idea tasks!"
private const val REPORT_PATH_ERROR =
"Make sure the report path is specified where idea inspections are stored!"
private const val INSPECTION_PROFILE_ERROR =
"Make sure the path to an inspection profile is provided!"
private fun inspect(path: String): String = "$path/bin/" + if (isWindows) "inspect.bat" else "inspect.sh"
private fun format(path: String): String = "$path/bin/" + if (isWindows) "format.bat" else "format.sh"
| apache-2.0 | 70063bf388f5dc92a7ad859066dd4bf8 | 40.34 | 108 | 0.699565 | 3.704301 | false | false | false | false |
TheFallOfRapture/Morph | src/test/kotlin/com/morph/demos/test/particlePhysics/ParticlePhysicsSystem.kt | 2 | 4267 | package com.morph.demos.test.particlePhysics
import com.morph.engine.core.GameSystem
import com.morph.engine.entities.Entity
import com.morph.engine.graphics.components.Particle
import com.morph.engine.math.Vector2f
import com.morph.engine.math.Vector3f
import com.morph.engine.physics.components.RigidBody
import com.morph.engine.physics.components.Transform2D
class ParticlePhysicsSystem(game : PartPhysGame) : GameSystem(game) {
var time = 0f
override fun acceptEntity(e: Entity): Boolean = e.hasComponent<Transform2D>() && e.hasComponent<RigidBody>() && e.hasComponent<Particle>()
override fun initSystem() {}
override fun fixedUpdate(e: Entity, dt: Float) {
val rb = e.getComponent<RigidBody>()!!
val gravitationalCenter = Vector2f(0f, 0f)
// val gravitationalCenter = Vector2f(Math.cos(time.toDouble() * 3).toFloat(), Math.sin(time.toDouble() * 3).toFloat()) * 2f
val gravity = gravityForce(e.getComponent<Transform2D>()!!.position, gravitationalCenter, rb.mass, 50000f)
val downGravity = Vector2f(0f, -9.8f * rb.mass)
val position = e.getComponent<Transform2D>()!!.position
val centripetalForce = (gravitationalCenter - position).normalize() *
(rb.mass * (rb.velocity dot rb.velocity)) * (1f / (gravitationalCenter - position).length)
// rb.applyForce(centripetalForce)
// rb.applyForce(gravity)
// rb.applyForce(downGravity)
val scale = 20f
// rb.applyForce(turningForce(position, Vector2f(0f, 0f)) * scale * rb.mass)
// rb.applyForce(-position.normalize() * 25f * scale * rb.mass)
val center = Vector2f(0f, 10f)
val rest = Vector2f(0f, 10f)
val k = 20f
val b = 0.75f
val springForce = (position - rest) * -k
val frictionForce = rb.velocity * -b
rb.applyForce(springForce)
// rb.applyForce(frictionForce)
// rb.applyForce(downGravity)
val locusP = game.world.getEntityByName("locus")?.getComponent<Transform2D>()?.position!!
// val denom = (locusP - position).length
val tolerance = 0.01f
val power = 0.0
val locusGravity = (locusP - position).normalize() * 200f
// rb.applyForce(locusGravity)
}
fun turningForce(position : Vector2f, center : Vector2f) : Vector2f =
(Vector3f((center - position), 0f) cross Vector3f(0f, 0f, -1f)).xy.normalize()
fun gravityForce(position : Vector2f, center : Vector2f, mass1 : Float, mass2 : Float) : Vector2f {
val direction = (center - position).normalize()
val gravityConstant = 1e-3f
val forceStrength = gravityConstant * mass1 * mass2 / Math.abs((center - position) dot (center - position))
return direction * forceStrength
}
fun gravityStrength(position : Vector2f, center : Vector2f, mass1 : Float, mass2 : Float) : Float {
val direction = (center - position).normalize()
val gravityConstant = 1e-3f
val forceStrength = gravityConstant * mass1 * mass2 / Math.abs((center - position) dot (center - position))
return forceStrength
}
override fun systemFixedUpdate(dt: Float) {
time += dt
}
// override fun systemFixedUpdate(dt: Float) {
// time += dt
//
// val entities = game.world.entities.filter(::acceptEntity)
//
// for (i in 0 until entities.size) {
// for (j in i + 1 until entities.size) {
// val e1 = entities[i]
// val e2 = entities[j]
//
// val t1 = e1.getComponent<Transform2D>()!!
// val t2 = e2.getComponent<Transform2D>()!!
// val rb1 = e1.getComponent<RigidBody>()!!
// val rb2 = e2.getComponent<RigidBody>()!!
//
// val gravity = gravityStrength(
// t1.position,
// t2.position,
// rb1.mass,
// rb2.mass
// )
//
// val d1 = (t2.position - t1.position).normalize()
// val d2 = (t1.position - t2.position).normalize()
//
// rb1.applyForce(d1 * gravity)
// rb2.applyForce(d2 * gravity)
// }
// }
// }
} | mit | c29f02b3d1d5389452554bf03899eb46 | 39.264151 | 142 | 0.60464 | 3.628401 | false | false | false | false |
googlearchive/android-AutofillFramework | kotlinApp/Application/src/main/java/com/example/android/autofillframework/multidatasetservice/AutofillFieldMetadata.kt | 4 | 3484 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofillframework.multidatasetservice
import android.app.assist.AssistStructure.ViewNode;
import android.service.autofill.SaveInfo
import android.view.View
import android.view.autofill.AutofillId
/**
* A stripped down version of a [ViewNode] that contains only autofill-relevant metadata. It also
* contains a `saveType` flag that is calculated based on the [ViewNode]'s autofill hints.
*/
class AutofillFieldMetadata(view: ViewNode) {
var saveType = 0
private set
val autofillHints = view.autofillHints.filter(AutofillHelper::isValidHint).toTypedArray()
val autofillId: AutofillId = view.autofillId
val autofillType: Int = view.autofillType
val autofillOptions: Array<CharSequence>? = view.autofillOptions
val isFocused: Boolean = view.isFocused
init {
updateSaveTypeFromHints()
}
/**
* When the [ViewNode] is a list that the user needs to choose a string from (i.e. a spinner),
* this is called to return the index of a specific item in the list.
*/
fun getAutofillOptionIndex(value: CharSequence): Int {
if (autofillOptions != null) {
return autofillOptions.indexOf(value)
} else {
return -1
}
}
private fun updateSaveTypeFromHints() {
saveType = 0
for (hint in autofillHints) {
when (hint) {
View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE,
View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY,
View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH,
View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR,
View.AUTOFILL_HINT_CREDIT_CARD_NUMBER,
View.AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_CREDIT_CARD
}
View.AUTOFILL_HINT_EMAIL_ADDRESS -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_EMAIL_ADDRESS
}
View.AUTOFILL_HINT_PHONE, View.AUTOFILL_HINT_NAME -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_GENERIC
}
View.AUTOFILL_HINT_PASSWORD -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_PASSWORD
saveType = saveType and SaveInfo.SAVE_DATA_TYPE_EMAIL_ADDRESS.inv()
saveType = saveType and SaveInfo.SAVE_DATA_TYPE_USERNAME.inv()
}
View.AUTOFILL_HINT_POSTAL_ADDRESS,
View.AUTOFILL_HINT_POSTAL_CODE -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_ADDRESS
}
View.AUTOFILL_HINT_USERNAME -> {
saveType = saveType or SaveInfo.SAVE_DATA_TYPE_USERNAME
}
}
}
}
}
| apache-2.0 | 6ba3af7e6293d3e53ce83fe714e0fce9 | 39.511628 | 98 | 0.633467 | 4.32795 | false | false | false | false |
http4k/http4k | http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/client/AccessTokens.kt | 1 | 1004 | package org.http4k.security.oauth.client
import org.http4k.security.AccessToken
import org.http4k.security.ExpiringCredentials
import org.http4k.security.oauth.core.RefreshToken
interface AccessTokens {
operator fun get(refreshToken: RefreshToken): ExpiringCredentials<AccessToken>?
operator fun set(refreshToken: RefreshToken, accessToken: ExpiringCredentials<AccessToken>)
companion object
}
fun AccessTokens.Companion.None() = object : AccessTokens {
override fun get(refreshToken: RefreshToken): Nothing? = null
override fun set(refreshToken: RefreshToken, accessToken: ExpiringCredentials<AccessToken>) {}
}
fun AccessTokens.Companion.InMemory() = object : AccessTokens {
var tokens = mutableMapOf<RefreshToken, ExpiringCredentials<AccessToken>>()
override fun get(refreshToken: RefreshToken) = tokens[refreshToken]
override fun set(refreshToken: RefreshToken, accessToken: ExpiringCredentials<AccessToken>) {
tokens[refreshToken] = accessToken
}
}
| apache-2.0 | 1e8dbc70983a41db47aae508716d1079 | 37.615385 | 98 | 0.785857 | 4.502242 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/api/datamanager/DataManagerCheckerInbox.kt | 1 | 1881 | package com.mifos.api.datamanager
import com.mifos.api.BaseApiManager
import com.mifos.api.GenericResponse
import com.mifos.objects.CheckerTask
import com.mifos.objects.checkerinboxandtasks.CheckerInboxSearchTemplate
import com.mifos.objects.checkerinboxandtasks.RescheduleLoansTask
import rx.Observable
import javax.inject.Inject
class DataManagerCheckerInbox @Inject constructor() {
//class DataManagerCheckerInbox {
val mBaseApiManager = BaseApiManager()
fun getCheckerTaskList(actionName: String? = null, entityName: String? = null,
resourceId: Int? = null): Observable<List<CheckerTask>> {
return mBaseApiManager.checkerInboxApi.getCheckerList(
actionName, entityName, resourceId)
}
fun approveCheckerEntry(auditId: Int): Observable<GenericResponse> {
return mBaseApiManager.checkerInboxApi.approveCheckerEntry(auditId)
}
fun rejectCheckerEntry(auditId: Int): Observable<GenericResponse> {
return mBaseApiManager.checkerInboxApi.rejectCheckerEntry(auditId)
}
fun deleteCheckerEntry(auditId: Int): Observable<GenericResponse> {
return mBaseApiManager.checkerInboxApi.deleteCheckerEntry(auditId)
}
fun getRechdeduleLoansTaskList(): Observable<List<RescheduleLoansTask>> {
return mBaseApiManager.checkerInboxApi.getRescheduleLoansTaskList()
}
fun getCheckerInboxSearchTemplate(): Observable<CheckerInboxSearchTemplate> {
return mBaseApiManager.checkerInboxApi.getCheckerInboxSearchTempalate()
}
fun getCheckerTaskFromResourceId(actionName: String? = null, entityName: String? = null,
resourceId: Int? = null): Observable<List<CheckerTask>> {
return mBaseApiManager.checkerInboxApi.getCheckerTasksFromResourceId(
actionName, entityName, resourceId)
}
}
| mpl-2.0 | e4cd5b10976d65769e11f53ea6d6e3ec | 39.021277 | 94 | 0.743753 | 4.75 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/fragment/ViewVideoFragment.kt | 1 | 5399 | /* Copyright 2017 Andrew Dawson
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky.fragment
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.MediaController
import android.widget.TextView
import com.keylesspalace.tusky.R
import com.keylesspalace.tusky.ViewMediaActivity
import com.keylesspalace.tusky.entity.Attachment
import com.keylesspalace.tusky.util.hide
import com.keylesspalace.tusky.util.visible
import kotlinx.android.synthetic.main.activity_view_media.*
import kotlinx.android.synthetic.main.fragment_view_video.*
class ViewVideoFragment : ViewMediaFragment() {
private lateinit var toolbar: View
private val handler = Handler(Looper.getMainLooper())
private val hideToolbar = Runnable {
// Hoist toolbar hiding to activity so it can track state across different fragments
// This is explicitly stored as runnable so that we pass it to the handler later for cancellation
mediaActivity.onPhotoTap()
}
private lateinit var mediaActivity: ViewMediaActivity
private val TOOLBAR_HIDE_DELAY_MS = 3000L
override lateinit var descriptionView : TextView
private lateinit var mediaController : MediaController
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
// Start/pause/resume video playback as fragment is shown/hidden
super.setUserVisibleHint(isVisibleToUser)
if (videoPlayer == null) {
return
}
if (isVisibleToUser) {
if (mediaActivity.isToolbarVisible()) {
handler.postDelayed(hideToolbar, TOOLBAR_HIDE_DELAY_MS)
}
videoPlayer.start()
} else {
handler.removeCallbacks(hideToolbar)
videoPlayer.pause()
mediaController.hide()
}
}
@SuppressLint("ClickableViewAccessibility")
override fun setupMediaView(url: String) {
descriptionView = mediaDescription
val videoView = videoPlayer
videoView.transitionName = url
videoView.setVideoPath(url)
mediaController = MediaController(mediaActivity)
mediaController.setMediaPlayer(videoPlayer)
videoPlayer.setMediaController(mediaController)
videoView.requestFocus()
videoView.setOnTouchListener { _, _ ->
mediaActivity.onPhotoTap()
false
}
videoView.setOnPreparedListener { mp ->
progressBar.hide()
mp.isLooping = true
if (arguments!!.getBoolean(ViewMediaFragment.ARG_START_POSTPONED_TRANSITION)) {
hideToolbarAfterDelay(TOOLBAR_HIDE_DELAY_MS)
videoView.start()
}
}
if (arguments!!.getBoolean(ViewMediaFragment.ARG_START_POSTPONED_TRANSITION)) {
mediaActivity.onBringUp()
}
}
private fun hideToolbarAfterDelay(delayMilliseconds: Long) {
handler.postDelayed(hideToolbar, delayMilliseconds)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
toolbar = activity!!.toolbar
mediaActivity = activity as ViewMediaActivity
return inflater.inflate(R.layout.fragment_view_video, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val attachment = arguments?.getParcelable<Attachment>(ViewMediaFragment.ARG_ATTACHMENT)
val url: String
if (attachment == null) {
throw IllegalArgumentException("attachment has to be set")
}
url = attachment.url
finalizeViewSetup(url, attachment.description)
}
override fun onToolbarVisibilityChange(visible: Boolean) {
if (videoPlayer == null || !userVisibleHint) {
return
}
isDescriptionVisible = showingDescription && visible
val alpha = if (isDescriptionVisible) 1.0f else 0.0f
descriptionView.animate().alpha(alpha)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
descriptionView.visible(isDescriptionVisible)
animation.removeListener(this)
}
})
.start()
if (visible) {
hideToolbarAfterDelay(TOOLBAR_HIDE_DELAY_MS)
} else {
handler.removeCallbacks(hideToolbar)
}
}
}
| gpl-3.0 | d92fa6ae37598b6ff2b5f21895b86c6e | 37.021127 | 115 | 0.684016 | 5.083804 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/user/UserModule.kt | 1 | 1581 | package de.westnordost.streetcomplete.data.user
import android.content.SharedPreferences
import dagger.Module
import dagger.Provides
import oauth.signpost.OAuthConsumer
import oauth.signpost.OAuthProvider
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer
import se.akerfeldt.okhttp.signpost.OkHttpOAuthProvider
import javax.inject.Named
import javax.inject.Provider
@Module
object UserModule {
private const val BASE_OAUTH_URL = "https://www.openstreetmap.org/oauth/"
private const val CONSUMER_KEY = "L3JyJMjVk6g5atwACVySRWgmnrkBAH7u0U18ALO7"
private const val CONSUMER_SECRET = "uNjPaXZw15CPHdCSeMzttRm20tyFGaBPO7jHt52c"
private const val CALLBACK_SCHEME = "streetcomplete"
private const val CALLBACK_HOST = "oauth"
@Provides fun oAuthStore(prefs: SharedPreferences): OAuthStore = OAuthStore(
prefs, Provider { oAuthConsumer() }
)
@Provides fun oAuthProvider(): OAuthProvider = OkHttpOAuthProvider(
BASE_OAUTH_URL + "request_token",
BASE_OAUTH_URL + "access_token",
BASE_OAUTH_URL + "authorize"
)
@Provides fun oAuthConsumer(): OAuthConsumer =
OkHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
@Provides fun userDataSource(controller: UserDataController): UserDataSource = controller
@Provides fun userLoginStatusSource(controller: UserLoginStatusController): UserLoginStatusSource = controller
@Provides @Named("OAuthCallbackScheme")
fun oAuthCallbackScheme(): String = CALLBACK_SCHEME
@Provides @Named("OAuthCallbackHost")
fun oAuthCallbackHost(): String = CALLBACK_HOST
}
| gpl-3.0 | 5a21d4346de526ce34cea5484e177166 | 36.642857 | 114 | 0.776091 | 4.022901 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/max_height/AddMaxHeightForm.kt | 1 | 6368 | package de.westnordost.streetcomplete.quests.max_height
import android.os.Bundle
import android.text.InputFilter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.mapdata.ElementType
import de.westnordost.streetcomplete.ktx.allowOnlyNumbers
import de.westnordost.streetcomplete.ktx.numberOrNull
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.max_height.HeightMeasurementUnit.FOOT_AND_INCH
import de.westnordost.streetcomplete.quests.max_height.HeightMeasurementUnit.METER
import de.westnordost.streetcomplete.util.TextChangedWatcher
class AddMaxHeightForm : AbstractQuestFormAnswerFragment<MaxHeightAnswer>() {
override val otherAnswers = listOf(
AnswerItem(R.string.quest_maxheight_answer_noSign) { confirmNoSign() }
)
private var meterInput: EditText? = null
private var feetInput: EditText? = null
private var inchInput: EditText? = null
private var heightUnitSelect: Spinner? = null
private var meterInputSign: View? = null
private var feetInputSign: View? = null
private val heightUnits get() = countryInfo.lengthUnits.map { it.toHeightMeasurementUnit() }
override fun isFormComplete() = getHeightFromInput() != null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
setMaxHeightSignLayout(R.layout.quest_maxheight, heightUnits.first())
return view
}
private fun setMaxHeightSignLayout(resourceId: Int, unit: HeightMeasurementUnit) {
val contentView = setContentView(resourceId)
val splitWayHint = contentView.findViewById<TextView>(R.id.splitWayHint)
splitWayHint?.text = getString(R.string.quest_maxheight_split_way_hint, getString(R.string.quest_generic_answer_differs_along_the_way))
splitWayHint?.isGone = osmElement!!.type == ElementType.NODE
meterInput = contentView.findViewById(R.id.meterInput)
feetInput = contentView.findViewById(R.id.feetInput)
inchInput = contentView.findViewById(R.id.inchInput)
val onTextChangedListener = TextChangedWatcher { checkIsFormComplete() }
meterInput?.addTextChangedListener(onTextChangedListener)
feetInput?.addTextChangedListener(onTextChangedListener)
inchInput?.addTextChangedListener(onTextChangedListener)
meterInputSign = contentView.findViewById(R.id.meterInputSign)
feetInputSign = contentView.findViewById(R.id.feetInputSign)
heightUnitSelect = contentView.findViewById(R.id.heightUnitSelect)
heightUnitSelect?.isGone = heightUnits.size == 1
heightUnitSelect?.adapter = ArrayAdapter(requireContext(), R.layout.spinner_item_centered, heightUnits)
heightUnitSelect?.setSelection(0)
heightUnitSelect?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parentView: AdapterView<*>, selectedItemView: View?, position: Int, id: Long) {
switchLayout(heightUnitSelect?.selectedItem as HeightMeasurementUnit)
}
override fun onNothingSelected(parentView: AdapterView<*>) {}
}
inchInput?.filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend ->
val destStr = dest.toString()
val input = destStr.substring(0, dstart) + source.toString() + destStr.substring(dend, destStr.length)
if(input.isEmpty() || input.toIntOrNull() != null && input.toInt() <= 12) null else ""
})
meterInput?.allowOnlyNumbers()
switchLayout(unit)
}
private fun switchLayout(unit: HeightMeasurementUnit) {
val isMetric = unit == METER
val isImperial = unit == FOOT_AND_INCH
meterInputSign?.isGone = !isMetric
feetInputSign?.isGone = !isImperial
if (isMetric) meterInput?.requestFocus()
if (isImperial) feetInput?.requestFocus()
}
override fun onClickOk() {
if (userSelectedUnrealisticHeight()) {
confirmUnusualInput { applyMaxHeightFormAnswer() }
} else {
applyMaxHeightFormAnswer()
}
}
private fun userSelectedUnrealisticHeight(): Boolean {
val height = getHeightFromInput() ?: return false
val m = height.toMeters()
return m > 6 || m < 1.9
}
private fun applyMaxHeightFormAnswer() {
applyAnswer(MaxHeight(getHeightFromInput()!!))
}
private fun getHeightFromInput(): HeightMeasure? {
when(heightUnitSelect?.selectedItem as HeightMeasurementUnit? ?: heightUnits.first()) {
METER -> {
return meterInput?.numberOrNull?.let { Meters(it) }
}
FOOT_AND_INCH -> {
val feet = feetInput?.numberOrNull?.toInt()
val inches = inchInput?.numberOrNull?.toInt()
if (feet != null && inches != null) {
return ImperialFeetAndInches(feet, inches)
}
}
}
return null
}
private fun confirmNoSign() {
activity?.let { AlertDialog.Builder(it)
.setMessage(R.string.quest_maxheight_answer_noSign_question)
.setPositiveButton(R.string.quest_maxheight_answer_noSign_question_yes) { _, _ -> applyAnswer(NoMaxHeightSign(true)) }
.setNegativeButton(R.string.quest_maxheight_answer_noSign_question_no) { _, _ -> applyAnswer(NoMaxHeightSign(false)) }
.show()
}
}
private fun confirmUnusualInput(callback: () -> (Unit)) {
activity?.let { AlertDialog.Builder(it)
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_maxheight_unusualInput_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> callback() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
}
| gpl-3.0 | fea2c782bde5784fdce529421b0633c2 | 41.738255 | 143 | 0.692054 | 4.738095 | false | false | false | false |
MichaelRocks/Sunny | app/src/main/kotlin/io/michaelrocks/forecast/model/cities/sqlite/SqliteCitiesRepository.kt | 1 | 4653 | /*
* Copyright 2016 Michael Rozumyanskiy
*
* 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.michaelrocks.forecast.model.cities.sqlite
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.CancellationSignal
import io.michaelrocks.forecast.model.MainThread
import io.michaelrocks.forecast.model.cities.CitiesRepository
import io.michaelrocks.forecast.model.City
import io.michaelrocks.forecast.model.cities.CloseableList
import io.michaelrocks.forecast.model.cities.emptyCloseableList
import rx.Observable
import rx.Scheduler
import rx.schedulers.Schedulers
import rx.subscriptions.Subscriptions
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
const val CITIES_TABLE = "cities"
const val ID_COLUMN = "_id"
const val NAME_COLUMN = "name"
const val COUNTRY_COLUMN = "country"
private const val DATABASE_VERSION = 1
private const val PROJECTION = "$ID_COLUMN, $NAME_COLUMN, $COUNTRY_COLUMN"
private const val CITIES_QUERY =
"select $PROJECTION from $CITIES_TABLE order by $NAME_COLUMN"
private const val CITIES_WITH_PREFIX_QUERY =
"select $PROJECTION from $CITIES_TABLE where $NAME_COLUMN match ? order by $NAME_COLUMN"
private const val CITY_BY_ID_QUERY =
"select $PROJECTION from $CITIES_TABLE where $ID_COLUMN = ?"
private val EMPTY_ARRAY = arrayOf<String>()
class SqliteCitiesRepository @Inject private constructor(
private val context: Context,
private val databaseInstaller: DatabaseInstaller,
@MainThread private val mainThreadScheduler: Scheduler
) : CitiesRepository {
private val helperLazy = lazy {
databaseInstaller.maybeInstallDatabase()
createOpenHelper(databaseInstaller.databaseName)
}
private val helper by helperLazy
override fun getCities(): Observable<CloseableList<City>> =
performQuery { helper.readableDatabase.rawQuery(CITIES_QUERY, EMPTY_ARRAY, it) }
override fun getCitiesWithPrefix(prefix: String): Observable<CloseableList<City>> =
if (prefix.isBlank()) getCities()
else performQuery { helper.readableDatabase.rawQuery(CITIES_WITH_PREFIX_QUERY, arrayOf(toQuery(prefix)), it) }
override fun findCityById(id: Int): Observable<City?> =
performQuery { helper.readableDatabase.rawQuery(CITY_BY_ID_QUERY, arrayOf(id.toString()), it) }
.map { it.firstOrNull() }
private fun toQuery(prefix: String): String = "${prefix.replace("*", "")}*"
private inline fun performQuery(crossinline body: (CancellationSignal) -> Cursor?): Observable<CloseableList<City>> =
Observable
.create<CloseableList<City>> { subscriber ->
val complete = AtomicBoolean(false)
val cancellationSignal = CancellationSignal()
subscriber.add(Subscriptions.create {
if (!complete.get()) {
cancellationSignal.cancel()
}
})
val cursor = body(cancellationSignal)
// Ensure the cursor window is filled.
cursor?.count
complete.set(true)
val cities = cursor?.let { CityCursorWrapperList(it) } ?: emptyCloseableList<City>()
subscriber.onNext(cities)
subscriber.onCompleted()
}
.observeOn(mainThreadScheduler)
.subscribeOn(Schedulers.computation())
private fun createOpenHelper(name: String): SQLiteOpenHelper =
object : SQLiteOpenHelper(context, name, null, DATABASE_VERSION) {
override fun onCreate(database: SQLiteDatabase) {
error("Database must be created")
}
override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
error("Database must have version $newVersion instead of $oldVersion")
}
override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
error("Database must have version $newVersion instead of $oldVersion")
}
}
override fun close() {
if (helperLazy.isInitialized()) {
helperLazy.value.close()
}
}
}
| apache-2.0 | 5e09f28dcdc26c43d42e1d1120263a28 | 37.139344 | 119 | 0.716957 | 4.504356 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/service/SyncAdapter.kt | 1 | 13035 | package com.boardgamegeek.service
import android.accounts.Account
import android.app.PendingIntent
import android.content.*
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import com.boardgamegeek.BggApplication
import com.boardgamegeek.BuildConfig
import com.boardgamegeek.R
import com.boardgamegeek.extensions.*
import com.boardgamegeek.io.Adapter
import com.boardgamegeek.pref.SyncPrefs
import com.boardgamegeek.pref.setCurrentTimestamp
import com.boardgamegeek.util.HttpUtils
import com.boardgamegeek.util.RemoteConfig
import com.google.firebase.crashlytics.FirebaseCrashlytics
import okhttp3.Request
import timber.log.Timber
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.*
class SyncAdapter(private val application: BggApplication) : AbstractThreadedSyncAdapter(application.applicationContext, false) {
private var currentTask: SyncTask? = null
private var isCancelled = false
private val cancelReceiver = CancelReceiver()
private val syncPrefs: SharedPreferences = SyncPrefs.getPrefs(application)
private val prefs: SharedPreferences by lazy { context.preferences() }
init {
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler { _: Thread?, throwable: Throwable? ->
Timber.e(throwable, "Uncaught sync exception, suppressing UI in release build.")
}
}
application.registerReceiver(cancelReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
internal object CrashKeys {
const val SYNC_TYPES = "SYNC_TYPES"
const val SYNC_TYPE = "SYNC_TYPE"
const val SYNC_SETTINGS = "SYNC_SETTINGS"
}
/**
* Perform a sync. This builds a list of sync tasks from the types specified in the `extras bundle`, iterating
* over each. It posts and removes a `SyncEvent` with the type of sync task. As well as showing the progress
* in a notification.
*/
override fun onPerformSync(account: Account, extras: Bundle, authority: String, provider: ContentProviderClient, syncResult: SyncResult) {
RemoteConfig.fetch()
isCancelled = false
val uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false)
val manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)
val initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)
val type = extras.getInt(SyncService.EXTRA_SYNC_TYPE, SyncService.FLAG_SYNC_ALL)
Timber.i("Beginning sync for account %s, uploadOnly=%s manualSync=%s initialize=%s, type=%d", account.name, uploadOnly, manualSync, initialize, type)
FirebaseCrashlytics.getInstance().setCustomKey(CrashKeys.SYNC_TYPES, type)
var statuses = listOf(prefs.getSyncStatusesOrDefault()).formatList()
if (prefs.getBoolean(PREFERENCES_KEY_SYNC_PLAYS, false)) statuses += " | plays"
if (prefs.getBoolean(PREFERENCES_KEY_SYNC_BUDDIES, false)) statuses += " | buddies"
FirebaseCrashlytics.getInstance().setCustomKey(CrashKeys.SYNC_SETTINGS, statuses)
if (initialize) {
ContentResolver.setIsSyncable(account, authority, 1)
ContentResolver.setSyncAutomatically(account, authority, true)
val b = Bundle()
ContentResolver.addPeriodicSync(account, authority, b, (24 * 60 * 60).toLong()) // 24 hours
}
if (!shouldContinueSync()) {
finishSync()
return
}
toggleCancelReceiver(true)
val tasks = createTasks(application, type, uploadOnly, syncResult, account)
for (i in tasks.indices) {
if (isCancelled) {
Timber.i("Cancelling all sync tasks")
notifySyncIsCancelled(currentTask?.notificationSummaryMessageId ?: SyncTask.NO_NOTIFICATION)
break
}
currentTask = tasks[i]
try {
syncPrefs.setCurrentTimestamp()
currentTask?.let {
FirebaseCrashlytics.getInstance().setCustomKey(CrashKeys.SYNC_TYPE, it.syncType)
it.updateProgressNotification()
it.execute()
}
if (currentTask?.isCancelled == true) {
Timber.i("Sync task %s has requested the sync operation to be cancelled", currentTask)
break
}
} catch (e: Exception) {
Timber.e(e, "Syncing %s", currentTask)
syncResult.stats.numIoExceptions += 10
showException(currentTask, e)
if (e.cause is SocketTimeoutException) {
break
}
}
}
finishSync()
}
private fun finishSync() {
context.cancelNotification(NotificationTags.SYNC_PROGRESS)
toggleCancelReceiver(false)
syncPrefs.setCurrentTimestamp(0L)
try {
context.unregisterReceiver(cancelReceiver)
} catch (e: Exception) {
Timber.w(e)
}
}
/**
* Indicates that a sync operation has been canceled.
*/
override fun onSyncCanceled() {
super.onSyncCanceled()
Timber.i("Sync cancel requested.")
isCancelled = true
currentTask?.cancel()
}
/**
* Determine if the sync should continue based on the current state of the device.
*/
private fun shouldContinueSync(): Boolean {
if (context.isOffline()) {
Timber.i("Skipping sync; offline")
return false
}
if (prefs.getSyncOnlyCharging() && !context.isCharging()) {
Timber.i("Skipping sync; not charging")
return false
}
if (prefs.getSyncOnlyWifi() && !context.isOnWiFi()) {
Timber.i("Skipping sync; not on wifi")
return false
}
if (context.isBatteryLow()) {
Timber.i("Skipping sync; battery low")
return false
}
if (!RemoteConfig.getBoolean(RemoteConfig.KEY_SYNC_ENABLED)) {
Timber.i("Sync disabled remotely")
return false
}
if (hasPrivacyError()) {
Timber.i("User still hasn't accepted the new privacy policy.")
return false
}
return true
}
private fun hasPrivacyError(): Boolean {
val weeksToCompare = RemoteConfig.getInt(RemoteConfig.KEY_PRIVACY_CHECK_WEEKS)
val weeks = prefs.getLastPrivacyCheckTimestamp().howManyWeeksOld()
if (weeks < weeksToCompare) {
Timber.i("We checked the privacy statement less than %,d weeks ago; skipping", weeksToCompare)
return false
}
val httpClient = HttpUtils.getHttpClientWithAuth(context)
val url = "https://www.boardgamegeek.com"
val request: Request = Request.Builder().url(url).build()
return try {
val response = httpClient.newCall(request).execute()
val body = response.body
val content = body?.string()?.trim().orEmpty()
if (content.contains("Please update your privacy and marketing preferences")) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
)
val message = context.getString(R.string.sync_notification_message_privacy_error)
val builder = context
.createNotificationBuilder(R.string.sync_notification_title_error, NotificationChannels.ERROR)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setPriority(NotificationCompat.PRIORITY_HIGH)
context.notify(builder, NotificationTags.SYNC_ERROR, Int.MAX_VALUE)
true
} else {
prefs.setLastPrivacyCheckTimestamp()
false
}
} catch (e: IOException) {
Timber.w(e)
true
}
}
/**
* Create a list of sync tasks based on the specified type.
*/
private fun createTasks(
application: BggApplication,
typeList: Int,
uploadOnly: Boolean,
syncResult: SyncResult,
account: Account
): List<SyncTask> {
val service = Adapter.createForXmlWithAuth(application)
val tasks: MutableList<SyncTask> = ArrayList()
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_COLLECTION_UPLOAD)) {
tasks.add(SyncCollectionUpload(application, service, syncResult))
}
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_COLLECTION_DOWNLOAD) && !uploadOnly) {
tasks.add(SyncCollectionComplete(application, service, syncResult, account))
tasks.add(SyncCollectionModifiedSince(application, service, syncResult, account))
tasks.add(SyncCollectionUnupdated(application, service, syncResult, account))
}
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_GAMES) && !uploadOnly) {
tasks.add(SyncGamesRemove(application, service, syncResult))
tasks.add(SyncGamesOldest(application, service, syncResult))
tasks.add(SyncGamesUnupdated(application, service, syncResult))
}
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_PLAYS_UPLOAD)) {
tasks.add(SyncPlaysUpload(application, service, syncResult))
}
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_PLAYS_DOWNLOAD) && !uploadOnly) {
tasks.add(SyncPlays(application, service, syncResult, account))
}
if (shouldCreateTask(typeList, SyncService.FLAG_SYNC_BUDDIES) && !uploadOnly) {
tasks.add(SyncBuddiesList(application, service, syncResult))
tasks.add(SyncBuddiesDetailOldest(application, service, syncResult))
tasks.add(SyncBuddiesDetailUnupdated(application, service, syncResult))
}
return tasks
}
private fun shouldCreateTask(typeList: Int, type: Int): Boolean {
return (typeList and type) == type
}
/**
* Enable or disable the cancel receiver. (There's no reason for the receiver to be enabled when the sync isn't running.
*/
private fun toggleCancelReceiver(enable: Boolean) {
val receiver = ComponentName(context, CancelReceiver::class.java)
context.packageManager.setComponentEnabledSetting(
receiver,
if (enable) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
)
}
/**
* Show a notification of any exception thrown by a sync task that isn't caught by the task.
*/
private fun showException(task: SyncTask?, t: Throwable) {
val message = t.message?.ifEmpty {
t.cause?.toString()
} ?: t.cause?.toString()
Timber.w(message)
if (!prefs.getSyncShowErrors() || task == null) return
val messageId = task.notificationSummaryMessageId
if (messageId != SyncTask.NO_NOTIFICATION) {
val text = context.getText(messageId)
val builder = context
.createNotificationBuilder(R.string.sync_notification_title_error, NotificationChannels.ERROR)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ERROR)
if (!message.isNullOrBlank()) {
builder.setStyle(NotificationCompat.BigTextStyle().bigText(message).setSummaryText(text))
}
context.notify(builder, NotificationTags.SYNC_ERROR)
}
}
/**
* Show that the sync was cancelled in a notification. This may be useless since the notification is cancelled
* almost immediately after this is shown.
*/
private fun notifySyncIsCancelled(messageId: Int) {
if (!prefs.getSyncShowNotifications()) return
val contextText = if (messageId == SyncTask.NO_NOTIFICATION) "" else context.getText(messageId)
val builder = context
.createNotificationBuilder(R.string.sync_notification_title_cancel, NotificationChannels.SYNC_PROGRESS)
.setContentText(contextText)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
context.notify(builder, NotificationTags.SYNC_PROGRESS)
}
}
| gpl-3.0 | 73d39943c9ceca1e017d914a6dd37833 | 42.45 | 157 | 0.642424 | 4.905909 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-server/src/com/hendraanggrian/openpss/route/AuthRouting.kt | 1 | 1139 | package com.hendraanggrian.openpss.route
import com.hendraanggrian.openpss.Server
import com.hendraanggrian.openpss.nosql.transaction
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.schema.Employees
import io.ktor.application.call
import io.ktor.response.respond
import io.ktor.routing.Routing
import io.ktor.routing.get
import kotlinx.nosql.equal
fun Routing.auth() {
get("login") {
val name = call.getString("name")
val password = call.getString("password")
val employee = transaction { Employees { this.name.equal(name) }.singleOrNull() }
when {
employee == null -> {
call.respond(Employee.NOT_FOUND)
Server.log?.error("Employee not found: $name")
}
employee.password != password -> {
call.respond(Employee.NOT_FOUND)
Server.log?.error("Wrong password: $name")
}
else -> {
employee.clearPassword()
call.respond(employee)
Server.log?.info("Logged in: $name")
}
}
}
}
| apache-2.0 | e995a99c5f69cec5535522b585133487 | 32.5 | 89 | 0.612818 | 4.347328 | false | false | false | false |
KDatabases/Kuery | src/main/kotlin/com/sxtanna/database/ext/kdata.kt | 1 | 1437 | @file:JvmName("KData")
package com.sxtanna.database.ext
import com.sxtanna.database.struct.obj.Sort
import com.sxtanna.database.struct.obj.SqlType
import com.sxtanna.database.struct.obj.Target
import kotlin.reflect.KProperty1
/**
* Implement data validation for client side failing
*/
const val MIN_UNSIGN = 0
const val TINY_MAX_SIGN = Byte.MAX_VALUE.toInt()
const val TINY_MIN_SIGN = Byte.MIN_VALUE.toInt()
const val TINY_MAX_UNSIGN = 255
const val SMALL_MAX_SIGN = Short.MAX_VALUE.toInt()
const val SMALL_MIN_SIGN = Short.MIN_VALUE.toInt()
const val SMALL_MAX_UNSIGN = 65535
const val MEDIUM_MAX_SIGN = 8388607
const val MEDIUM_MIN_SIGN = -8388608
const val MEDIUM_MAX_UNSIGN = 16777215
const val NORM_MAX_SIGN = Int.MAX_VALUE
const val NORM_MIN_SIGN = Int.MIN_VALUE
const val NORM_MAX_UNSIGN = 4294967295
const val BIG_MAX_SIGN = "9223372036854775807"
const val BIG_MIN_SIGN = "-9223372036854775808"
const val BIG_MAX_UNSIGNED = "18446744073709551615"
const val VARCHAR_SIZE = 255
const val TEXT_SIZE = SMALL_MAX_UNSIGN
const val TINY_TEXT_SIZE = TINY_MAX_UNSIGN
const val MEDIUM_TEXT_SIZE = MEDIUM_MAX_UNSIGN
const val LONG_TEXT_SIZE = NORM_MAX_UNSIGN
/**
* Represents all rows in a select statement
*/
@get:JvmName("allRows")
val ALL_ROWS = arrayOf("*")
@get:JvmName("noSort")
val NO_SORTS = arrayOf<Sort>()
@get:JvmName("noWhere")
val NO_WHERE = arrayOf<Target>()
typealias Adapter = KProperty1<*, *>.() -> SqlType | apache-2.0 | 4290500ba8a89d9bed614aef03cad3db | 26.132075 | 52 | 0.749478 | 3.057447 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/MakeConfigurable.kt | 1 | 1745 | package name.kropp.intellij.makefile
import com.intellij.openapi.fileChooser.*
import com.intellij.openapi.options.*
import com.intellij.openapi.project.*
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.*
import com.intellij.ui.components.*
import com.intellij.uiDesigner.core.*
import com.intellij.util.ui.*
import javax.swing.*
class MakeConfigurable(project: Project?) : Configurable {
private val settings = project?.getService(MakefileProjectSettings::class.java)
private val pathField = TextFieldWithBrowseButton()
private val cygwinField = JBCheckBox("Use Cygwin${if (!SystemInfo.isWindows) " (Windows only)" else ""}")
init {
pathField.addBrowseFolderListener("Make", "Path to make executable", project, FileChooserDescriptor(true, false, false, false, false, false))
}
override fun isModified(): Boolean {
return settings?.settings?.path != pathField.text ||
settings.settings?.useCygwin != cygwinField.isSelected
}
override fun getDisplayName() = "Make"
override fun apply() {
settings?.settings?.path = pathField.text
settings?.settings?.useCygwin = cygwinField.isSelected
}
override fun createComponent(): JComponent {
return FormBuilder.createFormBuilder()
.setAlignLabelOnRight(false)
.setHorizontalGap(UIUtil.DEFAULT_HGAP)
.setVerticalGap(UIUtil.DEFAULT_VGAP)
.addLabeledComponent("Path to &Make executable", pathField)
.addComponent(cygwinField)
.addComponentFillVertically(Spacer(), 0)
.panel
}
override fun reset() {
pathField.text = settings?.settings?.path ?: ""
cygwinField.isSelected = settings?.settings?.useCygwin ?: false
}
override fun getHelpTopic(): String? = null
} | mit | 6704b9e70eccea6007a2dd1bdd7cdfe3 | 33.92 | 145 | 0.728367 | 4.266504 | false | false | false | false |
sys1yagi/swipe-android | core/src/main/java/com/sys1yagi/swipe/core/tool/ColorConverter.kt | 1 | 1098 | package com.sys1yagi.swipe.core.tool
import android.graphics.Color
import android.support.annotation.Size
class ColorConverter {
companion object {
fun toColorInt(@Size(min = 3) color: String?): Int {
if (color == null) {
return Color.BLACK
}
var colorString = color
if (colorString.startsWith("#")) {
colorString = colorString.substring(1)
}
if (colorString.length == 3) {
colorString = StringBuilder(6)
.append(colorString[0])
.append(colorString[0])
.append(colorString[1])
.append(colorString[1])
.append(colorString[2])
.append(colorString[2]).toString()
}
var convertColor = java.lang.Long.parseLong(colorString, 16)
if (colorString.length < 8) {
convertColor = convertColor or -16777216
}
return convertColor.toInt()
}
}
}
| mit | 6596f01bba833fb8eff377e68e2814d2 | 31.294118 | 72 | 0.499089 | 4.712446 | false | false | false | false |
MehdiK/Humanizer.jvm | test/main/kotlin/org/humanizer/jvm/tests/PluralizeTests.kt | 1 | 9284 | package org.humanizer.jvm.tests
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.givenData
import org.humanizer.jvm.titleize
import org.jetbrains.spek.api.shouldEqual
import org.humanizer.jvm.pluralize
import org.humanizer.jvm.singularize
import java.util.GregorianCalendar
import java.util.Calendar
import org.humanizer.jvm.humanize
import java.util.ArrayList
public class PluralizeTests() : Spek() {
init {
var data = listOf(
"search" to "searches",
"switch" to "switches",
"fix" to "fixes",
"box" to "boxes",
"process" to "processes",
"address" to "addresses",
"case" to "cases",
"stack" to "stacks",
"wish" to "wishes",
"fish" to "fish",
"category" to "categories",
"query" to "queries",
"ability" to "abilities",
"agency" to "agencies",
"movie" to "movies",
"archive" to "archives",
"index" to "indices",
"wife" to "wives",
"safe" to "saves",
"half" to "halves",
"move" to "moves",
"salesperson" to "salespeople",
"person" to "people",
"spokesman" to "spokesmen",
"man" to "men",
"woman" to "women",
"basis" to "bases",
"diagnosis" to "diagnoses",
"datum" to "data",
"medium" to "media",
"analysis" to "analyses",
"node_child" to "node_children",
"child" to "children",
"experience" to "experiences",
"day" to "days",
"comment" to "comments",
"foobar" to "foobars",
"newsletter" to "newsletters",
"old_news" to "old_news",
"news" to "news",
"series" to "series",
"species" to "species",
"quiz" to "quizzes",
"perspective" to "perspectives",
"ox" to "oxen",
"photo" to "photos",
"buffalo" to "buffaloes",
"tomato" to "tomatoes",
"dwarf" to "dwarves",
"elf" to "elves",
"information" to "information",
"equipment" to "equipment",
"bus" to "buses",
"status" to "statuses",
"status_code" to "status_codes",
"mouse" to "mice",
"louse" to "lice",
"house" to "houses",
"octopus" to "octopi",
"virus" to "viri",
"alias" to "aliases",
"portfolio" to "portfolios",
"vertex" to "vertices",
"matrix" to "matrices",
"axis" to "axes",
"testis" to "testes",
"crisis" to "crises",
"rice" to "rice",
"shoe" to "shoes",
"horse" to "horses",
"prize" to "prizes",
"edge" to "edges",
"deer" to "deer",
"sheep" to "sheep",
"wolf" to "wolves",
"codex" to "codices",
"radix" to "radices",
"bacterium" to "bacteria",
"agendum" to "agenda",
"desideratum" to "desiderata",
"erratum" to "errata",
"stratum" to "strata",
"ovum" to "ova",
"extremum" to "extrema",
"candelabrum" to "candelabra",
"alumnus" to "alumni",
"alveolus" to "alveoli",
"bacillus" to "bacilli",
"bronchus" to "bronchi",
"locus" to "loci",
"nucleus" to "nuclei",
"stimulus" to "stimuli",
"meniscus" to "menisci",
"thesaurus" to "thesauri",
"criterion" to "criteria",
"perihelion" to "perihelia",
"aphelion" to "aphelia",
"phenomenon" to "phenomena",
"prolegomenon" to "prolegomena",
"noumenon" to "noumena",
"organon" to "organa",
"asyndeton" to "asyndeta",
"hyperbaton" to "hyperbata",
"alumna" to "alumnae",
"alga" to "algae",
"vertebra" to "vertebrae",
"persona" to "personae",
"albino" to "albinos",
"archipelago" to "archipelagos",
"armadillo" to "armadillos",
"commando" to "commandos",
"crescendo" to "crescendos",
"fiasco" to "fiascos",
"ditto" to "dittos",
"dynamo" to "dynamos",
"embryo" to "embryos",
"ghetto" to "ghettos",
"guano" to "guanos",
"inferno" to "infernos",
"jumbo" to "jumbos",
"lumbago" to "lumbagos",
"magneto" to "magnetos",
"manifesto" to "manifestos",
"medico" to "medicos",
"octavo" to "octavos",
"pro" to "pros",
"quarto" to "quartos",
"canto" to "cantos",
"lingo" to "lingos",
"generalissimo" to "generalissimos",
"stylo" to "stylos",
"rhino" to "rhinos",
"casino" to "casinos",
"auto" to "autos",
"macro" to "macros",
"zero" to "zeros",
"solo" to "solos",
"soprano" to "sopranos",
"basso" to "bassos",
"alto" to "altos",
"contralto" to "contraltos",
"tempo" to "tempos",
"piano" to "pianos",
"virtuoso" to "virtuosos",
"stamen" to "stamina",
"foramen" to "foramina",
"lumen" to "lumina",
"anathema" to "anathemas",
"enema" to "enemas",
"oedema" to "oedemas",
"bema" to "bemas",
"enigma" to "enigmas",
"sarcoma" to "sarcomas",
"carcinoma" to "carcinomas",
"gumma" to "gummas",
"schema" to "schemas",
"charisma" to "charismas",
"lemma" to "lemmas",
"soma" to "somas",
"diploma" to "diplomas",
"lymphoma" to "lymphomas",
"stigma" to "stigmas",
"dogma" to "dogmas",
"magma" to "magmas",
"stoma" to "stomas",
"drama" to "dramas",
"melisma" to "melismas",
"trauma" to "traumas",
"edema" to "edemas",
"miasma" to "miasmas",
"afreet" to "afreeti",
"afrit" to "afriti",
"efreet" to "efreeti",
"cherub" to "cherubim",
"goy" to "goyim",
"seraph" to "seraphim",
"human" to "humans",
"Alabaman" to "Alabamans",
"Bahaman" to "Bahamans",
"Burman" to "Burmans",
"German" to "Germans",
"Hiroshiman" to "Hiroshimans",
"Liman" to "Limans",
"Nakayaman" to "Nakayamans",
"Oklahoman" to "Oklahomans",
"Panaman" to "Panamans",
"Selman" to "Selmans",
"Sonaman" to "Sonamans",
"Tacoman" to "Tacomans",
"Yakiman" to "Yakimans",
"Yokohaman" to "Yokohamans",
"Yuman" to "Yumans"
)
givenData(data) {
val (value, expected) = it
on("calling pluralize on String", {
val actual = value.pluralize()
it("should be ${expected}", {
shouldEqual(expected, actual)
})
})
}
givenData(data) {
val (expected, value) = it
on("calling singularize on String", {
val actual = value.singularize()
it("should be ${expected}", {
shouldEqual(expected, actual)
})
})
}
given("datalist should not contain doubles") {
on("grouping by plural", {
val doubles = data.groupBy { it.component1() }.map {
val key = it.key
val count = data.count { it.first == key }
Pair(key, count)
}.filter { it.second > 1 }.map { it.first }.join(",")
it("should be empty for all groups", {
shouldEqual("", doubles)
})
})
}
}
}
| apache-2.0 | 02b760e54c62fb1213d45d778ff6428d | 32.157143 | 69 | 0.40866 | 3.891031 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/menu/AbstractFileListItemMenuBuilder.kt | 2 | 1705 | package com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.client.browsing.items.menu.BuildListItemMenuViewContainers
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.browsing.items.menu.OnViewChangedListener
abstract class AbstractFileListItemMenuBuilder<TViewContainer : RecyclerView.ViewHolder>
protected constructor(@param:LayoutRes private val menuLayoutId: Int)
: BuildListItemMenuViewContainers<TViewContainer>
{
private var onViewChangedListener: OnViewChangedListener? = null
fun setOnViewChangedListener(onViewChangedListener: OnViewChangedListener?) {
this.onViewChangedListener = onViewChangedListener
}
override fun newViewHolder(parent: ViewGroup): TViewContainer {
val fileItemMenu = FileListItemContainer(parent.context)
val notifyOnFlipViewAnimator = fileItemMenu.viewAnimator
val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val fileMenu = inflater.inflate(menuLayoutId, parent, false) as LinearLayout
notifyOnFlipViewAnimator.addView(fileMenu)
notifyOnFlipViewAnimator.setViewChangedListener(onViewChangedListener)
notifyOnFlipViewAnimator.setOnLongClickListener(LongClickViewAnimatorListener(notifyOnFlipViewAnimator))
return newViewHolder(fileItemMenu)
}
abstract fun newViewHolder(fileItemMenu: FileListItemContainer): TViewContainer
}
| lgpl-3.0 | 3ec0b80f2014f5986a02b350f814588c | 43.868421 | 106 | 0.864516 | 4.830028 | false | false | false | false |
JVMDeveloperID/kotlin-android-example | app/src/main/kotlin/com/gojek/sample/kotlin/internal/data/local/dao/ContactDao.kt | 1 | 1797 | package com.gojek.sample.kotlin.internal.data.local.dao
import com.gojek.sample.kotlin.extensions.membersOf
import com.gojek.sample.kotlin.internal.data.local.realm.ContactRealm
import io.realm.Realm
import io.realm.RealmResults
import io.realm.internal.IOException
class ContactDao : Dao<ContactRealm> {
override fun saveOrUpdate(data: ContactRealm) {
val realm: Realm = Realm.getDefaultInstance()
realm.executeTransactionAsync({ realm -> realm.insertOrUpdate(data) }, { realm.close() }) { realm.close() }
}
override fun findAll(): List<ContactRealm> {
val realm: Realm = Realm.getDefaultInstance()
val data: RealmResults<ContactRealm> = realm.where(membersOf<ContactRealm>()).findAll()
realm.close()
return data
}
override fun findOne(): ContactRealm {
try {
val realm: Realm = Realm.getDefaultInstance()
val data: ContactRealm = realm.copyFromRealm(realm.where(membersOf<ContactRealm>()).findFirst())
realm.close()
return data
} catch (e: IOException) {
e.printStackTrace()
return ContactRealm()
}
}
override fun delete() {
val realm: Realm = Realm.getDefaultInstance()
realm.executeTransactionAsync({ realm -> realm.delete(membersOf<ContactRealm>()) }, { realm.close() }) { realm.close() }
}
fun findById(id: Int?): ContactRealm? {
val realm: Realm = Realm.getDefaultInstance()
var data: ContactRealm? = realm.where<ContactRealm>(membersOf<ContactRealm>()).equalTo("id", id).findFirst()
if (null != data) {
data = realm.copyFromRealm(data)
} else {
data = ContactRealm()
}
realm.close()
return data
}
} | apache-2.0 | 4883679959cd2d2ca86b8b5ef74b95a8 | 31.690909 | 128 | 0.636617 | 4.503759 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt | 7 | 2130 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.platform.android
import javax.net.ssl.SSLSocket
import okhttp3.Protocol
/**
* Deferred implementation of SocketAdapter that works by observing the socket
* and initializing on first use.
*
* We use this because eager classpath checks cause confusion and excessive logging in Android,
* and we can't rely on classnames after proguard, so are probably best served by falling through
* to a situation of trying our least likely noisiest options.
*/
class DeferredSocketAdapter(private val socketAdapterFactory: Factory) : SocketAdapter {
private var delegate: SocketAdapter? = null
override fun isSupported(): Boolean {
return true
}
override fun matchesSocket(sslSocket: SSLSocket): Boolean =
socketAdapterFactory.matchesSocket(sslSocket)
override fun configureTlsExtensions(
sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) {
getDelegate(sslSocket)?.configureTlsExtensions(sslSocket, hostname, protocols)
}
override fun getSelectedProtocol(sslSocket: SSLSocket): String? {
return getDelegate(sslSocket)?.getSelectedProtocol(sslSocket)
}
@Synchronized private fun getDelegate(sslSocket: SSLSocket): SocketAdapter? {
if (this.delegate == null && socketAdapterFactory.matchesSocket(sslSocket)) {
this.delegate = socketAdapterFactory.create(sslSocket)
}
return delegate
}
interface Factory {
fun matchesSocket(sslSocket: SSLSocket): Boolean
fun create(sslSocket: SSLSocket): SocketAdapter
}
}
| apache-2.0 | bb1a92560df76ffdbf9407aed70957f7 | 32.809524 | 97 | 0.752582 | 4.580645 | false | false | false | false |
NextFaze/dev-fun | demo/src/main/java/com/nextfaze/devfun/demo/util/Optional.kt | 1 | 716 | package com.nextfaze.devfun.demo.util
import com.nextfaze.devfun.demo.util.Optional.Some
import io.reactivex.Observable
sealed class Optional<out T : Any> {
abstract val isPresent: Boolean
object None : Optional<Nothing>() {
override val isPresent: Boolean = false
}
data class Some<out T : Any>(val value: T) : Optional<T>() {
override val isPresent: Boolean = true
}
}
val <T : Any> Optional<T>.value: T?
get() = when (this) {
is Optional.Some -> value
else -> null
}
fun <T : Any> T?.toOptional(): Optional<T> = this?.let(::Some) ?: Optional.None
private inline fun <reified R : Any> Observable<*>.ofType(): Observable<R> = ofType(R::class.java)
| apache-2.0 | 7b59668f717bee3d244c3e3e97ce5ad0 | 26.538462 | 98 | 0.643855 | 3.634518 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/multiblocks/tilerenderers/Machines.kt | 2 | 8479 | package com.cout970.magneticraft.features.multiblocks.tilerenderers
import com.cout970.magneticraft.features.automatic_machines.Blocks
import com.cout970.magneticraft.features.automatic_machines.TileRendererConveyorBelt
import com.cout970.magneticraft.features.multiblocks.tileentities.*
import com.cout970.magneticraft.misc.RegisterRenderer
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import com.cout970.magneticraft.misc.resource
import com.cout970.magneticraft.systems.tilerenderers.*
import com.cout970.modelloader.api.*
import com.cout970.modelloader.api.formats.gltf.GltfAnimationBuilder
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.GlStateManager.*
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.util.ResourceLocation
import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks
@RegisterRenderer(TileGrinder::class)
object TileRendererGrinder : TileRendererMultiblock<TileGrinder>() {
override fun init() {
createModel(Multiblocks.grinder, ModelSelector("animation", FilterAlways, FilterRegex("animation", FilterTarget.ANIMATION)))
}
override fun render(te: TileGrinder) {
Utilities.rotateFromCenter(te.facing, 0f)
translate(0, 0, -1)
if (te.processModule.working) renderModel("animation") else renderModel("default")
}
}
@RegisterRenderer(TileSieve::class)
object TileRendererSieve : TileRendererMultiblock<TileSieve>() {
override fun init() {
createModel(Multiblocks.sieve, ModelSelector("animation", FilterAlways, FilterRegex("animation", FilterTarget.ANIMATION)))
}
override fun render(te: TileSieve) {
Utilities.rotateFromCenter(te.facing, 180f)
translate(0, 0, 2)
if (te.processModule.working) renderModel("animation") else renderModel("default")
}
}
@RegisterRenderer(TileHydraulicPress::class)
object TileRendererHydraulicPress : TileRendererMultiblock<TileHydraulicPress>() {
override fun init() {
createModel(Multiblocks.hydraulicPress, ModelSelector("animation", FilterAlways, FilterRegex("animation", FilterTarget.ANIMATION)))
}
override fun render(te: TileHydraulicPress) {
Utilities.rotateFromCenter(te.facing, 0f)
translate(0, 0, -1)
if (te.processModule.working) renderModel("animation") else renderModel("default")
val stack = te.inventory[0]
if (stack.isNotEmpty) {
stackMatrix {
translate(0.5f, 2f, 0.5f)
if (!Minecraft.getMinecraft().renderItem.shouldRenderItemIn3D(stack)) {
scale(2.0)
} else {
translate(0f, -PIXEL, 0f)
}
Utilities.renderItem(stack)
}
}
}
}
@RegisterRenderer(TileBigCombustionChamber::class)
object TileRendererBigCombustionChamber : TileRendererMultiblock<TileBigCombustionChamber>() {
override fun init() {
createModel(Multiblocks.bigCombustionChamber,
ModelSelector("fire_off", FilterString("fire_off")),
ModelSelector("fire_on", FilterString("fire_on"))
)
}
override fun render(te: TileBigCombustionChamber) {
Utilities.rotateFromCenter(te.facing, 0f)
translate(0, 0, -1)
renderModel("default")
if (te.bigCombustionChamberModule.working()) renderModel("fire_on") else renderModel("fire_off")
}
}
@RegisterRenderer(TileBigSteamBoiler::class)
object TileRendererBigSteamBoiler : TileRendererMultiblock<TileBigSteamBoiler>() {
override fun init() {
createModel(Multiblocks.bigSteamBoiler)
}
override fun render(te: TileBigSteamBoiler) {
Utilities.rotateFromCenter(te.facing, 0f)
renderModel("default")
}
}
@RegisterRenderer(TileSteamTurbine::class)
object TileRendererSteamTurbine : TileRendererMultiblock<TileSteamTurbine>() {
override fun init() {
createModel(Multiblocks.steamTurbine,
ModelSelector("blade", FilterRegex("blade.*")),
ModelSelector("not_blade", FilterNotRegex("blade.*"))
)
}
override fun render(te: TileSteamTurbine) {
Utilities.rotateFromCenter(te.facing, 0f)
translate(-1, 0, 0)
renderModel("not_blade")
val speed = 0.25f * te.steamGeneratorModule.production.storage / te.steamGeneratorModule.maxProduction
// Smooth changes in speed
if (te.turbineSpeed < speed) {
te.turbineSpeed += 0.25f / 20
} else if (te.turbineSpeed > speed) {
te.turbineSpeed -= 0.25f / 20
}
// Smooth rotation
val now = (System.currentTimeMillis() % 0xFFFF).toFloat()
val delta = now - te.lastTime
te.lastTime = now
te.turbineAngle += te.turbineSpeed * delta
translate(1.5f, 1.5f, 0f)
repeat(12) {
stackMatrix {
rotate(it * 360 / 12f + te.turbineAngle, 0, 0, 1)
translate(-1.5f, -1.5f, 0f)
renderModel("blade")
}
}
}
}
@RegisterRenderer(TileBigElectricFurnace::class)
object TileRendererBigElectricFurnace : TileRendererMultiblock<TileBigElectricFurnace>() {
var belt: IRenderCache? = null
override fun init() {
createModelWithoutTexture(Multiblocks.bigElectricFurnace,
ModelSelector("multiblock", FilterAlways),
ModelSelector("dark", FilterString("Object 26"))
)
createModel(Blocks.conveyorBelt, listOf(
ModelSelector("back_legs", FilterRegex("back_leg.*")),
ModelSelector("front_legs", FilterRegex("front_leg.*")),
ModelSelector("lateral_left", FilterRegex("lateral_left")),
ModelSelector("lateral_right", FilterRegex("lateral_right")),
ModelSelector("panel_left", FilterRegex("panel_left")),
ModelSelector("panel_right", FilterRegex("panel_right"))
), "base")
val anim = modelOf(Blocks.conveyorBelt, "anim")
//cleaning
belt?.close()
val beltModel = ModelLoaderApi.getModelEntry(anim) ?: return
val texture = resource("blocks/machines/conveyor_belt_anim")
belt = updateTexture(beltModel, texture)
}
override fun render(te: TileBigElectricFurnace) {
Utilities.rotateFromCenter(te.facing, 0f)
// Input belt
renderBelt()
TileRendererConveyorBelt.renderDynamicParts(te.inConveyor, ticks)
// Main structure
translate(0f, 0f, -1f)
if (te.processModule.working) {
bindTexture(resource("textures/blocks/multiblocks/big_electric_furnace_on.png"))
} else {
bindTexture(resource("textures/blocks/multiblocks/big_electric_furnace_off.png"))
}
renderModel("multiblock")
// Dark interior
disableTexture2D()
if (te.processModule.working) {
color(0.2f, 0.1f, 0.05f, 1f)
} else {
color(0f, 0f, 0f, 1f)
}
renderModel("dark")
enableTexture2D()
color(1f, 1f, 1f, 1f)
// Exit belt
translate(0f, 0f, -1f)
renderBelt()
TileRendererConveyorBelt.renderDynamicParts(te.outConveyor, ticks)
}
fun renderBelt() {
belt?.render()
renderModel("default")
renderModel("panel_left")
renderModel("panel_right")
renderModel("back_legs")
renderModel("front_legs")
}
private fun updateTexture(model: ModelEntry, texture: ResourceLocation): IRenderCache {
val raw = model.raw
val textureMap = Minecraft.getMinecraft().textureMapBlocks
val animTexture = textureMap.getAtlasSprite(texture.toString())
return when (raw) {
is Model.Mcx -> {
val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture)
TextureModelCache(TextureMap.LOCATION_BLOCKS_TEXTURE, ModelCache { ModelUtilities.renderModel(finalModel) })
}
is Model.Gltf -> {
val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture)
val anim = GltfAnimationBuilder().buildPlain(finalModel)
AnimationRenderCache(anim) { 0.0 }
}
else -> error("Invalid type: $raw, ${raw::class.java}")
}
}
} | gpl-2.0 | 9221c9a85c3f54c66ce2899d7be81dc1 | 34.630252 | 139 | 0.652435 | 4.404675 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/OptionsManager.kt | 1 | 2441 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.options
import java.io.File
object OptionsManager {
private val topLevelMap = mutableMapOf<String, TopLevelOptions>()
fun getTopLevelOptions(optionsName: String): TopLevelOptions {
val found = topLevelMap[optionsName]
if (found == null) {
val newTL = TopLevelOptions(optionsName)
topLevelMap.put(optionsName, newTL)
return newTL
} else {
return found
}
}
fun findNonRowOption(code: String, optionsName: String): Option? {
return getTopLevelOptions(optionsName).findNonRowOption(code)
}
fun findOptionForRow(code: String, optionsName: String, row: Any): Option? {
return getTopLevelOptions(optionsName).findOptionForRow(code, row)
}
private val pathMap = mutableMapOf<File, OptionsPath>()
private fun getOptionsPath(directory: File): OptionsPath {
val found = pathMap[directory]
if (found == null) {
val newOP = OptionsPath(directory)
pathMap.put(directory, newOP)
return newOP
} else {
return found
}
}
fun getFileOptions(optionsName: String, directory: File): FileOptions {
return getOptionsPath(directory).getFileOptions(optionsName)
}
}
data class OptionsPath(val directory: File) {
val fileOptionsMap = mutableMapOf<String, FileOptions>()
fun getFileOptions(optionsName: String): FileOptions {
val found = fileOptionsMap[optionsName]
if (found == null) {
val result = FileOptions(File(directory, optionsName + ".json"))
fileOptionsMap.put(optionsName, result)
return result
} else {
return found
}
}
}
| gpl-3.0 | ff1088ac0da71f3e47fb47122d545a56 | 30.701299 | 80 | 0.676772 | 4.487132 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleHeatPipeConnections.kt | 2 | 1233 | package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.misc.tileentity.canConnect
import com.cout970.magneticraft.misc.vector.plus
import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER
import com.cout970.magneticraft.registry.getOrNull
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.util.EnumFacing
class ModuleHeatPipeConnections(
val heatModule: ModuleHeat,
override val name: String = "module_heat_pipe_connections"
) : IModule {
override lateinit var container: IModuleContainer
fun canConnect(side: EnumFacing): Boolean {
val tile = world.getTileEntity(pos + side) ?: return false
val handler = tile.getOrNull(HEAT_NODE_HANDLER, side.opposite) ?: return false
if (handler === heatModule) return false
val heatNodes = handler.nodes.filterIsInstance<IHeatNode>()
heatNodes.forEach { otherNode ->
if (canConnect(heatModule, heatModule.heatNodes[0], handler, otherNode, side.opposite)) {
return true
}
}
return false
}
} | gpl-2.0 | 03fb249d0cbfb7d85f0ad58ba3b2076c | 37.5625 | 101 | 0.74047 | 4.341549 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/model/IndicatorCategory.kt | 1 | 823 | package net.nemerosa.ontrack.extension.indicators.model
/**
* Catagory grouping several [indicator types][IndicatorType] together.
*
* @param id Unique ID of the category
* @param name Display name for the category
* @param source Optional source for this category. `null` means that the category was provisioned manually.
* @param deprecated Optional deprecation reason
*/
class IndicatorCategory(
val id: String,
val name: String,
val source: IndicatorSource?,
val deprecated: String? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IndicatorCategory) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
} | mit | cdf18885ae4f8b50e4f1fdb21d4d7f66 | 25.580645 | 108 | 0.665857 | 4.546961 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/ui/adapter/UnifiedSearchItemViewHolder.kt | 1 | 5134 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.content.res.ResourcesCompat
import com.afollestad.sectionedrecyclerview.SectionedViewHolder
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.nextcloud.client.account.User
import com.nextcloud.client.network.ClientFactory
import com.owncloud.android.R
import com.owncloud.android.databinding.UnifiedSearchItemBinding
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.lib.common.SearchResultEntry
import com.owncloud.android.ui.interfaces.UnifiedSearchListInterface
import com.owncloud.android.utils.BitmapUtils
import com.owncloud.android.utils.MimeTypeUtil
import com.owncloud.android.utils.glide.CustomGlideStreamLoader
import com.owncloud.android.utils.theme.ViewThemeUtils
@Suppress("LongParameterList")
class UnifiedSearchItemViewHolder(
val binding: UnifiedSearchItemBinding,
val user: User,
val clientFactory: ClientFactory,
private val storageManager: FileDataStorageManager,
private val listInterface: UnifiedSearchListInterface,
val context: Context,
private val viewThemeUtils: ViewThemeUtils
) :
SectionedViewHolder(binding.root) {
fun bind(entry: SearchResultEntry) {
binding.title.text = entry.title
binding.subline.text = entry.subline
if (entry.isFile && storageManager.getFileByDecryptedRemotePath(entry.remotePath()) != null) {
binding.localFileIndicator.visibility = View.VISIBLE
} else {
binding.localFileIndicator.visibility = View.GONE
}
val mimetype = MimeTypeUtil.getBestMimeTypeByFilename(entry.title)
val placeholder = getPlaceholder(entry, mimetype)
Glide.with(context).using(CustomGlideStreamLoader(user, clientFactory))
.load(entry.thumbnailUrl)
.asBitmap()
.placeholder(placeholder)
.error(placeholder)
.animate(android.R.anim.fade_in)
.listener(RoundIfNeededListener(entry))
.into(binding.thumbnail)
binding.unifiedSearchItemLayout.setOnClickListener { listInterface.onSearchResultClicked(entry) }
}
private fun getPlaceholder(
entry: SearchResultEntry,
mimetype: String?
): Drawable {
val drawable = with(entry.icon) {
when {
equals("icon-folder") ->
ResourcesCompat.getDrawable(context.resources, R.drawable.folder, null)
startsWith("icon-note") ->
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_edit, null)
startsWith("icon-contacts") ->
ResourcesCompat.getDrawable(context.resources, R.drawable.file_vcard, null)
startsWith("icon-calendar") ->
ResourcesCompat.getDrawable(context.resources, R.drawable.file_calendar, null)
startsWith("icon-deck") ->
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_deck, null)
else ->
MimeTypeUtil.getFileTypeIcon(mimetype, entry.title, context, viewThemeUtils)
}
}
return viewThemeUtils.platform.tintPrimaryDrawable(context, drawable)!!
}
private inner class RoundIfNeededListener(private val entry: SearchResultEntry) :
RequestListener<String, Bitmap> {
override fun onException(
e: Exception?,
model: String?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean = false
override fun onResourceReady(
resource: Bitmap?,
model: String?,
target: Target<Bitmap>?,
isFromMemoryCache: Boolean,
isFirstResource: Boolean
): Boolean {
if (entry.rounded) {
val drawable = BitmapUtils.bitmapToCircularBitmapDrawable(context.resources, resource)
binding.thumbnail.setImageDrawable(drawable)
return true
}
return false
}
}
}
| gpl-2.0 | 3d853a22f41370ddc2051b25985565e5 | 38.492308 | 105 | 0.691079 | 4.866351 | false | false | false | false |
fabmax/binparse | src/main/kotlin/de/fabmax/binparse/ArrayDef.kt | 1 | 5066 | package de.fabmax.binparse
import java.util.*
/**
* Created by max on 17.11.2015.
*/
class ArrayDef private constructor(fieldName: String, type: FieldDef<*>, length: ArrayDef.Length) :
FieldDef<ArrayField>(fieldName) {
companion object {
internal val nullTermCtx: ContainerField<*> = NullTermCtx()
}
private class NullTermCtx : ContainerField<IntField>("null", IntField("null", 0)) {
override fun get(name: String): Field<*> = value
override fun get(index: Int): Field<*> = value
}
internal enum class LengthMode {
FIXED,
BY_FIELD,
BY_VALUE
}
internal data class Length(
val mode: LengthMode,
val strLength: String,
val intLength: Int,
val termParser: IntDef?)
private val type = type
private val length = length
protected override fun parse(reader: BinReader, parent: ContainerField<*>): ArrayField {
val array = ArrayField(fieldName)
if (length.mode == LengthMode.BY_VALUE) {
while (length.termParser != null) {
reader.mark()
if (length.termParser.parseField(reader, nullTermCtx).value == 0L) {
break
}
reader.reset()
if (parseItem(array, reader, parent)) {
break
}
}
} else {
val length = when (length.mode) {
LengthMode.FIXED -> length.intLength
LengthMode.BY_FIELD -> parent.getInt(length.strLength).intValue
else -> 0
}
for (i in 1..length) {
if (parseItem(array, reader, parent)) {
break
}
}
}
return array
}
override fun prepareWrite(parent: ContainerField<*>) {
super.prepareWrite(parent)
val array = parent.getArray(fieldName);
if (length.mode == LengthMode.BY_FIELD) {
parent.getInt(length.strLength).intValue = array.size
}
for (i in 0 .. array.size - 1) {
type.fieldName = i.toString()
type.prepareWrite(array)
}
}
override fun write(writer: BinWriter, parent: ContainerField<*>) {
val array = parent.getArray(fieldName);
var isBreak = false;
for (i in 0 .. array.size - 1) {
type.fieldName = i.toString()
type.write(writer, array)
if (array[i].hasQualifier(Field.QUAL_BREAK)) {
isBreak = true;
break;
}
}
if (length.mode == ArrayDef.LengthMode.BY_VALUE && length.termParser != null && !isBreak) {
length.termParser.write(writer, nullTermCtx)
}
}
override fun matchesDef(parent: ContainerField<*>): Boolean {
val array = parent[fieldName]
if (array is ArrayField) {
for (i in 0 .. array.size - 1) {
type.fieldName = i.toString()
if (!type.matchesDef(array)) {
return false
}
}
return true
}
return false
}
private fun parseItem(field: ArrayField, reader: BinReader, context: ContainerField<*>): Boolean {
val item = type.parseField(reader, context)
item.index = field.value.size
item.name = item.index.toString()
field.value.add(item)
return item.hasQualifier(Field.QUAL_BREAK)
}
override fun toString(): String {
return "$fieldName: ArrayParser: type: $type, length-mode: $length"
}
internal class Factory() : FieldDefFactory() {
companion object {
internal fun parseLength(definition: Item): Length {
val lengthItem = FieldDefFactory.getItem(definition.childrenMap, "length")
var lenMode = LengthMode.BY_FIELD
val strLen = lengthItem.value
val decLen = FieldDefFactory.parseDecimal(strLen)
var intLen = 0
var termParser: IntDef? = null
if (decLen != null) {
lenMode = LengthMode.FIXED
intLen = decLen.toInt()
if (intLen <= 0) {
throw IllegalArgumentException("Invalid length specified: $intLen")
}
} else if (FieldDefFactory.isType(strLen)) {
lenMode = LengthMode.BY_VALUE
termParser = FieldDefFactory.createParser(lengthItem) as IntDef
}
return Length(lenMode, strLen, intLen, termParser)
}
}
override fun createParser(definition: Item): ArrayDef {
return ArrayDef(definition.identifier, parseType(definition), parseLength(definition))
}
private fun parseType(definition: Item): FieldDef<*> {
return FieldDefFactory.createParser(getItem(definition.childrenMap, "type"))
}
}
}
| apache-2.0 | eb08d409ea6fcca06a2286b07795e7b7 | 32.328947 | 102 | 0.542242 | 4.686401 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/ref/RsStructExprFieldReferenceImpl.kt | 1 | 1554 | package org.rust.lang.core.resolve.ref
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsStructLiteralField
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.resolve.*
import org.rust.lang.core.types.BoundElement
class RsStructLiteralFieldReferenceImpl(
field: RsStructLiteralField
) : RsReferenceBase<RsStructLiteralField>(field),
RsReference {
override val RsStructLiteralField.referenceAnchor: PsiElement get() = referenceNameElement
override fun getVariants(): Array<out LookupElement> =
collectCompletionVariants { processStructLiteralFieldResolveVariants(element, it) }
override fun resolveInner(): List<BoundElement<RsCompositeElement>> =
collectResolveVariants(element.referenceName) {
processStructLiteralFieldResolveVariants(element, it)
}
override fun handleElementRename(newName: String): PsiElement {
return if (element.colon != null) {
super.handleElementRename(newName)
} else {
val psiFactory = RsPsiFactory(element.project)
val newIdent = psiFactory.createIdentifier(newName)
val colon = psiFactory.createColon()
val initExpression = psiFactory.createExpression(element.identifier.text)
element.identifier.replace(newIdent)
element.add(colon)
element.add(initExpression)
return element
}
}
}
| mit | c1276a259cf194c8da3c0b585b33faf0 | 36.902439 | 94 | 0.727156 | 5.045455 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/test/groovy/graphql/StarWarsData.kt | 1 | 3078 | package graphql
import graphql.schema.DataFetcher
import graphql.schema.TypeResolver
import java.util.concurrent.CompletableFuture
val luke = mapOf(
"id" to "1000",
"name" to "Luke Skywalker",
"friends" to listOf("1002", "1003", "2000", "2001"),
"appearsIn" to listOf(4, 5, 6),
"homePlanet" to "Tatooine"
);
val vader = mapOf(
"id" to "1001",
"name" to "Darth Vader",
"friends" to listOf("1004"),
"appearsIn" to listOf(4, 5, 6),
"homePlanet" to "Tatooine")
val han = mapOf(
"id" to "1002",
"name" to "Han Solo",
"friends" to listOf("1000", "1003", "2001"),
"appearsIn" to listOf(4, 5, 6)
)
val leia = mapOf(
"id" to "1003",
"name" to "Leia Organa",
"friends" to listOf("1000", "1002", "2000", "2001"),
"appearsIn" to listOf(4, 5, 6),
"homePlanet" to "Alderaan"
)
val tarkin = mapOf(
"id" to "1004",
"name" to "Wilhuff Tarkin",
"friends" to listOf("1001"),
"appearsIn" to listOf(4)
)
val humanData = mapOf(
"1000" to luke,
"1001" to vader,
"1002" to han,
"1003" to leia,
"1004" to tarkin
)
val threepio = mapOf(
"id" to "2000",
"name" to "C-3PO",
"friends" to listOf("1000", "1002", "1003", "2001"),
"appearsIn" to listOf(4, 5, 6),
"primaryFunction" to "Protocol"
)
val artoo = mapOf(
"id" to "2001",
"name" to "R2-D2",
"friends" to listOf("1000", "1002", "1003"),
"appearsIn" to listOf(4, 5, 6),
"primaryFunction" to "Astromech"
)
val droidData = mapOf(
"2000" to threepio,
"2001" to artoo
)
fun getCharacter(id: String): Any? {
if (humanData[id] != null) return humanData[id]
if (droidData[id] != null) return droidData[id]
return null
}
val humanDataFetcher: DataFetcher<Any> = { environment ->
val id = environment.arguments["id"]
CompletableFuture.completedFuture(humanData[id])
}
val droidDataFetcher: DataFetcher<Any> = { environment ->
val id = environment.arguments["id"]
CompletableFuture.completedFuture(droidData[id])
}
val characterTypeResolver: TypeResolver = {
val data: Map<String, Any?> = it as Map<String, Any?>
val id: String = data["id"] as String
if (humanData.containsKey(id))
humanType
else if(droidData.containsKey(id))
droidType
else
null
}
val friendsDataFetcher: DataFetcher<List<Any?>> = { environment ->
val map = environment.source<Map<String, Any?>>()
val friends = map["friends"] as List<String>;
val result = mutableListOf<Any?>()
for (friend in friends) {
result += getCharacter(friend);
}
CompletableFuture.completedFuture(result)
}
val heroDataFetcher: DataFetcher<Any?> = { environment ->
if (environment.containsArgument("episode")
&& 5 == environment.arguments["episode"])
CompletableFuture.completedFuture("luke")
else CompletableFuture.completedFuture("artoo")
}
| mit | 3bcd27b4a008565dce63678278633261 | 24.229508 | 66 | 0.592268 | 3.477966 | false | false | false | false |
google-pay/loyalty-api-kotlin | app/src/main/java/com/example/loyaltyapidemo/activity/signup/SignUpActivity.kt | 1 | 4085 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.loyaltyapidemo.activity.signup
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.loyaltyapidemo.R
import com.example.loyaltyapidemo.databinding.ActivitySignupBinding
class SignUpActivity : AppCompatActivity() {
private lateinit var signUpViewModel: SignUpViewModel
private lateinit var binding: ActivitySignupBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignupBinding.inflate(layoutInflater)
setContentView(binding.root)
signUpViewModel = ViewModelProvider(this, SignUpViewModelFactory())
.get(SignUpViewModel::class.java)
signUpViewModel.signUpFormState.observe(
this@SignUpActivity,
Observer {
val signUpState = it ?: return@Observer
// disable sign up button unless both name and email are valid
binding.signUp.isEnabled = signUpState.isDataValid
binding.name.error = signUpState.nameError?.let(::getString)
binding.email.error =
if (binding.email.text.isNotBlank()) {
signUpState.emailError?.let(::getString)
} else {
null
}
}
)
// watch for signUpResult
signUpViewModel.signUpResult.observe(
this@SignUpActivity,
Observer {
val signUpResult = it ?: return@Observer
binding.loading.visibility = View.GONE
if (signUpResult.error != null) {
Toast.makeText(applicationContext, R.string.sign_up_failed, Toast.LENGTH_LONG)
.show()
return@Observer
}
// Step 1: start SignUpConfirmationActivity with the JWT from the signUpResult
throw NotImplementedError("TODO: implement me")
}
)
binding.name.afterTextChanged {
signUpViewModel.signUpDataChanged(
binding.name.text.toString(),
binding.email.text.toString()
)
}
binding.email.afterTextChanged {
signUpViewModel.signUpDataChanged(
binding.name.text.toString(),
binding.email.text.toString()
)
}
binding.signUp.setOnClickListener {
binding.loading.visibility = View.VISIBLE
// on signUp click, initiate the signUp process
signUpViewModel.signUp(binding.name.text.toString(), binding.email.text.toString())
}
}
}
/**
* Extension function to simplify setting an afterTextChanged action to EditText components.
*/
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
}
| apache-2.0 | adf8a50e1e73c881a7daee0532d9e2ac | 34.521739 | 98 | 0.645777 | 5.061958 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/repository/git/filter/GitFilters.kt | 1 | 1167 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.filter
import svnserver.context.LocalContext
import svnserver.ext.gitlfs.LfsFilter
import svnserver.ext.gitlfs.storage.LfsStorage
/**
* @author Marat Radchenko <[email protected]>
*/
class GitFilters constructor(context: LocalContext, lfsStorage: LfsStorage?) {
val raw: GitFilter
val link: GitFilter
private val filters: Array<GitFilter>
operator fun get(name: String): GitFilter? {
for (filter: GitFilter in filters) if ((filter.name == name)) return filter
return null
}
init {
raw = GitFilterRaw(context)
link = GitFilterLink(context)
filters = arrayOf(
raw,
link,
GitFilterGzip(context),
LfsFilter(context, lfsStorage)
)
}
}
| gpl-2.0 | 72e73906887b918f9942800b401b95b5 | 31.416667 | 83 | 0.683805 | 4.024138 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JS/src/main/kotlin/o/katydid/css/colors/ColorConstants.kt | 1 | 10049 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
@file:Suppress("unused")
package o.katydid.css.colors
import i.katydid.css.colors.RgbColor
//---------------------------------------------------------------------------------------------------------------------
val aliceblue : Color = RgbColor(240, 248, 255, 1f, "aliceblue")
val antiquewhite : Color = RgbColor(250, 235, 215, 1f, "antiquewhite")
val aqua : Color = RgbColor(0, 255, 255, 1f, "aqua")
val aquamarine : Color = RgbColor(127, 255, 212, 1f, "aquamarine")
val azure : Color = RgbColor(240, 255, 255, 1f, "azure")
val beige : Color = RgbColor(245, 245, 220, 1f, "beige")
val bisque : Color = RgbColor(255, 228, 196, 1f, "bisque")
val black : Color = RgbColor(0, 0, 0, 1f, "black")
val blanchedalmond : Color = RgbColor(255, 235, 205, 1f, "blanchedalmond")
val blue : Color = RgbColor(0, 0, 255, 1f, "blue")
val blueviolet : Color = RgbColor(138, 43, 226, 1f, "blueviolet")
val brown : Color = RgbColor(165, 42, 42, 1f, "brown")
val burlywood : Color = RgbColor(222, 184, 135, 1f, "burlywood")
val cadetblue : Color = RgbColor(95, 158, 160, 1f, "cadetblue")
val chartreuse : Color = RgbColor(127, 255, 0, 1f, "chartreuse")
val chocolate : Color = RgbColor(210, 105, 30, 1f, "chocolate")
val coral : Color = RgbColor(255, 127, 80, 1f, "coral")
val cornflowerblue : Color = RgbColor(100, 149, 237, 1f, "cornflowerblue")
val cornsilk : Color = RgbColor(255, 248, 220, 1f, "cornsilk")
val crimson : Color = RgbColor(220, 20, 60, 1f, "crimson")
val cyan : Color = RgbColor(0, 255, 255, 1f, "cyan")
val darkblue : Color = RgbColor(0, 0, 139, 1f, "darkblue")
val darkcyan : Color = RgbColor(0, 139, 139, 1f, "darkcyan")
val darkgoldenrod : Color = RgbColor(184, 134, 11, 1f, "darkgoldenrod")
val darkgray : Color = RgbColor(169, 169, 169, 1f, "darkgray")
val darkgreen : Color = RgbColor(0, 100, 0, 1f, "darkgreen")
val darkgrey : Color = RgbColor(169, 169, 169, 1f)
val darkkhaki : Color = RgbColor(189, 183, 107, 1f, "darkkhaki")
val darkmagenta : Color = RgbColor(139, 0, 139, 1f, "darkmagenta")
val darkolivegreen : Color = RgbColor(85, 107, 47, 1f, "darkolivegreen")
val darkorange : Color = RgbColor(255, 140, 0, 1f, "darkorange")
val darkorchid : Color = RgbColor(153, 50, 204, 1f, "darkorchid")
val darkred : Color = RgbColor(139, 0, 0, 1f, "darkred")
val darksalmon : Color = RgbColor(233, 150, 122, 1f, "darksalmon")
val darkseagreen : Color = RgbColor(143, 188, 143, 1f, "darkseagreen")
val darkslateblue : Color = RgbColor(72, 61, 139, 1f, "darkslateblue")
val darkslategray : Color = RgbColor(47, 79, 79, 1f, "darkslategray")
val darkslategrey : Color = RgbColor(47, 79, 79, 1f)
val darkturquoise : Color = RgbColor(0, 206, 209, 1f, "darkturquoise")
val darkviolet : Color = RgbColor(148, 0, 211, 1f, "darkviolet")
val deeppink : Color = RgbColor(255, 20, 147, 1f, "deeppink")
val deepskyblue : Color = RgbColor(0, 191, 255, 1f, "deepskyblue")
val dimgray : Color = RgbColor(105, 105, 105, 1f, "dimgray")
val dimgrey : Color = RgbColor(105, 105, 105, 1f)
val dodgerblue : Color = RgbColor(30, 144, 255, 1f, "dodgerblue")
val firebrick : Color = RgbColor(178, 34, 34, 1f, "firebrick")
val floralwhite : Color = RgbColor(255, 250, 240, 1f, "floralwhite")
val forestgreen : Color = RgbColor(34, 139, 34, 1f, "forestgreen")
val fuchsia : Color = RgbColor(255, 0, 255, 1f, "fuchsia")
val gainsboro : Color = RgbColor(220, 220, 220, 1f, "gainsboro")
val ghostwhite : Color = RgbColor(248, 248, 255, 1f, "ghostwhite")
val gold : Color = RgbColor(255, 215, 0, 1f, "gold")
val goldenrod : Color = RgbColor(218, 165, 32, 1f, "goldenrod")
val gray : Color = RgbColor(128, 128, 128, 1f, "gray")
val green : Color = RgbColor(0, 128, 0, 1f, "green")
val greenyellow : Color = RgbColor(173, 255, 47, 1f, "greenyellow")
val grey : Color = RgbColor(128, 128, 128, 1f)
val honeydew : Color = RgbColor(240, 255, 240, 1f, "honeydew")
val hotpink : Color = RgbColor(255, 105, 180, 1f, "hotpink")
val indianred : Color = RgbColor(205, 92, 92, 1f, "indianred")
val indigo : Color = RgbColor(75, 0, 130, 1f, "indigo")
val ivory : Color = RgbColor(255, 255, 240, 1f, "ivory")
val khaki : Color = RgbColor(240, 230, 140, 1f, "khaki")
val lavender : Color = RgbColor(230, 230, 250, 1f, "lavender")
val lavenderblush : Color = RgbColor(255, 240, 245, 1f, "lavendarblush")
val lawngreen : Color = RgbColor(124, 252, 0, 1f, "lawngreen")
val lemonchiffon : Color = RgbColor(255, 250, 205, 1f, "lemonchiffon")
val lightblue : Color = RgbColor(173, 216, 230, 1f, "lightblue")
val lightcoral : Color = RgbColor(240, 128, 128, 1f, "lightcoral")
val lightcyan : Color = RgbColor(224, 255, 255, 1f, "lightcyan")
val lightgoldenrodyellow : Color = RgbColor(250, 250, 210, 1f, "lightgoldenrodyellow")
val lightgray : Color = RgbColor(211, 211, 211, 1f, "lightgray")
val lightgreen : Color = RgbColor(144, 238, 144, 1f, "lightgreen")
val lightgrey : Color = RgbColor(211, 211, 211, 1f)
val lightpink : Color = RgbColor(255, 182, 193, 1f, "lightpink")
val lightsalmon : Color = RgbColor(255, 160, 122, 1f, "lightsalmon")
val lightseagreen : Color = RgbColor(32, 178, 170, 1f, "lightseagreen")
val lightskyblue : Color = RgbColor(135, 206, 250, 1f, "lightskyblue")
val lightslategray : Color = RgbColor(119, 136, 153, 1f, "lightslategray")
val lightslategrey : Color = RgbColor(119, 136, 153, 1f)
val lightsteelblue : Color = RgbColor(176, 196, 222, 1f, "lightsteelblue")
val lightyellow : Color = RgbColor(255, 255, 224, 1f, "lightyellow")
val lime : Color = RgbColor(0, 255, 0, 1f, "lime")
val limegreen : Color = RgbColor(50, 205, 50, 1f, "limegreen")
val linen : Color = RgbColor(250, 240, 230, 1f, "linen")
val magenta : Color = RgbColor(255, 0, 255, 1f, "magenta")
val maroon : Color = RgbColor(128, 0, 0, 1f, "maroon")
val mediumaquamarine : Color = RgbColor(102, 205, 170, 1f, "mediumaquamarine")
val mediumblue : Color = RgbColor(0, 0, 205, 1f, "mediumblue")
val mediumorchid : Color = RgbColor(186, 85, 211, 1f, "mediumorchid")
val mediumpurple : Color = RgbColor(147, 112, 219, 1f, "mediumpurple")
val mediumseagreen : Color = RgbColor(60, 179, 113, 1f, "mediumseagreen")
val mediumslateblue : Color = RgbColor(123, 104, 238, 1f, "mediumslateblue")
val mediumspringgreen : Color = RgbColor(0, 250, 154, 1f, "mediumspringgreen")
val mediumturquoise : Color = RgbColor(72, 209, 204, 1f, "mediumturquoise")
val mediumvioletred : Color = RgbColor(199, 21, 133, 1f, "mediumvioletred")
val midnightblue : Color = RgbColor(25, 25, 112, 1f, "midnightblue")
val mintcream : Color = RgbColor(245, 255, 250, 1f, "mintcream")
val mistyrose : Color = RgbColor(255, 228, 225, 1f, "mistyrose")
val moccasin : Color = RgbColor(255, 228, 181, 1f, "moccasin")
val navajowhite : Color = RgbColor(255, 222, 173, 1f, "navajowhite")
val navy : Color = RgbColor(0, 0, 128, 1f, "navy")
val oldlace : Color = RgbColor(253, 245, 230, 1f, "oldlace")
val olive : Color = RgbColor(128, 128, 0, 1f, "olive")
val olivedrab : Color = RgbColor(107, 142, 35, 1f, "olivedrab")
val orange : Color = RgbColor(255, 165, 0, 1f, "orange")
val orangered : Color = RgbColor(255, 69, 0, 1f, "orangered")
val orchid : Color = RgbColor(218, 112, 214, 1f, "orchid")
val palegoldenrod : Color = RgbColor(238, 232, 170, 1f, "palegoldenrod")
val palegreen : Color = RgbColor(152, 251, 152, 1f, "palegreen")
val paleturquoise : Color = RgbColor(175, 238, 238, 1f, "paleturquoise")
val palevioletred : Color = RgbColor(219, 112, 147, 1f, "palevioletred")
val papayawhip : Color = RgbColor(255, 239, 213, 1f, "papayawhip")
val peachpuff : Color = RgbColor(255, 218, 185, 1f, "peachpuff")
val peru : Color = RgbColor(205, 133, 63, 1f, "peru")
val pink : Color = RgbColor(255, 192, 203, 1f, "pink")
val plum : Color = RgbColor(221, 160, 221, 1f, "plum")
val powderblue : Color = RgbColor(176, 224, 230, 1f, "powderblue")
val purple : Color = RgbColor(128, 0, 128, 1f, "purple")
val red : Color = RgbColor(255, 0, 0, 1f, "red")
val rosybrown : Color = RgbColor(188, 143, 143, 1f, "rosybrown")
val royalblue : Color = RgbColor(65, 105, 225, 1f, "royalblue")
val saddlebrown : Color = RgbColor(139, 69, 19, 1f, "saddlebrown")
val salmon : Color = RgbColor(250, 128, 114, 1f, "salmon")
val sandybrown : Color = RgbColor(244, 164, 96, 1f, "sandybrown")
val seagreen : Color = RgbColor(46, 139, 87, 1f, "seagreen")
val seashell : Color = RgbColor(255, 245, 238, 1f, "seashell")
val sienna : Color = RgbColor(160, 82, 45, 1f, "sienna")
val silver : Color = RgbColor(192, 192, 192, 1f, "silver")
val skyblue : Color = RgbColor(135, 206, 235, 1f, "skyblue")
val slateblue : Color = RgbColor(106, 90, 205, 1f, "slateblue")
val slategray : Color = RgbColor(112, 128, 144, 1f, "slategray")
val slategrey : Color = RgbColor(112, 128, 144, 1f)
val snow : Color = RgbColor(255, 250, 250, 1f, "snow")
val springgreen : Color = RgbColor(0, 255, 127, 1f, "springgreen")
val steelblue : Color = RgbColor(70, 130, 180, 1f, "steelblue")
val tan : Color = RgbColor(210, 180, 140, 1f, "tan")
val teal : Color = RgbColor(0, 128, 128, 1f, "teal")
val thistle : Color = RgbColor(216, 191, 216, 1f, "thistle")
val tomato : Color = RgbColor(255, 99, 71, 1f, "tomato")
val transparent : Color = RgbColor(0, 0, 0, 0f, "transparent")
val turquoise : Color = RgbColor(64, 224, 208, 1f, "turquoise")
val violet : Color = RgbColor(238, 130, 238, 1f, "violet")
val wheat : Color = RgbColor(245, 222, 179, 1f, "wheat")
val white : Color = RgbColor(255, 255, 255, 1f, "white")
val whitesmoke : Color = RgbColor(245, 245, 245, 1f, "whitesmoke")
val yellow : Color = RgbColor(255, 255, 0, 1f, "yellow")
val yellowgreen : Color = RgbColor(154, 205, 50, 1f, "yellowgreen")
//---------------------------------------------------------------------------------------------------------------------
/**
* Call this function to initialize the color names before first use if they are wanted even when not
* referenced directly.
*/
fun useCssColorNames() {}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 9a434d3fed9e158f2b3426f7ef4c54ab | 57.424419 | 119 | 0.662852 | 2.648656 | false | false | false | false |
ToxicBakery/ViewPagerTransforms | library/src/main/java/com/ToxicBakery/viewpager/transforms/ForegroundToBackgroundTransformer.kt | 1 | 1196 | /*
* Copyright 2014 Toxic Bakery
*
* 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.ToxicBakery.viewpager.transforms
import android.view.View
open class ForegroundToBackgroundTransformer : ABaseTransformer() {
override fun onTransform(page: View, position: Float) {
val height = page.height.toFloat()
val width = page.width.toFloat()
val scale = min(if (position > 0) 1f else Math.abs(1f + position), 0.5f)
page.scaleX = scale
page.scaleY = scale
page.pivotX = width * 0.5f
page.pivotY = height * 0.5f
page.translationX = if (position > 0) width * position else -width * position * 0.25f
}
}
| apache-2.0 | ce3037e0fab9bc28fa34c9f8b25c59bd | 33.171429 | 93 | 0.692308 | 3.908497 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CardBillingAddressElement.kt | 1 | 1914 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import com.stripe.android.ui.core.address.AddressRepository
import com.stripe.android.ui.core.address.FieldType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/**
* This is a special type of AddressElement that
* removes fields from the address based on the country. It
* is only intended to be used with the card payment method.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class CardBillingAddressElement(
identifier: IdentifierSpec,
rawValuesMap: Map<IdentifierSpec, String?> = emptyMap(),
addressRepository: AddressRepository,
countryCodes: Set<String> = emptySet(),
countryDropdownFieldController: DropdownFieldController = DropdownFieldController(
CountryConfig(countryCodes),
rawValuesMap[IdentifierSpec.Country]
),
sameAsShippingElement: SameAsShippingElement?,
shippingValuesMap: Map<IdentifierSpec, String?>?
) : AddressElement(
identifier,
addressRepository,
rawValuesMap,
AddressType.Normal(),
countryCodes,
countryDropdownFieldController,
sameAsShippingElement,
shippingValuesMap
) {
// Save for future use puts this in the controller rather than element
// card and achv2 uses save for future use
val hiddenIdentifiers: Flow<Set<IdentifierSpec>> =
countryDropdownFieldController.rawFieldValue.map { countryCode ->
when (countryCode) {
"US", "GB", "CA" -> {
FieldType.values()
.filterNot { it == FieldType.PostalCode }
.map { it.identifierSpec }
.toSet()
}
else -> {
FieldType.values()
.map { it.identifierSpec }
.toSet()
}
}
}
}
| mit | 80547298f391fe19703648f871ba78be | 34.444444 | 86 | 0.647858 | 4.945736 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheet.kt | 1 | 31584 | package com.stripe.android.paymentsheet
import android.content.Context
import android.content.res.ColorStateList
import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.annotation.ColorInt
import androidx.annotation.FontRes
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.fragment.app.Fragment
import com.stripe.android.link.account.CookieStore
import com.stripe.android.model.PaymentIntent
import com.stripe.android.model.SetupIntent
import com.stripe.android.paymentsheet.addresselement.AddressDetails
import com.stripe.android.paymentsheet.flowcontroller.FlowControllerFactory
import com.stripe.android.paymentsheet.model.PaymentOption
import com.stripe.android.ui.core.PaymentsThemeDefaults
import com.stripe.android.ui.core.getRawValueFromDimenResource
import kotlinx.parcelize.Parcelize
/**
* A drop-in class that presents a bottom sheet to collect and process a customer's payment.
*/
class PaymentSheet internal constructor(
private val paymentSheetLauncher: PaymentSheetLauncher
) {
/**
* Constructor to be used when launching the payment sheet from an Activity.
*
* @param activity the Activity that is presenting the payment sheet.
* @param callback called with the result of the payment after the payment sheet is dismissed.
*/
constructor(
activity: ComponentActivity,
callback: PaymentSheetResultCallback
) : this(
DefaultPaymentSheetLauncher(activity, callback)
)
/**
* Constructor to be used when launching the payment sheet from a Fragment.
*
* @param fragment the Fragment that is presenting the payment sheet.
* @param callback called with the result of the payment after the payment sheet is dismissed.
*/
constructor(
fragment: Fragment,
callback: PaymentSheetResultCallback
) : this(
DefaultPaymentSheetLauncher(fragment, callback)
)
/**
* Present the payment sheet to process a [PaymentIntent].
* If the [PaymentIntent] is already confirmed, [PaymentSheetResultCallback] will be invoked
* with [PaymentSheetResult.Completed].
*
* @param paymentIntentClientSecret the client secret for the [PaymentIntent].
* @param configuration optional [PaymentSheet] settings.
*/
@JvmOverloads
fun presentWithPaymentIntent(
paymentIntentClientSecret: String,
configuration: Configuration? = null
) {
paymentSheetLauncher.presentWithPaymentIntent(paymentIntentClientSecret, configuration)
}
/**
* Present the payment sheet to process a [SetupIntent].
* If the [SetupIntent] is already confirmed, [PaymentSheetResultCallback] will be invoked
* with [PaymentSheetResult.Completed].
*
* @param setupIntentClientSecret the client secret for the [SetupIntent].
* @param configuration optional [PaymentSheet] settings.
*/
@JvmOverloads
fun presentWithSetupIntent(
setupIntentClientSecret: String,
configuration: Configuration? = null
) {
paymentSheetLauncher.presentWithSetupIntent(setupIntentClientSecret, configuration)
}
/** Configuration for [PaymentSheet] **/
@Parcelize
data class Configuration @JvmOverloads constructor(
/**
* Your customer-facing business name.
*
* The default value is the name of your app.
*/
val merchantDisplayName: String,
/**
* If set, the customer can select a previously saved payment method within PaymentSheet.
*/
val customer: CustomerConfiguration? = null,
/**
* Configuration related to the Stripe Customer making a payment.
*
* If set, PaymentSheet displays Google Pay as a payment option.
*/
val googlePay: GooglePayConfiguration? = null,
/**
* The color of the Pay or Add button. Keep in mind the text color is white.
*
* If set, PaymentSheet displays the button with this color.
*/
@Deprecated(
message = "Use Appearance parameter to customize primary button color",
replaceWith = ReplaceWith(
expression = "Appearance.colorsLight/colorsDark.primary " +
"or PrimaryButton.colorsLight/colorsDark.background"
)
)
val primaryButtonColor: ColorStateList? = null,
/**
* The billing information for the customer.
*
* If set, PaymentSheet will pre-populate the form fields with the values provided.
*/
val defaultBillingDetails: BillingDetails? = null,
/**
* The shipping information for the customer.
* If set, PaymentSheet will pre-populate the form fields with the values provided.
* This is used to display a "Billing address is same as shipping" checkbox if `defaultBillingDetails` is not provided.
* If `name` and `line1` are populated, it's also [attached to the PaymentIntent](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping) during payment.
*/
val shippingDetails: AddressDetails? = null,
/**
* If true, allows payment methods that do not move money at the end of the checkout.
* Defaults to false.
*
* Some payment methods can't guarantee you will receive funds from your customer at the end
* of the checkout because they take time to settle (eg. most bank debits, like SEPA or ACH)
* or require customer action to complete (e.g. OXXO, Konbini, Boleto). If this is set to
* true, make sure your integration listens to webhooks for notifications on whether a
* payment has succeeded or not.
*
* See [payment-notification](https://stripe.com/docs/payments/payment-methods#payment-notification).
*/
val allowsDelayedPaymentMethods: Boolean = false,
/**
* If `true`, allows payment methods that require a shipping address, like Afterpay and
* Affirm. Defaults to `false`.
*
* Set this to `true` if you collect shipping addresses via [shippingDetails] or
* [FlowController.shippingDetails].
*
* **Note**: PaymentSheet considers this property `true` if `shipping` details are present
* on the PaymentIntent when PaymentSheet loads.
*/
val allowsPaymentMethodsRequiringShippingAddress: Boolean = false,
/**
* Describes the appearance of Payment Sheet.
*/
val appearance: Appearance = Appearance(),
/**
* The label to use for the primary button.
*
* If not set, Payment Sheet will display suitable default labels for payment and setup
* intents.
*/
val primaryButtonLabel: String? = null,
) : Parcelable {
/**
* [Configuration] builder for cleaner object creation from Java.
*/
class Builder(
private var merchantDisplayName: String
) {
private var customer: CustomerConfiguration? = null
private var googlePay: GooglePayConfiguration? = null
private var primaryButtonColor: ColorStateList? = null
private var defaultBillingDetails: BillingDetails? = null
private var shippingDetails: AddressDetails? = null
private var allowsDelayedPaymentMethods: Boolean = false
private var allowsPaymentMethodsRequiringShippingAddress: Boolean = false
private var appearance: Appearance = Appearance()
fun merchantDisplayName(merchantDisplayName: String) =
apply { this.merchantDisplayName = merchantDisplayName }
fun customer(customer: CustomerConfiguration?) =
apply { this.customer = customer }
fun googlePay(googlePay: GooglePayConfiguration?) =
apply { this.googlePay = googlePay }
@Deprecated(
message = "Use Appearance parameter to customize primary button color",
replaceWith = ReplaceWith(
expression = "Appearance.colorsLight/colorsDark.primary " +
"or PrimaryButton.colorsLight/colorsDark.background"
)
)
fun primaryButtonColor(primaryButtonColor: ColorStateList?) =
apply { this.primaryButtonColor = primaryButtonColor }
fun defaultBillingDetails(defaultBillingDetails: BillingDetails?) =
apply { this.defaultBillingDetails = defaultBillingDetails }
fun shippingDetails(shippingDetails: AddressDetails?) =
apply { this.shippingDetails = shippingDetails }
fun allowsDelayedPaymentMethods(allowsDelayedPaymentMethods: Boolean) =
apply { this.allowsDelayedPaymentMethods = allowsDelayedPaymentMethods }
fun allowsPaymentMethodsRequiringShippingAddress(
allowsPaymentMethodsRequiringShippingAddress: Boolean,
) = apply {
this.allowsPaymentMethodsRequiringShippingAddress =
allowsPaymentMethodsRequiringShippingAddress
}
fun appearance(appearance: Appearance) =
apply { this.appearance = appearance }
fun build() = Configuration(
merchantDisplayName,
customer,
googlePay,
primaryButtonColor,
defaultBillingDetails,
shippingDetails,
allowsDelayedPaymentMethods,
allowsPaymentMethodsRequiringShippingAddress,
appearance
)
}
}
@Parcelize
data class Appearance(
/**
* Describes the colors used while the system is in light mode.
*/
val colorsLight: Colors = Colors.defaultLight,
/**
* Describes the colors used while the system is in dark mode.
*/
val colorsDark: Colors = Colors.defaultDark,
/**
* Describes the appearance of shapes.
*/
val shapes: Shapes = Shapes.default,
/**
* Describes the typography used for text.
*/
val typography: Typography = Typography.default,
/**
* Describes the appearance of the primary button (e.g., the "Pay" button).
*/
val primaryButton: PrimaryButton = PrimaryButton()
) : Parcelable {
fun getColors(isDark: Boolean): Colors {
return if (isDark) colorsDark else colorsLight
}
class Builder {
private var colorsLight = Colors.defaultLight
private var colorsDark = Colors.defaultDark
private var shapes = Shapes.default
private var typography = Typography.default
private var primaryButton: PrimaryButton = PrimaryButton()
fun colorsLight(colors: Colors) = apply { this.colorsLight = colors }
fun colorsDark(colors: Colors) = apply { this.colorsDark = colors }
fun shapes(shapes: Shapes) = apply { this.shapes = shapes }
fun typography(typography: Typography) = apply { this.typography = typography }
fun primaryButton(primaryButton: PrimaryButton) =
apply { this.primaryButton = primaryButton }
}
}
@Parcelize
data class Colors(
/**
* A primary color used throughout PaymentSheet.
*/
@ColorInt
val primary: Int,
/**
* The color used for the surfaces (backgrounds) of PaymentSheet.
*/
@ColorInt
val surface: Int,
/**
* The color used for the background of inputs, tabs, and other components.
*/
@ColorInt
val component: Int,
/**
* The color used for borders of inputs, tabs, and other components.
*/
@ColorInt
val componentBorder: Int,
/**
* The color of the divider lines used inside inputs, tabs, and other components.
*/
@ColorInt
val componentDivider: Int,
/**
* The default color used for text and on other elements that live on components.
*/
@ColorInt
val onComponent: Int,
/**
* The color used for items appearing over the background in Payment Sheet.
*/
@ColorInt
val onSurface: Int,
/**
* The color used for text of secondary importance.
* For example, this color is used for the label above input fields.
*/
@ColorInt
val subtitle: Int,
/**
* The color used for input placeholder text.
*/
@ColorInt
val placeholderText: Int,
/**
* The color used for icons in PaymentSheet, such as the close or back icons.
*/
@ColorInt
val appBarIcon: Int,
/**
* A color used to indicate errors or destructive actions in PaymentSheet.
*/
@ColorInt
val error: Int
) : Parcelable {
constructor(
primary: Color,
surface: Color,
component: Color,
componentBorder: Color,
componentDivider: Color,
onComponent: Color,
subtitle: Color,
placeholderText: Color,
onSurface: Color,
appBarIcon: Color,
error: Color
) : this(
primary = primary.toArgb(),
surface = surface.toArgb(),
component = component.toArgb(),
componentBorder = componentBorder.toArgb(),
componentDivider = componentDivider.toArgb(),
onComponent = onComponent.toArgb(),
subtitle = subtitle.toArgb(),
placeholderText = placeholderText.toArgb(),
onSurface = onSurface.toArgb(),
appBarIcon = appBarIcon.toArgb(),
error = error.toArgb()
)
companion object {
val defaultLight = Colors(
primary = PaymentsThemeDefaults.colorsLight.materialColors.primary,
surface = PaymentsThemeDefaults.colorsLight.materialColors.surface,
component = PaymentsThemeDefaults.colorsLight.component,
componentBorder = PaymentsThemeDefaults.colorsLight.componentBorder,
componentDivider = PaymentsThemeDefaults.colorsLight.componentDivider,
onComponent = PaymentsThemeDefaults.colorsLight.onComponent,
subtitle = PaymentsThemeDefaults.colorsLight.subtitle,
placeholderText = PaymentsThemeDefaults.colorsLight.placeholderText,
onSurface = PaymentsThemeDefaults.colorsLight.materialColors.onSurface,
appBarIcon = PaymentsThemeDefaults.colorsLight.appBarIcon,
error = PaymentsThemeDefaults.colorsLight.materialColors.error
)
val defaultDark = Colors(
primary = PaymentsThemeDefaults.colorsDark.materialColors.primary,
surface = PaymentsThemeDefaults.colorsDark.materialColors.surface,
component = PaymentsThemeDefaults.colorsDark.component,
componentBorder = PaymentsThemeDefaults.colorsDark.componentBorder,
componentDivider = PaymentsThemeDefaults.colorsDark.componentDivider,
onComponent = PaymentsThemeDefaults.colorsDark.onComponent,
subtitle = PaymentsThemeDefaults.colorsDark.subtitle,
placeholderText = PaymentsThemeDefaults.colorsDark.placeholderText,
onSurface = PaymentsThemeDefaults.colorsDark.materialColors.onSurface,
appBarIcon = PaymentsThemeDefaults.colorsDark.appBarIcon,
error = PaymentsThemeDefaults.colorsDark.materialColors.error
)
}
}
@Parcelize
data class Shapes(
/**
* The corner radius used for tabs, inputs, buttons, and other components in PaymentSheet.
*/
val cornerRadiusDp: Float,
/**
* The border used for inputs, tabs, and other components in PaymentSheet.
*/
val borderStrokeWidthDp: Float
) : Parcelable {
constructor(context: Context, cornerRadiusDp: Int, borderStrokeWidthDp: Int) : this(
cornerRadiusDp = context.getRawValueFromDimenResource(cornerRadiusDp),
borderStrokeWidthDp = context.getRawValueFromDimenResource(borderStrokeWidthDp)
)
companion object {
val default = Shapes(
cornerRadiusDp = PaymentsThemeDefaults.shapes.cornerRadius,
borderStrokeWidthDp = PaymentsThemeDefaults.shapes.borderStrokeWidth
)
}
}
@Parcelize
data class Typography(
/**
* The scale factor for all fonts in PaymentSheet, the default value is 1.0.
* When this value increases fonts will increase in size and decrease when this value is lowered.
*/
val sizeScaleFactor: Float,
/**
* The font used in text. This should be a resource ID value.
*/
@FontRes
val fontResId: Int?
) : Parcelable {
companion object {
val default = Typography(
sizeScaleFactor = PaymentsThemeDefaults.typography.fontSizeMultiplier,
fontResId = PaymentsThemeDefaults.typography.fontFamily
)
}
}
@Parcelize
data class PrimaryButton(
/**
* Describes the colors used while the system is in light mode.
*/
val colorsLight: PrimaryButtonColors = PrimaryButtonColors.defaultLight,
/**
* Describes the colors used while the system is in dark mode.
*/
val colorsDark: PrimaryButtonColors = PrimaryButtonColors.defaultDark,
/**
* Describes the shape of the primary button.
*/
val shape: PrimaryButtonShape = PrimaryButtonShape(),
/**
* Describes the typography of the primary button.
*/
val typography: PrimaryButtonTypography = PrimaryButtonTypography()
) : Parcelable
@Parcelize
data class PrimaryButtonColors(
/**
* The background color of the primary button.
* Note: If 'null', {@link Colors#primary} is used.
*/
@ColorInt
val background: Int?,
/**
* The color of the text and icon in the primary button.
*/
@ColorInt
val onBackground: Int,
/**
* The border color of the primary button.
*/
@ColorInt
val border: Int
) : Parcelable {
constructor(
background: Color?,
onBackground: Color,
border: Color
) : this(
background = background?.toArgb(),
onBackground = onBackground.toArgb(),
border = border.toArgb()
)
companion object {
val defaultLight = PrimaryButtonColors(
background = null,
onBackground =
PaymentsThemeDefaults.primaryButtonStyle.colorsLight.onBackground.toArgb(),
border = PaymentsThemeDefaults.primaryButtonStyle.colorsLight.border.toArgb()
)
val defaultDark = PrimaryButtonColors(
background = null,
onBackground =
PaymentsThemeDefaults.primaryButtonStyle.colorsDark.onBackground.toArgb(),
border = PaymentsThemeDefaults.primaryButtonStyle.colorsDark.border.toArgb()
)
}
}
@Parcelize
data class PrimaryButtonShape(
/**
* The corner radius of the primary button.
* Note: If 'null', {@link Shapes#cornerRadiusDp} is used.
*/
val cornerRadiusDp: Float? = null,
/**
* The border width of the primary button.
* Note: If 'null', {@link Shapes#borderStrokeWidthDp} is used.
*/
val borderStrokeWidthDp: Float? = null
) : Parcelable {
constructor(
context: Context,
cornerRadiusDp: Int? = null,
borderStrokeWidthDp: Int? = null
) : this(
cornerRadiusDp = cornerRadiusDp?.let {
context.getRawValueFromDimenResource(it)
},
borderStrokeWidthDp = borderStrokeWidthDp?.let {
context.getRawValueFromDimenResource(it)
}
)
}
@Parcelize
data class PrimaryButtonTypography(
/**
* The font used in the primary button.
* Note: If 'null', Appearance.Typography.fontResId is used.
*/
@FontRes
val fontResId: Int? = null,
/**
* The font size in the primary button.
* Note: If 'null', {@link Typography#sizeScaleFactor} is used.
*/
val fontSizeSp: Float? = null
) : Parcelable {
constructor(
context: Context,
fontResId: Int? = null,
fontSizeSp: Int
) : this(
fontResId = fontResId,
fontSizeSp = context.getRawValueFromDimenResource(fontSizeSp)
)
}
@Parcelize
data class Address(
/**
* City, district, suburb, town, or village.
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val city: String? = null,
/**
* Two-letter country code (ISO 3166-1 alpha-2).
*/
val country: String? = null,
/**
* Address line 1 (e.g., street, PO Box, or company name).
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val line1: String? = null,
/**
* Address line 2 (e.g., apartment, suite, unit, or building).
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val line2: String? = null,
/**
* ZIP or postal code.
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val postalCode: String? = null,
/**
* State, county, province, or region.
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val state: String? = null
) : Parcelable {
/**
* [Address] builder for cleaner object creation from Java.
*/
class Builder {
private var city: String? = null
private var country: String? = null
private var line1: String? = null
private var line2: String? = null
private var postalCode: String? = null
private var state: String? = null
fun city(city: String?) = apply { this.city = city }
fun country(country: String?) = apply { this.country = country }
fun line1(line1: String?) = apply { this.line1 = line1 }
fun line2(line2: String?) = apply { this.line2 = line2 }
fun postalCode(postalCode: String?) = apply { this.postalCode = postalCode }
fun state(state: String?) = apply { this.state = state }
fun build() = Address(city, country, line1, line2, postalCode, state)
}
}
@Parcelize
data class BillingDetails(
/**
* The customer's billing address.
*/
val address: Address? = null,
/**
* The customer's email.
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val email: String? = null,
/**
* The customer's full name.
* The value set is displayed in the payment sheet as-is. Depending on the payment method, the customer may be required to edit this value.
*/
val name: String? = null,
/**
* The customer's phone number without formatting e.g. 5551234567
*/
val phone: String? = null
) : Parcelable {
/**
* [BillingDetails] builder for cleaner object creation from Java.
*/
class Builder {
private var address: Address? = null
private var email: String? = null
private var name: String? = null
private var phone: String? = null
fun address(address: Address?) = apply { this.address = address }
fun address(addressBuilder: Address.Builder) =
apply { this.address = addressBuilder.build() }
fun email(email: String?) = apply { this.email = email }
fun name(name: String?) = apply { this.name = name }
fun phone(phone: String?) = apply { this.phone = phone }
fun build() = BillingDetails(address, email, name, phone)
}
}
@Parcelize
data class CustomerConfiguration(
/**
* The identifier of the Stripe Customer object.
* See [Stripe's documentation](https://stripe.com/docs/api/customers/object#customer_object-id).
*/
val id: String,
/**
* A short-lived token that allows the SDK to access a Customer's payment methods.
*/
val ephemeralKeySecret: String
) : Parcelable
@Parcelize
data class GooglePayConfiguration(
/**
* The Google Pay environment to use.
*
* See [Google's documentation](https://developers.google.com/android/reference/com/google/android/gms/wallet/Wallet.WalletOptions#environment) for more information.
*/
val environment: Environment,
/**
* The two-letter ISO 3166 code of the country of your business, e.g. "US".
* See your account's country value [here](https://dashboard.stripe.com/settings/account).
*/
val countryCode: String,
/**
* The three-letter ISO 4217 alphabetic currency code, e.g. "USD" or "EUR".
* Required in order to support Google Pay when processing a Setup Intent.
*/
val currencyCode: String? = null
) : Parcelable {
constructor(
environment: Environment,
countryCode: String
) : this(environment, countryCode, null)
enum class Environment {
Production,
Test
}
}
/**
* A class that presents the individual steps of a payment sheet flow.
*/
interface FlowController {
var shippingDetails: AddressDetails?
/**
* Configure the FlowController to process a [PaymentIntent].
*
* @param paymentIntentClientSecret the client secret for the [PaymentIntent].
* @param configuration optional [PaymentSheet] settings.
* @param callback called with the result of configuring the FlowController.
*/
fun configureWithPaymentIntent(
paymentIntentClientSecret: String,
configuration: Configuration? = null,
callback: ConfigCallback
)
/**
* Configure the FlowController to process a [SetupIntent].
*
* @param setupIntentClientSecret the client secret for the [SetupIntent].
* @param configuration optional [PaymentSheet] settings.
* @param callback called with the result of configuring the FlowController.
*/
fun configureWithSetupIntent(
setupIntentClientSecret: String,
configuration: Configuration? = null,
callback: ConfigCallback
)
/**
* Retrieve information about the customer's desired payment option.
* You can use this to e.g. display the payment option in your UI.
*/
fun getPaymentOption(): PaymentOption?
/**
* Present a sheet where the customer chooses how to pay, either by selecting an existing
* payment method or adding a new one.
* Call this when your "Select a payment method" button is tapped.
*/
fun presentPaymentOptions()
/**
* Complete the payment or setup.
*/
fun confirm()
sealed class Result {
object Success : Result()
class Failure(
val error: Throwable
) : Result()
}
fun interface ConfigCallback {
fun onConfigured(
success: Boolean,
error: Throwable?
)
}
companion object {
/**
* Create the FlowController when launching the payment sheet from an Activity.
*
* @param activity the Activity that is presenting the payment sheet.
* @param paymentOptionCallback called when the customer's desired payment method
* changes. Called in response to the [PaymentSheet#presentPaymentOptions()]
* @param paymentResultCallback called when a [PaymentSheetResult] is available.
*/
@JvmStatic
fun create(
activity: ComponentActivity,
paymentOptionCallback: PaymentOptionCallback,
paymentResultCallback: PaymentSheetResultCallback
): FlowController {
return FlowControllerFactory(
activity,
paymentOptionCallback,
paymentResultCallback
).create()
}
/**
* Create the FlowController when launching the payment sheet from a Fragment.
*
* @param fragment the Fragment that is presenting the payment sheet.
* @param paymentOptionCallback called when the customer's [PaymentOption] selection changes.
* @param paymentResultCallback called when a [PaymentSheetResult] is available.
*/
@JvmStatic
fun create(
fragment: Fragment,
paymentOptionCallback: PaymentOptionCallback,
paymentResultCallback: PaymentSheetResultCallback
): FlowController {
return FlowControllerFactory(
fragment,
paymentOptionCallback,
paymentResultCallback
).create()
}
}
}
companion object {
/**
* Deletes all persisted authentication state associated with a customer.
*
* You must call this method when the user logs out from your app.
* This will ensure that any persisted authentication state in PaymentSheet, such as
* authentication cookies, is also cleared during logout.
*
* @param context the Application [Context].
*/
fun resetCustomer(context: Context) {
CookieStore(context).clear()
}
}
}
| mit | f95ddea9e7a4a316be95e87f28ec1bba | 36.377515 | 188 | 0.604008 | 5.415638 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/operator/overloading/PointIndex.kt | 1 | 903 | package operator.overloading
//实现get的约定方法
operator fun Point.get(index: Int): Int {
return when (index) {
0 -> x
1 -> y
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
data class MutablePoint(var x: Int, var y: Int) //var可以被改动
//实现set的约定方法。
// set的最后一个参数用了接收赋值语句中(等号)右边的值,其他参数作为方括号内的下标
// x[a,b]=c ---> x.set(a,b,c)
operator fun MutablePoint.set(index: Int, value: Int) {
when (index) {
0 -> x = value
1 -> y = value
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
fun main(args: Array<String>) {
val p1 = Point(10, 20)
println(p1[1]) //20
val p2 = MutablePoint(10, 20)
p2[1] = 42
println(p2) //MutablePoint(x=10, y=42)
} | apache-2.0 | 1859641279bb16eb03a2ddf8a87e6608 | 21.514286 | 72 | 0.590851 | 2.925651 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/tensor/NDArrayMappingRule.kt | 1 | 3040 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.tensor
import org.nd4j.ir.OpNamespace
import org.nd4j.ir.TensorNamespace
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.tensor.BaseNDArrayMappingRule
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRTensor
import org.tensorflow.framework.*
@MappingRule("tensorflow","ndarraymapping","tensor")
class NDArrayMappingRule(mappingNamesToPerform: MutableMap<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()):
BaseNDArrayMappingRule<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) {
override fun createTensorProto(input: TensorProto): TensorNamespace.TensorProto {
return TensorflowIRTensor(input).toArgTensor()
}
override fun isInputTensorName(inputName: String): Boolean {
if(mappingProcess == null)
throw IllegalArgumentException("No mapping process found for rule!")
if(!OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow").containsKey(mappingProcess!!.inputFrameworkOpName()))
throw java.lang.IllegalArgumentException("No op definition found for op name ${mappingProcess!!.inputFrameworkOpName()}")
val tfOp = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess!!.inputFrameworkOpName()]!!
return tfOp.inputArgList.map { input -> input.name }.contains(inputName)
}
override fun isOutputTensorName(outputName: String): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess!!.opName())
return nd4jOpDescriptor.argDescriptorList.filter { inputDescriptor -> inputDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR }
.map {inputDescriptor -> inputDescriptor.name }.contains(outputName)
}
} | apache-2.0 | 0c22d72f3fff85baf541887f8c552a1a | 51.431034 | 189 | 0.716447 | 4.99179 | false | false | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/atoms/AtomProtocol.kt | 1 | 2081 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.monksanctum.xand11.atoms
import org.monksanctum.xand11.comm.*
import org.monksanctum.xand11.core.Throws
import org.monksanctum.xand11.errors.AtomError
import org.monksanctum.xand11.errors.XError
class AtomProtocol : Dispatcher.PacketHandler {
private val mAtomManager: AtomManager
override val opCodes: ByteArray
get() = HANDLED_OPS
init {
mAtomManager = AtomManager.instance
}
@Throws(XError::class)
override fun handleRequest(client: Client, reader: PacketReader, writer: PacketWriter) {
when (reader.majorOpCode) {
Request.INTERN_ATOM.code -> handleInternAtom(reader, writer)
Request.GET_ATOM_NAME.code -> handleGetAtomName(reader, writer)
}
}
private fun handleInternAtom(reader: PacketReader, writer: PacketWriter) {
val length = reader.readCard16()
reader.readPadding(2)
val name = reader.readPaddedString(length)
writer.writeCard32(mAtomManager.internAtom(name))
writer.writePadding(20)
}
@Throws(AtomError::class)
private fun handleGetAtomName(reader: PacketReader, writer: PacketWriter) {
val atom = reader.readCard32()
val str = mAtomManager.getString(atom)
writer.writeCard16(str.length)
writer.writePadding(22)
writer.writePaddedString(str)
}
companion object {
private val HANDLED_OPS = byteArrayOf(Request.INTERN_ATOM.code, Request.GET_ATOM_NAME.code)
}
}
| apache-2.0 | 134bb421e16affbfe4e4032704b264cf | 32.564516 | 99 | 0.708313 | 4.048638 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/relocation/BringIntoViewDemo.kt | 3 | 3994 | /*
* 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.demos.relocation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Blue
import androidx.compose.ui.graphics.Color.Companion.Cyan
import androidx.compose.ui.graphics.Color.Companion.DarkGray
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.graphics.Color.Companion.LightGray
import androidx.compose.ui.graphics.Color.Companion.Magenta
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.graphics.Color.Companion.Yellow
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BringIntoViewDemo() {
val greenRequester = remember { BringIntoViewRequester() }
val redRequester = remember { BringIntoViewRequester() }
val coroutineScope = rememberCoroutineScope()
Column {
Column(Modifier.requiredHeight(100.dp).verticalScroll(rememberScrollState())) {
Row(Modifier.width(300.dp).horizontalScroll(rememberScrollState())) {
Box(Modifier.background(Blue).size(100.dp))
Box(Modifier.background(Green).size(100.dp).bringIntoViewRequester(greenRequester))
Box(Modifier.background(Yellow).size(100.dp))
Box(Modifier.background(Magenta).size(100.dp))
Box(Modifier.background(Gray).size(100.dp))
Box(Modifier.background(Black).size(100.dp))
}
Row(Modifier.width(300.dp).horizontalScroll(rememberScrollState())) {
Box(Modifier.background(Black).size(100.dp))
Box(Modifier.background(Cyan).size(100.dp))
Box(Modifier.background(DarkGray).size(100.dp))
Box(Modifier.background(White).size(100.dp))
Box(Modifier.background(Red).size(100.dp).bringIntoViewRequester(redRequester))
Box(Modifier.background(LightGray).size(100.dp))
}
}
Button(onClick = { coroutineScope.launch { greenRequester.bringIntoView() } }) {
Text("Bring Green box into view")
}
Button(onClick = { coroutineScope.launch { redRequester.bringIntoView() } }) {
Text("Bring Red box into view")
}
}
}
| apache-2.0 | c8ecab1513b56f9066835c5b4afc1633 | 46.547619 | 99 | 0.751627 | 4.432852 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/BasicAnimation.kt | 1 | 3205 | package com.teamwizardry.librarianlib.math
public abstract class BasicAnimation<T>(
/**
* The duration of a single loop of the animation. The actual animation may last longer, depending on the value of
* [repeatCount].
*/
public open val duration: Float
): Animation<T> {
/**
* The number of times this animation should loop. [Int.MAX_VALUE] is interpreted as infinity, and non-positive
* values will be interpreted as 1.
*/
public var repeatCount: Int = 1
/**
* If true, the animation will "bounce", reversing direction on every loop
*/
public var reverseOnRepeat: Boolean = false
/**
* A callback to run when the animation completes or is interrupted
*/
private var completionCallback: Runnable? = null
/**
* Get the value of the animation at the passed fractional time, which has been adjusted based on the duration and
* repeat settings to be in the range `[0, 1]`.
*
* @param time The time to sample in the range `[0, 1]`
* @param loopCount The number of times the animation wrapped around between the previous sample and this sample
*/
protected abstract fun getValueAt(time: Float, loopCount: Int): T
override val end: Float
get() = if(repeatCount == Int.MAX_VALUE)
Float.POSITIVE_INFINITY
else
duration * repeatCount.clamp(1, Int.MAX_VALUE)
/**
* Get the value at the specified [time]. Time should increase monotonically for each instance. Some animations may
* behave erratically if [time] ever decreases.
*/
override fun animate(time: Float): T {
if(duration == 0f)
return if(time == 0f) getValueAt(0f, 0) else getValueAt(1f, 0)
var loopCount = (time / duration).toInt()
var loopedTime = time % duration
// If we don't do this check the animation will snap back to its initial value exactly at the end of its loop.
if(time != 0f && loopedTime == 0f) {
loopedTime = duration
loopCount--
}
if(reverseOnRepeat && loopCount % 2 == 1) {
loopedTime = duration - loopedTime
}
return getValueAt(loopedTime / duration, loopCount)
}
override fun onStarted() {
// nop
}
override fun onStopped(time: Float): T {
val finalValue = getValueAt(1f, 0)
completionCallback?.run()
return finalValue
}
//region Builders
public fun repeat(repeatCount: Int): BasicAnimation<T> = build {
this.repeatCount = repeatCount
}
public fun repeat(): BasicAnimation<T> = build {
this.repeatCount = Int.MAX_VALUE
}
public fun reverseOnRepeat(): BasicAnimation<T> = build {
this.reverseOnRepeat = true
}
public fun reverseOnRepeat(reverseOnRepeat: Boolean): BasicAnimation<T> = build {
this.reverseOnRepeat = reverseOnRepeat
}
public fun onComplete(completionCallback: Runnable?): BasicAnimation<T> = build {
this.completionCallback = completionCallback
}
private fun build(cb: () -> Unit): BasicAnimation<T> {
cb()
return this
}
//endregion
} | lgpl-3.0 | ca7a28bd453c76792d230b0c81ab3ffc | 31.383838 | 119 | 0.634009 | 4.414601 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/Quaternion.kt | 1 | 30412 | package com.teamwizardry.librarianlib.math
import com.teamwizardry.librarianlib.core.util.vec
import java.io.Serializable
import net.minecraft.util.math.Vec3d
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.acos
import kotlin.math.asin
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sign
import kotlin.math.sin
import kotlin.math.sqrt
// adapted from flow/math: https://github.com/flow/math
/**
* Represent a quaternion of the form `xi + yj + zk + w`. The x, y, z and w components are stored as doubles. This class is immutable.
*/
public class Quaternion(
/**
* Gets the x (imaginary) component of this quaternion.
*
* @return The x (imaginary) component
*/
public val x: Double,
/**
* Gets the y (imaginary) component of this quaternion.
*
* @return The y (imaginary) component
*/
public val y: Double,
/**
* Gets the z (imaginary) component of this quaternion.
*
* @return The z (imaginary) component
*/
public val z: Double,
/**
* Gets the w (real) component of this quaternion.
*
* @return The w (real) component
*/
public val w: Double
): Comparable<Quaternion>, Serializable, Cloneable {
@Volatile
@Transient
private var hashCode = 0
/**
* Returns a unit vector representing the direction of this quaternion, which is the +Z unit vector rotated by this
* quaternion.
*
* @return The vector representing the direction this quaternion is pointing to
*/
public val direction: Vec3d
get() = rotate(vec(0, 0, 1))
/**
* Returns the axis of rotation for this quaternion.
*
* @return The axis of rotation
*/
public val axis: Vec3d
get() {
val q = fastInvSqrt(1 - w * w)
return vec(x * q, y * q, z * q)
}
/**
* Returns the angles in degrees around the x, y and z axes that correspond to the rotation represented by this quaternion.
*
* @return The angle in degrees for each axis, stored in a vector, in the corresponding component
*/
public val axesAnglesDeg: Vec3d
get() = axesAnglesRad * (180 / PI)
/**
* Returns the angles in radians around the x, y and z axes that correspond to the rotation represented by this quaternion.
*
* @return The angle in radians for each axis, stored in a vector, in the corresponding component
*/
public val axesAnglesRad: Vec3d
get() {
val roll: Double
val pitch: Double
val yaw: Double
val test = w * x - y * z
if (abs(test) < 0.4999) {
roll = atan2(2 * (w * z + x * y), 1 - 2 * (x * x + z * z))
pitch = asin(2 * test)
yaw = atan2(2 * (w * y + z * x), 1 - 2 * (x * x + y * y))
} else {
val sign = if (test < 0) -1 else 1
roll = 0.0
pitch = sign * Math.PI / 2
yaw = -sign * 2 * atan2(z, w)
}
return Vec3d(pitch, yaw, roll)
}
/**
* Constructs a new quaternion from the float components.
*
* @param x The x (imaginary) component
* @param y The y (imaginary) component
* @param z The z (imaginary) component
* @param w The w (real) component
*/
public constructor(x: Float, y: Float, z: Float, w: Float): this(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
/**
* Copy constructor.
*
* @param q The quaternion to copy
*/
public constructor(q: Quaternion): this(q.x, q.y, q.z, q.w) {}
/** Operator function for Kotlin */
public operator fun component1(): Double {
return x
}
/** Operator function for Kotlin */
public operator fun component2(): Double {
return y
}
/** Operator function for Kotlin */
public operator fun component3(): Double {
return z
}
/** Operator function for Kotlin */
public operator fun component4(): Double {
return w
}
/**
* Adds another quaternion to this one.
*
* @param q The quaternion to add
* @return A new quaternion, which is the sum of both
*/
@JvmName("add")
public operator fun plus(q: Quaternion): Quaternion {
return add(q.x, q.y, q.z, q.w)
}
/**
* Adds the float components of another quaternion to this one.
*
* @param x The x (imaginary) component of the quaternion to add
* @param y The y (imaginary) component of the quaternion to add
* @param z The z (imaginary) component of the quaternion to add
* @param w The w (real) component of the quaternion to add
* @return A new quaternion, which is the sum of both
*/
public fun add(x: Float, y: Float, z: Float, w: Float): Quaternion {
return add(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
}
/**
* Adds the double components of another quaternion to this one.
*
* @param x The x (imaginary) component of the quaternion to add
* @param y The y (imaginary) component of the quaternion to add
* @param z The z (imaginary) component of the quaternion to add
* @param w The w (real) component of the quaternion to add
* @return A new quaternion, which is the sum of both
*/
public fun add(x: Double, y: Double, z: Double, w: Double): Quaternion {
return Quaternion(this.x + x, this.y + y, this.z + z, this.w + w)
}
/**
* Subtracts another quaternion from this one.
*
* @param q The quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
@JvmName("sub")
public operator fun minus(q: Quaternion): Quaternion {
return sub(q.x, q.y, q.z, q.w)
}
/**
* Subtracts the float components of another quaternion from this one.
*
* @param x The x (imaginary) component of the quaternion to subtract
* @param y The y (imaginary) component of the quaternion to subtract
* @param z The z (imaginary) component of the quaternion to subtract
* @param w The w (real) component of the quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
public fun sub(x: Float, y: Float, z: Float, w: Float): Quaternion {
return sub(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
}
/**
* Subtracts the double components of another quaternion from this one.
*
* @param x The x (imaginary) component of the quaternion to subtract
* @param y The y (imaginary) component of the quaternion to subtract
* @param z The z (imaginary) component of the quaternion to subtract
* @param w The w (real) component of the quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
public fun sub(x: Double, y: Double, z: Double, w: Double): Quaternion {
return Quaternion(this.x - x, this.y - y, this.z - z, this.w - w)
}
/**
* Multiplies the components of this quaternion by a float scalar.
*
* @param a The multiplication scalar
* @return A new quaternion, which has each component multiplied by the scalar
*/
public fun mul(a: Float): Quaternion {
return mul(a.toDouble())
}
/** Operator function for Kotlin */
public operator fun times(a: Float): Quaternion {
return mul(a)
}
/**
* Multiplies the components of this quaternion by a double scalar.
*
* @param a The multiplication scalar
* @return A new quaternion, which has each component multiplied by the scalar
*/
public fun mul(a: Double): Quaternion {
return Quaternion(x * a, y * a, z * a, w * a)
}
/** Operator function for Kotlin */
public operator fun times(a: Double): Quaternion {
return mul(a)
}
/**
* Multiplies another quaternion with this one.
*
* @param q The quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
@JvmName("mul")
public operator fun times(q: Quaternion): Quaternion {
return mul(q.x, q.y, q.z, q.w)
}
/**
* Multiplies the float components of another quaternion with this one.
*
* @param x The x (imaginary) component of the quaternion to multiply with
* @param y The y (imaginary) component of the quaternion to multiply with
* @param z The z (imaginary) component of the quaternion to multiply with
* @param w The w (real) component of the quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
public fun mul(x: Float, y: Float, z: Float, w: Float): Quaternion {
return mul(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
}
/**
* Multiplies the double components of another quaternion with this one.
*
* @param x The x (imaginary) component of the quaternion to multiply with
* @param y The y (imaginary) component of the quaternion to multiply with
* @param z The z (imaginary) component of the quaternion to multiply with
* @param w The w (real) component of the quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
public fun mul(x: Double, y: Double, z: Double, w: Double): Quaternion {
return Quaternion(
this.w * x + this.x * w + this.y * z - this.z * y,
this.w * y + this.y * w + this.z * x - this.x * z,
this.w * z + this.z * w + this.x * y - this.y * x,
this.w * w - this.x * x - this.y * y - this.z * z)
}
/**
* Divides the components of this quaternion by a float scalar.
*
* @param a The division scalar
* @return A new quaternion, which has each component divided by the scalar
*/
public operator fun div(a: Float): Quaternion {
return div(a.toDouble())
}
/**
* Divides the components of this quaternion by a double scalar.
*
* @param a The division scalar
* @return A new quaternion, which has each component divided by the scalar
*/
public operator fun div(a: Double): Quaternion {
return Quaternion(x / a, y / a, z / a, w / a)
}
/**
* Divides this quaternions by another one.
*
* @param q The quaternion to divide with
* @return The quotient of the two quaternions
*/
public operator fun div(q: Quaternion): Quaternion {
return div(q.x, q.y, q.z, q.w)
}
/**
* Divides this quaternions by the float components of another one.
*
* @param x The x (imaginary) component of the quaternion to divide with
* @param y The y (imaginary) component of the quaternion to divide with
* @param z The z (imaginary) component of the quaternion to divide with
* @param w The w (real) component of the quaternion to divide with
* @return The quotient of the two quaternions
*/
public fun div(x: Float, y: Float, z: Float, w: Float): Quaternion {
return div(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
}
/**
* Divides this quaternions by the double components of another one.
*
* @param x The x (imaginary) component of the quaternion to divide with
* @param y The y (imaginary) component of the quaternion to divide with
* @param z The z (imaginary) component of the quaternion to divide with
* @param w The w (real) component of the quaternion to divide with
* @return The quotient of the two quaternions
*/
public fun div(x: Double, y: Double, z: Double, w: Double): Quaternion {
val d = x * x + y * y + z * z + w * w
return Quaternion(
(this.x * w - this.w * x - this.z * y + this.y * z) / d,
(this.y * w + this.z * x - this.w * y - this.x * z) / d,
(this.z * w - this.y * x + this.x * y - this.w * z) / d,
(this.w * w + this.x * x + this.y * y + this.z * z) / d)
}
/**
* Returns the dot product of this quaternion with another one.
*
* @param q The quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public fun dot(q: Quaternion): Double {
return dot(q.x, q.y, q.z, q.w)
}
/**
* Returns the dot product of this quaternion with the float components of another one.
*
* @param x The x (imaginary) component of the quaternion to calculate the dot product with
* @param y The y (imaginary) component of the quaternion to calculate the dot product with
* @param z The z (imaginary) component of the quaternion to calculate the dot product with
* @param w The w (real) component of the quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public fun dot(x: Float, y: Float, z: Float, w: Float): Double {
return dot(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
}
/**
* Returns the dot product of this quaternion with the double components of another one.
*
* @param x The x (imaginary) component of the quaternion to calculate the dot product with
* @param y The y (imaginary) component of the quaternion to calculate the dot product with
* @param z The z (imaginary) component of the quaternion to calculate the dot product with
* @param w The w (real) component of the quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public fun dot(x: Double, y: Double, z: Double, w: Double): Double {
return this.x * x + this.y * y + this.z * z + this.w * w
}
/**
* Rotates a vector by this quaternion.
*
* @param v The vector to rotate
* @return The rotated vector
*/
public fun rotate(v: Vec3d): Vec3d {
return rotate(v.getX(), v.getY(), v.getZ())
}
/**
* Rotates the float components of a vector by this quaternion.
*
* @param x The x component of the vector
* @param y The y component of the vector
* @param z The z component of the vector
* @return The rotated vector
*/
public fun rotate(x: Float, y: Float, z: Float): Vec3d {
return rotate(x.toDouble(), y.toDouble(), z.toDouble())
}
/**
* Rotates the double components of a vector by this quaternion.
*
* @param x The x component of the vector
* @param y The y component of the vector
* @param z The z component of the vector
* @return The rotated vector
*/
public fun rotate(x: Double, y: Double, z: Double): Vec3d {
val length = length()
if (abs(length) < DBL_EPSILON) {
throw ArithmeticException("Cannot rotate by the zero quaternion")
}
val nx = this.x / length
val ny = this.y / length
val nz = this.z / length
val nw = this.w / length
val px = nw * x + ny * z - nz * y
val py = nw * y + nz * x - nx * z
val pz = nw * z + nx * y - ny * x
val pw = -nx * x - ny * y - nz * z
return Vec3d(
pw * -nx + px * nw - py * nz + pz * ny,
pw * -ny + py * nw - pz * nx + px * nz,
pw * -nz + pz * nw - px * ny + py * nx)
}
/**
* Conjugates the quaternion. <br></br> Conjugation of a quaternion `a` is an operation returning quaternion `a'` such that `a' * a = a * a' = |a|<sup>2</sup>` where
* `|a|<sup>2<sup></sup></sup>` is squared length of `a`.
*
* @return the conjugated quaternion
*/
public fun conjugate(): Quaternion {
return Quaternion(-x, -y, -z, w)
}
/**
* Inverts the quaternion. <br></br> Inversion of a quaternion `a` returns quaternion `a<sup>-1</sup> = a' / |a|<sup>2</sup>` where `a'` is [ conjugation][.conjugate] of `a`, and `|a|<sup>2</sup>` is squared length of `a`. <br></br> For any quaternions `a, b, c`, such that `a * b = c` equations
* `a<sup>-1</sup> * c = b` and `c * b<sup>-1</sup> = a` are true.
*
* @return the inverted quaternion
*/
public fun invert(): Quaternion {
val lengthSquared = lengthSquared()
if (abs(lengthSquared) < DBL_EPSILON) {
throw ArithmeticException("Cannot invert a quaternion of length zero")
}
return conjugate().div(lengthSquared)
}
/**
* Returns the square of the length of this quaternion.
*
* @return The square of the length
*/
public fun lengthSquared(): Double {
return x * x + y * y + z * z + w * w
}
/**
* Returns the length of this quaternion.
*
* @return The length
*/
public fun length(): Double {
return sqrt(lengthSquared())
}
/**
* Normalizes this quaternion.
*
* @return A new quaternion of unit length
*/
public fun normalize(): Quaternion {
val length = length()
if (abs(length) < DBL_EPSILON) {
throw ArithmeticException("Cannot normalize the zero quaternion")
}
return Quaternion(x / length, y / length, z / length, w / length)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is Quaternion) {
return false
}
if (other.w.compareTo(w) != 0) {
return false
} else if (other.x.compareTo(x) != 0) {
return false
} else if (other.y.compareTo(y) != 0) {
return false
} else if (other.z.compareTo(z) != 0) {
return false
}
return true
}
override fun hashCode(): Int {
if (hashCode != 0) {
var result = if (x != +0.0) x.hashCode() else 0
result = 31 * result + if (y != +0.0) y.hashCode() else 0
result = 31 * result + if (z != +0.0) z.hashCode() else 0
result = 31 * result + if (w != +0.0) w.hashCode() else 0
hashCode = if (result == 0) 1 else result
}
return hashCode
}
override fun compareTo(other: Quaternion): Int {
return sign(lengthSquared() - other.lengthSquared()).toInt()
}
public override fun clone(): Quaternion {
return Quaternion(this)
}
override fun toString(): String {
return "($x, $y, $z, $w)"
}
public companion object {
private val DBL_EPSILON = Double.fromBits(0x3cb0000000000000L)
/**
* An immutable identity (0, 0, 0, 0) quaternion.
*/
public val ZERO: Quaternion = Quaternion(0f, 0f, 0f, 0f)
/**
* An immutable identity (0, 0, 0, 1) quaternion.
*/
public val IDENTITY: Quaternion = Quaternion(0f, 0f, 0f, 1f)
/**
* Creates a new quaternion from the double real component.
*
*
* The [.ZERO] constant is re-used when `w` is 0.
*
* @param w The w (real) component
* @return The quaternion created from the double real component
*/
public fun fromReal(w: Double): Quaternion {
return if (w == 0.0) ZERO else Quaternion(0.0, 0.0, 0.0, w)
}
/**
* Creates a new quaternion from the double imaginary components.
*
*
* The [.ZERO] constant is re-used when `x`, `y`, and `z` are 0.
*
* @param x The x (imaginary) component
* @param y The y (imaginary) component
* @param z The z (imaginary) component
* @return The quaternion created from the double imaginary components
*/
public fun fromImaginary(x: Double, y: Double, z: Double): Quaternion {
return if (x == 0.0 && y == 0.0 && z == 0.0) ZERO else Quaternion(x, y, z, 0.0)
}
/**
* Creates a new quaternion from the double components.
*
*
* The [.ZERO] constant is re-used when `x`, `y`, `z`, and `w` are 0.
*
* @param x The x (imaginary) component
* @param y The y (imaginary) component
* @param z The z (imaginary) component
* @param w The w (real) component
* @return The quaternion created from the double components
*/
public fun from(x: Double, y: Double, z: Double, w: Double): Quaternion {
return if (x == 0.0 && y == 0.0 && z == 0.0 && w == 0.0) ZERO else Quaternion(x, y, z, w)
}
/**
* Creates a new quaternion from the float angles in degrees around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public fun fromAxesAnglesDeg(pitch: Float, yaw: Float, roll: Float): Quaternion {
return fromAxesAnglesDeg(pitch.toDouble(), yaw.toDouble(), roll.toDouble())
}
/**
* Creates a new quaternion from the float angles in radians around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public fun fromAxesAnglesRad(pitch: Float, yaw: Float, roll: Float): Quaternion {
return fromAxesAnglesRad(pitch.toDouble(), yaw.toDouble(), roll.toDouble())
}
/**
* Creates a new quaternion from the double angles in degrees around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public fun fromAxesAnglesDeg(pitch: Double, yaw: Double, roll: Double): Quaternion {
return fromAngleDegAxis(yaw, vec(0, 1, 0)) * fromAngleDegAxis(pitch, vec(1, 0, 0)) * fromAngleDegAxis(roll, vec(0, 0, 1))
}
/**
* Creates a new quaternion from the double angles in radians around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public fun fromAxesAnglesRad(pitch: Double, yaw: Double, roll: Double): Quaternion {
return fromAngleRadAxis(yaw, vec(0, 1, 0)) * fromAngleRadAxis(pitch, vec(1, 0, 0)) * fromAngleRadAxis(roll, vec(0, 0, 1))
}
/**
* Creates a new quaternion from the angle-axis rotation defined from the first to the second vector.
*
* @param from The first vector
* @param to The second vector
* @return The quaternion defined by the angle-axis rotation between the vectors
*/
public fun fromRotationTo(from: Vec3d, to: Vec3d): Quaternion {
return fromAngleRadAxis(acos((from dot to) / (from.length() * to.length())), from cross to)
}
/**
* Creates a new quaternion from the rotation float angle in degrees around the axis vector.
*
* @param angle The rotation angle in degrees
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleDegAxis(angle: Float, axis: Vec3d): Quaternion {
return fromAngleRadAxis(Math.toRadians(angle.toDouble()), axis)
}
/**
* Creates a new quaternion from the rotation float angle in radians around the axis vector.
*
* @param angle The rotation angle in radians
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleRadAxis(angle: Float, axis: Vec3d): Quaternion {
return fromAngleRadAxis(angle.toDouble(), axis)
}
/**
* Creates a new quaternion from the rotation double angle in degrees around the axis vector.
*
* @param angle The rotation angle in degrees
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleDegAxis(angle: Double, axis: Vec3d): Quaternion {
return fromAngleRadAxis(Math.toRadians(angle), axis)
}
/**
* Creates a new quaternion from the rotation double angle in radians around the axis vector.
*
* @param angle The rotation angle in radians
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleRadAxis(angle: Double, axis: Vec3d): Quaternion {
return fromAngleRadAxis(angle, axis.getX(), axis.getY(), axis.getZ())
}
/**
* Creates a new quaternion from the rotation float angle in degrees around the axis vector float components.
*
* @param angle The rotation angle in degrees
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleDegAxis(angle: Float, x: Float, y: Float, z: Float): Quaternion {
return fromAngleRadAxis(Math.toRadians(angle.toDouble()), x.toDouble(), y.toDouble(), z.toDouble())
}
/**
* Creates a new quaternion from the rotation float angle in radians around the axis vector float components.
*
* @param angle The rotation angle in radians
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleRadAxis(angle: Float, x: Float, y: Float, z: Float): Quaternion {
return fromAngleRadAxis(angle.toDouble(), x.toDouble(), y.toDouble(), z.toDouble())
}
/**
* Creates a new quaternion from the rotation double angle in degrees around the axis vector double components.
*
* @param angle The rotation angle in degrees
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleDegAxis(angle: Double, x: Double, y: Double, z: Double): Quaternion {
return fromAngleRadAxis(Math.toRadians(angle), x, y, z)
}
/**
* Creates a new quaternion from the rotation double angle in radians around the axis vector double components.
*
* @param angle The rotation angle in radians
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public fun fromAngleRadAxis(angle: Double, x: Double, y: Double, z: Double): Quaternion {
val halfAngle = angle / 2
val q = sin(halfAngle) / sqrt(x * x + y * y + z * z)
return Quaternion(x * q, y * q, z * q, cos(halfAngle))
}
/**
* Creates a new quaternion from the rotation matrix. The matrix will be interpreted as a rotation matrix even if it is not.
*
* @param matrix The rotation matrix
* @return The quaternion defined by the rotation matrix
*/
public fun fromRotationMatrix(matrix: Matrix3d): Quaternion {
val trace = matrix.trace()
if (trace < 0) {
if (matrix.m11 > matrix.m00) {
if (matrix.m22 > matrix.m11) {
val r = sqrt(matrix.m22 - matrix.m00 - matrix.m11 + 1)
val s = 0.5f / r
return Quaternion(
(matrix.m20 + matrix.m02) * s,
(matrix.m12 + matrix.m21) * s,
0.5f * r,
(matrix.m10 - matrix.m01) * s)
} else {
val r = sqrt(matrix.m11 - matrix.m22 - matrix.m00 + 1)
val s = 0.5f / r
return Quaternion(
(matrix.m01 + matrix.m10) * s,
0.5f * r,
(matrix.m12 + matrix.m21) * s,
(matrix.m02 - matrix.m20) * s)
}
} else if (matrix.m22 > matrix.m00) {
val r = sqrt(matrix.m22 - matrix.m00 - matrix.m11 + 1)
val s = 0.5f / r
return Quaternion(
(matrix.m20 + matrix.m02) * s,
(matrix.m12 + matrix.m21) * s,
0.5f * r,
(matrix.m10 - matrix.m01) * s)
} else {
val r = sqrt(matrix.m00 - matrix.m11 - matrix.m22 + 1)
val s = 0.5f / r
return Quaternion(
0.5f * r,
(matrix.m01 + matrix.m10) * s,
(matrix.m20 - matrix.m02) * s,
(matrix.m21 - matrix.m12) * s)
}
} else {
val r = sqrt(trace + 1)
val s = 0.5f / r
return Quaternion(
(matrix.m21 - matrix.m12) * s,
(matrix.m02 - matrix.m20) * s,
(matrix.m10 - matrix.m01) * s,
0.5f * r)
}
}
}
}
/**
* Constructs a new quaternion. The components are set to the identity (0, 0, 0, 1).
*/
| lgpl-3.0 | 5d00d200d59d9195120abe8fd7d04e69 | 36.967541 | 299 | 0.573852 | 4.063602 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsSelfParameter.kt | 4 | 1438 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsSelfParameter
import org.rust.lang.core.stubs.RsSelfParameterStub
import org.rust.lang.core.types.ty.Mutability
val RsSelfParameter.mutability: Mutability get() = Mutability.valueOf(greenStub?.isMut ?: (mut != null))
val RsSelfParameter.isRef: Boolean get() = greenStub?.isRef ?: (and != null)
val RsSelfParameter.isExplicitType get() = greenStub?.isExplicitType ?: (colon != null)
val RsSelfParameter.parentFunction: RsFunction get() = ancestorStrict()!!
abstract class RsSelfParameterImplMixin : RsStubbedElementImpl<RsSelfParameterStub>, RsSelfParameter {
constructor(node: ASTNode) : super(node)
constructor(stub: RsSelfParameterStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getNameIdentifier(): PsiElement = self
override fun getName(): String = "self"
override fun setName(name: String): PsiElement? {
// can't rename self
throw UnsupportedOperationException()
}
override fun getTextOffset(): Int = nameIdentifier.textOffset
override fun getIcon(flags: Int) = RsIcons.ARGUMENT
}
| mit | 198337c5b10ca6b64c634597b06304bb | 35.871795 | 104 | 0.757302 | 4.108571 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/repository/ChatMessageLocalRepository.kt | 1 | 1325 | package de.tum.`in`.tumcampusapp.component.ui.chat.repository
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage
import de.tum.`in`.tumcampusapp.database.TcaDb
import java.util.concurrent.Executor
import java.util.concurrent.Executors
object ChatMessageLocalRepository {
private val executor: Executor = Executors.newSingleThreadExecutor();
lateinit var db: TcaDb
fun markAsRead(room: Int) = db.chatMessageDao().markAsRead(room)
fun deleteOldEntries() = db.chatMessageDao().deleteOldEntries()
fun addToUnsent(message: ChatMessage) {
executor.execute { db.chatMessageDao().replaceMessage(message) }
}
fun getAllChatMessagesList(room: Int): List<ChatMessage> = db.chatMessageDao().getAll(room)
fun getUnsent(): List<ChatMessage> = db.chatMessageDao().unsent
fun getUnsentInChatRoom(roomId: Int): List<ChatMessage> = db.chatMessageDao().getUnsentInChatRoom(roomId)
fun replaceMessages(chatMessages: List<ChatMessage>) {
chatMessages.forEach { replaceMessage(it) }
}
fun replaceMessage(chatMessage: ChatMessage) {
executor.execute { db.chatMessageDao().replaceMessage(chatMessage) }
}
fun removeUnsent(chatMessage: ChatMessage) {
executor.execute { db.chatMessageDao().removeUnsent(chatMessage.text) }
}
} | gpl-3.0 | 3404a1be3d988601eaf8db23048b5426 | 31.341463 | 109 | 0.741132 | 4.26045 | false | false | false | false |
yuncheolkim/gitmt | src/main/kotlin/com/joyouskim/vertx/HttpServerVertx.kt | 1 | 3794 | package com.joyouskim.vertx
import com.joyouskim.git.sendError
import com.joyouskim.http.Action
import com.joyouskim.http.getOut
import com.joyouskim.http.httpRequestAdapter
import com.joyouskim.http.httpResponseAdapter
import com.joyouskim.log.COMMON
import com.joyouskim.log.MSG
import io.vertx.core.AbstractVerticle
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.BodyHandler
import io.vertx.ext.web.handler.StaticHandler
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
/**
* Created by jinyunzhe on 16/4/5.
*/
class HttpServerVertx() : AbstractVerticle() {
lateinit var gitAction: Action
override fun start() {
COMMON.info("start")
gitAction.init()
val router = Router.router(vertx);
// We need cookies, sessions and request bodies
// router.route().handler(io.vertx.ext.web.handler.CookieHandler.create());
router.route().handler(BodyHandler.create());
// router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
val route = router.route()
//git请求
route.pathRegex("/(.+)/(.+\\.git)/?.*").handler {
val userName = it.request().getParam("param0")
val git_r = it.request().getParam("param1")
// val path = Paths.get("gr/$userName/$git_r")
// if (!Files.exists(path)) {
// Files.createDirectories(path)
// }
COMMON.info(it.request().uri())
COMMON.info("user:$userName,git_repository:$git_r")
it.response().isChunked = true
val buffer = it.body
COMMON.debug("buffer length:${buffer.length()} ,size:${it.fileUploads().size}")
val httpServerRequest = it.request()
val httpServerResponse = it.response()
COMMON.debug("${httpServerRequest.toString()}")
var i = 0
buffer.bytes.forEach {
if(i++ > 50)
return@forEach
println(it.toString())
}
vertx.executeBlocking<String>({
gitAction.doAction(httpRequestAdapter(buffer, httpServerRequest), httpResponseAdapter(httpServerResponse))
},{
if (it.failed()) {
COMMON.error("",it.cause())
}
httpServerResponse.end()
})
}
router.route().path("/test/*").handler {
val request = httpRequestAdapter(it.body, it.request())
val response = httpResponseAdapter(it.response())
sendError(request, response, 502)
}
router.post("/some/path/uploads").handler({
val uploads = it.fileUploads();
val response = it.response()
response.isChunked = true
uploads.forEach {
try {
val fileName = URLDecoder.decode(it.fileName(), it.charSet());
val p = Paths.get("gr", fileName)
if (!Files.exists(p)) {
Files.createFile(p)
}
vertx.fileSystem().readFile(it.uploadedFileName(), {
Files.write(p, it.result().bytes)
});
} catch (e: UnsupportedEncodingException) {
e.printStackTrace();
}
}
});
// Serve the non private static pages
router.route().handler(StaticHandler.create());
vertx.createHttpServer().requestHandler({
router.accept(it)
}).listen(5000)
}
}
| mit | f0a2f6f521135b7cc18c90172689f4ca | 31.672414 | 122 | 0.558575 | 4.522673 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/stubs/index/ElmNamedElementIndex.kt | 1 | 1543 | package org.elm.lang.core.stubs.index
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.stubs.ElmFileStub
/**
* An index of all Elm named things across the entire IntelliJ project.
*
* IMPORTANT: See [ElmLookup] for an alternative API that properly
* handles visibility of named things based on the Elm project which
* wants to access it.
*
*/
class ElmNamedElementIndex : StringStubIndexExtension<ElmNamedElement>() {
override fun getVersion() =
ElmFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, ElmNamedElement> =
KEY
companion object {
val KEY: StubIndexKey<String, ElmNamedElement> =
StubIndexKey.createIndexKey("org.elm.lang.core.stubs.index.ElmNamedElementIndex")
/**
* Find all [ElmNamedElement]s whose name matches [name] in [scope].
*/
fun find(name: String, project: Project, scope: GlobalSearchScope): Collection<ElmNamedElement> =
StubIndex.getElements(KEY, name, project, scope, ElmNamedElement::class.java)
/**
* Get the name of every element stored in this index.
*/
fun getAllNames(project: Project): Collection<String> =
StubIndex.getInstance().getAllKeys(KEY, project)
}
}
| mit | 475209c5adf6dfc27260ea4083faa395 | 34.883721 | 105 | 0.70512 | 4.60597 | false | false | false | false |
IRA-Team/VKPlayer | app/src/main/java/com/irateam/vkplayer/activity/MainActivity.kt | 1 | 8540 | /*
* Copyright (C) 2015 IRA-Team
*
* 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.irateam.vkplayer.activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.irateam.vkplayer.R
import com.irateam.vkplayer.activity.settings.SettingsActivity
import com.irateam.vkplayer.api.service.LocalAudioService
import com.irateam.vkplayer.api.service.UserService
import com.irateam.vkplayer.api.service.VKAudioService
import com.irateam.vkplayer.controller.PlayerController
import com.irateam.vkplayer.fragment.*
import com.irateam.vkplayer.model.User
import com.irateam.vkplayer.player.PlayerPlayEvent
import com.irateam.vkplayer.player.PlayerStopEvent
import com.irateam.vkplayer.service.PlayerService
import com.irateam.vkplayer.util.EventBus
import com.irateam.vkplayer.util.extension.*
import com.melnykov.fab.FloatingActionButton
import com.vk.sdk.VKSdk
import org.greenrobot.eventbus.Subscribe
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener,
PlayerController.VisibilityController {
//Services
private lateinit var userService: UserService
private lateinit var audioService: VKAudioService
private lateinit var localAudioService: LocalAudioService
//Views
private lateinit var toolbar: Toolbar
private lateinit var drawerLayout: DrawerLayout
private lateinit var navigationView: NavigationView
private lateinit var container: FrameLayout
private lateinit var coordinatorLayout: CoordinatorLayout
private lateinit var fab: FloatingActionButton
//User views
private lateinit var userPhoto: ImageView
private lateinit var userFullName: TextView
private lateinit var userLink: TextView
//Player helpers
private lateinit var playerController: PlayerController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
audioService = VKAudioService(this)
localAudioService = LocalAudioService(this)
userService = UserService(this)
toolbar = getViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setNavigationOnClickListener { drawerLayout.openDrawer(GravityCompat.START) }
drawerLayout = getViewById(R.id.drawer_layout)
val drawerToggle = ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(drawerToggle)
drawerToggle.syncState()
navigationView = getViewById(R.id.navigation_view)
navigationView.setNavigationItemSelectedListener(this)
val header = navigationView.getHeaderView(0)
userPhoto = header.getViewById(R.id.user_photo)
userFullName = header.getViewById(R.id.user_full_name)
userLink = header.getViewById(R.id.user_vk_link)
container = getViewById(R.id.container)
coordinatorLayout = getViewById(R.id.coordinator_layout)
fab = getViewById(R.id.fab)
fab.setOnClickListener { startActivity(Intent(this, AudioActivity::class.java)) }
playerController = PlayerController(this, findViewById(R.id.player_panel)!!)
playerController.initialize()
startService<PlayerService>()
initializeUser()
initializeFragment()
EventBus.register(this)
EventBus.register(playerController)
}
override fun onDestroy() {
EventBus.unregister(this)
EventBus.unregister(playerController)
super.onDestroy()
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
drawerLayout.closeDrawers()
val itemId = menuItem.itemId
val groupId = menuItem.groupId
if (groupId == R.id.audio_group) {
val fragment: BaseFragment = when (itemId) {
R.id.current_playlist -> CurrentPlaylistFragment.newInstance()
R.id.local_audio -> LocalAudioListFragment.newInstance()
R.id.my_audio -> VKMyAudioFragment.newInstance()
R.id.recommended_audio -> VKRecommendationAudioFragment.newInstance()
R.id.popular_audio -> VKPopularAudioFragment.newInstance()
R.id.cached_audio -> VKCachedAudioFragment.newInstance()
else -> throw IllegalStateException("This item doesn't support.")
}
setFragment(fragment)
return true
} else if (groupId == R.id.secondary_group) {
when (itemId) {
R.id.settings -> startActivity(Intent(this, SettingsActivity::class.java))
R.id.exit -> VkLogout()
}
return true
}
return false
}
@Subscribe
fun onPlayEvent(e: PlayerPlayEvent) {
if (!playerController.isVisible()) {
showPlayerController()
}
val fragment = supportFragmentManager.findFragmentByTag(TOP_LEVEL_FRAGMENT)
if (fragment !is CurrentPlaylistFragment) {
navigationView.menu.findItem(R.id.current_playlist)?.isChecked = true
setFragment(CurrentPlaylistFragment.newInstance())
}
}
@Subscribe
fun onStopEvent(e: PlayerStopEvent) {
hidePlayerController()
}
override fun showPlayerController() {
container.layoutParams.apply {
if (this is RelativeLayout.LayoutParams) {
addRule(RelativeLayout.ABOVE, 0)
playerController.show { addRule(RelativeLayout.ABOVE, R.id.player_panel) }
} else {
playerController.show()
}
}
}
override fun hidePlayerController() {
playerController.hide()
}
private fun initializeUser() {
userService.getCurrentCached().execute {
onSuccess {
setUser(it)
}
onError {
}
onFinish {
loadUser()
}
}
}
private fun loadUser() {
userService.getCurrent().execute {
onSuccess {
setUser(it)
}
}
}
private fun setUser(user: User) {
userPhoto.setRoundImageURL(user.photo100px)
userFullName.text = user.fullName
userLink.text = "http://vk.com/id${user.id}"
}
override fun onBackPressed() {
val fragment = supportFragmentManager.findFragmentByTag(TOP_LEVEL_FRAGMENT)
fragment?.let {
if (it !is BackPressedListener || !it.onBackPressed()) {
super.onBackPressed()
}
}
}
private fun initializeFragment() {
val item = navigationView.menu.findItem(R.id.local_audio)
item.isChecked = true
//onNavigationItemSelected(item)
setFragment(SettingsFragment.newInstance())
}
fun setFragment(fragment: BaseFragment) {
supportActionBar?.title = getString(fragment.getTitleRes())
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment, TOP_LEVEL_FRAGMENT)
.commit()
}
private fun VkLogout() {
VKSdk.logout()
startActivity<LoginActivity>()
finish()
}
companion object {
val TOP_LEVEL_FRAGMENT = "top_level_fragment"
}
}
| apache-2.0 | edd5977a702c949e7c7f88c6a20075b8 | 32.754941 | 93 | 0.677283 | 4.936416 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/CachedFileProvider.kt | 1 | 3279 | package nl.mpcjanssen.simpletask
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.io.FileNotFoundException
class CachedFileProvider : ContentProvider() {
// UriMatcher used to match against incoming requests
private var uriMatcher: UriMatcher? = null
override fun onCreate(): Boolean {
uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
// Add a URI to the matcher which will match against the form
// 'content://com.stephendnicholas.gmailattach.provider/*'
// and return 1 in the case that the incoming Uri matches this pattern
uriMatcher!!.addURI(AUTHORITY, "*", 1)
return true
}
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
Log.d(TAG, "Called with uri: '" + uri + "'." + uri.lastPathSegment)
// Check incoming Uri against the matcher
when (uriMatcher!!.match(uri)) {
// If it returns 1 - then it matches the Uri defined in onCreate
1 -> {
// The desired file name is specified by the last segment of the
// path
// E.g.
// 'content://com.stephendnicholas.gmailattach.provider/Test.txt'
// Take this and build the path to the file
val fileLocation = File(context.cacheDir , uri.lastPathSegment)
// Create & return a ParcelFileDescriptor pointing to the file
// Note: I don't care what mode they ask for - they're only getting
// read only
return ParcelFileDescriptor.open(fileLocation, ParcelFileDescriptor.MODE_READ_ONLY)
}
// Otherwise unrecognised Uri
else -> {
Log.d(TAG, "Unsupported uri: '$uri'.")
throw FileNotFoundException("Unsupported uri: " + uri.toString())
}
}
}
// //////////////////////////////////////////////////////////////
// Not supported / used / required for this example
// //////////////////////////////////////////////////////////////
override fun update(uri: Uri, contentvalues: ContentValues, s: String,
`as`: Array<String>): Int {
return 0
}
override fun delete(uri: Uri, s: String, `as`: Array<String>): Int {
return 0
}
override fun insert(uri: Uri, contentvalues: ContentValues): Uri? {
return null
}
override fun getType(uri: Uri): String {
if (uri.toString().endsWith(".db")) {
return "application/x-sqlite3"
}
return "text/plain"
}
override fun query(uri: Uri, projection: Array<String>?, s: String?, as1: Array<String>?,
s1: String? ): Cursor? {
return null
}
companion object {
private val TAG = CachedFileProvider::class.java.simpleName
// The authority is the symbolic name for the provider class
const val AUTHORITY = BuildConfig.APPLICATION_ID + ".provider." + BuildConfig.FLAVOR
}
}
| gpl-3.0 | 8831ca241e0223c8c4a688be3520b267 | 32.459184 | 99 | 0.591034 | 4.923423 | false | false | false | false |
msmoljan/coordinate-logger | src/main/kotlin/com/matkosmoljan/coordinate_logger/CoordinateLogger.kt | 1 | 683 | package com.matkosmoljan.coordinate_logger
typealias CoordinateList = List<Coordinate>
class CoordinateLogger {
interface Listener {
fun onCoordinatesUpdated(coordinates: CoordinateList)
}
var listener: Listener? = null
private val mutableCoordinates: MutableList<Coordinate> = mutableListOf()
val coordinates: List<Coordinate>
get() = mutableCoordinates
fun log(coordinate: Coordinate) {
mutableCoordinates.add(coordinate)
notifyListener()
}
fun clear() {
mutableCoordinates.clear()
notifyListener()
}
private fun notifyListener() = listener?.onCoordinatesUpdated(mutableCoordinates)
}
| mit | f0ec131e0a7eeb3ea210710796e809e8 | 23.392857 | 85 | 0.704246 | 5.022059 | false | false | false | false |
springboot-angular2-tutorial/android-app | app/src/androidTest/kotlin/com/hana053/micropost/pages/login/LoginActivityTest.kt | 1 | 3237 | package com.hana053.micropost.pages.login
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.*
import android.support.test.espresso.assertion.ViewAssertions
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.view.View
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.hana053.micropost.R
import com.hana053.micropost.service.LoginService
import com.hana053.micropost.service.Navigator
import com.hana053.micropost.testing.InjectableTest
import com.hana053.micropost.testing.InjectableTestImpl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.hamcrest.CoreMatchers.not
import org.hamcrest.Matcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import rx.Observable
@RunWith(AndroidJUnit4::class)
@LargeTest
class LoginActivityTest : InjectableTest by InjectableTestImpl() {
@Rule @JvmField
val activityRule = ActivityTestRule(LoginActivity::class.java, false, false)
val loginBtn: Matcher<View> = withId(R.id.btn_login)
val emailEditText: Matcher<View> = withId(R.id.et_email)
val passwordEditText: Matcher<View> = withId(R.id.et_password)
@Test
fun shouldBeOpened() {
activityRule.launchActivity(null)
onView(withText(R.string.log_in_to_micropost)).check(matches(isDisplayed()))
}
@Test
fun shouldDisableOrEnableBtn() {
activityRule.launchActivity(null)
onView(loginBtn).check(ViewAssertions.matches(not(isEnabled())))
onView(emailEditText).perform(typeText("[email protected]"), closeSoftKeyboard())
onView(passwordEditText).perform(typeText("secret123"), closeSoftKeyboard())
onView(loginBtn).check(ViewAssertions.matches(isEnabled()))
onView(passwordEditText).perform(clearText(), closeSoftKeyboard())
onView(loginBtn).check(ViewAssertions.matches(not(isEnabled())))
onView(emailEditText).perform(clearText(), closeSoftKeyboard())
onView(passwordEditText).perform(typeText("secret123"), closeSoftKeyboard())
onView(loginBtn).check(ViewAssertions.matches(not(isEnabled())))
}
@Test
fun shouldNavigateToMainWhenEmailAndPasswordIsValid() {
val navigator = mock<Navigator>()
overrideAppBindings {
bind<LoginService>(overrides = true) with instance(mock<LoginService> {
on { login(any(), any()) } doReturn Observable.just<Void>(null)
})
bind<Navigator>(overrides = true) with instance(navigator)
}
activityRule.launchActivity(null)
onView(emailEditText).perform(typeText("[email protected]"), closeSoftKeyboard())
onView(passwordEditText).perform(typeText("secret123"), closeSoftKeyboard())
onView(loginBtn).perform(click())
verify(navigator).navigateToMain()
}
} | mit | c7ef24a43f032e99aa5912f5b085d060 | 38.012048 | 85 | 0.751004 | 4.39213 | false | true | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactViewRotationAnimator.kt | 1 | 965 | package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.ObjectAnimator
import android.view.View
import com.facebook.react.views.view.ReactViewGroup
import com.reactnativenavigation.options.SharedElementTransitionOptions
class ReactViewRotationAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactViewGroup>(from, to) {
private val fromRotation = from.rotation
private val toRotation = to.rotation
override fun shouldAnimateProperty(fromChild: ReactViewGroup, toChild: ReactViewGroup): Boolean {
return fromRotation != toRotation &&
fromChild.childCount == 0 &&
toChild.childCount == 0
}
override fun create(options: SharedElementTransitionOptions): Animator {
to.rotation = fromRotation
to.pivotX = 0f
to.pivotY = 0f
return ObjectAnimator.ofFloat(to, View.ROTATION, fromRotation, toRotation)
}
} | mit | 965a2f7b5103589d17edb5bc1b52d8ad | 37.64 | 107 | 0.744041 | 4.948718 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_info/ui/adapter/CourseInfoAdapter.kt | 1 | 2203 | package org.stepik.android.view.course_info.ui.adapter
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import kotlinx.android.synthetic.main.view_course_info_block.view.*
import org.stepik.android.model.user.User
import org.stepik.android.view.course_info.model.CourseInfoItem
import org.stepik.android.view.course_info.ui.adapter.delegates.CourseInfoInstructorsDelegate
import org.stepik.android.view.course_info.ui.adapter.delegates.CourseInfoOrganizationDelegate
import org.stepik.android.view.course_info.ui.adapter.delegates.CourseInfoTextBlockDelegate
import org.stepik.android.view.course_info.ui.adapter.delegates.CourseInfoVideoBlockDelegate
import org.stepik.android.view.video_player.model.VideoPlayerMediaData
import ru.nobird.android.ui.adapterdelegates.DelegateAdapter
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class CourseInfoAdapter(
onVideoClicked: ((VideoPlayerMediaData) -> Unit)? = null,
onUserClicked: (User) -> Unit
) : DelegateAdapter<CourseInfoItem, CourseInfoAdapter.ViewHolder>() {
private var blocks: List<CourseInfoItem> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
init {
addDelegate(CourseInfoTextBlockDelegate())
addDelegate(CourseInfoInstructorsDelegate(onUserClicked))
addDelegate(CourseInfoVideoBlockDelegate(onVideoClicked))
addDelegate(CourseInfoOrganizationDelegate(onUserClicked))
}
fun setSortedData(sortedBlocks: List<CourseInfoItem>) {
blocks = sortedBlocks
}
override fun getItemCount(): Int =
blocks.size
override fun getItemAtPosition(position: Int): CourseInfoItem =
blocks[position]
abstract class ViewHolder(root: View) : DelegateViewHolder<CourseInfoItem>(root)
abstract class ViewHolderWithTitle(root: View) : ViewHolder(root) {
protected val blockIcon: ImageView = root.blockIcon
protected val blockTitle: TextView = root.blockTitle
override fun onBind(data: CourseInfoItem) {
blockIcon.setImageResource(data.type.icon)
blockTitle.setText(data.type.title)
}
}
} | apache-2.0 | 39d26e368114ecc649b4efa6a8969c8f | 39.072727 | 94 | 0.758965 | 4.505112 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuApi.kt | 1 | 9960 | package eu.kanade.tachiyomi.data.track.kitsu
import androidx.core.net.toUri
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.network.jsonMime
import eu.kanade.tachiyomi.network.parseAs
import eu.kanade.tachiyomi.util.lang.withIOContext
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import okhttp3.FormBody
import okhttp3.Headers.Companion.headersOf
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
class KitsuApi(private val client: OkHttpClient, interceptor: KitsuInterceptor) {
private val authClient = client.newBuilder().addInterceptor(interceptor).build()
suspend fun addLibManga(track: Track, userId: String): Track {
return withIOContext {
val data = buildJsonObject {
putJsonObject("data") {
put("type", "libraryEntries")
putJsonObject("attributes") {
put("status", track.toKitsuStatus())
put("progress", track.last_chapter_read.toInt())
}
putJsonObject("relationships") {
putJsonObject("user") {
putJsonObject("data") {
put("id", userId)
put("type", "users")
}
}
putJsonObject("media") {
putJsonObject("data") {
put("id", track.media_id)
put("type", "manga")
}
}
}
}
}
authClient.newCall(
POST(
"${baseUrl}library-entries",
headers = headersOf(
"Content-Type",
"application/vnd.api+json",
),
body = data.toString().toRequestBody("application/vnd.api+json".toMediaType()),
),
)
.await()
.parseAs<JsonObject>()
.let {
track.media_id = it["data"]!!.jsonObject["id"]!!.jsonPrimitive.long
track
}
}
}
suspend fun updateLibManga(track: Track): Track {
return withIOContext {
val data = buildJsonObject {
putJsonObject("data") {
put("type", "libraryEntries")
put("id", track.media_id)
putJsonObject("attributes") {
put("status", track.toKitsuStatus())
put("progress", track.last_chapter_read.toInt())
put("ratingTwenty", track.toKitsuScore())
put("startedAt", KitsuDateHelper.convert(track.started_reading_date))
put("finishedAt", KitsuDateHelper.convert(track.finished_reading_date))
}
}
}
authClient.newCall(
Request.Builder()
.url("${baseUrl}library-entries/${track.media_id}")
.headers(
headersOf(
"Content-Type",
"application/vnd.api+json",
),
)
.patch(data.toString().toRequestBody("application/vnd.api+json".toMediaType()))
.build(),
)
.await()
.parseAs<JsonObject>()
.let {
track
}
}
}
suspend fun search(query: String): List<TrackSearch> {
return withIOContext {
authClient.newCall(GET(algoliaKeyUrl))
.await()
.parseAs<JsonObject>()
.let {
val key = it["media"]!!.jsonObject["key"]!!.jsonPrimitive.content
algoliaSearch(key, query)
}
}
}
private suspend fun algoliaSearch(key: String, query: String): List<TrackSearch> {
return withIOContext {
val jsonObject = buildJsonObject {
put("params", "query=${URLEncoder.encode(query, StandardCharsets.UTF_8.name())}$algoliaFilter")
}
client.newCall(
POST(
algoliaUrl,
headers = headersOf(
"X-Algolia-Application-Id",
algoliaAppId,
"X-Algolia-API-Key",
key,
),
body = jsonObject.toString().toRequestBody(jsonMime),
),
)
.await()
.parseAs<JsonObject>()
.let {
it["hits"]!!.jsonArray
.map { KitsuSearchManga(it.jsonObject) }
.filter { it.subType != "novel" }
.map { it.toTrack() }
}
}
}
suspend fun findLibManga(track: Track, userId: String): Track? {
return withIOContext {
val url = "${baseUrl}library-entries".toUri().buildUpon()
.encodedQuery("filter[manga_id]=${track.media_id}&filter[user_id]=$userId")
.appendQueryParameter("include", "manga")
.build()
authClient.newCall(GET(url.toString()))
.await()
.parseAs<JsonObject>()
.let {
val data = it["data"]!!.jsonArray
if (data.size > 0) {
val manga = it["included"]!!.jsonArray[0].jsonObject
KitsuLibManga(data[0].jsonObject, manga).toTrack()
} else {
null
}
}
}
}
suspend fun getLibManga(track: Track): Track {
return withIOContext {
val url = "${baseUrl}library-entries".toUri().buildUpon()
.encodedQuery("filter[id]=${track.media_id}")
.appendQueryParameter("include", "manga")
.build()
authClient.newCall(GET(url.toString()))
.await()
.parseAs<JsonObject>()
.let {
val data = it["data"]!!.jsonArray
if (data.size > 0) {
val manga = it["included"]!!.jsonArray[0].jsonObject
KitsuLibManga(data[0].jsonObject, manga).toTrack()
} else {
throw Exception("Could not find manga")
}
}
}
}
suspend fun login(username: String, password: String): OAuth {
return withIOContext {
val formBody: RequestBody = FormBody.Builder()
.add("username", username)
.add("password", password)
.add("grant_type", "password")
.add("client_id", clientId)
.add("client_secret", clientSecret)
.build()
client.newCall(POST(loginUrl, body = formBody))
.await()
.parseAs()
}
}
suspend fun getCurrentUser(): String {
return withIOContext {
val url = "${baseUrl}users".toUri().buildUpon()
.encodedQuery("filter[self]=true")
.build()
authClient.newCall(GET(url.toString()))
.await()
.parseAs<JsonObject>()
.let {
it["data"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content
}
}
}
companion object {
private const val clientId =
"dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd"
private const val clientSecret =
"54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151"
private const val baseUrl = "https://kitsu.io/api/edge/"
private const val loginUrl = "https://kitsu.io/api/oauth/token"
private const val baseMangaUrl = "https://kitsu.io/manga/"
private const val algoliaKeyUrl = "https://kitsu.io/api/edge/algolia-keys/media/"
private const val algoliaUrl =
"https://AWQO5J657S-dsn.algolia.net/1/indexes/production_media/query/"
private const val algoliaAppId = "AWQO5J657S"
private const val algoliaFilter =
"&facetFilters=%5B%22kind%3Amanga%22%5D&attributesToRetrieve=%5B%22synopsis%22%2C%22canonicalTitle%22%2C%22chapterCount%22%2C%22posterImage%22%2C%22startDate%22%2C%22subtype%22%2C%22endDate%22%2C%20%22id%22%5D"
fun mangaUrl(remoteId: Long): String {
return baseMangaUrl + remoteId
}
fun refreshTokenRequest(token: String) = POST(
loginUrl,
body = FormBody.Builder()
.add("grant_type", "refresh_token")
.add("refresh_token", token)
.add("client_id", clientId)
.add("client_secret", clientSecret)
.build(),
)
}
}
| apache-2.0 | 655be1dd79462c93ce8a7ff4effcae7c | 37.604651 | 222 | 0.504618 | 4.896755 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt | 1 | 2240 | package info.nightscout.androidaps.setupwizard
import android.annotation.SuppressLint
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.events.EventStatus
import info.nightscout.androidaps.setupwizard.elements.SWItem
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import javax.inject.Inject
class SWEventListener constructor(
injector: HasAndroidInjector,
clazz: Class<out EventStatus>
) : SWItem(injector, Type.LISTENER) {
private val disposable = CompositeDisposable()
private var textLabel = 0
private var status = ""
private var textView: TextView? = null
private var visibilityValidator: SWValidator? = null
@Inject lateinit var aapsSchedulers: AapsSchedulers
// TODO: Adrian how to clear disposable in this case?
init {
disposable.add(rxBus
.toObservable(clazz)
.observeOn(aapsSchedulers.main)
.subscribe { event: Any ->
status = (event as EventStatus).getStatus(rh)
@SuppressLint("SetTextI18n")
textView?.text = (if (textLabel != 0) rh.gs(textLabel) else "") + " " + status
}
)
}
override fun label(label: Int): SWEventListener {
textLabel = label
return this
}
fun initialStatus(status: String): SWEventListener {
this.status = status
return this
}
fun visibility(visibilityValidator: SWValidator): SWEventListener {
this.visibilityValidator = visibilityValidator
return this
}
@SuppressLint("SetTextI18n")
override fun generateDialog(layout: LinearLayout) {
val context = layout.context
textView = TextView(context)
textView?.id = View.generateViewId()
textView?.text = (if (textLabel != 0) rh.gs(textLabel) else "") + " " + status
layout.addView(textView)
}
override fun processVisibility() {
if (visibilityValidator != null && !visibilityValidator!!.isValid) textView?.visibility = View.GONE else textView?.visibility = View.VISIBLE
}
} | agpl-3.0 | 01e96d42052176f2be04437ec2f0f18a | 32.447761 | 148 | 0.6875 | 4.817204 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/ModifyTodoFragment.kt | 1 | 3918 | package com.rolandvitezhu.todocloud.ui.activity.main.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.databinding.FragmentModifytodoBinding
import com.rolandvitezhu.todocloud.helper.hideSoftInput
import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity
import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.DatePickerDialogFragment
import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.ReminderDatePickerDialogFragment
import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.ReminderTimePickerDialogFragment
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.TodosViewModel
class ModifyTodoFragment : Fragment() {
private val todosViewModel by lazy {
ViewModelProvider(requireActivity()).get(TodosViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentModifytodoBinding: FragmentModifytodoBinding =
FragmentModifytodoBinding.inflate(inflater, container, false)
val view: View = fragmentModifytodoBinding.root
fragmentModifytodoBinding.lifecycleOwner = this
fragmentModifytodoBinding.modifyTodoFragment = this
fragmentModifytodoBinding.todosViewModel = todosViewModel
fragmentModifytodoBinding.executePendingBindings()
return view
}
override fun onResume() {
super.onResume()
(activity as MainActivity?)!!.onSetActionBarTitle(getString(R.string.modifytodo_title))
}
/**
* Handle the modify todo action. If the title field is empty, we set the default title because
* it is a required field. If the title field is not empty, we apply the modification which
* the user have made.
*/
fun handleModifyTodo() {
hideSoftInput()
if (todosViewModel.todoTitle.isNullOrBlank()) {
// Set the original title of the todo on the UI. That was the title of the todo
// as we have opened it.
todosViewModel.todoTitle = todosViewModel.originalTitle
} else {
// Apply the modifications which the user did for the todo item. Persist the
// modifications and navigate back to the previous screen.
todosViewModel.onModifyTodo()
(activity as MainActivity?)?.onBackPressed()
}
}
private fun openDatePickerDialogFragment() {
val datePickerDialogFragment = DatePickerDialogFragment()
datePickerDialogFragment.setTargetFragment(this, 0)
datePickerDialogFragment.show(parentFragmentManager, "DatePickerDialogFragment")
}
private fun openReminderDatePickerDialogFragment() {
val reminderDatePickerDialogFragment = ReminderDatePickerDialogFragment()
reminderDatePickerDialogFragment.setTargetFragment(this@ModifyTodoFragment, 0)
reminderDatePickerDialogFragment.show(
parentFragmentManager,
"ReminderDatePickerDialogFragment"
)
}
fun onSelectReminderDate() {
openReminderTimePickerDialogFragment()
}
private fun openReminderTimePickerDialogFragment() {
val reminderTimePickerDialogFragment = ReminderTimePickerDialogFragment()
reminderTimePickerDialogFragment.setTargetFragment(this, 0)
reminderTimePickerDialogFragment.show(
parentFragmentManager,
"ReminderTimePickerDialogFragment"
)
}
fun onDueDateClick() {
openDatePickerDialogFragment()
}
fun onReminderDateTimeClick() {
openReminderDatePickerDialogFragment()
}
} | mit | 639355765cebe0be95a2c7e14fac9c59 | 37.048544 | 99 | 0.728943 | 5.549575 | false | false | false | false |
MaTriXy/android-UniversalMusicPlayer | common/src/main/java/com/example/android/uamp/media/library/BrowseTree.kt | 2 | 6415 | /*
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.content.Context
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.MusicService
import com.example.android.uamp.media.R
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.albumArt
import com.example.android.uamp.media.extensions.albumArtUri
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.flag
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.title
import com.example.android.uamp.media.extensions.trackNumber
import com.example.android.uamp.media.extensions.urlEncoded
/**
* Represents a tree of media that's used by [MusicService.onLoadChildren].
*
* [BrowseTree] maps a media id (see: [MediaMetadataCompat.METADATA_KEY_MEDIA_ID]) to one (or
* more) [MediaMetadataCompat] objects, which are children of that media id.
*
* For example, given the following conceptual tree:
* root
* +-- Albums
* | +-- Album_A
* | | +-- Song_1
* | | +-- Song_2
* ...
* +-- Artists
* ...
*
* Requesting `browseTree["root"]` would return a list that included "Albums", "Artists", and
* any other direct children. Taking the media ID of "Albums" ("Albums" in this example),
* `browseTree["Albums"]` would return a single item list "Album_A", and, finally,
* `browseTree["Album_A"]` would return "Song_1" and "Song_2". Since those are leaf nodes,
* requesting `browseTree["Song_1"]` would return null (there aren't any children of it).
*/
class BrowseTree(context: Context, musicSource: MusicSource) {
private val mediaIdToChildren = mutableMapOf<String, MutableList<MediaMetadataCompat>>()
/**
* Whether to allow clients which are unknown (non-whitelisted) to use search on this
* [BrowseTree].
*/
val searchableByUnknownCaller = true
/**
* In this example, there's a single root node (identified by the constant
* [UAMP_BROWSABLE_ROOT]). The root's children are each album included in the
* [MusicSource], and the children of each album are the songs on that album.
* (See [BrowseTree.buildAlbumRoot] for more details.)
*
* TODO: Expand to allow more browsing types.
*/
init {
val rootList = mediaIdToChildren[UAMP_BROWSABLE_ROOT] ?: mutableListOf()
val recommendedMetadata = MediaMetadataCompat.Builder().apply {
id = UAMP_RECOMMENDED_ROOT
title = context.getString(R.string.recommended_title)
albumArtUri = RESOURCE_ROOT_URI +
context.resources.getResourceEntryName(R.drawable.ic_recommended)
flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE
}.build()
val albumsMetadata = MediaMetadataCompat.Builder().apply {
id = UAMP_ALBUMS_ROOT
title = context.getString(R.string.albums_title)
albumArtUri = RESOURCE_ROOT_URI +
context.resources.getResourceEntryName(R.drawable.ic_album)
flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE
}.build()
rootList += recommendedMetadata
rootList += albumsMetadata
mediaIdToChildren[UAMP_BROWSABLE_ROOT] = rootList
musicSource.forEach { mediaItem ->
val albumMediaId = mediaItem.album.urlEncoded
val albumChildren = mediaIdToChildren[albumMediaId] ?: buildAlbumRoot(mediaItem)
albumChildren += mediaItem
// Add the first track of each album to the 'Recommended' category
if (mediaItem.trackNumber == 1L){
val recommendedChildren = mediaIdToChildren[UAMP_RECOMMENDED_ROOT]
?: mutableListOf()
recommendedChildren += mediaItem
mediaIdToChildren[UAMP_RECOMMENDED_ROOT] = recommendedChildren
}
}
}
/**
* Provide access to the list of children with the `get` operator.
* i.e.: `browseTree\[UAMP_BROWSABLE_ROOT\]`
*/
operator fun get(mediaId: String) = mediaIdToChildren[mediaId]
/**
* Builds a node, under the root, that represents an album, given
* a [MediaMetadataCompat] object that's one of the songs on that album,
* marking the item as [MediaItem.FLAG_BROWSABLE], since it will have child
* node(s) AKA at least 1 song.
*/
private fun buildAlbumRoot(mediaItem: MediaMetadataCompat) : MutableList<MediaMetadataCompat> {
val albumMetadata = MediaMetadataCompat.Builder().apply {
id = mediaItem.album.urlEncoded
title = mediaItem.album
artist = mediaItem.artist
albumArt = mediaItem.albumArt
albumArtUri = mediaItem.albumArtUri.toString()
flag = MediaItem.FLAG_BROWSABLE
}.build()
// Adds this album to the 'Albums' category.
val rootList = mediaIdToChildren[UAMP_ALBUMS_ROOT] ?: mutableListOf()
rootList += albumMetadata
mediaIdToChildren[UAMP_ALBUMS_ROOT] = rootList
// Insert the album's root with an empty list for its children, and return the list.
return mutableListOf<MediaMetadataCompat>().also {
mediaIdToChildren[albumMetadata.id] = it
}
}
}
const val UAMP_BROWSABLE_ROOT = "/"
const val UAMP_EMPTY_ROOT = "@empty@"
const val UAMP_RECOMMENDED_ROOT = "__RECOMMENDED__"
const val UAMP_ALBUMS_ROOT = "__ALBUMS__"
const val MEDIA_SEARCH_SUPPORTED = "android.media.browse.SEARCH_SUPPORTED"
const val RESOURCE_ROOT_URI = "android.resource://com.example.android.uamp.next/drawable/"
| apache-2.0 | 66be6347fec3d621c82336cdc8de19b4 | 40.928105 | 99 | 0.68636 | 4.476622 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ComponentStyleSet.kt | 1 | 1588 | package org.hexworks.zircon.api.component
import org.hexworks.zircon.api.builder.component.ComponentStyleSetBuilder
import org.hexworks.zircon.api.component.data.ComponentState
import org.hexworks.zircon.api.graphics.StyleSet
import kotlin.jvm.JvmStatic
/**
* This interface represents a collection of [StyleSet]s which
* will be used when a [Component]'s [ComponentState] changes.
* @see ComponentState
*/
@Suppress("JVM_STATIC_IN_INTERFACE_1_6")
interface ComponentStyleSet {
val isUnknown: Boolean
get() = this === UNKNOWN
val isNotUnknown: Boolean
get() = isUnknown.not()
/**
* Returns the [StyleSet] for the given `state`.
*/
fun fetchStyleFor(state: ComponentState): StyleSet
companion object {
private val UNKNOWN = newBuilder().build()
/**
* Creates a new [ComponentStyleSetBuilder] for creating styles.
*/
@JvmStatic
fun newBuilder(): ComponentStyleSetBuilder = ComponentStyleSetBuilder.newBuilder()
/**
* Returns the empty [ComponentStyleSet] which uses [StyleSet.defaultStyle]
* for all states.
*/
@JvmStatic
fun defaultStyleSet() = ComponentStyleSetBuilder.newBuilder().build()
/**
* Returns the empty [ComponentStyleSet] which uses [StyleSet.empty]
* for all states.
*/
@JvmStatic
fun empty() = ComponentStyleSetBuilder.newBuilder()
.withDefaultStyle(StyleSet.empty())
.build()
@JvmStatic
fun unknown() = UNKNOWN
}
}
| apache-2.0 | fbaef1a444b4d87e083f6b965bac7794 | 26.859649 | 90 | 0.649874 | 4.812121 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToScopeIntention.kt | 1 | 14659 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.ConvertToScopeIntention.ScopeFunction.*
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
sealed class ConvertToScopeIntention(private val scopeFunction: ScopeFunction) : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("convert.to.0", scopeFunction.functionName)
) {
enum class ScopeFunction(val functionName: String, val isParameterScope: Boolean) {
ALSO(functionName = "also", isParameterScope = true),
APPLY(functionName = "apply", isParameterScope = false),
RUN(functionName = "run", isParameterScope = false),
WITH(functionName = "with", isParameterScope = false);
val receiver = if (isParameterScope) "it" else "this"
}
private data class RefactoringTargetAndItsValueExpression(
val targetElement: PsiElement,
val targetElementValue: PsiElement
)
private data class ScopedFunctionCallAndBlock(
val scopeFunctionCall: KtExpression,
val block: KtBlockExpression
)
override fun isApplicableTo(element: KtExpression, caretOffset: Int) = tryApplyTo(element, dryRun = true)
override fun applyTo(element: KtExpression, editor: Editor?) {
if (!tryApplyTo(element, dryRun = false)) {
val message = RefactoringBundle.getCannotRefactorMessage(
JavaRefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", text)
)
CommonRefactoringUtil.showErrorHint(element.project, editor, message, text, null)
}
}
private fun KtExpression.childOfBlock(): KtExpression? = PsiTreeUtil.findFirstParent(this) {
val parent = it.parent
parent is KtBlockExpression || parent is KtValueArgument
} as? KtExpression
private fun KtExpression.tryGetExpressionToApply(referenceName: String): KtExpression? {
val childOfBlock: KtExpression = childOfBlock() ?: return null
return if (childOfBlock is KtProperty || childOfBlock.isTarget(referenceName)) childOfBlock else null
}
private fun tryApplyTo(element: KtExpression, dryRun: Boolean): Boolean {
val invalidElementToRefactoring = when (element) {
is KtProperty -> !element.isLocal
is KtCallExpression -> false
is KtDotQualifiedExpression -> false
else -> true
}
if (invalidElementToRefactoring) return false
val (referenceElement, referenceName) = element.tryExtractReferenceName() ?: return false
val expressionToApply = element.tryGetExpressionToApply(referenceName) ?: return false
val (firstTarget, lastTarget) = expressionToApply.collectTargetElementsRange(referenceName, greedy = !dryRun) ?: return false
val refactoringTarget = tryGetFirstElementToRefactoring(expressionToApply, firstTarget, lastTarget, referenceElement) ?: return false
if (dryRun) return true
val psiFactory = KtPsiFactory(expressionToApply)
val (scopeFunctionCall, block) = createScopeFunctionCall(
psiFactory,
refactoringTarget.targetElement
) ?: return false
replaceReference(referenceElement, refactoringTarget.targetElementValue, lastTarget, psiFactory)
block.addRange(refactoringTarget.targetElementValue, lastTarget)
if (!scopeFunction.isParameterScope) {
removeRedundantThisQualifiers(block)
}
with(firstTarget) {
parent.addBefore(scopeFunctionCall, this)
parent.deleteChildRange(this, lastTarget)
}
return true
}
private fun removeRedundantThisQualifiers(block: KtBlockExpression) {
val thisDotSomethingExpressions = block.collectDescendantsOfType<KtDotQualifiedExpression> {
it.receiverExpression is KtThisExpression && it.selectorExpression !== null
}
thisDotSomethingExpressions.forEach { thisDotSomethingExpression ->
thisDotSomethingExpression.selectorExpression?.let { selector ->
thisDotSomethingExpression.replace(selector)
}
}
}
private fun tryGetFirstElementToRefactoring(
expressionToApply: KtExpression,
firstTarget: PsiElement,
lastTarget: PsiElement,
referenceElement: PsiElement
): RefactoringTargetAndItsValueExpression? {
val property = expressionToApply.prevProperty()
val propertyOrFirst = when (scopeFunction) {
ALSO, APPLY -> property
RUN, WITH -> firstTarget
} ?: return null
val isCorrectFirstOrProperty = when (scopeFunction) {
ALSO, APPLY -> propertyOrFirst is KtProperty && propertyOrFirst.name !== null && propertyOrFirst.initializer !== null
RUN -> propertyOrFirst is KtDotQualifiedExpression
WITH -> propertyOrFirst is KtDotQualifiedExpression
}
if (!isCorrectFirstOrProperty) return null
val targetElementValue =
property?.nextSibling?.takeIf { it.parent == referenceElement.parent && it.textOffset < lastTarget.textOffset } ?: firstTarget
return RefactoringTargetAndItsValueExpression(propertyOrFirst, targetElementValue)
}
private fun replaceReference(element: PsiElement, firstTarget: PsiElement, lastTarget: PsiElement, psiFactory: KtPsiFactory) {
val replacement by lazy(LazyThreadSafetyMode.NONE) {
if (scopeFunction.isParameterScope)
psiFactory.createSimpleName(scopeFunction.receiver)
else
psiFactory.createThisExpression()
}
val searchParameters = KotlinReferencesSearchParameters(
element, element.useScope(), ignoreAccessScope = false
)
val range = PsiTreeUtil.getElementsOfRange(firstTarget, lastTarget)
ReferencesSearch.search(searchParameters)
.mapNotNull { it.element as? KtNameReferenceExpression }
.filter { reference ->
range.any { rangeElement -> PsiTreeUtil.isAncestor(rangeElement, reference, /* strict = */ true) }
}
.forEach { referenceInRange ->
referenceInRange.replace(replacement)
}
}
private fun KtExpression.tryExtractReferenceName(): Pair<PsiElement, String>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val property = prevProperty()
val name = property?.name
if (name !== null) property to name else null
}
RUN, WITH -> {
val receiver = safeAs<KtDotQualifiedExpression>()?.getLeftMostReceiverExpression() as? KtNameReferenceExpression
val declaration = receiver?.mainReference?.resolve()?.takeUnless { it is PsiPackage } ?: return null
val selector = receiver.getQualifiedExpressionForReceiver()?.selectorExpression
?.let { it.safeAs<KtCallExpression>()?.calleeExpression ?: it } as? KtNameReferenceExpression
if (selector?.mainReference?.resolve() is KtClassOrObject) return null
declaration to receiver.getReferencedName()
}
}
}
private fun KtExpression.collectTargetElementsRange(referenceName: String, greedy: Boolean): Pair<PsiElement, PsiElement>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val firstTarget = this as? KtProperty ?: this.prevProperty() ?: this
val lastTargetSequence = firstTarget.collectTargetElements(referenceName, forward = true)
val lastTarget = if (firstTarget === this)
if (greedy) lastTargetSequence.lastOrNull()
else lastTargetSequence.firstOrNull()
else
if (greedy) lastTargetSequence.lastWithPersistedElementOrNull(elementShouldPersist = this)
else lastTargetSequence.firstOrNull { this === it }
if (lastTarget !== null) firstTarget to lastTarget else null
}
RUN, WITH -> {
val firstTarget = collectTargetElements(referenceName, forward = false).lastOrNull() ?: this
val lastTarget =
if (greedy) collectTargetElements(referenceName, forward = true).lastOrNull() ?: this
else this
firstTarget to lastTarget
}
}
}
private fun KtExpression.collectTargetElements(referenceName: String, forward: Boolean): Sequence<PsiElement> =
siblings(forward, withItself = false)
.filter { it !is PsiWhiteSpace && it !is PsiComment && !(it is LeafPsiElement && it.elementType == KtTokens.SEMICOLON) }
.takeWhile { it.isTarget(referenceName) }
private fun PsiElement.isTarget(referenceName: String): Boolean {
when (this) {
is KtDotQualifiedExpression -> {
val callExpr = callExpression ?: return false
if (callExpr.lambdaArguments.isNotEmpty() ||
callExpr.valueArguments.any { it.text == scopeFunction.receiver }
) return false
val leftMostReceiver = getLeftMostReceiverExpression()
if (leftMostReceiver.text != referenceName) return false
if (leftMostReceiver.mainReference?.resolve() is PsiClass) return false
}
is KtCallExpression -> {
val valueArguments = this.valueArguments
if (valueArguments.none { it.getArgumentExpression()?.text == referenceName }) return false
if (lambdaArguments.isNotEmpty() || valueArguments.any { it.text == scopeFunction.receiver }) return false
}
is KtBinaryExpression -> {
val left = this.left ?: return false
val right = this.right ?: return false
if (left !is KtDotQualifiedExpression && left !is KtCallExpression
&& right !is KtDotQualifiedExpression && right !is KtCallExpression
) return false
if ((left is KtDotQualifiedExpression || left is KtCallExpression) && !left.isTarget(referenceName)) return false
if ((right is KtDotQualifiedExpression || right is KtCallExpression) && !right.isTarget(referenceName)) return false
}
else -> return false
}
return !anyDescendantOfType<KtNameReferenceExpression> { it.text == scopeFunction.receiver }
}
private fun KtExpression.prevProperty(): KtProperty? = childOfBlock()
?.siblings(forward = false, withItself = true)
?.firstOrNull { it is KtProperty && it.isLocal } as? KtProperty
private fun createScopeFunctionCall(factory: KtPsiFactory, element: PsiElement): ScopedFunctionCallAndBlock? {
val scopeFunctionName = scopeFunction.functionName
val (scopeFunctionCall, callExpression) = when (scopeFunction) {
ALSO, APPLY -> {
if (element !is KtProperty) return null
val propertyName = element.name ?: return null
val initializer = element.initializer ?: return null
val initializerPattern = when (initializer) {
is KtDotQualifiedExpression, is KtCallExpression, is KtConstantExpression, is KtParenthesizedExpression -> initializer.text
else -> "(${initializer.text})"
}
val property = factory.createProperty(
name = propertyName,
type = element.typeReference?.text,
isVar = element.isVar,
initializer = "$initializerPattern.$scopeFunctionName {}"
)
val callExpression = (property.initializer as? KtDotQualifiedExpression)?.callExpression ?: return null
property to callExpression
}
RUN -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$0.$scopeFunctionName {}",
element.getLeftMostReceiverExpression()
) as? KtQualifiedExpression ?: return null
val callExpression = scopeFunctionCall.callExpression ?: return null
scopeFunctionCall to callExpression
}
WITH -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$scopeFunctionName($0) {}",
element.getLeftMostReceiverExpression()
) as? KtCallExpression ?: return null
scopeFunctionCall to scopeFunctionCall
}
}
val body = callExpression.lambdaArguments
.firstOrNull()
?.getLambdaExpression()
?.bodyExpression
?: return null
return ScopedFunctionCallAndBlock(scopeFunctionCall, body)
}
}
class ConvertToAlsoIntention : ConvertToScopeIntention(ALSO)
class ConvertToApplyIntention : ConvertToScopeIntention(APPLY)
class ConvertToRunIntention : ConvertToScopeIntention(RUN)
class ConvertToWithIntention : ConvertToScopeIntention(WITH)
| apache-2.0 | b2f3916a6444d88324f8f8b45c4036d5 | 44.383901 | 158 | 0.663961 | 5.930016 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ConventionUtils.kt | 1 | 941 | // 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.intentions.conventionNameCalls
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
fun KtExpression.isAnyEquals(): Boolean {
val resolvedCall = resolveToCall() ?: return false
return (resolvedCall.resultingDescriptor as? FunctionDescriptor)?.isAnyEquals() == true
}
fun FunctionDescriptor.isAnyEquals(): Boolean {
val overriddenDescriptors = findOriginalTopMostOverriddenDescriptors()
return overriddenDescriptors.any { it.fqNameUnsafe.asString() == "kotlin.Any.equals" }
} | apache-2.0 | 27f12915d64a8e1a67705f61835dfb45 | 48.578947 | 158 | 0.817216 | 4.825641 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-10/app-code/app/src/main/java/dev/mfazio/abl/scoreboard/ScoreboardViewModel.kt | 1 | 2129 | package dev.mfazio.abl.scoreboard
import android.app.Application
import androidx.lifecycle.*
import dev.mfazio.abl.data.BaseballDatabase
import dev.mfazio.abl.data.BaseballRepository
import dev.mfazio.abl.teams.UITeam
import dev.mfazio.abl.util.getErrorMessage
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class ScoreboardViewModel(application: Application) : AndroidViewModel(application) {
private val currentDateTextFormat = DateTimeFormatter.ofPattern("EEEE, MMM d")
private val repo: BaseballRepository
private val selectedDate = MutableLiveData(LocalDate.now())
val games: LiveData<List<ScheduledGame>>
val teams: LiveData<List<UITeam>>
val currentDateText: LiveData<String>
val errorMessage = MutableLiveData("")
init {
repo = BaseballDatabase
.getDatabase(application, viewModelScope)
.baseballDao()
.let { dao ->
BaseballRepository.getInstance(dao)
}
games = Transformations.switchMap(selectedDate) { selectedDate ->
refreshScores(selectedDate)
repo.getGamesForDate(selectedDate)
}
teams = Transformations.map(games) { scheduledGames ->
scheduledGames.flatMap { game ->
UITeam.fromTeamIds(game.homeTeamId, game.awayTeamId)
}.filterNotNull()
}
currentDateText = Transformations.map(selectedDate) { currentDate ->
currentDateTextFormat.format(currentDate)
}
}
fun goToDate(daysToMove: Long = 0, monthsToMove: Long? = null) {
selectedDate.value?.let { date ->
selectedDate.value = if (monthsToMove != null) {
date.plusMonths(monthsToMove)
} else {
date.plusDays(daysToMove)
}
}
}
private fun refreshScores(date: LocalDate) {
viewModelScope.launch {
repo.updateGamesForDate(date).getErrorMessage(getApplication())?.let { message ->
errorMessage.value = message
}
}
}
} | apache-2.0 | 8bcf198d2643d164aaa41f47a0ffffdb | 31.272727 | 93 | 0.653358 | 4.974299 | false | false | false | false |
GunoH/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/util/RemoteDevPathConstants.kt | 2 | 475 | package com.intellij.remoteDev.util
val REMOTE_DEV_CACHE_LOCATION = listOf(".cache", "JetBrains", "RemoteDev")
val REMOTE_DEV_IDE_DIR = REMOTE_DEV_CACHE_LOCATION + "dist"
val REMOTE_DEV_CUSTOM_IDE_DIR = REMOTE_DEV_CACHE_LOCATION + "userProvidedDist"
val REMOTE_DEV_RECENT_PROJECTS_DIR = REMOTE_DEV_CACHE_LOCATION + "recent"
val REMOTE_DEV_ACTIVE_PROJECTS_DIR = REMOTE_DEV_CACHE_LOCATION + "active"
const val REMOTE_DEV_EXPAND_SUCCEEDED_MARKER_FILE_NAME = ".expandSucceeded" | apache-2.0 | b4b7501f8faddf1dfaffccb1b5f728f7 | 51.888889 | 78 | 0.770526 | 3.321678 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/navigation/NavigatorWithinProject.kt | 4 | 10079 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.navigation
import com.intellij.ide.IdeBundle
import com.intellij.ide.RecentProjectListActionProvider
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.ReopenProjectAction
import com.intellij.ide.actions.searcheverywhere.SymbolSearchEverywhereContributor
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.getProjectOriginUrl
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.progress.EmptyProgressIndicator
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.project.guessProjectDir
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.psi.PsiElement
import com.intellij.util.PsiNavigateUtil
import com.intellij.util.containers.ComparatorUtil.max
import com.intellij.util.text.nullize
import kotlinx.coroutines.*
import java.io.File
import java.nio.file.Path
import java.util.regex.Pattern
const val NAVIGATE_COMMAND = "navigate"
const val REFERENCE_TARGET = "reference"
const val PROJECT_NAME_KEY = "project"
const val ORIGIN_URL_KEY = "origin"
const val SELECTION = "selection"
suspend fun openProject(parameters: Map<String, String?>): Project? {
val projectName = parameters.get(PROJECT_NAME_KEY)?.nullize(nullizeSpaces = true)
val originUrl = parameters.get(ORIGIN_URL_KEY)?.nullize(nullizeSpaces = true)
if (projectName == null && originUrl == null) {
throw IllegalArgumentException(IdeBundle.message("jb.protocol.navigate.missing.parameters"))
}
ProjectUtil.getOpenProjects().find {
projectName != null && it.name == projectName ||
originUrl != null && areOriginsEqual(originUrl, getProjectOriginUrl(it.guessProjectDir()?.toNioPath()))
}?.let { return it }
val recentProjectAction = RecentProjectListActionProvider.getInstance().getActions().asSequence()
.filterIsInstance(ReopenProjectAction::class.java)
.find {
projectName != null && it.projectName == projectName ||
originUrl != null && areOriginsEqual(originUrl, getProjectOriginUrl(Path.of(it.projectPath)))
} ?: return null
val project = RecentProjectsManagerBase.getInstanceEx().openProject(Path.of(recentProjectAction.projectPath), OpenProjectTask())
?: return null
return withContext(Dispatchers.EDT) {
if (project.isDisposed) {
null
}
else {
val future = CompletableDeferred<Project>()
StartupManager.getInstance(project).runAfterOpened {
future.complete(project)
}
future.join()
project
}
}
}
data class LocationInFile(val line: Int, val column: Int)
typealias LocationToOffsetConverter = (LocationInFile, Editor) -> Int
class NavigatorWithinProject(val project: Project, val parameters: Map<String, String>, locationToOffset_: LocationToOffsetConverter) {
companion object {
private const val FILE_PROTOCOL = "file://"
private const val PATH_GROUP = "path"
private const val LINE_GROUP = "line"
private const val COLUMN_GROUP = "column"
private const val REVISION = "revision"
private val PATH_WITH_LOCATION = Pattern.compile("(?<${PATH_GROUP}>[^:]+)(:(?<${LINE_GROUP}>[\\d]+))?(:(?<${COLUMN_GROUP}>[\\d]+))?")
fun parseNavigationPath(pathText: String): Triple<String?, String?, String?> {
val matcher = PATH_WITH_LOCATION.matcher(pathText)
return if (!matcher.matches()) Triple(null, null, null)
else Triple(matcher.group(PATH_GROUP), matcher.group(LINE_GROUP), matcher.group(COLUMN_GROUP))
}
private fun parseLocationInFile(range: String): LocationInFile? {
val position = range.split(':')
return if (position.size != 2) null
else try {
LocationInFile(position[0].toInt(), position[1].toInt())
}
catch (e: Exception) {
null
}
}
}
val locationToOffset: LocationToOffsetConverter = { locationInFile, editor ->
max(locationToOffset_(locationInFile, editor), 0)
}
enum class NavigationKeyPrefix(val prefix: String) {
FQN("fqn"),
PATH("path");
override fun toString() = prefix
}
private val navigatorByKeyPrefix = mapOf(
(NavigationKeyPrefix.FQN to this::navigateByFqn),
(NavigationKeyPrefix.PATH to this::navigateByPath)
)
private val selections by lazy { parseSelections() }
fun navigate(keysPrefixesToNavigate: List<NavigationKeyPrefix>) {
keysPrefixesToNavigate.forEach { keyPrefix ->
parameters.filterKeys { it.startsWith(keyPrefix.prefix) }.values.forEach { navigatorByKeyPrefix.get(keyPrefix)?.invoke(it) }
}
}
private fun navigateByFqn(reference: String) {
// handle single reference to method: com.intellij.navigation.JBProtocolNavigateCommand#perform
// multiple references are encoded and decoded properly
val fqn = parameters[JBProtocolCommand.FRAGMENT_PARAM_NAME]?.let { "$reference#$it" } ?: reference
runNavigateTask(reference) {
val dataContext = SimpleDataContext.getProjectContext(project)
val searcher = invokeAndWaitIfNeeded {
SymbolSearchEverywhereContributor(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext))
}
Disposer.register(project, searcher)
try {
searcher.search(fqn, EmptyProgressIndicator())
.filterIsInstance<PsiElement>()
.forEach {
invokeLater {
PsiNavigateUtil.navigate(it)
makeSelectionsVisible()
}
}
}
finally {
Disposer.dispose(searcher)
}
}
}
private fun navigateByPath(pathText: String) {
var (path, line, column) = parseNavigationPath(pathText)
if (path == null) {
return
}
val locationInFile = LocationInFile(line?.toInt() ?: 0, column?.toInt() ?: 0)
path = FileUtil.expandUserHome(path)
runNavigateTask(pathText) {
val virtualFile: VirtualFile
if (FileUtil.isAbsolute(path))
virtualFile = findFile(path, parameters[REVISION]) ?: return@runNavigateTask
else
virtualFile = (sequenceOf(project.guessProjectDir()?.path, project.basePath) +
ProjectRootManager.getInstance(project).contentRoots.map { it.path })
.filterNotNull()
.mapNotNull { projectPath -> findFile(File(projectPath, path).absolutePath, parameters[REVISION]) }
.firstOrNull() ?: return@runNavigateTask
ApplicationManager.getApplication().invokeLater {
FileEditorManager.getInstance(project).openFile(virtualFile, true)
.filterIsInstance<TextEditor>().first().let { textEditor ->
performEditorAction(textEditor, locationInFile)
}
}
}
}
private fun runNavigateTask(reference: String, task: (indicator: ProgressIndicator) -> Unit) {
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, IdeBundle.message("navigate.command.search.reference.progress.title", reference), true) {
override fun run(indicator: ProgressIndicator) {
task.invoke(indicator)
}
override fun shouldStartInBackground(): Boolean = !ApplicationManager.getApplication().isUnitTestMode
override fun isConditionalModal(): Boolean = !ApplicationManager.getApplication().isUnitTestMode
}
)
}
private fun performEditorAction(textEditor: TextEditor, locationInFile: LocationInFile) {
val editor = textEditor.editor
editor.caretModel.removeSecondaryCarets()
editor.caretModel.moveToOffset(locationToOffset(locationInFile, editor))
editor.scrollingModel.scrollToCaret(ScrollType.CENTER)
editor.selectionModel.removeSelection()
IdeFocusManager.getGlobalInstance().requestFocus(editor.contentComponent, true)
makeSelectionsVisible()
}
private fun makeSelectionsVisible() {
val editor = FileEditorManager.getInstance(project).selectedTextEditor
selections.forEach {
editor?.selectionModel?.setSelection(
locationToOffset(it.first, editor),
locationToOffset(it.second, editor)
)
}
}
private fun findFile(absolutePath: String?, revision: String?): VirtualFile? {
absolutePath ?: return null
if (revision != null) {
val virtualFile = JBProtocolRevisionResolver.processResolvers(project, absolutePath, revision)
if (virtualFile != null) return virtualFile
}
return VirtualFileManager.getInstance().findFileByUrl(FILE_PROTOCOL + absolutePath)
}
private fun parseSelections(): List<Pair<LocationInFile, LocationInFile>> =
parameters.filterKeys { it.startsWith(SELECTION) }.values.mapNotNull {
val split = it.split('-')
if (split.size != 2) return@mapNotNull null
val startLocation = parseLocationInFile(split[0])
val endLocation = parseLocationInFile(split[1])
if (startLocation != null && endLocation != null) {
return@mapNotNull Pair(startLocation, startLocation)
}
return@mapNotNull null
}
}
| apache-2.0 | 96cd3521806104b21064e05924076a33 | 38.996032 | 137 | 0.715349 | 4.756489 | false | false | false | false |
uramonk/AndroidTemplateApp | app/src/androidTest/java/com/uramonk/androidtemplateapp/domain/GetWeatherListUseCaseTest.kt | 1 | 2459 | package com.uramonk.androidtemplateapp.domain
import com.uramonk.androidtemplateapp.domain.interactor.GetWeatherListUseCase
import com.uramonk.androidtemplateapp.domain.model.Weather
import com.uramonk.androidtemplateapp.domain.model.WeatherList
import com.uramonk.androidtemplateapp.domain.repository.WeatherRepository
import com.uramonk.androidtemplateapp.domain.store.WeatherStore
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.TestScheduler
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import java.util.*
@RunWith(MockitoJUnitRunner::class)
class GetWeatherListUseCaseTest {
private lateinit var useCase: GetWeatherListUseCase
private lateinit var testScheduler: TestScheduler
private lateinit var weatherList: WeatherList
private val weatherRepository: WeatherRepository = mock(WeatherRepository::class.java)
private val weatherStore: WeatherStore = mock(WeatherStore::class.java)
@Before fun setUp() {
testScheduler = TestScheduler()
useCase = GetWeatherListUseCase(weatherRepository, weatherStore)
}
@Test fun testStoreUpdateAfterGetWeather() {
weatherList = WeatherList("base", ArrayList<Weather>(), 0L)
`when`(weatherStore.getValue()).thenReturn(Observable.just(weatherList))
`when`(weatherRepository.getWeatherList()).thenReturn(Observable.just(weatherList))
useCase.executionScheduler(testScheduler).postScheduler(testScheduler).execute(
onNext = Consumer {
assertThat(it).isEqualTo(weatherList)
verify(weatherRepository).getWeatherList()
verify(weatherStore).update(weatherList)
})
testScheduler.triggerActions()
}
@Test fun testStoreUpdateAfterGetLocalData() {
weatherList = WeatherList("base", ArrayList<Weather>(), System.currentTimeMillis())
`when`(weatherStore.getValue()).thenReturn(Observable.just(weatherList))
useCase.executionScheduler(testScheduler).postScheduler(testScheduler).execute(
onNext = Consumer {
assertThat(it).isEqualTo(weatherList)
verify(weatherStore).update(weatherList)
})
testScheduler.triggerActions()
}
}
| mit | e2e390a79b86d723c001b4902eb1316b | 43.709091 | 91 | 0.738918 | 4.774757 | false | true | false | false |
RoyaAoki/Megumin | common/src/main/java/com/sqrtf/common/activity/BaseFragment.kt | 1 | 1958 | package com.sqrtf.common.activity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.sqrtf.common.R
import com.sqrtf.common.api.ApiClient
import com.trello.rxlifecycle2.android.FragmentEvent
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException
open class BaseFragment : RxLifecycleFragment() {
var thisView: View? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.thisView = view
}
protected fun <T : View?> findViewById(resId: Int): T {
return thisView!!.findViewById<T>(resId)
}
protected fun <T> withLifecycle(
observable: Observable<T>,
subscribeOn: Scheduler = Schedulers.io(),
observeOn: Scheduler = AndroidSchedulers.mainThread(),
untilEvent: FragmentEvent = FragmentEvent.DESTROY): Observable<T> {
return observable
.subscribeOn(subscribeOn)
.observeOn(observeOn)
.compose(bindUntilEvent(untilEvent))
}
protected fun ignoreErrors(): Consumer<in Throwable> {
return Consumer {}
}
protected fun toastErrors(): Consumer<in Throwable> {
return Consumer {
var errorMessage = getString(R.string.unknown_error)
if (it is HttpException) {
val body = it.response().errorBody()
val message = body?.let { it1 ->
ApiClient.converterErrorBody(it1)
}
if (message?.message() != null) {
errorMessage = message.message()!!
}
}
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show()
}
}
} | mit | c0f067e37e30a02e5edf84def27f8a37 | 29.138462 | 79 | 0.639428 | 4.834568 | false | false | false | false |
AntonovAlexander/activecore | kernelip/reordex/src/control_structures.kt | 1 | 8653 | /*
* control_structures.kt
*
* Created on: 05.06.2019
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package reordex
import hwast.*
internal abstract class __control_structures(val cyclix_gen : cyclix.Generic,
val MultiExu_CFG : Reordex_CFG,
val CDB_NUM : Int,
val ExecUnits : MutableMap<String, Exu_CFG>,
val exu_descrs : MutableMap<String, __exu_descr>,
val exu_rst : hw_var
) {
var arf_dim = hw_dim_static()
var Backoff_ARF = cyclix_gen.uglobal("Backoff_ARF", arf_dim, "0")
var prf_src_dim = hw_dim_static()
var PRF_src = cyclix_gen.uglobal("genPRF_src", prf_src_dim, "0") // uncomputed PRF sources
init {
arf_dim.add(MultiExu_CFG.RF_width-1, 0)
arf_dim.add(MultiExu_CFG.ARF_depth-1, 0)
}
var states_toRollBack = ArrayList<hw_var>()
abstract fun RollBack()
abstract fun FetchRs(src_tag : hw_param) : hw_var
abstract fun FetchRsRdy(src_prf_index : hw_param) : hw_var
abstract fun FillReadRs(fetch_tag : hw_var, fetch_rdy : hw_var, fetch_data : hw_var, raddr : hw_param)
}
internal class __control_structures_scoreboarding(cyclix_gen : cyclix.Generic,
MultiExu_CFG : Reordex_CFG,
CDB_NUM : Int,
ExecUnits : MutableMap<String, Exu_CFG>,
exu_descrs : MutableMap<String, __exu_descr>,
exu_rst : hw_var
) : __control_structures(cyclix_gen, MultiExu_CFG, CDB_NUM, ExecUnits, exu_descrs, exu_rst) {
var ARF = cyclix_gen.uglobal("genARF", arf_dim, "0")
var ARF_rdy = cyclix_gen.uglobal("genARF_rdy", MultiExu_CFG.ARF_depth-1, 0, hw_imm_ones(MultiExu_CFG.ARF_depth))
val ARF_rdy_prev = cyclix_gen.local("genPRF_mapped_prev", ARF_rdy.vartype, ARF_rdy.defimm)
init {
if (!(MultiExu_CFG.REG_MGMT is REG_MGMT_SCOREBOARDING)) ERROR("Configuration inconsistent!")
prf_src_dim.add(GetWidthToContain(CDB_NUM)-1, 0)
prf_src_dim.add(MultiExu_CFG.ARF_depth-1, 0)
}
fun InitFreeARFRdy() {
cyclix_gen.assign(ARF_rdy_prev, ARF_rdy.readPrev())
}
override fun FetchRs(src_tag : hw_param) : hw_var {
return ARF.GetFracRef(src_tag)
}
override fun FetchRsRdy(src_prf_index : hw_param) : hw_var {
return ARF_rdy.GetFracRef(src_prf_index)
}
override fun FillReadRs(fetch_tag : hw_var, fetch_rdy : hw_var, fetch_data : hw_var, raddr : hw_param) {
cyclix_gen.MSG_COMMENT("Fetching data from architectural registers...")
fetch_tag.assign(raddr)
fetch_rdy.assign(FetchRsRdy(fetch_tag))
fetch_data.assign(FetchRs(fetch_tag))
cyclix_gen.MSG_COMMENT("Fetching data from architectural registers: done")
}
fun ReserveRd(rd_tag : hw_param) {
cyclix_gen.assign(ARF_rdy.GetFracRef(rd_tag), 0)
}
fun WriteARF(rd_tag : hw_param, src_wdata : hw_param) {
cyclix_gen.assign(ARF_rdy.GetFracRef(rd_tag), 1)
cyclix_gen.assign(ARF.GetFracRef(rd_tag), src_wdata)
}
override fun RollBack() {
cyclix_gen.assign(exu_rst, 1)
cyclix_gen.assign(ARF_rdy, ARF_rdy.defimm)
//cyclix_gen.assign(ARF_map, ARF_map_default) // TODO: fix error
cyclix_gen.assign(PRF_src, PRF_src.defimm)
for (reg_idx in 0 until Backoff_ARF.GetWidth()) {
cyclix_gen.assign(ARF.GetFracRef(reg_idx), Backoff_ARF.GetFracRef(reg_idx))
}
for (state in states_toRollBack) {
cyclix_gen.assign(state, state.defimm)
}
}
}
internal class __control_structures_renaming(cyclix_gen : cyclix.Generic,
MultiExu_CFG : Reordex_CFG,
CDB_NUM : Int,
ExecUnits : MutableMap<String, Exu_CFG>,
exu_descrs : MutableMap<String, __exu_descr>,
exu_rst : hw_var
) : __control_structures(cyclix_gen, MultiExu_CFG, CDB_NUM, ExecUnits, exu_descrs, exu_rst) {
var prf_dim = hw_dim_static()
var PRF = cyclix_gen.uglobal("genPRF", prf_dim, "0")
var PRF_mapped = cyclix_gen.uglobal("genPRF_mapped", (MultiExu_CFG.REG_MGMT as REG_MGMT_RENAMING).PRF_depth-1, 0, hw_imm_ones(MultiExu_CFG.ARF_depth))
var PRF_rdy = cyclix_gen.uglobal("genPRF_rdy", (MultiExu_CFG.REG_MGMT as REG_MGMT_RENAMING).PRF_depth-1, 0, hw_imm_ones(MultiExu_CFG.REG_MGMT.PRF_depth))
var arf_map_dim = hw_dim_static()
var ARF_map_default = hw_imm_arr(arf_map_dim)
var ARF_map = cyclix_gen.uglobal("genARF_map", arf_map_dim, ARF_map_default) // ARF-to-PRF mappings
val PRF_mapped_prev = cyclix_gen.local("genPRF_mapped_prev", PRF_mapped.vartype, PRF_mapped.defimm)
init {
if (!(MultiExu_CFG.REG_MGMT is REG_MGMT_RENAMING)) ERROR("Configuration inconsistent!")
prf_dim.add(MultiExu_CFG.RF_width-1, 0)
prf_dim.add((MultiExu_CFG.REG_MGMT as REG_MGMT_RENAMING).PRF_depth-1, 0)
arf_map_dim.add(MultiExu_CFG.PRF_addr_width-1, 0)
arf_map_dim.add(MultiExu_CFG.ARF_depth-1, 0)
for (RF_idx in 0 until (MultiExu_CFG.REG_MGMT as REG_MGMT_RENAMING).PRF_depth) {
if (RF_idx < MultiExu_CFG.ARF_depth) {
ARF_map_default.AddSubImm(RF_idx.toString())
} else {
ARF_map_default.AddSubImm("0")
}
}
prf_src_dim.add(GetWidthToContain(CDB_NUM)-1, 0)
prf_src_dim.add(MultiExu_CFG.REG_MGMT.PRF_depth-1, 0)
}
fun RenameReg(src_addr : hw_param) : hw_var {
return ARF_map.GetFracRef(src_addr)
}
override fun FetchRs(src_tag : hw_param) : hw_var {
return PRF.GetFracRef(src_tag)
}
override fun FetchRsRdy(src_prf_index : hw_param) : hw_var {
return PRF_rdy.GetFracRef(src_prf_index)
}
override fun FillReadRs(fetch_tag : hw_var, fetch_rdy : hw_var, fetch_data : hw_var, raddr : hw_param) {
cyclix_gen.MSG_COMMENT("Fetching data from physical registers...")
fetch_tag.assign(RenameReg(raddr))
fetch_rdy.assign(FetchRsRdy(fetch_tag))
fetch_data.assign(FetchRs(fetch_tag))
cyclix_gen.MSG_COMMENT("Fetching data from physical registers: done")
}
fun InitFreePRFBuf() {
cyclix_gen.assign(PRF_mapped_prev, PRF_mapped.readPrev())
}
fun GetFreePRF() : hw_astc.bit_position {
return cyclix_gen.min0(PRF_mapped_prev, 4)
}
fun ReserveRd(rd_addr : hw_param, rd_tag : hw_param) {
cyclix_gen.assign(ARF_map.GetFracRef(rd_addr), rd_tag)
cyclix_gen.assign(PRF_mapped.GetFracRef(rd_tag), 1)
cyclix_gen.assign(PRF_mapped_prev.GetFracRef(rd_tag), 1)
cyclix_gen.assign(PRF_rdy.GetFracRef(rd_tag), 0)
}
fun ReserveWriteRd(src_rd : hw_param, src_tag : hw_param, src_wdata : hw_param) {
cyclix_gen.assign(ARF_map.GetFracRef(src_rd), src_tag)
cyclix_gen.assign(PRF_mapped.GetFracRef(src_tag), 1)
cyclix_gen.assign(PRF_mapped_prev.GetFracRef(src_tag), 1)
cyclix_gen.assign(PRF_rdy.GetFracRef(src_tag), 1)
cyclix_gen.assign(PRF.GetFracRef(src_tag), src_wdata)
}
fun WritePRF(rd_tag : hw_param, src_wdata : hw_param) {
cyclix_gen.assign(PRF_rdy.GetFracRef(rd_tag), 1)
cyclix_gen.assign(PRF.GetFracRef(rd_tag), src_wdata)
}
fun FreePRF(src_tag : hw_param) {
cyclix_gen.assign(
PRF_mapped.GetFracRef(src_tag),
0)
}
override fun RollBack() {
cyclix_gen.assign(exu_rst, 1)
cyclix_gen.assign(PRF_mapped, PRF_mapped.defimm)
cyclix_gen.assign(PRF_rdy, PRF_rdy.defimm)
//cyclix_gen.assign(ARF_map, ARF_map_default) // TODO: fix error
for (reg_idx in 0 until ARF_map.GetWidth()) {
cyclix_gen.assign(ARF_map.GetFracRef(reg_idx), hw_imm(reg_idx))
}
cyclix_gen.assign(PRF_src, PRF_src.defimm)
for (reg_idx in 0 until Backoff_ARF.GetWidth()) {
cyclix_gen.assign(PRF.GetFracRef(reg_idx), Backoff_ARF.GetFracRef(reg_idx))
}
for (state in states_toRollBack) {
cyclix_gen.assign(state, state.defimm)
}
}
} | apache-2.0 | bef7eccd23e8a0a09ce59381afc8ee49 | 39.439252 | 157 | 0.587889 | 3.195347 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/chat/ChatComponent.kt | 1 | 6716 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.chat
import com.mcmoonlake.api.packet.PacketOutChat
import com.mcmoonlake.api.player.MoonLakePlayer
import org.bukkit.entity.Player
/**
* ## ChatComponent (聊天组件)
*
* * `JSON` operations component for minecraft client and server chat communication. [Details](https://minecraft.gamepedia.com/Commands#Raw_JSON_text)
* * Minecraft 客户端和服务端聊天通信的 `JSON` 操作组件. [详情](https://minecraft.gamepedia.com/Commands#Raw_JSON_text)
*
* @see [ChatSerializer]
* @see [ChatComponentFancy]
* @see [ChatComponentAbstract]
* @see [ChatComponentText]
* @see [ChatComponentTranslation]
* @see [ChatComponentScore]
* @see [ChatComponentSelector]
* @see [ChatComponentKeybind]
* @author lgou2w
* @since 2.0
*/
interface ChatComponent {
/**
* * Gets or sets the style of this chat component.
* * 获取或设置此聊天组件的样式.
*
* @see [setStyle]
* @see [ChatStyle]
*/
var style: ChatStyle
/**
* * Sets the style of this chat component. If `null` then use the default.
* * 获取或设置此聊天组件的样式. 如果为 `null` 则使用默认.
*
* @param style Chat style.
* @param style 聊天样式.
* @see [ChatStyle]
*/
fun setStyle(style: ChatStyle?): ChatComponent
/**
* * Get a list of extra component for this chat component.
* * 获取此聊天组件的附加组件列表.
*/
val extras: MutableList<ChatComponent>
/**
* * Get a size of extra component for this chat component.
* * 获取此聊天组件的附加组件大小.
*/
val extraSize: Int
/**
* * Appends the given string as a [ChatComponentText] to the list of extra component.
* * 将给定字符串以 [ChatComponentText] 追加到附加组件列表.
*
* @see [ChatComponentText]
* @param text Append string.
* @param text 追加字符串.
*/
fun append(text: String): ChatComponent
/**
* * Appends the given chat component to the list of extra component.
* * 将给定聊天组件追加到附加组件列表.
*
* @param extra Extra component.
* @param extra 附加组件.
*/
fun append(extra: ChatComponent): ChatComponent
/**
* * Convert this chat component to a `JSON` string.
* * 将此聊天组件转换为 `JSON` 字符串.
*
* @see [ChatSerializer.toJson]
*/
fun toJson(): String
/**
* * Convert this chat component to a raw string.
* * 将此聊天组件转换为源字符串.
*
* @see [ChatSerializer.toRaw]
* @param color Whether it has a color.
* @param color 是否拥有颜色.
*/
fun toRaw(color: Boolean = true): String
/**
* * Send this chat component to a given player.
* * 将此聊天组件发送到给定的玩家.
*
* @see [PacketOutChat]
* @param player Player.
* @param player 玩家.
* @param action Chat action.
* @param action 聊天交互.
*/
fun send(player: Player, action: ChatAction = ChatAction.CHAT)
/**
* * Send this chat component to a given moonlake player.
* * 将此聊天组件发送到给定的月色之湖玩家.
*
* @see [send]
* @see [PacketOutChat]
* @param player MoonLake player.
* @param player 月色之湖玩家.
* @param action Chat action.
* @param action 聊天交互.
*/
fun send(player: MoonLakePlayer, action: ChatAction = ChatAction.CHAT)
/**
* @see [append]
*/
operator fun plus(text: String): ChatComponent
/**
* @see [append]
*/
operator fun plus(extra: ChatComponent): ChatComponent
companion object {
/**
* * ### Null of ChatComponent
*
* - #### Sample:
* - `println(ChatComponent.NULL == null) // false`
* - `println(ChatComponent.NULL == ChatComponent) // false`
* - `println(ChatComponent.NULL is ChatComponent) // true`
*/
val NULL: ChatComponent by lazy {
object: ChatComponent {
override var style: ChatStyle
get() = throw UnsupportedOperationException()
set(value) = throw UnsupportedOperationException()
override fun setStyle(style: ChatStyle?): ChatComponent
= throw UnsupportedOperationException()
override val extras: MutableList<ChatComponent>
get() = throw UnsupportedOperationException()
override val extraSize: Int
get() = 0
override fun append(text: String): ChatComponent
= throw UnsupportedOperationException()
override fun append(extra: ChatComponent): ChatComponent
= throw UnsupportedOperationException()
override fun toJson(): String
= throw UnsupportedOperationException()
override fun toRaw(color: Boolean): String
= throw UnsupportedOperationException()
override fun send(player: MoonLakePlayer, action: ChatAction)
= throw UnsupportedOperationException()
override fun send(player: Player, action: ChatAction)
= throw UnsupportedOperationException()
override fun plus(text: String): ChatComponent
= throw UnsupportedOperationException()
override fun plus(extra: ChatComponent): ChatComponent
= throw UnsupportedOperationException()
override fun toString(): String
= "ChatComponent(NULL)"
override fun hashCode(): Int
= 0
override fun equals(other: Any?): Boolean
= other === NULL
}
}
}
}
| gpl-3.0 | f93602a48a6c44044ffd0105291b923d | 31.984293 | 150 | 0.600635 | 4.253883 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/utils/extensions/ViewExtensions.kt | 1 | 4442 | package com.ashish.movieguide.utils.extensions
import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.support.v4.util.Pair
import android.support.v4.view.ViewCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewAnimationUtils
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import com.ashish.movieguide.R
/**
* Created by Ashish on Dec 27.
*/
inline fun <reified T : View> View.find(id: Int): T = findViewById(id) as T
fun View.setVisibility(visible: Boolean) {
if (visible) show() else hide()
}
fun View.show() {
if (visibility != VISIBLE) visibility = VISIBLE
}
fun View.hide(viewGone: Boolean = true) {
visibility = if (viewGone) GONE else INVISIBLE
}
fun View.showSnackBar(messageId: Int, duration: Int = Snackbar.LENGTH_LONG,
@StringRes actionBtnTextId: Int = android.R.string.ok, action: (() -> Unit)? = null) {
val snackbar = Snackbar.make(this, messageId, duration)
.setAction(actionBtnTextId, { action?.invoke() })
snackbar.changeSnackBarFont(android.support.design.R.id.snackbar_text)
snackbar.changeSnackBarFont(android.support.design.R.id.snackbar_action)
snackbar.view.setBackgroundColor(context.getColorCompat(R.color.primary_gradient_end_color))
snackbar.show()
}
fun Snackbar.changeSnackBarFont(viewId: Int) = view.find<TextView>(viewId).changeTypeface()
fun View.animateBackgroundColorChange(startColor: Int, endColor: Int) {
animateColorChange(startColor, endColor, onAnimationUpdate = { setBackgroundColor(it) })
}
inline fun animateColorChange(startColor: Int, endColor: Int, duration: Long = 800L,
crossinline onAnimationUpdate: (color: Int) -> Unit) {
if (startColor != endColor) {
val colorAnimator = ValueAnimator.ofArgb(startColor, endColor)
colorAnimator.apply {
this.duration = duration
interpolator = FastOutSlowInInterpolator()
addUpdateListener { animation -> onAnimationUpdate(animation.animatedValue as Int) }
start()
}
}
}
fun View.getPosterImagePair(@StringRes transitionNameId: Int): Pair<View, String>? {
val posterImageView = findViewById(R.id.poster_image)
return if (posterImageView != null) Pair.create(posterImageView, context.getString(transitionNameId)) else null
}
@SuppressLint("InlinedApi")
fun View.setLightStatusBar() {
isMarshmallowOrAbove {
var flags = systemUiVisibility
flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
systemUiVisibility = flags
}
}
fun View.setTransitionName(@StringRes transitionNameId: Int) {
ViewCompat.setTransitionName(this, context.getString(transitionNameId))
}
fun View?.showKeyboard() {
if (this == null) return
requestFocus()
val imm = context.inputMethodManager!!
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
imm.showSoftInput(this, 0)
if (!imm.isActive(this)) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
inline fun View.startCircularRevealAnimation(cx: Int, cy: Int, startRadius: Float, endRadius: Float,
duration: Long = 400L, crossinline animationEnd: () -> Unit) {
val animator = ViewAnimationUtils.createCircularReveal(this, cx, cy, startRadius, endRadius)
animator.duration = duration
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationEnd(animation: Animator?) = animationEnd()
override fun onAnimationCancel(animation: Animator?) = animationEnd()
override fun onAnimationRepeat(animation: Animator?) {}
})
show()
animator.start()
}
inline fun View.onLayoutLaid(crossinline action: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
action.invoke()
}
})
} | apache-2.0 | bfca17cef6633c53de7dd010d3ad632a | 33.984252 | 115 | 0.721297 | 4.433134 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestChangesComponent.kt | 1 | 2959 | // 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.plugins.github.pullrequest.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.ui.ComponentWithEmptyText
import java.awt.BorderLayout
import javax.swing.border.Border
import kotlin.properties.Delegates
internal class GithubPullRequestChangesComponent(project: Project) : GithubDataLoadingComponent<List<Change>>(), Disposable {
private val changesBrowser = PullRequestChangesBrowserWithError(project)
private val loadingPanel = JBLoadingPanel(BorderLayout(), this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
val diffAction = changesBrowser.diffAction
init {
loadingPanel.add(changesBrowser, BorderLayout.CENTER)
changesBrowser.emptyText.text = DEFAULT_EMPTY_TEXT
setContent(loadingPanel)
}
override fun reset() {
changesBrowser.emptyText.text = DEFAULT_EMPTY_TEXT
changesBrowser.changes = emptyList()
}
override fun handleResult(result: List<Change>) {
changesBrowser.emptyText.text = "Pull request does not contain any changes"
changesBrowser.changes = result
}
override fun handleError(error: Throwable) {
changesBrowser.emptyText
.clear()
.appendText("Cannot load changes", SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(error.message ?: "Unknown error", SimpleTextAttributes.ERROR_ATTRIBUTES, null)
}
override fun setBusy(busy: Boolean) {
if (busy) {
changesBrowser.emptyText.clear()
loadingPanel.startLoading()
}
else {
loadingPanel.stopLoading()
}
}
override fun dispose() {}
companion object {
//language=HTML
private const val DEFAULT_EMPTY_TEXT = "Select pull request to view list of changed files"
private class PullRequestChangesBrowserWithError(project: Project)
: ChangesBrowserBase(project, false, false), ComponentWithEmptyText {
var changes: List<Change> by Delegates.observable(listOf()) { _, _, _ ->
myViewer.rebuildTree()
}
init {
init()
}
override fun buildTreeModel() = TreeModelBuilder.buildFromChanges(myProject, grouping, changes, null)
override fun onDoubleClick() {
if (canShowDiff()) super.onDoubleClick()
}
override fun getEmptyText() = myViewer.emptyText
override fun createViewerBorder(): Border = IdeBorderFactory.createBorder(SideBorder.TOP)
}
}
} | apache-2.0 | 9dc560df5ced941eaae22019987570eb | 33.022989 | 140 | 0.752957 | 4.696825 | false | false | false | false |
chromeos/video-decode-encode-demo | app/src/main/java/dev/hadrosaur/videodecodeencodedemo/MainActivity.kt | 1 | 28155 | /*
* Copyright (c) 2020 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 dev.hadrosaur.videodecodeencodedemo
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.KeyEvent.*
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
import dev.hadrosaur.videodecodeencodedemo.AudioHelpers.AudioBufferManager
import dev.hadrosaur.videodecodeencodedemo.AudioHelpers.AudioMainTrack
import dev.hadrosaur.videodecodeencodedemo.AudioHelpers.AudioMixTrack
import dev.hadrosaur.videodecodeencodedemo.Utils.*
import dev.hadrosaur.videodecodeencodedemo.VideoHelpers.FpsStats
import dev.hadrosaur.videodecodeencodedemo.VideoHelpers.VideoSurfaceManager
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.text.DecimalFormat
const val NUMBER_OF_STREAMS = 4
// TODO: replace this with proper file loading
const val VIDEO_RES_1 = R.raw.paris_01_1080p
const val VIDEO_RES_2 = R.raw.paris_02_1080p
const val VIDEO_RES_3 = R.raw.paris_03_1080p
const val VIDEO_RES_4 = R.raw.paris_04_1080p
class MainActivity : AppCompatActivity() {
// Preview surfaces
// TODO: Revisit the "To Delete" logic and make sure it is still necessary. Possibly remove it.
private var previewSurfaceViews = ArrayList<SurfaceView>()
private var previewSurfaceViewsToDelete = ArrayList<SurfaceView>()
// Counter to track if all surfaces are ready
private var numberOfReadySurfaces = 0
private var activeDecodes = 0
private var activeEncodes = 0
// Managers for internal surfaces
private var videoSurfaceManagers = ArrayList<VideoSurfaceManager>()
private var videoSurfaceManagersToDelete = ArrayList<VideoSurfaceManager>()
// Managers for audio buffers used for encoding
private var encodeAudioBufferManagers = ArrayList<AudioBufferManager>()
// The main audio mixdown track
private var audioMainTrack = AudioMainTrack()
// Audio / Video encoders
var audioVideoEncoders = ArrayList<AudioVideoEncoder>()
// ExoPlayers
val exoPlayers = arrayOfNulls<ExoPlayer>(NUMBER_OF_STREAMS)
// The GlManager manages the eglcontext for all renders and filters
private val glManager = GlManager()
val viewModel: MainViewModel by viewModels()
companion object {
const val LOG_VIDEO_EVERY_N_FRAMES = 300 // Log dropped frames and fps every N frames
const val LOG_AUDIO_EVERY_N_FRAMES = 500 // Log dropped frames and fps every N frames
const val MIN_DECODE_BUFFER_MS = 68 // Roughly 2 frames at 30fps.
const val LOG_TAG = "VideoDemo"
const val FILE_PREFIX = "VideoDemo"
var CAN_WRITE_FILES = false // Used to check if file write permissions have been granted
// Convenience logging function
fun logd(message: String) {
Log.d(LOG_TAG, message)
}
}
private fun initializeEncoders() {
// Free up old encoders and audio buffer managers
releaseEncoders()
// Stream 1
encodeAudioBufferManagers.add(AudioBufferManager())
audioVideoEncoders.add(AudioVideoEncoder(viewModel, videoSurfaceManagers[0].renderer.frameLedger, encodeAudioBufferManagers[0]))
// Stream 2 - 4 not currently permitted to encode
// Stream 2
// audioBufferManagers.add(AudioBufferManager())
// audioVideoEncoders.add(AudioVideoEncoder(viewModel, videoSurfaceManagers[1].renderer.frameLedger, audioBufferManagers[1]))
// Stream 3
// audioBufferManagers.add(AudioBufferManager())
// audioVideoEncoders.add(AudioVideoEncoder(viewModel, videoSurfaceManagers[2].renderer.frameLedger, audioBufferManagers[2]))
// Stream 4
// audioBufferManagers.add(AudioBufferManager())
// audioVideoEncoders.add(AudioVideoEncoder(viewModel, videoSurfaceManagers[3].renderer.frameLedger, audioBufferManagers[3]))
}
private fun initializeSurfaces() {
numberOfReadySurfaces = 0
// Create the preview surfaces
for (n in 0..NUMBER_OF_STREAMS) {
previewSurfaceViews.add(SurfaceView(this))
}
// Setup surface listeners to indicate when surfaces have been created/destroyed
for (n in 0..NUMBER_OF_STREAMS) {
previewSurfaceViews[n].holder.addCallback(VideoSurfaceViewListener(this))
}
// Create the internal SurfaceTextures that will be used for decoding
initializeInternalSurfaces()
// Add the preview surfaces to the UI
frame_one.addView(previewSurfaceViews[0])
frame_two.addView(previewSurfaceViews[1])
frame_three.addView(previewSurfaceViews[2])
frame_four.addView(previewSurfaceViews[3])
}
// Create the internal SurfaceTextures that will be used for decoding
private fun initializeInternalSurfaces() {
// Clean-up any surfaces that need deletion
releaseSurfacesMarkedForDeletion()
// Empty and free current arrays of surface managers
videoSurfaceManagers.clear()
for (n in 0..NUMBER_OF_STREAMS) {
videoSurfaceManagers.add(VideoSurfaceManager(viewModel, glManager, previewSurfaceViews[n], n))
}
}
/**
* To start a new test, fresh surfaces are needed but do not garbage collect them until the next
* time "Decode" is pressed.
*/
private fun markSurfacesForDeletion() {
// Point deletion handles to the old arrays of managers/views
previewSurfaceViewsToDelete = previewSurfaceViews
videoSurfaceManagersToDelete = videoSurfaceManagers
// Set up new arrays for the fresh managers/views
previewSurfaceViews = ArrayList()
videoSurfaceManagers = ArrayList()
}
/**
* Clear any surfaces/managers marked for deletion
*/
private fun releaseSurfacesMarkedForDeletion() {
previewSurfaceViewsToDelete.clear()
previewSurfaceViewsToDelete = ArrayList()
for (manager in videoSurfaceManagersToDelete) {
manager.release()
}
videoSurfaceManagersToDelete.clear()
videoSurfaceManagersToDelete = ArrayList()
}
// Empty and free current arrays encoders and audio managers
private fun releaseEncoders() {
encodeAudioBufferManagers.clear()
for (encoder in audioVideoEncoders) {
encoder.release()
}
audioVideoEncoders.clear()
}
private fun release() {
releaseSurfacesMarkedForDeletion()
releaseEncoders()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set up encoder default formats
setDefaultEncoderFormats(this, viewModel)
// Set up output directory for muxer
viewModel.encodeOutputDir = getAppSpecificVideoStorageDir(this, viewModel, FILE_PREFIX)
// Set up preview surfaces as well as internal, non-visible decoding surfaces
initializeSurfaces()
// Request file read/write permissions need to save encodes.
if (checkPermissions()) {
CAN_WRITE_FILES = true
} else {
updateLog("File permissions not granted. Encoding will not save to file.")
}
// Set up preview frame frequency seekbar
seek_framedelay.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
viewModel.setPreviewFrameFrequency(progress)
runOnUiThread {
text_frame_delay.text = "Preview every ${progress} frames"
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
viewModel.getPreviewFrameFrequency().observe(this, { frameFrequency ->
seek_framedelay.progress = frameFrequency
})
// Set up on-screen log
viewModel.getLogText().observe(this, { logText ->
runOnUiThread {
updateLog(logText)
}
})
// Set up decode checkboxes
checkbox_decode_stream1.setOnCheckedChangeListener{
_, isChecked -> viewModel.setDecodeStream1(isChecked) }
viewModel.getDecodeStream1().observe(this, {
isChecked -> checkbox_decode_stream1.isSelected = isChecked })
checkbox_decode_stream2.setOnCheckedChangeListener{
_, isChecked -> viewModel.setDecodeStream2(isChecked) }
viewModel.getDecodeStream2().observe(this, {
isChecked -> checkbox_decode_stream2.isSelected = isChecked })
checkbox_decode_stream3.setOnCheckedChangeListener{
_, isChecked -> viewModel.setDecodeStream3(isChecked) }
viewModel.getDecodeStream3().observe(this, {
isChecked -> checkbox_decode_stream3.isSelected = isChecked })
checkbox_decode_stream4.setOnCheckedChangeListener{
_, isChecked -> viewModel.setDecodeStream4(isChecked) }
viewModel.getDecodeStream4().observe(this, {
isChecked -> checkbox_decode_stream4.isSelected = isChecked })
// Set up toggle switches for encode, audio, filters, etc.
switch_filter.setOnCheckedChangeListener {
_, isChecked -> viewModel.setApplyGlFilter(isChecked) }
viewModel.getApplyGlFilter().observe(this, {
applyFilter -> switch_filter.isSelected = applyFilter })
switch_encode.setOnCheckedChangeListener {
_, isChecked -> viewModel.setEncodeStream1(isChecked) }
viewModel.getEncodeStream1().observe(this, {
encodeStream -> switch_encode.isSelected = encodeStream })
switch_audio.setOnCheckedChangeListener {
_, isChecked -> viewModel.setPlayAudio(isChecked) }
viewModel.getPlayAudio().observe(this) { playAudio ->
switch_audio.isSelected = playAudio
audioMainTrack.mute(!playAudio)
}
switch_loop.setOnCheckedChangeListener {
_, isChecked -> viewModel.setLoop(isChecked) }
viewModel.getLoop().observe(this, {
loop -> switch_loop.isSelected = loop
for (n in 0..NUMBER_OF_STREAMS-1) {
if (exoPlayers[n] != null) {
exoPlayers[n]?.repeatMode =
if (loop) ExoPlayer.REPEAT_MODE_ONE else ExoPlayer.REPEAT_MODE_OFF
}
}
})
// Setup FPS indicators
viewModel.getFps1().observe(this, { fps ->
updateFpsIndicator(text_fps_1, image_fps_indicator_1, fps)
})
viewModel.getIsChoppy1().observe(this, { isChoppy ->
text_fps_choppy_1.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps2().observe(this, { fps ->
updateFpsIndicator(text_fps_2, image_fps_indicator_2, fps)
})
viewModel.getIsChoppy2().observe(this, { isChoppy ->
text_fps_choppy_2.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps3().observe(this, { fps ->
updateFpsIndicator(text_fps_3, image_fps_indicator_3, fps)
})
viewModel.getIsChoppy3().observe(this, { isChoppy ->
text_fps_choppy_3.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps4().observe(this, { fps ->
updateFpsIndicator(text_fps_4, image_fps_indicator_4, fps)
})
viewModel.getIsChoppy4().observe(this, { isChoppy ->
text_fps_choppy_4.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
// Set up cancel button
button_cancel.isEnabled = false // Will be the opposite of Decode button
button_cancel.setOnClickListener {
for (n in 0..NUMBER_OF_STREAMS-1) {
if (exoPlayers[n] != null) {
exoPlayers[n]?.release()
exoPlayers[n] = null
decodeFinished()
}
}
}
// Setup FPS indicators
viewModel.getFps1().observe(this, { fps ->
updateFpsIndicator(text_fps_1, image_fps_indicator_1, fps)
})
viewModel.getIsChoppy1().observe(this, { isChoppy ->
text_fps_choppy_1.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps2().observe(this, { fps ->
updateFpsIndicator(text_fps_2, image_fps_indicator_2, fps)
})
viewModel.getIsChoppy2().observe(this, { isChoppy ->
text_fps_choppy_2.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps3().observe(this, { fps ->
updateFpsIndicator(text_fps_3, image_fps_indicator_3, fps)
})
viewModel.getIsChoppy3().observe(this, { isChoppy ->
text_fps_choppy_3.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
viewModel.getFps4().observe(this, { fps ->
updateFpsIndicator(text_fps_4, image_fps_indicator_4, fps)
})
viewModel.getIsChoppy4().observe(this, { isChoppy ->
text_fps_choppy_4.visibility = if (isChoppy) VISIBLE else INVISIBLE
})
// Set up cancel button
button_cancel.isEnabled = false // Will be the opposite of Decode button
button_cancel.setOnClickListener {
for (n in 0..NUMBER_OF_STREAMS-1) {
if (exoPlayers[n] != null) {
exoPlayers[n]?.release()
exoPlayers[n] = null
decodeFinished()
}
}
}
// Set up decode button
button_start_decode.setOnClickListener {
button_start_decode.isEnabled = false
button_cancel.isEnabled = true
// Release any old surfaces marked for deletion
releaseSurfacesMarkedForDeletion()
// Stream 1
if (viewModel.getDecodeStream1Val()) {
// Are we encoding this run?
if (viewModel.getEncodeStream1Val()) {
// Set-up an observer so the AudioVideoEncoder can signal the encode is complete
// through the view model
viewModel.getEncodingInProgress().value = true // Set this directly (not post) so the observer doesn't trigger immediately
viewModel.getEncodingInProgress().observe(this, {
inProgress -> if(inProgress == false) encodeFinished() })
activeEncodes++
// Set up encoder and audio buffer manager
initializeEncoders()
// Decode and Encode
beginVideoDecode(VIDEO_RES_1, videoSurfaceManagers[0], 0,
audioVideoEncoders[0], encodeAudioBufferManagers[0])
} else {
// Decode only
beginVideoDecode(VIDEO_RES_1, videoSurfaceManagers[0], 0)
}
}
// Stream 2
if (viewModel.getDecodeStream2Val()) {
beginVideoDecode(VIDEO_RES_2, videoSurfaceManagers[1], 1)
}
// Stream 3
if (viewModel.getDecodeStream3Val()) {
beginVideoDecode(VIDEO_RES_3, videoSurfaceManagers[2], 2)
}
// Stream 4
if (viewModel.getDecodeStream4Val()) {
beginVideoDecode(VIDEO_RES_4, videoSurfaceManagers[3], 3)
}
// Initialize main audio track as muted or unmuted
audioMainTrack.mute(!viewModel.getPlayAudioVal())
GlobalScope.launch(Dispatchers.Default) {
audioMainTrack.start()
}
}
// TODO: Add option to swap out input video files
// TODO: Add checkboxes to allow encodes for all streams
}
override fun onStop() {
release()
super.onStop()
}
override fun onDestroy() {
glManager.release()
super.onDestroy()
}
/**
* Handy keyboard shortcuts
*/
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
when (keyCode) {
// 1 - 4 : Toggle decode checkboxes
KEYCODE_1 -> { checkbox_decode_stream1.isChecked = ! checkbox_decode_stream1.isChecked; checkbox_decode_stream1.clearFocus(); return true }
KEYCODE_2 -> { checkbox_decode_stream2.isChecked = ! checkbox_decode_stream2.isChecked; checkbox_decode_stream2.clearFocus(); return true }
KEYCODE_3 -> { checkbox_decode_stream3.isChecked = ! checkbox_decode_stream3.isChecked; checkbox_decode_stream3.clearFocus(); return true }
KEYCODE_4 -> { checkbox_decode_stream4.isChecked = ! checkbox_decode_stream4.isChecked; checkbox_decode_stream4.clearFocus(); return true }
// E, F, A : Toggle switches
KEYCODE_E -> { switch_encode.isChecked = ! switch_encode.isChecked; switch_encode.clearFocus(); return true }
KEYCODE_F -> { switch_filter.isChecked = ! switch_filter.isChecked; switch_filter.clearFocus(); return true }
KEYCODE_A -> { switch_audio.isChecked = ! switch_audio.isChecked; switch_audio.clearFocus(); return true }
KEYCODE_L -> { switch_loop.isChecked = ! switch_loop.isChecked; switch_loop.clearFocus(); return true }
// D : Start decode
KEYCODE_D -> {
if (button_start_decode.isEnabled) {
button_start_decode.performClick()
return true
}
}
// C : Cancel decode
KEYCODE_C -> {
if (button_cancel.isEnabled) {
button_cancel.performClick()
return true
}
}
}
// Pass up any unused keystrokes
return super.onKeyUp(keyCode, event)
}
/**
* Set up ExoPlayer and begin a decode/encode run
*
* @param inputVideoRawId The raw resource ID for the video file to decode
* @param videoSurfaceManager The VideoSurfaceManger to use
* internal decoding surfaces
* @param streamNumber Stream number (0 - 3)
* @param audioVideoEncoder Optional AudioVideoEncoder (if encoding is desired)
* @param encodeAudioBufferManager Optional AudioBufferManager (if encoding is desired)
*/
// ,
// TODO: clean up line wrapping
private fun beginVideoDecode(inputVideoRawId: Int,
videoSurfaceManager: VideoSurfaceManager,
streamNumber: Int,
audioVideoEncoder: AudioVideoEncoder? = null,
encodeAudioBufferManager: AudioBufferManager? = null) {
// Keep track of active decodes to know when to re-enable decode button/clean up surfaces
activeDecodes++
// Set up audio track for this stream
val startTimeUS = 0L
val audioMixTrack = AudioMixTrack(startTimeUS)
audioMainTrack.addMixTrack(audioMixTrack)
// Setup custom video and audio renderers
// Here is where you could set a start time relative to master timeline
val renderersFactory = CustomExoRenderersFactory(this@MainActivity, viewModel,
videoSurfaceManager, streamNumber, audioMixTrack, encodeAudioBufferManager)
// Reduce default buffering to MIN_DECODE_BUFFER_MS to prevent over allocation
// when processing multiple large streams
val loadControl = DefaultLoadControl.Builder()
.setBufferDurationsMs(MIN_DECODE_BUFFER_MS, MIN_DECODE_BUFFER_MS * 2, MIN_DECODE_BUFFER_MS, MIN_DECODE_BUFFER_MS)
.createDefaultLoadControl()
// Make sure any previously allocated ExoPlayers have been released
if (exoPlayers[streamNumber] != null) {
exoPlayers[streamNumber]?.release()
}
exoPlayers[streamNumber] = ExoPlayer.Builder(this@MainActivity, renderersFactory)
.setLoadControl(loadControl)
.build()
if (audioVideoEncoder != null) {
// Set up encode and decode surfaces
videoSurfaceManager.initialize(exoPlayers[streamNumber]!!,
audioVideoEncoder.videoEncoderInputSurface,
audioVideoEncoder.encoderWidth,
audioVideoEncoder.encoderHeight)
// Start the encoder
audioVideoEncoder.startEncode()
} else {
// Only set up decode surfaces
videoSurfaceManager.initialize(exoPlayers[streamNumber]!!)
}
// Note: the decoder uses a custom MediaClock so this speed
// value is not used, but it is required by the ExoPlayer API
exoPlayers[streamNumber]?.setPlaybackParameters(PlaybackParameters(1f))
// Add a listener for when the video is done
exoPlayers[streamNumber]?.addListener(object: Player.Listener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
audioVideoEncoder?.signalDecodingComplete()
exoPlayers[streamNumber]?.release()
[email protected]()
}
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
if (reason == MEDIA_ITEM_TRANSITION_REASON_REPEAT) {
audioMixTrack.mediaClock.onRepeat()
}
super.onMediaItemTransition(mediaItem, reason)
}
})
// Set up video source and start the player
val videoSource = buildExoMediaSource(this, inputVideoRawId)
exoPlayers[streamNumber]?.setMediaSource(videoSource)
exoPlayers[streamNumber]?.prepare()
exoPlayers[streamNumber]?.repeatMode =
if (switch_loop.isChecked) Player.REPEAT_MODE_ONE else Player.REPEAT_MODE_OFF
// Clear FPS stats
FpsStats.get().reset()
exoPlayers[streamNumber]?.playWhenReady = true
}
// Indicate one more preview surface is available
// This is used to only enable the decode button only after all the decode surfaces are ready
fun surfaceAvailable() {
numberOfReadySurfaces++
if (numberOfReadySurfaces >= NUMBER_OF_STREAMS) {
runOnUiThread {
button_start_decode.isEnabled = true
button_cancel.isEnabled = false
}
}
}
// Indicate one more preview surface has been released
fun surfaceReleased() {
numberOfReadySurfaces--
if (numberOfReadySurfaces < NUMBER_OF_STREAMS) {
runOnUiThread {
button_start_decode.isEnabled = false
button_cancel.isEnabled = true
}
}
}
// Called for each completed decode. When there are no more on-going decodes or encodes, mark
// old surfaces for deletion and set-up fresh ones.
private fun decodeFinished() {
activeDecodes--
if (activeDecodes <= 0 && activeEncodes <= 0) {
runOnUiThread {
markSurfacesForDeletion()
initializeSurfaces()
updateLog("Decoding of all streams completed.")
}
audioMainTrack.reset()
}
}
// Called for each completed encode. When there are no more on-going decodes or encodes, mark
// old surfaces for deletion and set-up fresh ones.
private fun encodeFinished() {
activeEncodes--
viewModel.getEncodingInProgress().removeObservers(this)
if (activeDecodes == 0 && activeEncodes == 0) {
runOnUiThread {
markSurfacesForDeletion()
initializeSurfaces()
}
}
}
/**
* Check if this device is a Chrome OS device
*/
fun isArc(): Boolean {
return packageManager.hasSystemFeature("org.chromium.arc")
}
private val requestPermission = registerForActivityResult(RequestPermission()) { granted ->
if (granted) {
// Permission granted, restart the app
updateLog("Permissions granted! Encoding will save to file. Restarting app...")
val intent = this.intent
finish()
startActivity(intent)
} else {
// updateLog("File permissions not granted. Encoding will not save to file.")
}
}
/**
* Check for required app permissions and request them from user if necessary
*/
private fun checkPermissions(): Boolean {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Launch the permission request for WRITE_EXTERNAL_STORAGE
requestPermission.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE, )
return false
}
return true
}
// Convenience function to write to on-screen log and logcat log simultaneously
fun updateLog(message: String, clear: Boolean = false) {
// Don't log empty strings
if (!clear && message.equals("")) {
return
}
// Output to logcat
logd(message)
// Clear and/or update on-screen log
runOnUiThread {
if (clear)
text_log.text = ""
else
text_log.append("\n")
text_log.append(message)
scroll_log.post { scroll_log.fullScroll(View.FOCUS_DOWN) }
}
}
/**
* Set up options menu to allow debug logging and clearing cache'd data
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.menu_main, menu)
return true
}
/**
* Handle menu presses
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_delete_exports -> {
deleteEncodes(this, viewModel, FILE_PREFIX)
true
}
//R.id.menu_delete_logs -> {
// deleteLogs(this)
// true
//}
else -> super.onOptionsItemSelected(item)
}
}
fun updateFpsIndicator(tv: TextView, iv: ImageView, fps: Float) {
val df = DecimalFormat("00.0")
tv.text = df.format(fps)
if (fps < 25) {
iv.setImageResource(R.drawable.red_circle)
} else if (fps < 30) {
iv.setImageResource(R.drawable.orange_circle)
} else {
iv.setImageResource(R.drawable.green_circle)
}
}
}
| apache-2.0 | 56f4ad203fb08c0fe7a7e79b603cc0c9 | 38.65493 | 151 | 0.627135 | 4.807068 | false | false | false | false |
ogarcia/ultrasonic | ultrasonic/src/main/kotlin/org/moire/ultrasonic/domain/APIBookmarkConverter.kt | 2 | 668 | // Contains helper functions to convert api Bookmark entity to domain entity
@file:JvmName("APIBookmarkConverter")
package org.moire.ultrasonic.domain
import org.moire.ultrasonic.api.subsonic.models.Bookmark as ApiBookmark
fun ApiBookmark.toDomainEntity(): Bookmark = Bookmark(
position = [email protected](),
username = [email protected],
comment = [email protected],
created = [email protected]?.time,
changed = [email protected]?.time,
entry = [email protected]()
)
fun List<ApiBookmark>.toDomainEntitiesList(): List<Bookmark> = map { it.toDomainEntity() }
| gpl-3.0 | 8bcf34e8771dab156a9096418e85c8d3 | 40.75 | 90 | 0.776946 | 4.423841 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sns/src/main/kotlin/com/kotlin/sns/Unsubscribe.kt | 1 | 1651 | // snippet-sourcedescription:[Unsubscribe.kt demonstrates how to remove an Amazon Simple Notification Service (Amazon SNS) subscription.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Simple Notification Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sns
// snippet-start:[sns.kotlin.Unsubscribe.import]
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.UnsubscribeRequest
import kotlin.system.exitProcess
// snippet-end:[sns.kotlin.Unsubscribe.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<subscriptionArn>
Where:
subscriptionArn - The ARN of the subscription.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val subArn = args[0]
unSub(subArn)
}
// snippet-start:[sns.kotlin.Unsubscribe.main]
suspend fun unSub(subscriptionArnVal: String) {
val request = UnsubscribeRequest {
subscriptionArn = subscriptionArnVal
}
SnsClient { region = "us-east-1" }.use { snsClient ->
snsClient.unsubscribe(request)
println("Subscription was removed for ${request.subscriptionArn}")
}
}
// snippet-end:[sns.kotlin.Unsubscribe.main]
| apache-2.0 | 3203634885b38c0599b6e39c250f648f | 27.482143 | 137 | 0.683828 | 4.017032 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/data/science/ScienceController.kt | 1 | 12228 | package top.zbeboy.isy.web.data.science
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import top.zbeboy.isy.domain.tables.pojos.Science
import top.zbeboy.isy.service.data.ScienceService
import top.zbeboy.isy.web.bean.data.science.ScienceBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.common.PageParamControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.util.SmallPropsUtils
import top.zbeboy.isy.web.vo.data.science.ScienceVo
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
/**
* Created by zbeboy 2017-12-03 .
**/
@Controller
open class ScienceController {
@Resource
open lateinit var scienceService: ScienceService
@Resource
open lateinit var pageParamControllerCommon: PageParamControllerCommon
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
/**
* 通过系id获取全部专业
*
* @param departmentId 系id
* @return 系下全部专业
*/
@RequestMapping(value = ["/user/sciences"], method = [(RequestMethod.POST)])
@ResponseBody
fun sciences(@RequestParam("departmentId") departmentId: Int): AjaxUtils<Science> {
val ajaxUtils = AjaxUtils.of<Science>()
val sciences = ArrayList<Science>()
val isDel: Byte = 0
val science = Science(0, "请选择专业", null, isDel, 0)
sciences.add(science)
val scienceRecords = scienceService.findByDepartmentIdAndIsDel(departmentId, isDel)
scienceRecords.mapTo(sciences) { Science(it.scienceId, it.scienceName, it.scienceCode, it.scienceIsDel, it.departmentId) }
return ajaxUtils.success().msg("获取专业数据成功!").listData(sciences)
}
/**
* 通过年级与系id获取全部专业
*
* @param grade 年级
* @return 年级下全部专业
*/
@RequestMapping(value = ["/user/grade/sciences"], method = [(RequestMethod.POST)])
@ResponseBody
fun gradeSciences(@RequestParam("grade") grade: String, @RequestParam("departmentId") departmentId: Int): AjaxUtils<Science> {
val ajaxUtils = AjaxUtils.of<Science>()
val scienceRecords = scienceService.findByGradeAndDepartmentId(grade, departmentId)
val sciences = scienceRecords.into(Science::class.java)
return ajaxUtils.success().msg("获取专业数据成功!").listData(sciences)
}
/**
* 专业数据
*
* @return 专业数据页面
*/
@RequestMapping(value = ["/web/menu/data/science"], method = [(RequestMethod.GET)])
fun scienceData(): String {
return "web/data/science/science_data::#page-wrapper"
}
/**
* datatables ajax查询数据
*
* @param request 请求
* @return datatables数据
*/
@RequestMapping(value = ["/web/data/science/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun scienceDatas(request: HttpServletRequest): DataTablesUtils<ScienceBean> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("select")
headers.add("science_id")
headers.add("school_name")
headers.add("college_name")
headers.add("department_name")
headers.add("science_name")
headers.add("science_code")
headers.add("science_is_del")
headers.add("operator")
val dataTablesUtils = DataTablesUtils<ScienceBean>(request, headers)
val records = scienceService.findAllByPage(dataTablesUtils)
var scienceBeen: List<ScienceBean> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
scienceBeen = records.into(ScienceBean::class.java)
}
dataTablesUtils.data = scienceBeen
dataTablesUtils.setiTotalRecords(scienceService.countAll().toLong())
dataTablesUtils.setiTotalDisplayRecords(scienceService.countByCondition(dataTablesUtils).toLong())
return dataTablesUtils
}
/**
* 专业数据添加
*
* @return 添加页面
*/
@RequestMapping(value = ["/web/data/science/add"], method = [(RequestMethod.GET)])
fun scienceAdd(modelMap: ModelMap): String {
pageParamControllerCommon.currentUserRoleNameAndCollegeIdAndDepartmentIdPageParam(modelMap)
return "web/data/science/science_add::#page-wrapper"
}
/**
* 专业数据编辑
*
* @param id 专业id
* @param modelMap 页面对象
* @return 编辑页面
*/
@RequestMapping(value = ["/web/data/science/edit"], method = [(RequestMethod.GET)])
fun scienceEdit(@RequestParam("id") id: Int, modelMap: ModelMap): String {
val record = scienceService.findByIdRelation(id)
return if (record.isPresent) {
modelMap.addAttribute("science", record.get().into(ScienceBean::class.java))
pageParamControllerCommon.currentUserRoleNameAndCollegeIdAndDepartmentIdPageParam(modelMap)
"web/data/science/science_edit::#page-wrapper"
} else methodControllerCommon.showTip(modelMap, "未查询到相关专业信息")
}
/**
* 保存时检验专业名是否重复
*
* @param name 专业名
* @param departmentId 系id
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/science/save/valid/name"], method = [(RequestMethod.POST)])
@ResponseBody
fun saveValidName(@RequestParam("scienceName") name: String, @RequestParam("departmentId") departmentId: Int): AjaxUtils<*> {
val scienceName = StringUtils.trimWhitespace(name)
if (StringUtils.hasLength(scienceName)) {
val scienceRecords = scienceService.findByScienceNameAndDepartmentId(scienceName, departmentId)
return if (ObjectUtils.isEmpty(scienceRecords)) {
AjaxUtils.of<Any>().success().msg("专业名不存在")
} else {
AjaxUtils.of<Any>().fail().msg("专业名已存在")
}
}
return AjaxUtils.of<Any>().fail().msg("专业名不能为空")
}
/**
* 保存时检验专业代码是否重复
*
* @param code 专业代码
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/science/save/valid/code"], method = [(RequestMethod.POST)])
@ResponseBody
fun saveValidCode(@RequestParam("scienceCode") code: String): AjaxUtils<*> {
val scienceCode = StringUtils.trimWhitespace(code)
if (StringUtils.hasLength(scienceCode)) {
val scienceRecords = scienceService.findByScienceCode(scienceCode)
return if (ObjectUtils.isEmpty(scienceRecords)) {
AjaxUtils.of<Any>().success().msg("专业代码不存在")
} else {
AjaxUtils.of<Any>().fail().msg("专业代码已存在")
}
}
return AjaxUtils.of<Any>().fail().msg("专业代码不能为空")
}
/**
* 检验编辑时专业名重复
*
* @param id 专业id
* @param name 专业名
* @param departmentId 系id
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/science/update/valid/name"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateValidName(@RequestParam("scienceId") id: Int, @RequestParam("scienceName") name: String, @RequestParam("departmentId") departmentId: Int): AjaxUtils<*> {
val scienceName = StringUtils.trimWhitespace(name)
val scienceRecords = scienceService.findByScienceNameAndDepartmentIdNeScienceId(scienceName, id, departmentId)
return if (scienceRecords.isEmpty()) {
AjaxUtils.of<Any>().success().msg("专业名不重复")
} else AjaxUtils.of<Any>().fail().msg("专业名重复")
}
/**
* 检验编辑时专业代码重复
*
* @param id 专业id
* @param code 专业代码
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/science/update/valid/code"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateValidCode(@RequestParam("scienceId") id: Int, @RequestParam("scienceCode") code: String): AjaxUtils<*> {
val scienceCode = StringUtils.trimWhitespace(code)
val scienceRecords = scienceService.findByScienceCodeNeScienceId(scienceCode, id)
return if (scienceRecords.isEmpty()) {
AjaxUtils.of<Any>().success().msg("专业代码不重复")
} else AjaxUtils.of<Any>().fail().msg("专业代码重复")
}
/**
* 保存专业信息
*
* @param scienceVo 专业
* @param bindingResult 检验
* @return true 保存成功 false 保存失败
*/
@RequestMapping(value = ["/web/data/science/save"], method = [(RequestMethod.POST)])
@ResponseBody
fun scienceSave(@Valid scienceVo: ScienceVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors()) {
val science = Science()
science.scienceIsDel = if (!ObjectUtils.isEmpty(scienceVo.scienceIsDel) && scienceVo.scienceIsDel == 1.toByte()) {
1
} else {
0
}
science.scienceName = StringUtils.trimWhitespace(scienceVo.scienceName!!)
science.scienceCode = StringUtils.trimWhitespace(scienceVo.scienceCode!!)
science.departmentId = scienceVo.departmentId
scienceService.save(science)
return AjaxUtils.of<Any>().success().msg("保存成功")
}
return AjaxUtils.of<Any>().fail().msg("填写信息错误,请检查")
}
/**
* 保存专业更改
*
* @param scienceVo 专业
* @param bindingResult 检验
* @return true 更改成功 false 更改失败
*/
@RequestMapping(value = ["/web/data/science/update"], method = [(RequestMethod.POST)])
@ResponseBody
fun scienceUpdate(@Valid scienceVo: ScienceVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors() && !ObjectUtils.isEmpty(scienceVo.scienceId)) {
val science = scienceService.findById(scienceVo.scienceId!!)
if (!ObjectUtils.isEmpty(science)) {
science.scienceIsDel = if (!ObjectUtils.isEmpty(scienceVo.scienceIsDel) && scienceVo.scienceIsDel == 1.toByte()) {
1
} else {
0
}
science.scienceName = StringUtils.trimWhitespace(scienceVo.scienceName!!)
science.scienceCode = StringUtils.trimWhitespace(scienceVo.scienceCode!!)
science.departmentId = scienceVo.departmentId
scienceService.update(science)
return AjaxUtils.of<Any>().success().msg("更改成功")
}
}
return AjaxUtils.of<Any>().fail().msg("更改失败")
}
/**
* 批量更改专业状态
*
* @param scienceIds 专业ids
* @param isDel is_del
* @return true注销成功
*/
@RequestMapping(value = ["/web/data/science/update/del"], method = [(RequestMethod.POST)])
@ResponseBody
fun scienceUpdateDel(scienceIds: String, isDel: Byte?): AjaxUtils<*> {
if (StringUtils.hasLength(scienceIds) && SmallPropsUtils.StringIdsIsNumber(scienceIds)) {
scienceService.updateIsDel(SmallPropsUtils.StringIdsToList(scienceIds), isDel)
return AjaxUtils.of<Any>().success().msg("更改专业状态成功")
}
return AjaxUtils.of<Any>().fail().msg("更改专业状态失败")
}
} | mit | 13dba81647cebe6c6880ab103b1199dd | 37.649832 | 167 | 0.649852 | 4.097822 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/graduate/design/proposal/GraduationDesignProposalController.kt | 1 | 55216 | package top.zbeboy.isy.web.graduate.design.proposal
import org.apache.commons.lang.math.NumberUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartHttpServletRequest
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.domain.tables.pojos.*
import top.zbeboy.isy.service.common.FilesService
import top.zbeboy.isy.service.common.UploadService
import top.zbeboy.isy.service.data.StaffService
import top.zbeboy.isy.service.data.StudentService
import top.zbeboy.isy.service.graduate.design.GraduationDesignDatumGroupService
import top.zbeboy.isy.service.graduate.design.GraduationDesignDatumService
import top.zbeboy.isy.service.graduate.design.GraduationDesignTeacherService
import top.zbeboy.isy.service.graduate.design.GraduationDesignTutorService
import top.zbeboy.isy.service.platform.RoleService
import top.zbeboy.isy.service.platform.UsersService
import top.zbeboy.isy.service.platform.UsersTypeService
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.FilesUtils
import top.zbeboy.isy.service.util.RequestUtils
import top.zbeboy.isy.service.util.UUIDUtils
import top.zbeboy.isy.web.bean.error.ErrorBean
import top.zbeboy.isy.web.bean.file.FileBean
import top.zbeboy.isy.web.bean.graduate.design.proposal.GraduationDesignDatumBean
import top.zbeboy.isy.web.bean.graduate.design.proposal.GraduationDesignDatumGroupBean
import top.zbeboy.isy.web.bean.graduate.design.release.GraduationDesignReleaseBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.common.PageParamControllerCommon
import top.zbeboy.isy.web.graduate.design.common.GraduationDesignConditionCommon
import top.zbeboy.isy.web.graduate.design.common.GraduationDesignMethodControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.util.PaginationUtils
import top.zbeboy.isy.web.vo.graduate.design.proposal.GraduationDesignProposalAddVo
import java.io.IOException
import java.sql.Timestamp
import java.time.Clock
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.validation.Valid
/**
* Created by zbeboy 2018-01-29 .
**/
@Controller
open class GraduationDesignProposalController {
private val log = LoggerFactory.getLogger(GraduationDesignProposalController::class.java)
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
@Resource
open lateinit var graduationDesignDatumService: GraduationDesignDatumService
@Resource
open lateinit var graduationDesignDatumGroupService: GraduationDesignDatumGroupService
@Resource
open lateinit var graduationDesignTeacherService: GraduationDesignTeacherService
@Resource
open lateinit var usersTypeService: UsersTypeService
@Resource
open lateinit var graduationDesignTutorService: GraduationDesignTutorService
@Resource
open lateinit var usersService: UsersService
@Resource
open lateinit var studentService: StudentService
@Resource
open lateinit var uploadService: UploadService
@Resource
open lateinit var filesService: FilesService
@Resource
open lateinit var roleService: RoleService
@Resource
open lateinit var staffService: StaffService
@Resource
open lateinit var graduationDesignMethodControllerCommon: GraduationDesignMethodControllerCommon
@Resource
open lateinit var graduationDesignConditionCommon: GraduationDesignConditionCommon
@Resource
open lateinit var pageParamControllerCommon: PageParamControllerCommon
/**
* 毕业设计资料
*
* @return 毕业设计资料页面
*/
@RequestMapping(value = ["/web/menu/graduate/design/proposal"], method = [(RequestMethod.GET)])
fun proposal(): String {
return "web/graduate/design/proposal/design_proposal::#page-wrapper"
}
/**
* 获取毕业设计发布数据
*
* @param paginationUtils 分页工具
* @return 数据
*/
@RequestMapping(value = ["/web/graduate/design/proposal/design/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun designDatas(paginationUtils: PaginationUtils): AjaxUtils<GraduationDesignReleaseBean> {
return graduationDesignMethodControllerCommon.graduationDesignListDatas(paginationUtils)
}
/**
* 附件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param modelMap 页面对象
* @return 页面
*/
@RequestMapping(value = ["/web/graduate/design/proposal/affix"], method = [(RequestMethod.GET)])
fun affix(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String {
val errorBean = graduationDesignConditionCommon.basicCondition(graduationDesignReleaseId)
return if (!errorBean.isHasError()) {
modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId)
"web/graduate/design/proposal/design_proposal_affix::#page-wrapper"
} else {
methodControllerCommon.showTip(modelMap, errorBean.errorMsg!!)
}
}
/**
* 文件下载
*
* @param fileId 文件id
* @param request 请求
* @param response 响应
*/
@RequestMapping("/web/graduate/design/proposal/download/file")
fun downloadFile(@RequestParam("fileId") fileId: String, request: HttpServletRequest, response: HttpServletResponse) {
methodControllerCommon.downloadFile(fileId, request, response)
}
/**
* 我的资料页面
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param modelMap 页面对象
* @return 页面
*/
@RequestMapping(value = ["/web/graduate/design/proposal/my"], method = [(RequestMethod.GET)])
fun my(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String {
return if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val users = usersService.getUserFromSession()
val student = studentService.findByUsername(users!!.username)
val errorBean = studentAccessCondition(graduationDesignReleaseId, student.studentId!!)
if (!errorBean.isHasError()) {
modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId)
"web/graduate/design/proposal/design_proposal_my::#page-wrapper"
} else {
methodControllerCommon.showTip(modelMap, errorBean.errorMsg!!)
}
} else {
methodControllerCommon.showTip(modelMap, "目前仅提供学生使用")
}
}
/**
* 小组资料
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param modelMap 页面对象
* @return 页面
*/
@RequestMapping(value = ["/web/graduate/design/proposal/team"], method = [(RequestMethod.GET)])
fun team(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
return if (!errorBean.isHasError()) {
val graduationDesignRelease = errorBean.data
graduationDesignMethodControllerCommon.setStaffIdAndStudentId(modelMap, graduationDesignRelease!!)
pageParamControllerCommon.currentUserRoleNameAndTypeNamePageParam(modelMap)
modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId)
"web/graduate/design/proposal/design_proposal_team::#page-wrapper"
} else {
methodControllerCommon.showTip(modelMap, errorBean.errorMsg!!)
}
}
/**
* 组内资料
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param modelMap 页面对象
* @return 页面
*/
@RequestMapping(value = ["/web/graduate/design/proposal/group"], method = [(RequestMethod.GET)])
fun group(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String {
val page: String
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
val graduationDesignRelease = errorBean.data
var canUse = false
val users = usersService.getUserFromSession()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease!!.scienceId!!, graduationDesignRelease.allowGrade)
if (studentRecord.isPresent) {
val student = studentRecord.get().into(Student::class.java)
val staffRecord = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(student.studentId!!, graduationDesignReleaseId)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
modelMap.addAttribute("graduationDesignTeacherId", graduationDesignTeacher.graduationDesignTeacherId)
modelMap.addAttribute("currUseIsStaff", 0)
canUse = true
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
modelMap.addAttribute("graduationDesignTeacherId", graduationDesignTeacher.graduationDesignTeacherId)
modelMap.addAttribute("currUseIsStaff", 1)
canUse = true
}
}
}
page = if (canUse) {
modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId)
"web/graduate/design/proposal/design_proposal_group::#page-wrapper"
} else {
methodControllerCommon.showTip(modelMap, "您不符合进入条件")
}
} else {
page = methodControllerCommon.showTip(modelMap, errorBean.errorMsg!!)
}
return page
}
/**
* 我的资料数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/graduate/design/proposal/my/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun myData(request: HttpServletRequest): DataTablesUtils<GraduationDesignDatumBean> {
val graduationDesignReleaseId = request.getParameter("graduationDesignReleaseId")
var dataTablesUtils = DataTablesUtils.of<GraduationDesignDatumBean>()
if (!ObjectUtils.isEmpty(graduationDesignReleaseId)) {
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val users = usersService.getUserFromSession()
val student = studentService.findByUsername(users!!.username)
val errorBean = studentAccessCondition(graduationDesignReleaseId, student.studentId!!)
if (!errorBean.isHasError()) {
val graduationDesignTutor = errorBean.mapData!!["graduationDesignTutor"] as GraduationDesignTutor
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("original_file_name")
headers.add("graduation_design_datum_type_name")
headers.add("version")
headers.add("update_time")
headers.add("operator")
val otherCondition = GraduationDesignDatumBean()
dataTablesUtils = DataTablesUtils(request, headers)
var graduationDesignDatumBeens: List<GraduationDesignDatumBean> = ArrayList()
otherCondition.graduationDesignTutorId = graduationDesignTutor.graduationDesignTutorId
val records = graduationDesignDatumService.findAllByPage(dataTablesUtils, otherCondition)
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationDesignDatumBeens = records.into(GraduationDesignDatumBean::class.java)
graduationDesignDatumBeenFilter(graduationDesignDatumBeens)
}
dataTablesUtils.data = graduationDesignDatumBeens
dataTablesUtils.setiTotalRecords(graduationDesignDatumService.countAll(otherCondition).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationDesignDatumService.countByCondition(dataTablesUtils, otherCondition).toLong())
}
}
}
return dataTablesUtils
}
/**
* 小组数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/graduate/design/proposal/team/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun teamData(request: HttpServletRequest): DataTablesUtils<GraduationDesignDatumBean> {
val graduationDesignReleaseId = request.getParameter("graduationDesignReleaseId")
var dataTablesUtils = DataTablesUtils.of<GraduationDesignDatumBean>()
if (!ObjectUtils.isEmpty(graduationDesignReleaseId)) {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("real_name")
headers.add("student_number")
headers.add("organize_name")
headers.add("original_file_name")
headers.add("version")
headers.add("graduation_design_datum_type_name")
headers.add("update_time")
headers.add("operator")
dataTablesUtils = DataTablesUtils(request, headers)
val otherCondition = GraduationDesignDatumBean()
val staffId = NumberUtils.toInt(request.getParameter("staffId"))
otherCondition.graduationDesignReleaseId = graduationDesignReleaseId
otherCondition.staffId = staffId
var graduationDesignDatumBeens: List<GraduationDesignDatumBean> = ArrayList()
val records = graduationDesignDatumService.findTeamAllByPage(dataTablesUtils, otherCondition)
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationDesignDatumBeens = records.into(GraduationDesignDatumBean::class.java)
graduationDesignDatumBeenFilter(graduationDesignDatumBeens)
}
dataTablesUtils.data = graduationDesignDatumBeens
dataTablesUtils.setiTotalRecords(graduationDesignDatumService.countTeamAll(otherCondition).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationDesignDatumService.countTeamByCondition(dataTablesUtils, otherCondition).toLong())
}
}
return dataTablesUtils
}
/**
* 过滤数据,保护隐私
*
* @param graduationDesignDatumBeens 数据
*/
private fun graduationDesignDatumBeenFilter(graduationDesignDatumBeens: List<GraduationDesignDatumBean>) {
graduationDesignDatumBeens.forEach { i ->
i.updateTimeStr = DateTimeUtils.formatDate(i.updateTime)
i.relativePath = ""
}
}
/**
* 组内资料数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/graduate/design/proposal/group/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun groupData(request: HttpServletRequest): DataTablesUtils<GraduationDesignDatumGroupBean> {
val graduationDesignReleaseId = request.getParameter("graduationDesignReleaseId")
val graduationDesignTeacherId = request.getParameter("graduationDesignTeacherId")
var dataTablesUtils = DataTablesUtils.of<GraduationDesignDatumGroupBean>()
if (!ObjectUtils.isEmpty(graduationDesignReleaseId)) {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("original_file_name")
headers.add("upload_time")
headers.add("operator")
dataTablesUtils = DataTablesUtils(request, headers)
val otherCondition = GraduationDesignDatumGroupBean()
otherCondition.graduationDesignReleaseId = graduationDesignReleaseId
otherCondition.graduationDesignTeacherId = graduationDesignTeacherId
var graduationDesignDatumGroupBeens: List<GraduationDesignDatumGroupBean> = ArrayList()
val records = graduationDesignDatumGroupService.findAllByPage(dataTablesUtils, otherCondition)
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationDesignDatumGroupBeens = records.into(GraduationDesignDatumGroupBean::class.java)
graduationDesignDatumGroupBeens.forEach { i ->
i.uploadTimeStr = DateTimeUtils.formatDate(i.uploadTime)
i.relativePath = ""
}
}
dataTablesUtils.data = graduationDesignDatumGroupBeens
dataTablesUtils.setiTotalRecords(graduationDesignDatumGroupService.countAll(otherCondition).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationDesignDatumGroupService.countByCondition(dataTablesUtils, otherCondition).toLong())
}
}
return dataTablesUtils
}
/**
* 保存或更新毕业设计资料
*
* @param graduationDesignProposalAddVo 数据
* @param multipartHttpServletRequest 文件
* @param request 请求
* @return true or false
*/
@RequestMapping("/web/graduate/design/proposal/my/save")
@ResponseBody
fun mySave(@Valid graduationDesignProposalAddVo: GraduationDesignProposalAddVo, bindingResult: BindingResult,
multipartHttpServletRequest: MultipartHttpServletRequest, request: HttpServletRequest): AjaxUtils<FileBean> {
val ajaxUtils = AjaxUtils.of<FileBean>()
try {
if (!bindingResult.hasErrors()) {
// 学生使用
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val users = usersService.getUserFromSession()
val student = studentService.findByUsername(users!!.username)
val errorBean = graduationDesignConditionCommon.isRangeGraduationDateCondition(graduationDesignProposalAddVo.graduationDesignReleaseId!!)
graduationDesignConditionCommon.isNotOkTeacherAdjust(errorBean)
if (!errorBean.isHasError()) {
val graduationDesignRelease = errorBean.data
// 是否符合该毕业设计条件
val record = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(student.studentId!!, graduationDesignRelease!!.graduationDesignReleaseId)
if (record.isPresent) {
var canUse = true
val graduationDesignTutor = record.get().into(GraduationDesignTutor::class.java)
// 是否更新
val recordDatum = graduationDesignDatumService.findByGraduationDesignTutorIdAndGraduationDesignDatumTypeId(graduationDesignTutor.graduationDesignTutorId, graduationDesignProposalAddVo.graduationDesignDatumTypeId!!)
var graduationDesignDatum: GraduationDesignDatum? = null
var isUpdate = false
if (recordDatum.isPresent) {
val graduationDesignDatumBean = recordDatum.get().into(GraduationDesignDatumBean::class.java)
if (student.studentId == graduationDesignDatumBean.studentId) {
graduationDesignDatum = recordDatum.get().into(GraduationDesignDatum::class.java)
isUpdate = true
} else {
canUse = false
}
} else {
graduationDesignDatum = GraduationDesignDatum()
}
if (canUse) {
val path = Workbook.graduationDesignProposalPath(users)
val fileBeen = uploadService.upload(multipartHttpServletRequest,
RequestUtils.getRealPath(request) + path, request.remoteAddr)
if (fileBeen.isNotEmpty()) {
val fileId = UUIDUtils.getUUID()
val tempFile = fileBeen[0]
val files = Files()
files.fileId = fileId
files.ext = tempFile.ext
files.newName = tempFile.newName
files.originalFileName = tempFile.originalFileName
files.size = tempFile.size.toString()
files.relativePath = path + tempFile.newName!!
filesService.save(files)
if (isUpdate) {
// 删除旧文件
val oldFile = filesService.findById(graduationDesignDatum!!.fileId)
FilesUtils.deleteFile(RequestUtils.getRealPath(request) + oldFile.relativePath)
graduationDesignDatum.fileId = fileId
graduationDesignDatum.updateTime = DateTimeUtils.getNow()
graduationDesignDatum.version = graduationDesignProposalAddVo.version
graduationDesignDatumService.update(graduationDesignDatum)
filesService.deleteById(oldFile.fileId)
} else {
graduationDesignDatum!!.graduationDesignDatumId = UUIDUtils.getUUID()
graduationDesignDatum.fileId = fileId
graduationDesignDatum.updateTime = DateTimeUtils.getNow()
graduationDesignDatum.graduationDesignTutorId = graduationDesignTutor.graduationDesignTutorId
graduationDesignDatum.version = graduationDesignProposalAddVo.version
graduationDesignDatum.graduationDesignDatumTypeId = graduationDesignProposalAddVo.graduationDesignDatumTypeId
graduationDesignDatumService.save(graduationDesignDatum)
}
ajaxUtils.success().msg("保存成功")
} else {
ajaxUtils.fail().msg("未查询到文件信息")
}
} else {
ajaxUtils.fail().msg("无法核实该文件属于您")
}
} else {
ajaxUtils.fail().msg("您的账号不符合该毕业设计条件")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} else {
ajaxUtils.fail().msg("目前仅提供学生使用")
}
} else {
ajaxUtils.fail().msg("参数异常")
}
} catch (e: Exception) {
log.error("Upload graduation design proposal error, error is {}", e)
ajaxUtils.fail().msg("保存文件异常")
}
return ajaxUtils
}
/**
* 删除文件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param graduationDesignDatumId 毕业资料id
* @param request 请求
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/del"], method = [(RequestMethod.POST)])
@ResponseBody
fun proposalDelete(@RequestParam("id") graduationDesignReleaseId: String, @RequestParam("graduationDesignDatumId") graduationDesignDatumId: String, request: HttpServletRequest): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<FileBean>()
try {
val errorBean = graduationDesignConditionCommon.isRangeGraduationDateCondition(graduationDesignReleaseId)
graduationDesignConditionCommon.isNotOkTeacherAdjust(errorBean)
if (!errorBean.isHasError()) {
val users = usersService.getUserFromSession()
val graduationDesignDatum = canUseCondition(graduationDesignDatumId, users)
if (!ObjectUtils.isEmpty(graduationDesignDatum)) {
val files = filesService.findById(graduationDesignDatum!!.fileId)
if (!ObjectUtils.isEmpty(files)) {
FilesUtils.deleteFile(RequestUtils.getRealPath(request) + files.relativePath)
graduationDesignDatumService.deleteById(graduationDesignDatumId)
filesService.deleteById(files.fileId)
ajaxUtils.success().msg("删除成功")
} else {
ajaxUtils.fail().msg("未查询到该文件信息")
}
} else {
ajaxUtils.fail().msg("不符合条件,删除失败")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} catch (e: IOException) {
log.error("Delete graduation design proposal error, error is {}", e)
ajaxUtils.fail().msg("保存文件异常")
}
return ajaxUtils
}
/**
* 下载文件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param graduationDesignDatumId 毕业资料id
* @param request 请求
*/
@RequestMapping(value = ["/web/graduate/design/proposal/download"], method = [(RequestMethod.GET)])
fun download(@RequestParam("id") graduationDesignReleaseId: String, @RequestParam("graduationDesignDatumId") graduationDesignDatumId: String, response: HttpServletResponse, request: HttpServletRequest) {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
var canUse = false
val users = usersService.getUserFromSession()
var graduationDesignDatum: GraduationDesignDatum? = null
if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) {
graduationDesignDatum = graduationDesignDatumService.findById(graduationDesignDatumId)
canUse = true
} else {
// 学生
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val record = graduationDesignDatumService.findByIdRelation(graduationDesignDatumId)
if (record.isPresent) {
val student = studentService.findByUsername(users!!.username)
val graduationDesignDatumBean = record.get().into(GraduationDesignDatumBean::class.java)
if (student.studentId == graduationDesignDatumBean.studentId) {
graduationDesignDatum = record.get().into(GraduationDesignDatum::class.java)
canUse = true
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
graduationDesignDatum = graduationDesignDatumService.findById(graduationDesignDatumId)
canUse = true
}
}
if (canUse) {
val files = filesService.findById(graduationDesignDatum!!.fileId)
if (!ObjectUtils.isEmpty(files)) {
uploadService.download(files.originalFileName + "V" + graduationDesignDatum.version, files.relativePath, response, request)
}
}
}
}
/**
* 获取毕业设计资料信息
*
* @param graduationDesignReleaseId 毕业设计发布id
* @param graduationDesignDatumId 毕业设计资料id
* @return 数据
*/
@RequestMapping(value = ["/web/graduate/design/proposal/team/datum"], method = [(RequestMethod.POST)])
@ResponseBody
fun teamDatum(@RequestParam("id") graduationDesignReleaseId: String, @RequestParam("graduationDesignDatumId") graduationDesignDatumId: String): AjaxUtils<GraduationDesignDatumBean> {
val ajaxUtils = AjaxUtils.of<GraduationDesignDatumBean>()
val errorBean = graduationDesignConditionCommon.basicCondition(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
val record = graduationDesignDatumService.findByIdRelation(graduationDesignDatumId)
if (record.isPresent) {
val graduationDesignDatum = record.get().into(GraduationDesignDatumBean::class.java)
ajaxUtils.success().msg("获取数据成功").obj(graduationDesignDatum)
} else {
ajaxUtils.fail().msg("未查询到相关毕业设计资料信息")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
return ajaxUtils
}
/**
* 更新毕业设计资料
*
* @param graduationDesignProposalAddVo 数据
* @param multipartHttpServletRequest 文件
* @param request 请求
* @return true or false
*/
@RequestMapping("/web/graduate/design/proposal/team/update")
@ResponseBody
fun teamUpdate(@Valid graduationDesignProposalAddVo: GraduationDesignProposalAddVo, bindingResult: BindingResult,
multipartHttpServletRequest: MultipartHttpServletRequest, request: HttpServletRequest): AjaxUtils<FileBean> {
val ajaxUtils = AjaxUtils.of<FileBean>()
try {
if (!bindingResult.hasErrors() && StringUtils.hasLength(graduationDesignProposalAddVo.graduationDesignDatumId)) {
val errorBean = graduationDesignConditionCommon.isRangeGraduationDateCondition(graduationDesignProposalAddVo.graduationDesignReleaseId!!)
graduationDesignConditionCommon.isNotOkTeacherAdjust(errorBean)
if (!errorBean.isHasError()) {
val users = usersService.getUserFromSession()
val graduationDesignDatum = canUseCondition(graduationDesignProposalAddVo.graduationDesignDatumId!!, users)
if (!ObjectUtils.isEmpty(graduationDesignDatum)) {
val path = Workbook.graduationDesignProposalPath(users!!)
val fileBeen = uploadService.upload(multipartHttpServletRequest,
RequestUtils.getRealPath(request) + path, request.remoteAddr)
if (fileBeen.isNotEmpty()) {
val fileId = UUIDUtils.getUUID()
val tempFile = fileBeen[0]
val files = Files()
files.fileId = fileId
files.ext = tempFile.ext
files.newName = tempFile.newName
files.originalFileName = tempFile.originalFileName
files.size = tempFile.size.toString()
files.relativePath = path + tempFile.newName!!
filesService.save(files)
val oldFile = filesService.findById(graduationDesignDatum!!.fileId)
FilesUtils.deleteFile(RequestUtils.getRealPath(request) + oldFile.relativePath)
graduationDesignDatum.fileId = fileId
graduationDesignDatum.updateTime = DateTimeUtils.getNow()
graduationDesignDatum.version = graduationDesignProposalAddVo.version
graduationDesignDatumService.update(graduationDesignDatum)
filesService.deleteById(oldFile.fileId)
ajaxUtils.success().msg("保存成功")
} else {
ajaxUtils.fail().msg("未查询到文件信息")
}
} else {
ajaxUtils.fail().msg("不符合保存条件,保存失败")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} else {
ajaxUtils.fail().msg("参数异常")
}
} catch (e: Exception) {
log.error("Upload graduation design proposal error, error is {}", e)
ajaxUtils.fail().msg("保存文件异常")
}
return ajaxUtils
}
/**
* 保存组内资料
*
* @param graduationDesignReleaseId 毕业设计发布oid
* @param multipartHttpServletRequest 文件
* @param request 请求
* @return true or false
*/
@RequestMapping("/web/graduate/design/proposal/group/save")
@ResponseBody
fun groupSave(@RequestParam("graduationDesignReleaseId") graduationDesignReleaseId: String,
multipartHttpServletRequest: MultipartHttpServletRequest, request: HttpServletRequest): AjaxUtils<FileBean> {
val ajaxUtils = AjaxUtils.of<FileBean>()
try {
val errorBean = graduationDesignConditionCommon.isRangeGraduationDateCondition(graduationDesignReleaseId)
graduationDesignConditionCommon.isNotOkTeacherAdjust(errorBean)
if (!errorBean.isHasError()) {
val users = usersService.getUserFromSession()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
val path = Workbook.graduationDesignProposalPath(users)
val fileBeen = uploadService.upload(multipartHttpServletRequest,
RequestUtils.getRealPath(request) + path, request.remoteAddr)
if (fileBeen.isNotEmpty()) {
val fileId = UUIDUtils.getUUID()
val tempFile = fileBeen[0]
val files = Files()
files.fileId = fileId
files.ext = tempFile.ext
files.newName = tempFile.newName
files.originalFileName = tempFile.originalFileName
files.size = tempFile.size.toString()
files.relativePath = path + tempFile.newName!!
filesService.save(files)
val graduationDesignDatumGroup = GraduationDesignDatumGroup()
graduationDesignDatumGroup.graduationDesignDatumGroupId = UUIDUtils.getUUID()
graduationDesignDatumGroup.fileId = fileId
graduationDesignDatumGroup.graduationDesignTeacherId = graduationDesignTeacher.graduationDesignTeacherId
graduationDesignDatumGroup.uploadTime = Timestamp(Clock.systemDefaultZone().millis())
graduationDesignDatumGroupService.save(graduationDesignDatumGroup)
ajaxUtils.success().msg("保存成功")
} else {
ajaxUtils.fail().msg("保存文件失败")
}
} else {
ajaxUtils.fail().msg("您不是该毕业设计指导教师")
}
} else {
ajaxUtils.fail().msg("未查询到教职工信息")
}
} else {
ajaxUtils.fail().msg("您的注册类型不符合进入条件")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} catch (e: Exception) {
log.error("Upload graduation design proposal error, error is {}", e)
ajaxUtils.fail().msg("保存文件异常")
}
return ajaxUtils
}
/**
* 删除组内资料
*
* @param graduationDesignReleaseId 毕业设计发布oid
* @param graduationDesignDatumGroupId 组内资料id
* @param request 请求
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/group/del"], method = [(RequestMethod.POST)])
@ResponseBody
fun groupDel(@RequestParam("id") graduationDesignReleaseId: String,
@RequestParam("graduationDesignDatumGroupId") graduationDesignDatumGroupId: String, request: HttpServletRequest): AjaxUtils<FileBean> {
val ajaxUtils = AjaxUtils.of<FileBean>()
try {
val errorBean = graduationDesignConditionCommon.isRangeGraduationDateCondition(graduationDesignReleaseId)
graduationDesignConditionCommon.isNotOkTeacherAdjust(errorBean)
if (!errorBean.isHasError()) {
val users = usersService.getUserFromSession()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
val graduationDesignDatumGroup = graduationDesignDatumGroupService.findById(graduationDesignDatumGroupId)
if (!ObjectUtils.isEmpty(graduationDesignDatumGroup)) {
if (graduationDesignTeacher.graduationDesignTeacherId == graduationDesignDatumGroup.graduationDesignTeacherId) {
val files = filesService.findById(graduationDesignDatumGroup.fileId)
if (!ObjectUtils.isEmpty(files)) {
FilesUtils.deleteFile(RequestUtils.getRealPath(request) + files.relativePath)
graduationDesignDatumGroupService.delete(graduationDesignDatumGroup)
filesService.deleteById(files.fileId)
ajaxUtils.success().msg("删除文件成功")
} else {
ajaxUtils.fail().msg("未查询到文件信息")
}
} else {
ajaxUtils.fail().msg("该文件不属于您")
}
} else {
ajaxUtils.fail().msg("未查询到组内文件信息")
}
} else {
ajaxUtils.fail().msg("您不是该毕业设计指导教师")
}
} else {
ajaxUtils.fail().msg("未查询到教职工信息")
}
} else {
ajaxUtils.fail().msg("您的注册类型不符合进入条件")
}
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} catch (e: Exception) {
log.error("Delete graduation design proposal file error, error is {}", e)
ajaxUtils.fail().msg("删除文件异常")
}
return ajaxUtils
}
/**
* 下载组内资料
*
* @param graduationDesignReleaseId 毕业设计发布oid
* @param graduationDesignDatumGroupId 组内资料id
* @param request 请求
* @param response 响应
*/
@RequestMapping("/web/graduate/design/proposal/group/download")
@ResponseBody
fun groupDownload(@RequestParam("id") graduationDesignReleaseId: String,
@RequestParam("graduationDesignDatumGroupId") graduationDesignDatumGroupId: String,
request: HttpServletRequest, response: HttpServletResponse) {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
val graduationDesignRelease = errorBean.data
val users = usersService.getUserFromSession()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease!!.scienceId!!, graduationDesignRelease.allowGrade)
if (studentRecord.isPresent) {
val student = studentRecord.get().into(Student::class.java)
if (!ObjectUtils.isEmpty(student)) {
val staffRecord = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(student.studentId!!, graduationDesignReleaseId)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
val graduationDesignDatumGroup = graduationDesignDatumGroupService.findById(graduationDesignDatumGroupId)
groupDownloadBuild(graduationDesignTeacher, graduationDesignDatumGroup, request, response)
}
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
val graduationDesignDatumGroup = graduationDesignDatumGroupService.findById(graduationDesignDatumGroupId)
groupDownloadBuild(graduationDesignTeacher, graduationDesignDatumGroup, request, response)
}
}
}
}
}
/**
* 组内资料下载构建
*
* @param graduationDesignTeacher 指导教师信息
* @param graduationDesignDatumGroup 组内资料信息
* @param request 请求
* @param response 响应
*/
private fun groupDownloadBuild(graduationDesignTeacher: GraduationDesignTeacher, graduationDesignDatumGroup: GraduationDesignDatumGroup,
request: HttpServletRequest, response: HttpServletResponse) {
if (!ObjectUtils.isEmpty(graduationDesignDatumGroup)) {
if (graduationDesignTeacher.graduationDesignTeacherId == graduationDesignDatumGroup.graduationDesignTeacherId) {
val files = filesService.findById(graduationDesignDatumGroup.fileId)
if (!ObjectUtils.isEmpty(files)) {
uploadService.download(files.originalFileName, files.relativePath, response, request)
}
}
}
}
/**
* 团队进入条件入口
*
* @param graduationDesignDatumId 毕业资料id
* @param users 用户信息
* @return 毕业资料数据
*/
private fun canUseCondition(graduationDesignDatumId: String, users: Users?): GraduationDesignDatum? {
var graduationDesignDatum: GraduationDesignDatum? = null
if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) {
graduationDesignDatum = graduationDesignDatumService.findById(graduationDesignDatumId)
} else {
// 学生
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val record = graduationDesignDatumService.findByIdRelation(graduationDesignDatumId)
if (record.isPresent) {
val student = studentService.findByUsername(users!!.username)
val graduationDesignDatumBean = record.get().into(GraduationDesignDatumBean::class.java)
if (student.studentId == graduationDesignDatumBean.studentId) {
graduationDesignDatum = record.get().into(GraduationDesignDatum::class.java)
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staffRecord = graduationDesignDatumService.findByIdRelation(graduationDesignDatumId)
if (staffRecord.isPresent) {
val staff = staffService.findByUsername(users!!.username)
val graduationDesignDatumBean = staffRecord.get().into(GraduationDesignDatumBean::class.java)
if (staff.staffId == graduationDesignDatumBean.staffId) {
graduationDesignDatum = staffRecord.get().into(GraduationDesignDatum::class.java)
}
}
}
}
return graduationDesignDatum
}
/**
* 我的资料页面判断条件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/my/condition"], method = [(RequestMethod.POST)])
@ResponseBody
fun myCondition(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<Any>()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val users = usersService.getUserFromSession()
val student = studentService.findByUsername(users!!.username)
val errorBean = studentAccessCondition(graduationDesignReleaseId, student.studentId!!)
if (!errorBean.isHasError()) {
ajaxUtils.success().msg("在条件范围,允许使用")
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
} else {
ajaxUtils.fail().msg("目前仅提供学生使用")
}
return ajaxUtils
}
/**
* 小组页面判断条件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/team/condition"], method = [(RequestMethod.POST)])
@ResponseBody
fun teamCondition(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<Any>()
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
ajaxUtils.success().msg("在条件范围,允许使用")
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
return ajaxUtils
}
/**
* 组内资料页面判断条件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/group/condition"], method = [(RequestMethod.POST)])
@ResponseBody
fun groupCondition(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<Any>()
val errorBean = groupAccessCondition(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
ajaxUtils.success().msg("在条件范围,允许使用")
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
return ajaxUtils
}
/**
* 进入页面判断条件
*
* @param graduationDesignReleaseId 毕业设计发布id
* @return true or false
*/
@RequestMapping(value = ["/web/graduate/design/proposal/condition"], method = [(RequestMethod.POST)])
@ResponseBody
fun canUse(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<Any>()
val errorBean = graduationDesignConditionCommon.basicCondition(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
ajaxUtils.success().msg("在条件范围,允许使用")
} else {
ajaxUtils.fail().msg(errorBean.errorMsg!!)
}
return ajaxUtils
}
/**
* 进入学生资料条件
*
* @param graduationDesignReleaseId 发布
* @param studentId 学生id
* @return true or false
*/
private fun studentAccessCondition(graduationDesignReleaseId: String, studentId: Int): ErrorBean<GraduationDesignRelease> {
val dataMap = HashMap<String, Any>()
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
val record = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(studentId, graduationDesignReleaseId)
if (record.isPresent) {
val graduationDesignTutor = record.get().into(GraduationDesignTutor::class.java)
dataMap["graduationDesignTutor"] = graduationDesignTutor
errorBean.hasError = false
} else {
errorBean.hasError = true
errorBean.errorMsg = "您不符合该毕业设计条件"
}
errorBean.mapData = dataMap
}
return errorBean
}
/**
* 组内资料页面判断条件Id
*
* @param graduationDesignReleaseId 毕业设计发布
* @return 条件
*/
private fun groupAccessCondition(graduationDesignReleaseId: String): ErrorBean<GraduationDesignRelease> {
val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId)
if (!errorBean.isHasError()) {
val graduationDesignRelease = errorBean.data
var canUse = false
val users = usersService.getUserFromSession()
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease!!.scienceId!!, graduationDesignRelease.allowGrade)
if (studentRecord.isPresent) {
val student = studentRecord.get().into(Student::class.java)
if (!ObjectUtils.isEmpty(student)) {
val staffRecord = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(student.studentId!!, graduationDesignReleaseId)
if (staffRecord.isPresent) {
canUse = true
}
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
canUse = true
}
}
}
if (canUse) {
errorBean.hasError = false
} else {
errorBean.hasError = true
errorBean.errorMsg = "您不符合进入条件"
}
}
return errorBean
}
} | mit | 80ef4174f66a9ac71e3eebf02e74478c | 49.615894 | 242 | 0.61357 | 5.737881 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/model/payment/Payment.kt | 1 | 1113 | package backend.model.payment
import backend.model.BasicEntity
import backend.model.user.User
import backend.model.user.UserAccount
import org.javamoney.moneta.Money
import java.time.LocalDateTime
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.ManyToOne
import javax.persistence.PreRemove
@Entity
abstract class Payment : BasicEntity {
lateinit var amount: Money
private set
@Column(unique = true)
var fidorId: Long? = null
private set
@ManyToOne
var user: UserAccount? = null
@ManyToOne
var invoice: Invoice? = null
@Column
var date: LocalDateTime? = null
constructor()
constructor(amount: Money, user: User, fidorId: Long? = null, date: LocalDateTime? = null) {
this.amount = amount
this.user = user.account
this.fidorId = fidorId
this.date = date
}
abstract fun getPaymentMethod(): String
fun user(): User? {
return this.user
}
@PreRemove
fun preRemove() {
this.user?.payments?.remove(this)
this.user = null
}
}
| agpl-3.0 | b5876714340f87d147191c1f6a78d8c6 | 20.403846 | 96 | 0.674753 | 4.062044 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/util/psi-utils.kt | 1 | 7558 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModule
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.OrderEntryUtil
import com.intellij.psi.ElementManipulator
import com.intellij.psi.ElementManipulators
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiKeyword
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifier.ModifierConstant
import com.intellij.psi.PsiParameter
import com.intellij.psi.PsiParameterList
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiType
import com.intellij.psi.ResolveResult
import com.intellij.psi.filters.ElementFilter
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.refactoring.changeSignature.ChangeSignatureUtil
import com.siyeh.ig.psiutils.ImportUtils
import java.util.stream.Stream
// Parent
fun PsiElement.findModule(): Module? = ModuleUtilCore.findModuleForPsiElement(this)
fun PsiElement.findContainingClass(): PsiClass? = findParent(resolveReferences = false)
fun PsiElement.findReferencedClass(): PsiClass? = findParent(resolveReferences = true)
fun PsiElement.findReferencedMember(): PsiMember? = findParent({ it is PsiClass }, resolveReferences = true)
fun PsiElement.findContainingMember(): PsiMember? = findParent({ it is PsiClass }, resolveReferences = false)
fun PsiElement.findContainingMethod(): PsiMethod? = findParent({ it is PsiClass }, resolveReferences = false)
private inline fun <reified T : PsiElement> PsiElement.findParent(resolveReferences: Boolean): T? {
return findParent({ false }, resolveReferences)
}
private inline fun <reified T : PsiElement> PsiElement.findParent(
stop: (PsiElement) -> Boolean,
resolveReferences: Boolean
): T? {
var el: PsiElement = this
while (true) {
if (resolveReferences && el is PsiReference) {
el = el.resolve() ?: return null
}
if (el is T) {
return el
}
if (el is PsiFile || el is PsiDirectory || stop(el)) {
return null
}
el = el.parent ?: return null
}
}
// Children
fun PsiClass.findFirstMember(): PsiMember? = findChild()
fun PsiElement.findNextMember(): PsiMember? = findSibling(true)
private inline fun <reified T : PsiElement> PsiElement.findChild(): T? {
return firstChild?.findSibling(strict = false)
}
private inline fun <reified T : PsiElement> PsiElement.findSibling(strict: Boolean): T? {
var sibling = if (strict) nextSibling ?: return null else this
while (true) {
if (sibling is T) {
return sibling
}
sibling = sibling.nextSibling ?: return null
}
}
fun PsiElement.findKeyword(name: String): PsiKeyword? {
forEachChild {
if (it is PsiKeyword && it.text == name) {
return it
}
}
return null
}
private inline fun PsiElement.forEachChild(func: (PsiElement) -> Unit) {
firstChild?.forEachSibling(func, strict = false)
}
private inline fun PsiElement.forEachSibling(func: (PsiElement) -> Unit, strict: Boolean) {
var sibling = if (strict) nextSibling ?: return else this
while (true) {
func(sibling)
sibling = sibling.nextSibling ?: return
}
}
inline fun PsiElement.findLastChild(condition: (PsiElement) -> Boolean): PsiElement? {
var child = firstChild ?: return null
var lastChild: PsiElement? = null
while (true) {
if (condition(child)) {
lastChild = child
}
child = child.nextSibling ?: return lastChild
}
}
fun <T : Any> Sequence<T>.filter(filter: ElementFilter?, context: PsiElement): Sequence<T> {
filter ?: return this
return filter { filter.isAcceptable(it, context) }
}
fun Stream<out PsiElement>.toResolveResults(): Array<ResolveResult> = map(::PsiElementResolveResult).toTypedArray()
fun PsiParameterList.synchronize(newParams: List<PsiParameter>) {
ChangeSignatureUtil.synchronizeList(this, newParams, { it.parameters.asList() }, BooleanArray(newParams.size))
}
val PsiElement.constantValue: Any?
get() = JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(this)
val PsiElement.constantStringValue: String?
get() = constantValue as? String
private val ACCESS_MODIFIERS =
listOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED, PsiModifier.PRIVATE, PsiModifier.PACKAGE_LOCAL)
fun isAccessModifier(@ModifierConstant modifier: String): Boolean {
return modifier in ACCESS_MODIFIERS
}
infix fun PsiElement.equivalentTo(other: PsiElement): Boolean {
return manager.areElementsEquivalent(this, other)
}
fun PsiType?.isErasureEquivalentTo(other: PsiType?): Boolean {
// TODO: Do more checks for generics instead
return TypeConversionUtil.erasure(this) == TypeConversionUtil.erasure(other)
}
val PsiMethod.nameAndParameterTypes: String
get() = "$name(${parameterList.parameters.joinToString(", ") { it.type.presentableText }})"
val <T : PsiElement> T.manipulator: ElementManipulator<T>?
get() = ElementManipulators.getManipulator(this)
inline fun <T> PsiElement.cached(crossinline compute: () -> T): T {
return CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create(compute(), this) }
}
fun LookupElementBuilder.withImportInsertion(toImport: List<PsiClass>): LookupElementBuilder =
this.withInsertHandler { insertionContext, _ ->
toImport.forEach { ImportUtils.addImportIfNeeded(it, insertionContext.file) }
}
fun PsiElement.findMcpModule() = this.cached {
val file = containingFile?.virtualFile ?: return@cached null
val index = ProjectFileIndex.getInstance(project)
val modules = if (index.isInLibrary(file)) {
val library = index.getOrderEntriesForFile(file)
.asSequence()
.mapNotNull { it as? LibraryOrderEntry }
.firstOrNull()
?.library
?: return@cached null
ModuleManager.getInstance(project).modules.asSequence()
.filter { OrderEntryUtil.findLibraryOrderEntry(ModuleRootManager.getInstance(it), library) != null }
} else sequenceOf(this.findModule())
modules.mapNotNull { it?.findMcpModule() }.firstOrNull()
}
private fun Module.findMcpModule(): McpModule? {
var result: McpModule? = null
ModuleUtilCore.visitMeAndDependentModules(this) {
result = MinecraftFacet.getInstance(it, McpModuleType)
result == null
}
return result
}
val PsiElement.mcVersion: SemanticVersion?
get() = this.cached {
findMcpModule()?.let {
SemanticVersion.parse(it.getSettings().minecraftVersion ?: return@let null)
}
}
| mit | f0dc0eee4cf6ada04aa88ddc5ec0513e | 32.892377 | 115 | 0.732072 | 4.453742 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerServiceImpl.kt | 2 | 10601 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.formatting.visualLayer
import com.intellij.application.options.CodeStyle
import com.intellij.codeInspection.incorrectFormatting.FormattingChanges
import com.intellij.codeInspection.incorrectFormatting.detectFormattingChanges
import com.intellij.formatting.visualLayer.VisualFormattingLayerElement.*
import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.LineSet
import com.intellij.psi.PsiDocumentManager
import kotlin.math.min
@Service
class VisualFormattingLayerServiceImpl : VisualFormattingLayerService() {
override fun getVisualFormattingLayerElements(editor: Editor): List<VisualFormattingLayerElement> {
val project = editor.project ?: return emptyList()
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return emptyList()
val codeStyleSettings = editor.visualFormattingLayerCodeStyleSettings ?: return emptyList()
var formattingChanges: FormattingChanges? = null
CodeStyle.doWithTemporarySettings(file.project, codeStyleSettings, Runnable {
if (file.isValid) {
formattingChanges = detectFormattingChanges(file)
}
})
if (formattingChanges == null) {
return emptyList()
}
val tabSize = codeStyleSettings.getTabSize(file.fileType)
return formattingChanges!!.mismatches
.flatMap { mismatch -> formattingElements(editor.document, formattingChanges!!.postFormatText, mismatch, tabSize) }
.filterNotNull()
.toList()
}
private fun formattingElements(document: Document,
formattedText: CharSequence,
mismatch: FormattingChanges.WhitespaceMismatch,
tabSize: Int): Sequence<VisualFormattingLayerElement?> = sequence {
val originalText = document.text
val replacementLines = LineSet.createLineSet(formattedText)
val originalFirstLine = document.getLineNumber(mismatch.preFormatRange.startOffset)
val replacementFirstLine = replacementLines.findLineIndex(mismatch.postFormatRange.startOffset)
val n = document.getLineNumber(mismatch.preFormatRange.endOffset) - originalFirstLine + 1
val m = mismatch.postFormatRange.let { replacementLines.findLineIndex(it.endOffset) - replacementLines.findLineIndex(it.startOffset) } + 1
// This case needs soft wraps to visually split the existing line.
// Not supported by API yet, so we will just skip it for now.
if (1 == n && n < m) {
return@sequence
}
// Fold first (N - M + 1) lines into one line of the replacement...
if (n > m) {
val originalStartOffset = mismatch.preFormatRange.startOffset
val originalEndOffset = min(document.getLineEndOffset(originalFirstLine + n - m), mismatch.preFormatRange.endOffset)
val originalLineStartOffset = document.getLineStartOffset(originalFirstLine)
val replacementStartOffset = mismatch.postFormatRange.startOffset
val replacementEndOffset = min(replacementLines.getLineEnd(replacementFirstLine), mismatch.postFormatRange.endOffset)
val replacementLineStartOffset = replacementLines.getLineStart(replacementFirstLine)
yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalStartOffset, originalEndOffset,
formattedText, replacementLineStartOffset, replacementStartOffset, replacementEndOffset,
tabSize))
}
// ...or skip the first line by folding and add block inlay for (M - N) lines
if (n <= m) {
val originalStartOffset = mismatch.preFormatRange.startOffset
// This breaks down when (1 = N < M), but we've filtered out this case in the beginning
val originalEndOffset = min(document.getLineEndOffset(originalFirstLine), mismatch.preFormatRange.endOffset)
val originalLineStartOffset = document.getLineStartOffset(originalFirstLine)
val replacementStartOffset = mismatch.postFormatRange.startOffset
val replacementEndOffset = min(replacementLines.getLineEnd(replacementFirstLine), mismatch.postFormatRange.endOffset)
val replacementLineStartOffset = replacementLines.getLineStart(replacementFirstLine)
yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalStartOffset, originalEndOffset,
formattedText, replacementLineStartOffset, replacementStartOffset, replacementEndOffset,
tabSize))
// add block inlay for M - N lines after firstLine, might be empty.
yield(blockInlay(document.getLineStartOffset(originalFirstLine + 1), m - n))
}
/*
Now we have processed some lines. Both original whitespace and replacement
have similar number lines left to process. This number depends on (N < M)
but is always equal to MIN(N, M) - 1. See diagram for clarifying:
N > M N <= M
┌─────┐ ─────┐ Fold/Inlay ┌─────┐
│ 1 │ │ ┌────────► │ 1 │
├─────┤ │ │ ┌─────── ├─────┤
│ │ Fold │ │ │ │ │
│N - M│ │ ┌─────┐ ┌─────┐ │ │ Block │M - N│
│ │ ├─► │ 1 │ │ 1 │ ─┘ │ Inlay │ │
├─────┤ ─────┘ ├─────┤ ├─────┤ ◄──┴─────── ├─────┤
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ │Fold/Inlay│ │ │ │ Fold/Inlay │ │
│M - 1│ line by │M - 1│ │N - 1│ line by │N - 1│
│ │ line │ │ │ │ line │ │
│ │ ───────► │ │ │ │ ──────────► │ │
│ │ │ │ │ │ │ │
└─────┘ └─────┘ └─────┘ └─────┘
*/
// Fold the rest lines one by one
val linesToProcess = min(n, m) - 1
for (i in 1..linesToProcess) {
val originalLine = originalFirstLine + n - linesToProcess + i - 1 // goes up until last line inclusively
val replacementLine = replacementFirstLine + m - linesToProcess + i - 1 // goes up until last replacement line inclusively
val originalLineStartOffset = document.getLineStartOffset(originalLine)
val originalEndOffset = min(document.getLineEndOffset(originalLine), mismatch.preFormatRange.endOffset)
val replacementLineStartOffset = replacementLines.getLineStart(replacementLine)
val replacementEndOffset = min(replacementLines.getLineEnd(replacementLine), mismatch.postFormatRange.endOffset)
yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalLineStartOffset, originalEndOffset,
formattedText, replacementLineStartOffset, replacementLineStartOffset, replacementEndOffset,
tabSize))
}
}
// Visually replaces whitespace (or its absence) with a proper one
private fun inlayOrFold(original: CharSequence,
originalLineStartOffset: Int,
originalStartOffset: Int,
originalEndOffset: Int,
formatted: CharSequence,
replacementLineStartOffset: Int,
replacementStartOffset: Int,
replacementEndOffset: Int,
tabSize: Int) = sequence {
val (originalColumns, originalContainsTabs) = countColumnsWithinLine(original, originalLineStartOffset, originalStartOffset,
originalEndOffset, tabSize)
val (replacementColumns, _) = countColumnsWithinLine(formatted, replacementLineStartOffset, replacementStartOffset,
replacementEndOffset, tabSize)
val columnsDelta = replacementColumns - originalColumns
when {
columnsDelta > 0 -> yield(InlineInlay(originalEndOffset, columnsDelta))
columnsDelta < 0 -> {
val originalLength = originalEndOffset - originalStartOffset
if (originalContainsTabs) {
yield(Folding(originalStartOffset, originalLength))
if (replacementColumns > 0) {
yield(InlineInlay(originalEndOffset, replacementColumns))
}
}
else {
yield(Folding(originalStartOffset, -columnsDelta))
}
}
}
}
private fun blockInlay(offset: Int, lines: Int): VisualFormattingLayerElement? {
if (lines == 0) return null
return BlockInlay(offset, lines)
}
}
private fun countColumnsWithinLine(sequence: CharSequence,
lineStartOffset: Int,
fromOffset: Int,
untilOffset: Int,
tabSize: Int): Pair<Int, Boolean> {
val (startColumn, _) = countColumns(sequence, lineStartOffset, fromOffset, 0, tabSize)
return countColumns(sequence, fromOffset, untilOffset, startColumn, tabSize)
}
private fun countColumns(sequence: CharSequence,
fromOffset: Int,
untilOffset: Int,
startColumn: Int,
tabSize: Int): Pair<Int, Boolean> {
var cols = 0
var tabStopOffset = startColumn % tabSize
var containsTabs = false
for (offset in fromOffset until untilOffset) {
when (sequence[offset]) {
'\t' -> {
cols += tabSize - tabStopOffset
tabStopOffset = 0
containsTabs = true
}
'\n' -> {
break
}
else -> {
cols += 1
tabStopOffset = (tabStopOffset + 1) % tabSize
}
}
}
return Pair(cols, containsTabs)
}
| apache-2.0 | b1db3860556b069c09ffa3302c1062ad | 48.282927 | 142 | 0.61655 | 4.957311 | false | false | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/universal/UniversalEditionViewModel.kt | 1 | 2457 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.edition.universal
import com.sbgapps.scoreit.core.ext.replace
import com.sbgapps.scoreit.core.ui.BaseViewModel
import com.sbgapps.scoreit.data.interactor.GameUseCase
import com.sbgapps.scoreit.data.model.Player
import com.sbgapps.scoreit.data.model.UniversalLap
import io.uniflow.core.flow.data.UIState
class UniversalEditionViewModel(private val useCase: GameUseCase) : BaseViewModel() {
private val editedLap
get() = useCase.getEditedLap() as UniversalLap
fun loadContent() {
action {
setState { getContent() }
}
}
fun incrementScore(increment: Int, position: Int) {
action {
val oldPoints = editedLap.points
val newScore = oldPoints[position] + increment
val newPoints = oldPoints.replace(position, newScore)
useCase.updateEdition(UniversalLap(newPoints))
setState { getContent() }
}
}
fun setScore(position: Int, score: Int) {
action {
val newPoints = editedLap.points.replace(position, score)
useCase.updateEdition(UniversalLap(newPoints))
setState { getContent() }
}
}
fun cancelEdition() {
action {
useCase.cancelEdition()
setState { UniversalEditionState.Completed }
}
}
fun completeEdition() {
action {
useCase.completeEdition()
setState { UniversalEditionState.Completed }
}
}
private fun getContent(): UniversalEditionState.Content =
UniversalEditionState.Content(useCase.getPlayers(), editedLap.points)
}
sealed class UniversalEditionState : UIState() {
data class Content(val players: List<Player>, val results: List<Int>) : UniversalEditionState()
object Completed : UniversalEditionState()
}
| apache-2.0 | 21a943f6d6ffa4a85396ca169be53945 | 31.315789 | 99 | 0.680375 | 4.45735 | false | false | false | false |
resilience4j/resilience4j | resilience4j-kotlin/src/test/kotlin/io/github/resilience4j/kotlin/retry/RetryTest.kt | 1 | 7358 | /*
*
* Copyright 2019: Brad Newman
*
* 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.github.resilience4j.kotlin.retry
import io.github.resilience4j.kotlin.HelloWorldService
import io.github.resilience4j.retry.Retry
import org.assertj.core.api.Assertions
import org.junit.Test
import java.time.Duration
import java.util.concurrent.atomic.AtomicInteger
import java.util.function.BiConsumer
import java.util.function.Predicate
class RetryTest {
@Test
fun `should execute successful function`() {
val retry = Retry.ofDefaults("testName")
val metrics = retry.metrics
val helloWorldService = HelloWorldService()
//When
val result = retry.executeFunction {
helloWorldService.returnHelloWorld()
}
//Then
Assertions.assertThat(result).isEqualTo("Hello world")
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithoutRetryAttempt).isEqualTo(1)
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithRetryAttempt).isZero()
// Then the helloWorldService should be invoked 1 time
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1)
}
@Test
fun `should execute function with retries`() {
val retry = Retry.of("testName") {
RetryConfig { waitDuration(Duration.ofMillis(10)) }
}
val metrics = retry.metrics
val helloWorldService = HelloWorldService()
//When
val result = retry.executeFunction {
when (helloWorldService.invocationCounter) {
0 -> helloWorldService.throwException()
else -> helloWorldService.returnHelloWorld()
}
}
//Then
Assertions.assertThat(result).isEqualTo("Hello world")
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithRetryAttempt).isEqualTo(1)
Assertions.assertThat(metrics.numberOfFailedCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithRetryAttempt).isZero()
// Then the helloWorldService should be invoked twice
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(2)
}
@Test
fun `should execute function with retry of result`() {
val helloWorldService = HelloWorldService()
val retry = Retry.of("testName") {
RetryConfig {
waitDuration(Duration.ofMillis(10))
retryOnResult { helloWorldService.invocationCounter < 2 }
}
}
val metrics = retry.metrics
//When
val result = retry.executeFunction {
helloWorldService.returnHelloWorld()
}
//Then
Assertions.assertThat(result).isEqualTo("Hello world")
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithRetryAttempt).isEqualTo(1)
Assertions.assertThat(metrics.numberOfFailedCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithRetryAttempt).isZero()
// Then the helloWorldService should be invoked twice
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(2)
}
@Test
fun `should execute function with repeated failures`() {
val retry = Retry.of("testName") {
RetryConfig { waitDuration(Duration.ofMillis(10)) }
}
val metrics = retry.metrics
val helloWorldService = HelloWorldService()
//When
try {
retry.executeFunction {
helloWorldService.throwException()
}
Assertions.failBecauseExceptionWasNotThrown<Nothing>(IllegalStateException::class.java)
} catch (e: IllegalStateException) {
// nothing - proceed
}
//Then
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithRetryAttempt).isEqualTo(1)
// Then the helloWorldService should be invoked the maximum number of times
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(retry.retryConfig.maxAttempts)
}
@Test
fun `should decorate successful function`() {
val retry = Retry.ofDefaults("testName")
val metrics = retry.metrics
val helloWorldService = HelloWorldService()
//When
val function = retry.decorateFunction {
helloWorldService.returnHelloWorld()
}
//Then
Assertions.assertThat(function()).isEqualTo("Hello world")
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithoutRetryAttempt).isEqualTo(1)
Assertions.assertThat(metrics.numberOfSuccessfulCallsWithRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithoutRetryAttempt).isZero()
Assertions.assertThat(metrics.numberOfFailedCallsWithRetryAttempt).isZero()
// Then the helloWorldService should be invoked 1 time
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1)
}
@Test
fun `should perform consumeResultBeforeRetryAttempt on retry`() {
val helloWorldService = HelloWorldService()
val helloWorldServiceReturnValue = "Hello world"
val shouldRetry = Predicate { s: String? -> helloWorldServiceReturnValue == s }
val consumerInvocations = AtomicInteger(0)
val consumeResultBeforeRetryAttempt = BiConsumer { currentAttempt: Int?, value: String ->
if (helloWorldServiceReturnValue == value) {
consumerInvocations.set(currentAttempt!!)
}
}
val config = io.github.resilience4j.retry.RetryConfig.Builder<String>()
.retryOnResult(shouldRetry)
.consumeResultBeforeRetryAttempt(consumeResultBeforeRetryAttempt)
.build()
val retry = Retry.of("id", config)
val supplier = Retry.decorateSupplier(retry) { helloWorldService.returnHelloWorld() }
val result = supplier.get()
Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(3)
Assertions.assertThat(result).isEqualTo(helloWorldServiceReturnValue)
Assertions.assertThat(consumerInvocations.get()).isEqualTo(2)
}
}
| apache-2.0 | 437107aa17a5c8978618c42f36b5191f | 39.877778 | 107 | 0.697336 | 5.174402 | false | true | false | false |
allotria/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/PackageManagementPanel.kt | 1 | 3105 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.Separator
import com.intellij.ui.AutoScrollToSourceHandler
import com.intellij.ui.JBSplitter
import com.intellij.util.ui.JBUI
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchToolWindowModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.left.PackagesSmartPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.right.PackagesChosenPanel
import java.awt.Dimension
import javax.swing.JComponent
class PackageManagementPanel(private val viewModel: PackageSearchToolWindowModel) :
PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")) {
private val refreshAction =
object : AnAction(
PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.reload.text"),
PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.reload.description"),
AllIcons.Actions.Refresh
) {
override fun actionPerformed(e: AnActionEvent) {
viewModel.requestRefreshContext.fire(true)
}
}
private val autoScrollToSourceHandler = object : AutoScrollToSourceHandler() {
override fun isAutoScrollMode(): Boolean {
return PackageSearchGeneralConfiguration.getInstance(viewModel.project).autoScrollToSource
}
override fun setAutoScrollMode(state: Boolean) {
PackageSearchGeneralConfiguration.getInstance(viewModel.project).autoScrollToSource = state
}
}
private val mainSplitter = JBSplitter("PackageSearch.PackageManagementPanel.Splitter", 0.5f).apply {
firstComponent = PackagesSmartPanel(viewModel, autoScrollToSourceHandler).content.apply {
minimumSize = Dimension(JBUI.scale(250), 0)
}
secondComponent = PackagesChosenPanel(viewModel).content
orientation = false
dividerWidth = JBUI.scale(2)
}
override fun build() = mainSplitter
override fun buildToolbar(): JComponent? {
val actionGroup = DefaultActionGroup(
refreshAction,
Separator(),
ShowSettingsAction(viewModel.project),
autoScrollToSourceHandler.createToggleAction()
)
return ActionManager.getInstance().createActionToolbar("", actionGroup, false).component
}
}
| apache-2.0 | a1b9bbb93605d629baf4d6c3c48ed498 | 45.343284 | 108 | 0.767794 | 5.236088 | false | true | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/docs/loader/xml/block/HeadingState.kt | 1 | 980 | package de.theunknownxy.mcdocs.docs.loader.xml.block
import de.theunknownxy.mcdocs.docs.HeadingBlock
import de.theunknownxy.mcdocs.docs.loader.xml.State
import de.theunknownxy.mcdocs.docs.loader.xml.XMLParserHandler
import org.xml.sax.Attributes
import org.xml.sax.SAXException
class HeadingState(handler: XMLParserHandler, val level: Int) : State(handler) {
var text = ""
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
throw SAXException("Invalid tag '$qName' in heading")
}
override fun endElement(uri: String?, localName: String, qName: String) {
if (qName.equalsIgnoreCase("h$level")) {
assert(handler.xmlstate.pop() === this)
handler.document.content.blocks.add(HeadingBlock(level, text))
} else {
throw SAXException("Invalid end tag '$qName' in heading")
}
}
override fun characters(str: String) {
text += str
}
} | mit | 6aa62c27c8fc1a863e0142d5ee857dde | 34.035714 | 102 | 0.690816 | 4.06639 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/ThreadContextElement.kt | 1 | 12979 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
/**
* Defines elements in [CoroutineContext] that are installed into thread context
* every time the coroutine with this element in the context is resumed on a thread.
*
* Implementations of this interface define a type [S] of the thread-local state that they need to store on
* resume of a coroutine and restore later on suspend. The infrastructure provides the corresponding storage.
*
* Example usage looks like this:
*
* ```
* // Appends "name" of a coroutine to a current thread name when coroutine is executed
* class CoroutineName(val name: String) : ThreadContextElement<String> {
* // declare companion object for a key of this element in coroutine context
* companion object Key : CoroutineContext.Key<CoroutineName>
*
* // provide the key of the corresponding context element
* override val key: CoroutineContext.Key<CoroutineName>
* get() = Key
*
* // this is invoked before coroutine is resumed on current thread
* override fun updateThreadContext(context: CoroutineContext): String {
* val previousName = Thread.currentThread().name
* Thread.currentThread().name = "$previousName # $name"
* return previousName
* }
*
* // this is invoked after coroutine has suspended on current thread
* override fun restoreThreadContext(context: CoroutineContext, oldState: String) {
* Thread.currentThread().name = oldState
* }
* }
*
* // Usage
* launch(Dispatchers.Main + CoroutineName("Progress bar coroutine")) { ... }
* ```
*
* Every time this coroutine is resumed on a thread, UI thread name is updated to
* "UI thread original name # Progress bar coroutine" and the thread name is restored to the original one when
* this coroutine suspends.
*
* To use [ThreadLocal] variable within the coroutine use [ThreadLocal.asContextElement][asContextElement] function.
*
* ### Reentrancy and thread-safety
*
* Correct implementations of this interface must expect that calls to [restoreThreadContext]
* may happen in parallel to the subsequent [updateThreadContext] and [restoreThreadContext] operations.
* See [CopyableThreadContextElement] for advanced interleaving details.
*
* All implementations of [ThreadContextElement] should be thread-safe and guard their internal mutable state
* within an element accordingly.
*/
public interface ThreadContextElement<S> : CoroutineContext.Element {
/**
* Updates context of the current thread.
* This function is invoked before the coroutine in the specified [context] is resumed in the current thread
* when the context of the coroutine this element.
* The result of this function is the old value of the thread-local state that will be passed to [restoreThreadContext].
* This method should handle its own exceptions and do not rethrow it. Thrown exceptions will leave coroutine which
* context is updated in an undefined state and may crash an application.
*
* @param context the coroutine context.
*/
public fun updateThreadContext(context: CoroutineContext): S
/**
* Restores context of the current thread.
* This function is invoked after the coroutine in the specified [context] is suspended in the current thread
* if [updateThreadContext] was previously invoked on resume of this coroutine.
* The value of [oldState] is the result of the previous invocation of [updateThreadContext] and it should
* be restored in the thread-local state by this function.
* This method should handle its own exceptions and do not rethrow it. Thrown exceptions will leave coroutine which
* context is updated in an undefined state and may crash an application.
*
* @param context the coroutine context.
* @param oldState the value returned by the previous invocation of [updateThreadContext].
*/
public fun restoreThreadContext(context: CoroutineContext, oldState: S)
}
/**
* A [ThreadContextElement] copied whenever a child coroutine inherits a context containing it.
*
* When an API uses a _mutable_ [ThreadLocal] for consistency, a [CopyableThreadContextElement]
* can give coroutines "coroutine-safe" write access to that `ThreadLocal`.
*
* A write made to a `ThreadLocal` with a matching [CopyableThreadContextElement] by a coroutine
* will be visible to _itself_ and any child coroutine launched _after_ that write.
*
* Writes will not be visible to the parent coroutine, peer coroutines, or coroutines that happen
* to use the same thread. Writes made to the `ThreadLocal` by the parent coroutine _after_
* launching a child coroutine will not be visible to that child coroutine.
*
* This can be used to allow a coroutine to use a mutable ThreadLocal API transparently and
* correctly, regardless of the coroutine's structured concurrency.
*
* This example adapts a `ThreadLocal` method trace to be "coroutine local" while the method trace
* is in a coroutine:
*
* ```
* class TraceContextElement(private val traceData: TraceData?) : CopyableThreadContextElement<TraceData?> {
* companion object Key : CoroutineContext.Key<TraceContextElement>
*
* override val key: CoroutineContext.Key<TraceContextElement> = Key
*
* override fun updateThreadContext(context: CoroutineContext): TraceData? {
* val oldState = traceThreadLocal.get()
* traceThreadLocal.set(traceData)
* return oldState
* }
*
* override fun restoreThreadContext(context: CoroutineContext, oldState: TraceData?) {
* traceThreadLocal.set(oldState)
* }
*
* override fun copyForChild(): TraceContextElement {
* // Copy from the ThreadLocal source of truth at child coroutine launch time. This makes
* // ThreadLocal writes between resumption of the parent coroutine and the launch of the
* // child coroutine visible to the child.
* return TraceContextElement(traceThreadLocal.get()?.copy())
* }
*
* override fun mergeForChild(overwritingElement: CoroutineContext.Element): CoroutineContext {
* // Merge operation defines how to handle situations when both
* // the parent coroutine has an element in the context and
* // an element with the same key was also
* // explicitly passed to the child coroutine.
* // If merging does not require special behavior,
* // the copy of the element can be returned.
* return TraceContextElement(traceThreadLocal.get()?.copy())
* }
* }
* ```
*
* A coroutine using this mechanism can safely call Java code that assumes the corresponding thread local element's
* value is installed into the target thread local.
*
* ### Reentrancy and thread-safety
*
* Correct implementations of this interface must expect that calls to [restoreThreadContext]
* may happen in parallel to the subsequent [updateThreadContext] and [restoreThreadContext] operations.
*
* Even though an element is copied for each child coroutine, an implementation should be able to handle the following
* interleaving when a coroutine with the corresponding element is launched on a multithreaded dispatcher:
*
* ```
* coroutine.updateThreadContext() // Thread #1
* ... coroutine body ...
* // suspension + immediate dispatch happen here
* coroutine.updateThreadContext() // Thread #2, coroutine is already resumed
* // ... coroutine body after suspension point on Thread #2 ...
* coroutine.restoreThreadContext() // Thread #1, is invoked late because Thread #1 is slow
* coroutine.restoreThreadContext() // Thread #2, may happen in parallel with the previous restore
* ```
*
* All implementations of [CopyableThreadContextElement] should be thread-safe and guard their internal mutable state
* within an element accordingly.
*/
@DelicateCoroutinesApi
@ExperimentalCoroutinesApi
public interface CopyableThreadContextElement<S> : ThreadContextElement<S> {
/**
* Returns a [CopyableThreadContextElement] to replace `this` `CopyableThreadContextElement` in the child
* coroutine's context that is under construction if the added context does not contain an element with the same [key].
*
* This function is called on the element each time a new coroutine inherits a context containing it,
* and the returned value is folded into the context given to the child.
*
* Since this method is called whenever a new coroutine is launched in a context containing this
* [CopyableThreadContextElement], implementations are performance-sensitive.
*/
public fun copyForChild(): CopyableThreadContextElement<S>
/**
* Returns a [CopyableThreadContextElement] to replace `this` `CopyableThreadContextElement` in the child
* coroutine's context that is under construction if the added context does contain an element with the same [key].
*
* This method is invoked on the original element, accepting as the parameter
* the element that is supposed to overwrite it.
*/
public fun mergeForChild(overwritingElement: CoroutineContext.Element): CoroutineContext
}
/**
* Wraps [ThreadLocal] into [ThreadContextElement]. The resulting [ThreadContextElement]
* maintains the given [value] of the given [ThreadLocal] for coroutine regardless of the actual thread its is resumed on.
* By default [ThreadLocal.get] is used as a value for the thread-local variable, but it can be overridden with [value] parameter.
* Beware that context element **does not track** modifications of the thread-local and accessing thread-local from coroutine
* without the corresponding context element returns **undefined** value. See the examples for a detailed description.
*
*
* Example usage:
* ```
* val myThreadLocal = ThreadLocal<String?>()
* ...
* println(myThreadLocal.get()) // Prints "null"
* launch(Dispatchers.Default + myThreadLocal.asContextElement(value = "foo")) {
* println(myThreadLocal.get()) // Prints "foo"
* withContext(Dispatchers.Main) {
* println(myThreadLocal.get()) // Prints "foo", but it's on UI thread
* }
* }
* println(myThreadLocal.get()) // Prints "null"
* ```
*
* The context element does not track modifications of the thread-local variable, for example:
*
* ```
* myThreadLocal.set("main")
* withContext(Dispatchers.Main) {
* println(myThreadLocal.get()) // Prints "main"
* myThreadLocal.set("UI")
* }
* println(myThreadLocal.get()) // Prints "main", not "UI"
* ```
*
* Use `withContext` to update the corresponding thread-local variable to a different value, for example:
* ```
* withContext(myThreadLocal.asContextElement("foo")) {
* println(myThreadLocal.get()) // Prints "foo"
* }
* ```
*
* Accessing the thread-local without corresponding context element leads to undefined value:
* ```
* val tl = ThreadLocal.withInitial { "initial" }
*
* runBlocking {
* println(tl.get()) // Will print "initial"
* // Change context
* withContext(tl.asContextElement("modified")) {
* println(tl.get()) // Will print "modified"
* }
* // Context is changed again
* println(tl.get()) // <- WARN: can print either "modified" or "initial"
* }
* ```
* to fix this behaviour use `runBlocking(tl.asContextElement())`
*/
public fun <T> ThreadLocal<T>.asContextElement(value: T = get()): ThreadContextElement<T> =
ThreadLocalElement(value, this)
/**
* Return `true` when current thread local is present in the coroutine context, `false` otherwise.
* Thread local can be present in the context only if it was added via [asContextElement] to the context.
*
* Example of usage:
* ```
* suspend fun processRequest() {
* if (traceCurrentRequestThreadLocal.isPresent()) { // Probabilistic tracing
* // Do some heavy-weight tracing
* }
* // Process request regularly
* }
* ```
*/
public suspend inline fun ThreadLocal<*>.isPresent(): Boolean = coroutineContext[ThreadLocalKey(this)] !== null
/**
* Checks whether current thread local is present in the coroutine context and throws [IllegalStateException] if it is not.
* It is a good practice to validate that thread local is present in the context, especially in large code-bases,
* to avoid stale thread-local values and to have a strict invariants.
*
* E.g. one may use the following method to enforce proper use of the thread locals with coroutines:
* ```
* public suspend inline fun <T> ThreadLocal<T>.getSafely(): T {
* ensurePresent()
* return get()
* }
*
* // Usage
* withContext(...) {
* val value = threadLocal.getSafely() // Fail-fast in case of improper context
* }
* ```
*/
public suspend inline fun ThreadLocal<*>.ensurePresent(): Unit =
check(isPresent()) { "ThreadLocal $this is missing from context $coroutineContext" }
| apache-2.0 | 5e214f14ea83f3d73db0d038b3f5b722 | 44.222997 | 130 | 0.720086 | 4.534941 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogEditorTabSelector.kt | 1 | 2138 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManagerAdapter
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.TabbedContent
import com.intellij.vcs.log.ui.VcsLogUiImpl
import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
open class VcsLogEditorTabSelector(private val project: Project) : ContentManagerAdapter(), PropertyChangeListener {
override fun selectionChanged(event: ContentManagerEvent) {
if (ContentManagerEvent.ContentOperation.add == event.operation) {
val content = event.content
selectEditorTab(content)
}
}
protected open fun selectEditorTab(content: Content) {
val ui = VcsLogContentUtil.getLogUi(content.component)
if (ui is VcsLogUiImpl) {
val frame = ui.mainFrame
frame.openLogEditorTab()
}
}
override fun contentAdded(event: ContentManagerEvent) {
val content = event.content
if (content is TabbedContent) {
content.addPropertyChangeListener(this)
}
}
override fun contentRemoved(event: ContentManagerEvent) {
val content = event.content
if (content is TabbedContent) {
content.removePropertyChangeListener(this)
}
}
private fun getToolWindow(): ToolWindow? {
return ToolWindowManager.getInstance(project).getToolWindow(
ChangesViewContentManager.TOOLWINDOW_ID)
}
override fun propertyChange(evt: PropertyChangeEvent) {
if (evt.propertyName == Content.PROP_COMPONENT) {
val toolWindow = getToolWindow()
if (toolWindow != null && toolWindow.isVisible) {
val content = toolWindow.contentManager.selectedContent
if (content != null) {
selectEditorTab(content)
}
}
}
}
} | apache-2.0 | da267297274cad3b7c194fc7491d4be8 | 32.421875 | 140 | 0.747895 | 4.617711 | false | false | false | false |
stefanosiano/PowerfulImageView | powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/blur/algorithms/BlurManager.kt | 1 | 14361 | package com.stefanosiano.powerful_libraries.imageview.blur.algorithms
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.util.Log
import android.widget.ImageView
import androidx.annotation.VisibleForTesting
import com.stefanosiano.powerful_libraries.imageview.blur.BlurOptions
import com.stefanosiano.powerful_libraries.imageview.blur.PivBlurMode
import com.stefanosiano.powerful_libraries.imageview.extensions.createBitmap
import com.stefanosiano.powerful_libraries.imageview.extensions.isVector
import java.lang.ref.WeakReference
/** Manager class for blurring. Used to manage and blur the image. */
@Suppress("TooManyFunctions")
internal class BlurManager(view: ImageView, blurOptions: BlurOptions) : BlurOptions.BlurOptionsListener {
/** Drawable of the imageview to blur. */
private var mDrawable: Drawable? = null
/** Original bitmap, down-sampled if needed. */
private var mOriginalBitmap: Bitmap? = null
/** Last blurred bitmap. */
private var mBlurredBitmap: Bitmap? = null
/** Options to use to blur bitmap. */
private var mBlurOptions: BlurOptions = blurOptions
/** Mode to use to blur the image. */
private var mMode: PivBlurMode = PivBlurMode.DISABLED
/** Strength of the blur. */
private var mRadius: Int = 0
/** Whether the renderscript context is managed: if I added this view's context to the SharedBlurManager. */
private var mIsRenderscriptManaged: Boolean = false
/** Whether the bitmap has been already blurred. On static blur, it will only blur once! */
private var mIsAlreadyBlurred: Boolean = false
/** Width of the view. Used to calculate the original bitmap. */
private var mWidth: Int = 0
/** Height of the view. Used to calculate the original bitmap. */
private var mHeight: Int = 0
/** Last width of the calculated bitmap. Used to calculate the original bitmap. */
private var mLastSizeX: Int = 0
/** Last height of the calculated bitmap. Used to calculate the original bitmap. */
private var mLastSizeY: Int = 0
/** Last radius used to blur the image. Used to avoid blurring twice again the same image with the same radius. */
private var mLastRadius: Int = -1
// Using a weakReference to be sure not to leak memory
private var mView: WeakReference<ImageView> = WeakReference(view)
// Algorithms
private val mBox3x3BlurAlgorithm by lazy { Box3x3BlurAlgorithm() }
private val mBox3x3RenderscriptBlurAlgorithm by lazy { Box3x3RenderscriptBlurAlgorithm() }
private val mBox5x5BlurAlgorithm by lazy { Box5x5BlurAlgorithm() }
private val mBox5x5RenderscriptBlurAlgorithm by lazy { Box5x5RenderscriptBlurAlgorithm() }
private val mGaussian5x5BlurAlgorithm by lazy { Gaussian5x5BlurAlgorithm() }
private val mGaussian5x5RenderscriptBlurAlgorithm by lazy { Gaussian5x5RenderscriptBlurAlgorithm() }
private val mGaussian3x3BlurAlgorithm by lazy { Gaussian3x3BlurAlgorithm() }
private val mGaussian3x3RenderscriptBlurAlgorithm by lazy { Gaussian3x3RenderscriptBlurAlgorithm() }
private val mGaussianBlurAlgorithm by lazy { GaussianBlurAlgorithm() }
private val mGaussianRenderscriptBlurAlgorithm by lazy { GaussianRenderscriptBlurAlgorithm() }
private val mStackBlurAlgorithm by lazy { StackBlurAlgorithm() }
private val mDummyBlurAlgorithm by lazy { DummyBlurAlgorithm() }
/** Selected algorithm to blur the image. */
private var mBlurAlgorithm: BlurAlgorithm = mDummyBlurAlgorithm
init {
this.mBlurOptions.setListener(this)
}
/** Method that updates the [drawable] and bitmap to show. */
fun changeDrawable(drawable: Drawable?) {
if (drawable == mDrawable && mOriginalBitmap != null) {
return
}
if (!shouldBlur(drawable, true)) {
mBlurredBitmap = null
// If mDrawable is null, it means we never used the blur manager, so we can skip any work
if (mDrawable == null) {
return
}
}
val mLastDrawable = mDrawable
val lastOriginalBitmap = mOriginalBitmap
this.mDrawable = drawable
this.mOriginalBitmap = getOriginalBitmapFromDrawable(mLastDrawable, drawable)
if (lastOriginalBitmap != mOriginalBitmap) {
mIsAlreadyBlurred = false
lastOriginalBitmap?.recycle()
mLastRadius = -1
}
}
/** Changes the [blurMode] and/or [radius] of the image. */
fun changeMode(blurMode: PivBlurMode, radius: Int) {
// If there's no change, I don't do anything
if (blurMode == mMode && radius == mRadius) {
return
}
removeContext(true)
mMode = blurMode
addContext(true)
// Otherwise i need to blur the image again
updateAlgorithms(blurMode)
mLastRadius = -1
mRadius = radius
if (!shouldBlur(mDrawable, false)) {
mBlurredBitmap = null
}
}
/** Changes the [radius] (strength) of the blur method. */
fun changeRadius(radius: Int) = changeMode(mMode, radius)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun setLastRadius(r: Int) {
mLastRadius = r
}
/**
* Blurs the image with the specified [radius], if not already blurred.
* To get the image call [getLastBlurredBitmap].
*/
fun blur(radius: Int) {
mRadius = radius
val origBitmap = mOriginalBitmap ?: return
// If I already blurred the image with this radius, I won't do anything
val blurredWithLastRadius = mLastRadius == radius && mBlurredBitmap != null
// If I already blurred the image and it's a static blur, I won't have to blur anymore
val blurredStatic = mIsAlreadyBlurred && mBlurOptions.isStaticBlur
if (origBitmap.isRecycled || blurredWithLastRadius || blurredStatic) {
return
}
this.mLastRadius = radius
if (origBitmap != mBlurredBitmap) {
mBlurredBitmap?.recycle()
}
var bitmap: Bitmap?
addContext(false)
try {
bitmap = mBlurAlgorithm.blur(origBitmap, mRadius, mBlurOptions)
mIsAlreadyBlurred = true
} catch (e: RenderscriptException) {
// Something wrong occurred with renderscript: fallback to java or nothing, based on option...
// Changing mode to fallback one if enabled
mMode = if (mBlurOptions.useRsFallback) mMode.fallbackMode else PivBlurMode.DISABLED
Log.w(
BlurManager::class.java.simpleName,
"${e.message}\nFalling back to another blurring method: ${mMode.name}"
)
updateAlgorithms(mMode)
try {
bitmap = mBlurAlgorithm.blur(origBitmap, mRadius, mBlurOptions)
mIsAlreadyBlurred = true
} catch (e1: RenderscriptException) {
// The second blur failed: we now return a null bitmap as it will be reverted to the original one
e1.printStackTrace()
bitmap = null
}
}
removeContext(false)
if (mBlurOptions.isStaticBlur) {
mOriginalBitmap = bitmap ?: origBitmap
}
mBlurredBitmap = bitmap ?: mBlurredBitmap
}
/** Updates the saved width and height, used to calculate the blurred bitmap. */
fun onSizeChanged(width: Int, height: Int) {
this.mWidth = width
this.mHeight = height
}
/** Updates the algorithm used to blur the image, based on [blurMode]. */
private fun updateAlgorithms(blurMode: PivBlurMode?) {
val renderScript = SharedBlurManager.getRenderScriptContext()
mMode = blurMode ?: PivBlurMode.DISABLED
// If renderscript is null and the mode uses it, there was a problem getting it: let's use java or dummy
if (mMode.usesRenderscript && renderScript == null) {
return updateAlgorithms(mMode.getFallbackMode(mBlurOptions.useRsFallback))
}
addContext(false)
mBlurAlgorithm = getBlurAlgorithmFromBlurMode()
mBlurAlgorithm.setRenderscript(renderScript)
}
private fun getBlurAlgorithmFromBlurMode() = when (mMode) {
PivBlurMode.STACK -> mStackBlurAlgorithm
PivBlurMode.GAUSSIAN5X5_RS -> mGaussian5x5RenderscriptBlurAlgorithm
PivBlurMode.GAUSSIAN5X5 -> mGaussian5x5BlurAlgorithm
PivBlurMode.GAUSSIAN3X3_RS -> mGaussian3x3RenderscriptBlurAlgorithm
PivBlurMode.GAUSSIAN3X3 -> mGaussian3x3BlurAlgorithm
PivBlurMode.BOX5X5_RS -> mBox5x5RenderscriptBlurAlgorithm
PivBlurMode.BOX5X5 -> mBox5x5BlurAlgorithm
PivBlurMode.BOX3X3_RS -> mBox3x3RenderscriptBlurAlgorithm
PivBlurMode.BOX3X3 -> mBox3x3BlurAlgorithm
PivBlurMode.GAUSSIAN_RS -> mGaussianRenderscriptBlurAlgorithm
PivBlurMode.GAUSSIAN -> mGaussianBlurAlgorithm
PivBlurMode.DISABLED -> mDummyBlurAlgorithm
}
/** Check if the current options require the bitmap to be blurred. */
@Suppress("UnnecessaryParentheses")
fun shouldBlur(drawable: Drawable?, checkDrawable: Boolean): Boolean =
mMode != PivBlurMode.DISABLED &&
mRadius > 0 &&
(mLastRadius != mRadius || (checkDrawable && mDrawable != drawable))
/** Returns the blurred bitmap. If any problem occurs, the original bitmap (nullable) will be returned. */
fun getLastBlurredBitmap(): Bitmap? {
blur(mRadius)
return mBlurredBitmap ?: mOriginalBitmap
}
/** Returns the bitmap of the drawable, down-sampled if needed. */
private fun getOriginalBitmapFromDrawable(mLastDrawable: Drawable?, drawable: Drawable?): Bitmap? {
if (drawable == null || mWidth <= 0 || mHeight <= 0) {
return null
}
// Bitmap size should not be bigger than the view size
val ratio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight.toFloat()
var sizeX: Int = drawable.intrinsicWidth
var sizeY: Int = drawable.intrinsicHeight
val maxWidth = (mWidth.toFloat().coerceAtLeast(mHeight * ratio) / mBlurOptions.downSamplingRate).toInt()
val maxHeight = (mHeight.toFloat().coerceAtLeast(mWidth / ratio) / mBlurOptions.downSamplingRate).toInt()
val isTooWide = drawable.intrinsicWidth > maxWidth.coerceAtLeast(1)
val isTooHigh = drawable.intrinsicHeight > maxHeight.coerceAtLeast(1)
val isTooBig = isTooWide && isTooHigh
if (isTooBig || drawable.isVector()) {
sizeX = maxWidth
sizeY = maxHeight
}
// CoerceAtLeast(1) let us know if the size is correct (it must be > 0)
val sizeChanged = mLastSizeX == sizeX.coerceAtLeast(1) && mLastSizeY == sizeY.coerceAtLeast(1)
val originalBitmapValid = mOriginalBitmap?.isRecycled == false && mLastDrawable === drawable
// If i already decoded the bitmap i reuse it
return if (!sizeChanged && originalBitmapValid) {
mOriginalBitmap
} else {
try {
mLastSizeX = sizeX
mLastSizeY = sizeY
drawable.createBitmap(sizeX, sizeY)
} catch (e: IllegalArgumentException) {
Log.e(BlurManager::class.java.simpleName, e.message ?: "")
mOriginalBitmap
}
}
}
/**
* Adds the context to the renderscript manager, if needed.
* If the blur is static renderscript context is managed by the manager itself, to release it as soon as possible.
* If the blur is not static renderscript context is managed by the view itself, to keep it as long as it needs.
* [fromView] specifies if the function was called by the view.
*/
fun addContext(fromView: Boolean) {
if (mIsRenderscriptManaged || mView.get() == null) {
return
}
val context = mView.get()?.context?.applicationContext ?: return
if (mBlurOptions.isStaticBlur != fromView && mMode.usesRenderscript) {
mIsRenderscriptManaged = true
SharedBlurManager.addRenderscriptContext(context.applicationContext)
}
}
/**
* Removes the context from the renderscript manager, if needed.
* If the blur is static renderscript context is managed by the manager itself, to release it as soon as possible.
* If the blur is not static renderscript context is managed by the view itself, to keep it as long as it needs.
* [fromView] specifies if the function was called by the view.
*/
fun removeContext(fromView: Boolean) {
if (!mIsRenderscriptManaged) {
return
}
if (mBlurOptions.isStaticBlur != fromView && mMode.usesRenderscript) {
mIsRenderscriptManaged = false
SharedBlurManager.removeRenderscriptContext()
updateAlgorithms(mMode)
}
}
override fun onStaticBlurChanged() {
// If staticBlur is true, i release original bitmap and swap it with the blurred one, if it exists
if (mBlurOptions.isStaticBlur) {
if (mBlurredBitmap != null && mBlurredBitmap != mOriginalBitmap) {
mOriginalBitmap?.recycle()
mOriginalBitmap = mBlurredBitmap
mBlurredBitmap = null
}
removeContext(false)
} else {
addContext(true)
}
}
override fun onDownSamplingRateChanged() {
mLastRadius = -1
// If downSampling rate changes, i reload the bitmap and blur it
changeDrawable(mDrawable)
blur(mRadius)
getLastBlurredBitmap()?.let {
mView.get()?.setImageBitmap(it)
}
}
/** Returns the selected mode used for blurring. */
fun getBlurMode(): PivBlurMode = mMode
/** Returns the options used for blurring. */
fun getBlurOptions(): BlurOptions = mBlurOptions
/** Returns the selected radius used for blurring. */
fun getRadius(): Int = mRadius
/**
* Returns the original bitmap used to blur.
* If static blur is enabled, this will be the same as the blurred one, since the original bitmap has been released.
*/
fun getOriginalBitmap(): Bitmap? = mOriginalBitmap
}
| mit | 0f53ea96c71fd39f135863587305009a | 38.561983 | 120 | 0.66228 | 4.471046 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/timegraph/TimeGraphFragment.kt | 1 | 2772 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.timegraph
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.vrem.util.buildVersionP
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.databinding.GraphContentBinding
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.graphutils.GraphAdapter
private fun timeGraphViews(): List<TimeGraphView> = WiFiBand.values().map { TimeGraphView(it) }
class TimeGraphAdapter : GraphAdapter(timeGraphViews())
class TimeGraphFragment : Fragment(), OnRefreshListener {
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
lateinit var timeGraphAdapter: TimeGraphAdapter
private set
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = GraphContentBinding.inflate(inflater, container, false)
swipeRefreshLayout = binding.graphRefresh
swipeRefreshLayout.setOnRefreshListener(this)
if (buildVersionP()) {
swipeRefreshLayout.isRefreshing = false
swipeRefreshLayout.isEnabled = false
}
timeGraphAdapter = TimeGraphAdapter()
timeGraphAdapter.graphViews().forEach { binding.graphFlipper.addView(it) }
return binding.root
}
override fun onRefresh() {
swipeRefreshLayout.isRefreshing = true
MainContext.INSTANCE.scannerService.update()
swipeRefreshLayout.isRefreshing = false
}
override fun onResume() {
super.onResume()
MainContext.INSTANCE.scannerService.register(timeGraphAdapter)
onRefresh()
}
override fun onPause() {
MainContext.INSTANCE.scannerService.unregister(timeGraphAdapter)
super.onPause()
}
} | gpl-3.0 | 7a1f80bbaba3f009db746608a68e8807 | 37.513889 | 116 | 0.75469 | 4.846154 | false | false | false | false |
smmribeiro/intellij-community | platform/indexing-impl/src/com/intellij/model/search/impl/DefaultReferenceSearcher.kt | 12 | 4105 | // 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.model.search.impl
import com.intellij.lang.Language
import com.intellij.model.Pointer
import com.intellij.model.Symbol
import com.intellij.model.psi.*
import com.intellij.model.psi.impl.ReferenceProviders
import com.intellij.model.search.*
import com.intellij.model.search.SearchContext.IN_CODE
import com.intellij.model.search.SearchContext.IN_CODE_HOSTS
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.walkUp
import com.intellij.util.Query
internal class DefaultReferenceSearcher : PsiSymbolReferenceSearcher {
override fun collectSearchRequests(parameters: PsiSymbolReferenceSearchParameters): Collection<Query<out PsiSymbolReference>> {
val project: Project = parameters.project
val inputScope: SearchScope = parameters.searchScope
val target: Symbol = parameters.symbol
val targetPointer: Pointer<out Symbol> = target.createPointer()
val service = SearchService.getInstance()
val result = mutableListOf<Query<out PsiSymbolReference>>()
for (searcher: CodeReferenceSearcher in CodeReferenceSearcher.EP_NAME.extensionList) {
val request: SearchRequest = searcher.getSearchRequest(project, target) ?: continue
val language: Language = searcher.getReferencingLanguage(target)
val searchScope: SearchScope = request.searchScope?.intersectWith(inputScope) ?: inputScope
val injectionSearchScope: SearchScope = request.injectionSearchScope?.intersectWith(inputScope) ?: inputScope
val mapper: LeafOccurrenceMapper<PsiSymbolReference> = LeafOccurrenceMapper.withPointer(targetPointer, searcher::getReferences)
val builder: SearchWordQueryBuilder = service.searchWord(project, request.searchString)
result += builder
.inContexts(IN_CODE)
.inScope(searchScope)
.inFilesWithLanguage(language)
.buildQuery(mapper)
result += builder
.inContexts(IN_CODE_HOSTS)
.inScope(injectionSearchScope)
.inInjections(language)
.buildQuery(mapper)
}
val mapper = LeafOccurrenceMapper.withPointer(targetPointer, ::externalReferences)
for (providerBean: PsiSymbolReferenceProviderBean in ReferenceProviders.byTargetClass(target.javaClass)) {
val requests = providerBean.instance.getSearchRequests(project, target)
for (request: SearchRequest in requests) {
val language: Language = providerBean.getHostLanguage()
val searchScope: SearchScope = request.searchScope?.intersectWith(inputScope) ?: inputScope
val injectionSearchScope: SearchScope = request.injectionSearchScope?.intersectWith(inputScope) ?: inputScope
val builder: SearchWordQueryBuilder = service.searchWord(project, request.searchString)
.inContexts(IN_CODE_HOSTS)
result += builder
.inScope(searchScope)
.inFilesWithLanguage(language)
.buildQuery(mapper)
result += builder
.inScope(injectionSearchScope)
.inInjections(language)
.buildQuery(mapper)
}
}
return result
}
private fun externalReferences(target: Symbol, occurrence: LeafOccurrence): Collection<PsiSymbolReference> {
val (scope, start, offsetInStart) = occurrence
for ((element, offsetInElement) in walkUp(start, offsetInStart, scope)) {
if (element !is PsiExternalReferenceHost) {
continue
}
val hints = object : PsiSymbolReferenceHints {
override fun getTarget(): Symbol = target
override fun getOffsetInElement(): Int = offsetInElement
}
val externalReferences: Iterable<PsiSymbolReference> = PsiSymbolReferenceService.getService().getExternalReferences(element, hints)
return externalReferences.filter { reference ->
ProgressManager.checkCanceled()
reference.resolvesTo(target)
}
}
return emptyList()
}
}
| apache-2.0 | 1e49ed3a77334aa5967f2025e7eb69e6 | 45.123596 | 140 | 0.745432 | 4.857988 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/roots/GradleBuildRootsManager.kt | 2 | 19205 | // 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.gradleJava.scripting.roots
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorNotifications
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport
import org.jetbrains.kotlin.idea.core.script.configuration.ScriptingSupport
import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog
import org.jetbrains.kotlin.idea.core.script.scriptingErrorLog
import org.jetbrains.kotlin.idea.core.script.scriptingInfoLog
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.gradle.scripting.*
import org.jetbrains.kotlin.idea.gradleJava.scripting.getGradleProjectSettings
import org.jetbrains.kotlin.idea.gradleJava.scripting.importing.KotlinDslGradleBuildSync
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRoot.ImportingStatus.*
import org.jetbrains.kotlin.idea.gradleJava.scripting.scriptConfigurationsAreUpToDate
import org.jetbrains.kotlin.idea.gradleJava.scripting.getGradleVersion
import org.jetbrains.kotlin.idea.gradleJava.scripting.kotlinDslScriptsModelImportSupported
import org.jetbrains.kotlin.idea.gradleJava.scripting.scriptConfigurationsNeedToBeUpdated
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.settings.*
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean
/**
* [GradleBuildRoot] is a linked gradle build (don't confuse with gradle project and included build).
* Each [GradleBuildRoot] may have it's own Gradle version, Java home and other settings.
*
* Typically, IntelliJ project have no more than one [GradleBuildRoot].
*
* This manager allows to find related Gradle build by the Gradle Kotlin script file path.
* Each imported build have info about all of it's Kotlin Build Scripts.
* It is populated by calling [update], stored in FS and will be loaded from FS on next project opening
*
* [CompositeScriptConfigurationManager] may ask about known scripts by calling [collectConfigurations].
*
* It also used to show related notification and floating actions depending on root kind, state and script state itself.
*
* Roots may be:
* - [GradleBuildRoot] - Linked project, that may be itself:
* - [Legacy] - Gradle build with old Gradle version (<6.0)
* - [New] - not yet imported
* - [Imported] - imported
*/
class GradleBuildRootsManager(val project: Project) : GradleBuildRootsLocator(project), ScriptingSupport {
private val manager: CompositeScriptConfigurationManager
get() = ScriptConfigurationManager.getInstance(project) as CompositeScriptConfigurationManager
private val updater
get() = manager.updater
var enabled: Boolean = true
set(value) {
if (value != field) {
field = value
roots.list.toList().forEach {
reloadBuildRoot(it.pathPrefix, null)
}
}
}
////////////
/// ScriptingSupport.Provider implementation:
override fun isApplicable(file: VirtualFile): Boolean {
val scriptUnderRoot = findScriptBuildRoot(file) ?: return false
if (scriptUnderRoot.nearest is Legacy) return false
if (roots.isStandaloneScript(file.path)) return false
return true
}
override fun isConfigurationLoadingInProgress(file: KtFile): Boolean {
return findScriptBuildRoot(file.originalFile.virtualFile)?.nearest?.isImportingInProgress() ?: return false
}
@Suppress("MemberVisibilityCanBePrivate") // used in GradleImportHelper.kt.201
fun isConfigurationOutOfDate(file: VirtualFile): Boolean {
val script = getScriptInfo(file) ?: return false
if (script.buildRoot.isImportingInProgress()) return false
return !script.model.inputs.isUpToDate(project, file)
}
override fun collectConfigurations(builder: ScriptClassRootsBuilder) {
roots.list.forEach { root ->
if (root is Imported) {
root.collectConfigurations(builder)
}
}
}
override fun afterUpdate() {
roots.list.forEach { root ->
if (root.importing.compareAndSet(updatingCaches, updated)) {
updateNotifications { it.startsWith(root.pathPrefix) }
}
}
}
//////////////////
override fun getScriptInfo(localPath: String): GradleScriptInfo? =
manager.getLightScriptInfo(localPath) as? GradleScriptInfo
override fun getScriptFirstSeenTs(path: String): Long {
val nioPath = FileSystems.getDefault().getPath(path)
return Files.readAttributes(nioPath, BasicFileAttributes::class.java)
?.creationTime()?.toMillis()
?: Long.MAX_VALUE
}
fun fileChanged(filePath: String, ts: Long = System.currentTimeMillis()) {
findAffectedFileRoot(filePath)?.fileChanged(filePath, ts)
scheduleModifiedFilesCheck(filePath)
}
fun markImportingInProgress(workingDir: String, inProgress: Boolean = true) {
actualizeBuildRoot(workingDir, null)?.importing?.set(if (inProgress) importing else updated)
updateNotifications { it.startsWith(workingDir) }
}
fun update(sync: KotlinDslGradleBuildSync) {
val oldRoot = actualizeBuildRoot(sync.workingDir, sync.gradleVersion) ?: return
try {
val newRoot = updateRoot(oldRoot, sync)
if (newRoot == null) {
markImportingInProgress(sync.workingDir, false)
return
}
add(newRoot)
} catch (e: Exception) {
markImportingInProgress(sync.workingDir, false)
return
}
}
private fun updateRoot(oldRoot: GradleBuildRoot, sync: KotlinDslGradleBuildSync): Imported? {
// fast path for linked gradle builds without .gradle.kts support
if (sync.models.isEmpty()) {
if (oldRoot is Imported && oldRoot.data.models.isEmpty()) return null
}
if (oldRoot is Legacy) return null
scriptingDebugLog { "gradle project info after import: $sync" }
// TODO: can gradleHome be null, what to do in this case
val gradleHome = sync.gradleHome
if (gradleHome == null) {
scriptingInfoLog("Cannot find valid gradle home for ${sync.gradleHome} with version = ${sync.gradleVersion}, script models cannot be saved")
return null
}
oldRoot.importing.set(updatingCaches)
scriptingDebugLog { "save script models after import: ${sync.models}" }
val newData = GradleBuildRootData(sync.ts, sync.projectRoots, gradleHome, sync.javaHome, sync.models)
val mergedData = if (sync.failed && oldRoot is Imported) merge(oldRoot.data, newData) else newData
val newRoot = tryCreateImportedRoot(sync.workingDir, LastModifiedFiles()) { mergedData } ?: return null
val buildRootDir = newRoot.dir ?: return null
GradleBuildRootDataSerializer.write(buildRootDir, mergedData)
newRoot.saveLastModifiedFiles()
return newRoot
}
private fun merge(old: GradleBuildRootData, new: GradleBuildRootData): GradleBuildRootData {
val roots = old.projectRoots.toMutableSet()
roots.addAll(new.projectRoots)
val models = old.models.associateByTo(mutableMapOf()) { it.file }
new.models.associateByTo(models) { it.file }
return GradleBuildRootData(new.importTs, roots, new.gradleHome, new.javaHome, models.values)
}
private val modifiedFilesCheckScheduled = AtomicBoolean()
private val modifiedFiles = ConcurrentLinkedQueue<String>()
fun scheduleModifiedFilesCheck(filePath: String) {
modifiedFiles.add(filePath)
if (modifiedFilesCheckScheduled.compareAndSet(false, true)) {
val disposable = KotlinPluginDisposable.getInstance(project)
BackgroundTaskUtil.executeOnPooledThread(disposable) {
if (modifiedFilesCheckScheduled.compareAndSet(true, false)) {
checkModifiedFiles()
}
}
}
}
private fun checkModifiedFiles() {
updateNotifications(restartAnalyzer = false) { true }
roots.list.forEach {
it.saveLastModifiedFiles()
}
// process modifiedFiles queue
while (true) {
val file = modifiedFiles.poll() ?: break
// detect gradle version change
val buildDir = findGradleWrapperPropertiesBuildDir(file)
if (buildDir != null) {
actualizeBuildRoot(buildDir, null)
}
}
}
fun updateStandaloneScripts(update: StandaloneScriptsUpdater.() -> Unit) {
val changes = StandaloneScriptsUpdater.collectChanges(delegate = roots, update)
updateNotifications { it in changes.new || it in changes.removed }
loadStandaloneScriptConfigurations(changes.new)
}
init {
getGradleProjectSettings(project).forEach {
// don't call this.add, as we are inside scripting manager initialization
roots.add(loadLinkedRoot(it))
}
// subscribe to linked gradle project modification
val listener = object : GradleSettingsListenerAdapter() {
override fun onProjectsLinked(settings: MutableCollection<GradleProjectSettings>) {
settings.forEach {
add(loadLinkedRoot(it))
}
}
override fun onProjectsUnlinked(linkedProjectPaths: MutableSet<String>) {
linkedProjectPaths.forEach {
remove(it)
}
}
override fun onGradleHomeChange(oldPath: String?, newPath: String?, linkedProjectPath: String) {
val version = GradleInstallationManager.getGradleVersion(newPath)
reloadBuildRoot(linkedProjectPath, version)
}
override fun onGradleDistributionTypeChange(currentValue: DistributionType?, linkedProjectPath: String) {
reloadBuildRoot(linkedProjectPath, null)
}
}
val disposable = KotlinPluginDisposable.getInstance(project)
project.messageBus.connect(disposable).subscribe(GradleSettingsListener.TOPIC, listener)
}
private fun getGradleProjectSettings(workingDir: String): GradleProjectSettings? {
return (ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID) as GradleSettings)
.getLinkedProjectSettings(workingDir)
}
/**
* Check that root under [workingDir] in sync with it's [GradleProjectSettings].
* Actually this should be true, but we may miss some change events.
* For that cases we are rechecking this on each Gradle Project sync (importing/reimporting)
*/
private fun actualizeBuildRoot(workingDir: String, gradleVersion: String?): GradleBuildRoot? {
val actualSettings = getGradleProjectSettings(workingDir)
val buildRoot = getBuildRootByWorkingDir(workingDir)
val version = gradleVersion ?: actualSettings?.let { getGradleVersion(project, it) }
return when {
buildRoot != null -> {
when {
!buildRoot.checkActual(version) -> reloadBuildRoot(workingDir, version)
else -> buildRoot
}
}
actualSettings != null && version != null -> {
loadLinkedRoot(actualSettings, version)
}
else -> null
}
}
private fun GradleBuildRoot.checkActual(version: String?): Boolean {
if (version == null) return false
val knownAsSupported = this !is Legacy
val shouldBeSupported = kotlinDslScriptsModelImportSupported(version)
return knownAsSupported == shouldBeSupported
}
private fun reloadBuildRoot(rootPath: String, version: String?): GradleBuildRoot? {
val settings = getGradleProjectSettings(rootPath)
if (settings == null) {
remove(rootPath)
return null
} else {
val gradleVersion = version ?: getGradleVersion(project, settings)
val newRoot = loadLinkedRoot(settings, gradleVersion)
add(newRoot)
return newRoot
}
}
private fun loadLinkedRoot(settings: GradleProjectSettings, version: String = getGradleVersion(project, settings)): GradleBuildRoot {
if (!enabled) {
return Legacy(settings)
}
val supported = kotlinDslScriptsModelImportSupported(version)
return when {
supported -> tryLoadFromFsCache(settings, version) ?: New(settings)
else -> Legacy(settings)
}
}
private fun tryLoadFromFsCache(settings: GradleProjectSettings, version: String): Imported? {
return tryCreateImportedRoot(settings.externalProjectPath) {
GradleBuildRootDataSerializer.read(it)?.let { data ->
val gradleHome = data.gradleHome
if (gradleHome.isNotBlank() && GradleInstallationManager.getGradleVersion(gradleHome) != version) return@let null
addFromSettings(data, settings)
}
}
}
private fun addFromSettings(
data: GradleBuildRootData,
settings: GradleProjectSettings
) = data.copy(projectRoots = data.projectRoots.toSet() + settings.modules)
private fun tryCreateImportedRoot(
externalProjectPath: String,
lastModifiedFiles: LastModifiedFiles = loadLastModifiedFiles(externalProjectPath) ?: LastModifiedFiles(),
dataProvider: (buildRoot: VirtualFile) -> GradleBuildRootData?
): Imported? {
try {
val buildRoot = VfsUtil.findFile(Paths.get(externalProjectPath), true) ?: return null
val data = dataProvider(buildRoot) ?: return null
return Imported(externalProjectPath, data, lastModifiedFiles)
} catch (e: Exception) {
scriptingErrorLog("Cannot load script configurations from file attributes for $externalProjectPath", e)
return null
}
}
private fun add(newRoot: GradleBuildRoot) {
val old = roots.add(newRoot)
if (old is Imported && newRoot !is Imported) {
removeData(old.pathPrefix)
}
if (old !is Legacy || newRoot !is Legacy) {
updater.invalidateAndCommit()
}
updateNotifications { it.startsWith(newRoot.pathPrefix) }
}
private fun remove(rootPath: String) {
val removed = roots.remove(rootPath)
if (removed is Imported) {
removeData(rootPath)
updater.invalidateAndCommit()
}
updateNotifications { it.startsWith(rootPath) }
}
private fun removeData(rootPath: String) {
val buildRoot = LocalFileSystem.getInstance().findFileByPath(rootPath)
if (buildRoot != null) {
GradleBuildRootDataSerializer.remove(buildRoot)
LastModifiedFiles.remove(buildRoot)
}
}
@Suppress("MemberVisibilityCanBePrivate")
fun updateNotifications(
restartAnalyzer: Boolean = true,
shouldUpdatePath: (String) -> Boolean
) {
if (!project.isOpen) return
// import notification is a balloon, so should be shown only for selected editor
FileEditorManager.getInstance(project).selectedEditor?.file?.let {
if (shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path)) {
updateFloatingAction(it)
}
}
val openedScripts = FileEditorManager.getInstance(project).selectedEditors
.mapNotNull { it.file }
.filter {
shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path)
}
if (openedScripts.isEmpty()) return
GlobalScope.launch(EDT(project)) {
if (project.isDisposed) return@launch
openedScripts.forEach {
if (isApplicable(it)) {
DefaultScriptingSupport.getInstance(project).ensureNotificationsRemoved(it)
}
if (restartAnalyzer) {
// this required only for "pause" state
val ktFile = PsiManager.getInstance(project).findFile(it)
if (ktFile != null) DaemonCodeAnalyzer.getInstance(project).restart(ktFile)
}
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
}
private fun updateFloatingAction(file: VirtualFile) {
if (isConfigurationOutOfDate(file)) {
scriptConfigurationsNeedToBeUpdated(project, file)
} else {
scriptConfigurationsAreUpToDate(project)
}
}
private fun loadStandaloneScriptConfigurations(files: MutableSet<String>) {
runReadAction {
files.forEach {
val virtualFile = LocalFileSystem.getInstance().findFileByPath(it)
if (virtualFile != null) {
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as? KtFile
if (ktFile != null) {
DefaultScriptingSupport.getInstance(project)
.ensureUpToDatedConfigurationSuggested(ktFile, skipNotification = true)
}
}
}
}
}
companion object {
fun getInstanceSafe(project: Project): GradleBuildRootsManager =
ScriptingSupport.EPN.findExtensionOrFail(GradleBuildRootsManager::class.java, project)
fun getInstance(project: Project): GradleBuildRootsManager? =
ScriptingSupport.EPN.findExtension(GradleBuildRootsManager::class.java, project)
}
} | apache-2.0 | 1facd69612cfdd72031f7abc411b2986 | 39.433684 | 158 | 0.674043 | 5.147414 | false | true | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/canvas/cursor/CursorPartsTexture.kt | 1 | 3815 | package com.cout970.modeler.gui.canvas.cursor
//class CursorPartTranslateTexture(
// val cursor: Cursor,
// val parameters: CursorParameters,
// override val translationAxis: IVector3
//) : ITranslatable {
//
// override val polygons: List<IPolygon> = calculatePolygons()
//
// override val hitbox: IRayObstacle? = null
//
// fun calculatePolygons(): List<IPolygon> {
// val start = (cursor.center - Vector3.ONE * parameters.width).toVector2()
// val end = (cursor.center + translationAxis * parameters.length + Vector3.ONE * parameters.width).toVector2()
// return listOf((start to end).toTexturePolygon())
// }
//
// override fun applyTranslation(offset: Float, selection: ISelection, model: IModel, material: IMaterial): IModel {
// val dir = translationAxis.toVector2() * vec2Of(1, -1) / material.size
// return TransformationHelper.translateTexture(model, selection, dir * offset)
// }
//
// override fun equals(other: Any?): Boolean {
// if (this === other) return true
// if (other !is CursorPartTranslateTexture) return false
//
// if (translationAxis != other.translationAxis) return false
//
// return true
// }
//
// override fun hashCode(): Int {
// return translationAxis.hashCode()
// }
//}
//
//class CursorPartRotateTexture(
// val cursor: CursorableLinkedList.Cursor,
// parameters: CursorParameters
//) : IRotable {
//
// override val tangent: IVector3 = Vector3.Z_AXIS
// override val center: IVector3 get() = cursor.center
// override val polygons: List<IPolygon> = RenderUtil.createCirclePolygons(center.toVector2(), parameters.length,
// parameters.width)
//
// override val hitbox: IRayObstacle? = null
//
// override fun applyRotation(offset: Float, selection: ISelection, model: IModel, material: IMaterial): IModel {
// val center2 = PickupHelper.fromCanvasToMaterial(center.toVector2(), material)
// return TransformationHelper.rotateTexture(model, selection, center2, -offset.toDegrees())
// }
//
// override fun equals(other: Any?): Boolean {
// if (this === other) return true
// if (other !is CursorPartRotateTexture) return false
//
// if (cursor != other.cursor) return false
//
// return true
// }
//
// override fun hashCode(): Int {
// return cursor.hashCode()
// }
//}
//
//class CursorPartScaleTexture(
// val cursor: CursorableLinkedList.Cursor,
// val parameters: CursorParameters,
// override val scaleAxis: IVector3
//) : IScalable {
//
// override val polygons: List<IPolygon> = calculatePolygons()
// override val center: IVector3 get() = cursor.center
//
// override val hitbox: IRayObstacle? = null
//
// fun calculatePolygons(): List<IPolygon> {
// val start = (cursor.center - Vector3.ONE * parameters.width).toVector2()
// val end = (cursor.center + scaleAxis * parameters.length + Vector3.ONE * parameters.width).toVector2()
// return listOf((start to end).toTexturePolygon())
// }
//
// override fun applyScale(offset: Float, selection: ISelection, model: IModel, material: IMaterial): IModel {
// val dir = scaleAxis.toVector2() / material.size
// val center2 = PickupHelper.fromCanvasToMaterial(center.toVector2(), material)
// return TransformationHelper.scaleTexture(model, selection, center2, dir, offset)
// }
//
// override fun equals(other: Any?): Boolean {
// if (this === other) return true
// if (other !is CursorPartScaleTexture) return false
//
// if (scaleAxis != other.scaleAxis) return false
//
// return true
// }
//
// override fun hashCode(): Int {
// return scaleAxis.hashCode()
// }
//} | gpl-3.0 | 60b245294bbc9349ad04e48480bd88fa | 35.692308 | 119 | 0.648493 | 3.766041 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/controller/usecases/EditTransformation.kt | 1 | 6891 | package com.cout970.modeler.controller.usecases
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.core.model.TRSTransformation
import com.cout970.modeler.core.model.TRTSTransformation
import com.cout970.modeler.util.EulerRotation
import com.cout970.vector.extensions.vec3Of
import javax.script.ScriptEngineManager
val scriptEngine = ScriptEngineManager(null).getEngineByName("JavaScript")!!
fun updateTransformation(value: ITransformation, cmd: String, input: String, offset: Float): ITransformation? {
val newValue: ITransformation
when (value) {
is TRSTransformation -> newValue = when (cmd) {
"size.x" -> setTRSSizeX(value, x = getValue(input, value.scale.xf) + offset)
"size.y" -> setTRSSizeY(value, y = getValue(input, value.scale.yf) + offset)
"size.z" -> setTRSSizeZ(value, z = getValue(input, value.scale.zf) + offset)
"pos.x" -> setTRSPosX(value, x = getValue(input, value.translation.xf) + offset)
"pos.y" -> setTRSPosY(value, y = getValue(input, value.translation.yf) + offset)
"pos.z" -> setTRSPosZ(value, z = getValue(input, value.translation.zf) + offset)
"rot.x" -> setTRSRotationX(value, x = getValue(input, value.euler.angles.xf) + offset * 15f)
"rot.y" -> setTRSRotationY(value, getValue(input, value.euler.angles.yf) + offset * 15f)
"rot.z" -> setTRSRotationZ(value, z = getValue(input, value.euler.angles.zf) + offset * 15f)
else -> value
}
is TRTSTransformation -> newValue = when (cmd) {
"size.x" -> setTRTSSizeX(value, x = getValue(input, value.scale.xf) + offset)
"size.y" -> setTRTSSizeY(value, y = getValue(input, value.scale.yf) + offset)
"size.z" -> setTRTSSizeZ(value, z = getValue(input, value.scale.zf) + offset)
"pos.x" -> setTRTSPosX(value, x = getValue(input, value.translation.xf) + offset)
"pos.y" -> setTRTSPosY(value, y = getValue(input, value.translation.yf) + offset)
"pos.z" -> setTRTSPosZ(value, z = getValue(input, value.translation.zf) + offset)
"rot.x" -> setTRTSRotationX(value, x = getValue(input, value.rotation.xf) + offset * 15f)
"rot.y" -> setTRTSRotationY(value, y = getValue(input, value.rotation.yf) + offset * 15f)
"rot.z" -> setTRTSRotationZ(value, z = getValue(input, value.rotation.zf) + offset * 15f)
"pivot.x" -> setTRTSPivotX(value, x = getValue(input, value.translation.xf) + offset)
"pivot.y" -> setTRTSPivotY(value, y = getValue(input, value.translation.yf) + offset)
"pivot.z" -> setTRTSPivotZ(value, z = getValue(input, value.translation.zf) + offset)
else -> value
}
else -> error("Invalid ITransformation: $value")
}
if (value == newValue) return null
return newValue
}
// TRS
private fun setTRSSizeX(trans: TRSTransformation, x: Float): TRSTransformation =
trans.copy(scale = vec3Of(x, trans.scale.y, trans.scale.z))
private fun setTRSSizeY(trans: TRSTransformation, y: Float): TRSTransformation =
trans.copy(scale = vec3Of(trans.scale.x, y, trans.scale.z))
private fun setTRSSizeZ(trans: TRSTransformation, z: Float): TRSTransformation =
trans.copy(scale = vec3Of(trans.scale.x, trans.scale.y, z))
// TRTS
private fun setTRTSSizeX(trans: TRTSTransformation, x: Float): TRTSTransformation =
trans.copy(scale = vec3Of(x, trans.scale.y, trans.scale.z))
private fun setTRTSSizeY(trans: TRTSTransformation, y: Float): TRTSTransformation =
trans.copy(scale = vec3Of(trans.scale.x, y, trans.scale.z))
private fun setTRTSSizeZ(trans: TRTSTransformation, z: Float): TRTSTransformation =
trans.copy(scale = vec3Of(trans.scale.x, trans.scale.y, z))
// TRS
private fun setTRSPosX(trans: TRSTransformation, x: Float): TRSTransformation =
trans.copy(translation = vec3Of(x, trans.translation.y, trans.translation.z))
private fun setTRSPosY(trans: TRSTransformation, y: Float): TRSTransformation =
trans.copy(translation = vec3Of(trans.translation.x, y, trans.translation.z))
private fun setTRSPosZ(trans: TRSTransformation, z: Float): TRSTransformation =
trans.copy(translation = vec3Of(trans.translation.x, trans.translation.y, z))
// TRTS
private fun setTRTSPosX(trans: TRTSTransformation, x: Float): TRTSTransformation =
trans.copy(translation = vec3Of(x, trans.translation.y, trans.translation.z))
private fun setTRTSPosY(trans: TRTSTransformation, y: Float): TRTSTransformation =
trans.copy(translation = vec3Of(trans.translation.x, y, trans.translation.z))
private fun setTRTSPosZ(trans: TRTSTransformation, z: Float): TRTSTransformation =
trans.copy(translation = vec3Of(trans.translation.x, trans.translation.y, z))
// TRS
private fun setTRSRotationX(trans: TRSTransformation, x: Float): TRSTransformation {
val oldRot = trans.euler.angles
return trans.copy(rotation = EulerRotation(vec3Of(x.clampRot(), oldRot.yd, oldRot.zd)))
}
private fun setTRSRotationY(trans: TRSTransformation, y: Float): TRSTransformation {
val oldRot = trans.euler.angles
return trans.copy(rotation = EulerRotation(vec3Of(oldRot.xd, y.clampRot(), oldRot.zd)))
}
private fun setTRSRotationZ(trans: TRSTransformation, z: Float): TRSTransformation {
val oldRot = trans.euler.angles
return trans.copy(rotation = EulerRotation(vec3Of(oldRot.xd, oldRot.yd, z.clampRot())))
}
// TRTS
private fun setTRTSRotationX(trans: TRTSTransformation, x: Float): TRTSTransformation =
trans.copy(rotation = vec3Of(x.clampRot(), trans.rotation.y, trans.rotation.z))
private fun setTRTSRotationY(trans: TRTSTransformation, y: Float): TRTSTransformation =
trans.copy(rotation = vec3Of(trans.rotation.x, y.clampRot(), trans.rotation.z))
private fun setTRTSRotationZ(trans: TRTSTransformation, z: Float): TRTSTransformation =
trans.copy(rotation = vec3Of(trans.rotation.x, trans.rotation.y, z.clampRot()))
// TRTS
private fun setTRTSPivotX(trans: TRTSTransformation, x: Float): TRTSTransformation =
trans.copy(pivot = vec3Of(x, trans.pivot.y, trans.pivot.z))
private fun setTRTSPivotY(trans: TRTSTransformation, y: Float): TRTSTransformation =
trans.copy(pivot = vec3Of(trans.pivot.x, y, trans.pivot.z))
private fun setTRTSPivotZ(trans: TRTSTransformation, z: Float): TRTSTransformation =
trans.copy(pivot = vec3Of(trans.pivot.x, trans.pivot.y, z))
private fun Float.clampRot(): Double {
return when {
this > 180f -> this - 360f
this < -180f -> this + 360f
else -> this
}.toDouble()
}
fun getValue(input: String, default: Float): Float {
return try {
(scriptEngine.eval(input) as? Number)?.toFloat() ?: default
} catch (e: Exception) {
default
}
} | gpl-3.0 | f1d048b99c53bf9b802633ce56fe1e56 | 45.567568 | 111 | 0.691046 | 3.358187 | false | false | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/ui/common/AlertDialogComponent.kt | 1 | 1121 | package com.cn29.aac.ui.common
import android.app.AlertDialog
import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
/**
* Created by Charles Ng on 12/10/2017.
*/
class AlertDialogComponent(private val context: Context,
lifecycle: Lifecycle) :
LifecycleObserver {
private var alertDialog: AlertDialog? = null
fun showDialog(alertDialog: AlertDialog) {
this.alertDialog = alertDialog
alertDialog.show()
}
fun hideDialog() {
if (alertDialog != null) {
alertDialog!!.dismiss()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
if (alertDialog != null) {
alertDialog!!.dismiss()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
if (alertDialog != null) {
alertDialog!!.dismiss()
}
}
init {
lifecycle.addObserver(this)
}
} | apache-2.0 | 8f0ae8171115d27bfb26a81273c539f0 | 22.375 | 56 | 0.62355 | 4.670833 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/repl/src/org/jetbrains/kotlin/console/gutter/ReplIcons.kt | 1 | 1966 | // 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.console.gutter
import com.intellij.icons.AllIcons
import org.jetbrains.kotlin.KotlinIdeaReplBundle
import org.jetbrains.kotlin.idea.KotlinIcons
import javax.swing.Icon
data class IconWithTooltip(val icon: Icon, val tooltip: String?)
object ReplIcons {
val BUILD_WARNING_INDICATOR: IconWithTooltip = IconWithTooltip(AllIcons.General.Warning, null)
val HISTORY_INDICATOR: IconWithTooltip = IconWithTooltip(
AllIcons.Vcs.History,
KotlinIdeaReplBundle.message("icon.tool.tip.history.of.executed.commands")
)
val EDITOR_INDICATOR: IconWithTooltip = IconWithTooltip(
KotlinIcons.LAUNCH,
KotlinIdeaReplBundle.message("icon.tool.tip.write.your.commands.here")
)
val EDITOR_READLINE_INDICATOR: IconWithTooltip = IconWithTooltip(
AllIcons.General.Balloon,
KotlinIdeaReplBundle.message("icon.tool.tip.waiting.for.input")
)
val COMMAND_MARKER: IconWithTooltip = IconWithTooltip(
AllIcons.RunConfigurations.TestState.Run,
KotlinIdeaReplBundle.message("icon.tool.tip.executed.command")
)
val READLINE_MARKER: IconWithTooltip = IconWithTooltip(
AllIcons.Debugger.PromptInput,
KotlinIdeaReplBundle.message("icon.tool.tip.input.line")
)
// command result icons
val SYSTEM_HELP: IconWithTooltip = IconWithTooltip(AllIcons.Actions.Help, KotlinIdeaReplBundle.message("icon.tool.tip.system.help"))
val RESULT: IconWithTooltip = IconWithTooltip(AllIcons.Vcs.Equal, KotlinIdeaReplBundle.message("icon.tool.tip.result"))
val COMPILER_ERROR: Icon = AllIcons.General.Error
val RUNTIME_EXCEPTION: IconWithTooltip = IconWithTooltip(
AllIcons.General.BalloonWarning,
KotlinIdeaReplBundle.message("icon.tool.tip.runtime.exception")
)
} | apache-2.0 | e3eb5b1b9af568a38134b6420a95377b | 40.851064 | 158 | 0.753306 | 4.349558 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/profile/codeInspection/ui/DescriptionEditorPane.kt | 1 | 1805 | // 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.profile.codeInspection.ui
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.ui.ColorUtil
import com.intellij.ui.HintHint
import com.intellij.util.ObjectUtils
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Point
import java.io.IOException
import java.io.StringReader
import javax.swing.JEditorPane
import javax.swing.text.html.HTMLEditorKit
open class DescriptionEditorPane : JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML) {
init {
isEditable = false
isOpaque = false
val css = (this.editorKit as HTMLEditorKit).styleSheet
with(EditorColorsManager.getInstance().globalScheme) {
css.addRule("a {overflow-wrap: anywhere;}")
css.addRule("pre {padding:10px; background:#"
+ ColorUtil.toHex(ObjectUtils.notNull(getColor(EditorColors.READONLY_BACKGROUND_COLOR), defaultBackground))
+ ";}")
}
}
override fun getBackground(): Color = UIUtil.getLabelBackground()
companion object {
const val EMPTY_HTML = "<html><body></body></html>"
}
}
fun JEditorPane.readHTML(text: String) {
try {
read(StringReader(text), null)
}
catch (e: IOException) {
throw RuntimeException(e)
}
}
fun JEditorPane.toHTML(text: @Nls String?, miniFontSize: Boolean): String {
val hintHint = HintHint(this, Point(0, 0))
hintHint.setFont(if (miniFontSize) UIUtil.getLabelFont(UIUtil.FontSize.SMALL) else UIUtil.getLabelFont())
return HintUtil.prepareHintText(text!!, hintHint)
}
| apache-2.0 | fd309fbea9e5c9c5c6086bd0efd2c579 | 32.425926 | 140 | 0.745706 | 3.967033 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt | 1 | 4812 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.getFactoryForImplicitReceiverWithSubtypeOf
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
class ImplicitThisInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
if (expression.receiverExpression != null) return
handle(expression, expression.callableReference, ::CallableReferenceFix)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (expression !is KtNameReferenceExpression) return
if (expression.parent is KtThisExpression) return
if (expression.parent is KtCallableReferenceExpression) return
if (expression.isSelectorOfDotQualifiedExpression()) return
val parent = expression.parent
if (parent is KtCallExpression && parent.isSelectorOfDotQualifiedExpression()) return
handle(expression, expression, ::CallFix)
}
private fun handle(expression: KtExpression, reference: KtReferenceExpression, fixFactory: (String) -> LocalQuickFix) {
val context = reference.analyze()
val scope = reference.getResolutionScope(context) ?: return
val resolvedCall = reference.getResolvedCall(context) ?: return
val variableDescriptor = (resolvedCall as? VariableAsFunctionResolvedCall)?.variableCall?.resultingDescriptor
val callableDescriptor = resolvedCall.resultingDescriptor
val receiverDescriptor = variableDescriptor?.receiverDescriptor() ?: callableDescriptor.receiverDescriptor() ?: return
val receiverType = receiverDescriptor.type
val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType) ?: return
val receiverText = if (expressionFactory.isImmediate) "this" else expressionFactory.expressionText
val fix = fixFactory(receiverText)
holder.registerProblem(
expression,
KotlinBundle.message("callable.reference.fix.family.name", receiverText),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
fix
)
}
private fun CallableDescriptor.receiverDescriptor(): ReceiverParameterDescriptor? {
return extensionReceiverParameter ?: dispatchReceiverParameter
}
private fun KtExpression.isSelectorOfDotQualifiedExpression(): Boolean {
val parent = parent
return parent is KtDotQualifiedExpression && parent.selectorExpression == this
}
}
private class CallFix(private val receiverText: String) : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("callable.reference.fix.family.name", receiverText)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtExpression ?: return
val factory = KtPsiFactory(project)
val call = expression.parent as? KtCallExpression ?: expression
call.replace(factory.createExpressionByPattern("$0.$1", receiverText, call))
}
}
private class CallableReferenceFix(private val receiverText: String) : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("callable.reference.fix.family.name", receiverText)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtCallableReferenceExpression ?: return
val factory = KtPsiFactory(project)
val reference = expression.callableReference
expression.replace(factory.createExpressionByPattern("$0::$1", receiverText, reference))
}
}
} | apache-2.0 | 0797ce5f0bfef47f429472e8d1c07471 | 49.663158 | 158 | 0.731712 | 5.955446 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.