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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/ui/nav/OnStateChangedAction.kt | 1 | 3636 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.nav
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.floatingactionbutton.FloatingActionButton
/**
* An action to be performed when a bottom sheet's state is changed.
*/
interface OnStateChangedAction {
fun onStateChanged(sheet: View, newState: Int)
}
/**
* A state change action that tells the calling client when a open-sheet specific menu should be
* used.
*/
class ChangeSettingsMenuStateAction(
private val onShouldShowSettingsMenu: (showSettings: Boolean) -> Unit
) : OnStateChangedAction {
private var hasCalledShowSettingsMenu: Boolean = false
override fun onStateChanged(sheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
hasCalledShowSettingsMenu = false
onShouldShowSettingsMenu(false)
} else {
if (!hasCalledShowSettingsMenu) {
hasCalledShowSettingsMenu = true
onShouldShowSettingsMenu(true)
}
}
}
}
/**
* A state change action that handles showing the fab when the sheet is hidden and hiding the fab
* when the sheet is not hidden.
*/
class ShowHideFabStateAction(
private val fab: FloatingActionButton
) : OnStateChangedAction {
override fun onStateChanged(sheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
fab.show()
} else {
fab.hide()
}
}
}
/**
* A state change action that sets a view's visibility depending on whether the sheet is hidden
* or not.
*
* By default, the view will be hidden when the sheet is hidden and shown when the sheet is shown
* (not hidden). If [reverse] is set to true, the view will be shown when the sheet is hidden and
* hidden when the sheet is shown (not hidden).
*/
class VisibilityStateAction(
private val view: View,
private val reverse: Boolean = false
) : OnStateChangedAction {
override fun onStateChanged(sheet: View, newState: Int) {
val stateHiddenVisibility = if (!reverse) View.GONE else View.VISIBLE
val stateDefaultVisibility = if (!reverse) View.VISIBLE else View.GONE
when (newState) {
BottomSheetBehavior.STATE_HIDDEN -> view.visibility = stateHiddenVisibility
else -> view.visibility = stateDefaultVisibility
}
}
}
/**
* A state change action which scrolls a [RecyclerView] to the top when the sheet is hidden.
*
* This is used to make sure the navigation drawer's [RecyclerView] is never half-scrolled when
* opened to the half-expanded state, which can happen if the sheet is hidden while scrolled.
*/
class ScrollToTopStateAction(
private val recyclerView: RecyclerView
) : OnStateChangedAction {
override fun onStateChanged(sheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) recyclerView.scrollToPosition(0)
}
}
| apache-2.0 | fdfdfda80f3057ca45e840e2a4992ccc | 33.628571 | 97 | 0.710396 | 4.494438 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/domain/entities/Error.kt | 1 | 1015 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.entities
data class Error(val code: Int, val message: String) {
fun isValid(): Boolean = code != INVALID_ERROR
companion object {
const val INVALID_ERROR = -1
const val PERMISSION_ERROR = 0x9990
const val PERMISSION_RATIONALE_ERROR = 0x9991
const val NETWORK_ERROR = 0x9992
const val FATAL_ERROR = 0x9993
}
} | apache-2.0 | d3fd9f6f810fc5c444676ac54c571b69 | 30.75 | 75 | 0.728079 | 3.934109 | false | false | false | false |
apixandru/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateInfoParsingTest.kt | 1 | 5138 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.updates
import com.intellij.openapi.updateSettings.impl.ChannelStatus
import com.intellij.openapi.updateSettings.impl.UpdateChannel
import com.intellij.openapi.updateSettings.impl.UpdatesInfo
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.loadElement
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.IOException
import java.net.URL
import java.text.SimpleDateFormat
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class UpdateInfoParsingTest {
@Test fun liveJetbrainsUpdateFile() {
try {
val info = load(URL("https://www.jetbrains.com/updates/updates.xml").readText())
assertNotNull(info["IC"])
}
catch (e: IOException) {
assumeTrue(e.toString(), false)
}
}
@Test fun liveAndroidUpdateFile() {
try {
val info = load(URL("https://dl.google.com/android/studio/patches/updates.xml").readText())
assertNotNull(info["AI"])
}
catch (e: IOException) {
assumeTrue(e.toString(), false)
}
}
@Test fun emptyChannels() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<code>IC</code>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(0, product.channels.size)
assertEquals(product, info["IC"])
}
@Test fun oneProductOnly() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="idea90" name="IntelliJ IDEA 9 updates" status="release" url="https://www.jetbrains.com/idea/whatsnew">
<build number="95.627" version="9.0.4">
<message>IntelliJ IDEA 9.0.4 is available. Please visit https://www.jetbrains.com/idea to learn more and download it.</message>
<patch from="95.429" size="2"/>
</build>
</channel>
<channel id="IDEA10EAP" name="IntelliJ IDEA X EAP" status="eap" licensing="eap" url="http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP">
<build number="98.520" version="10" releaseDate="20110403">
<message>IntelliJ IDEA X RC is available. Please visit http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP to learn more.</message>
<button name="Download" url="http://www.jetbrains.com/idea" download="true"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(2, product.channels.size)
val channel = product.channels.find { it.id == "IDEA10EAP" }!!
assertEquals(ChannelStatus.EAP, channel.status)
assertEquals(UpdateChannel.LICENSING_EAP, channel.licensing)
assertEquals(1, channel.builds.size)
val build = channel.builds[0]
assertEquals(BuildNumber.fromString("98.520"), build.number)
assertEquals("2011-04-03", SimpleDateFormat("yyyy-MM-dd").format(build.releaseDate))
assertNotNull(build.downloadUrl)
assertEquals(0, build.patches.size)
assertEquals(1, product.channels.find { it.id == "idea90" }!!.builds[0].patches.size)
}
@Test fun targetRanges() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="2016.2.123" version="2016.2" targetSince="0" targetUntil="145.*"/>
<build number="2016.2.123" version="2016.2" targetSince="2016.1" targetUntil="2016.1.*"/>
<build number="2016.1.11" version="2016.1"/>
</channel>
</product>
</products>""".trimIndent())
assertEquals(2, info["IU"]!!.channels[0].builds.count { it.target != null })
}
@Test fun fullBuildNumbers() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="162.100" fullNumber="162.100.1" version="2016.2">
<patch from="162.99" fullFrom="162.99.2" size="1"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val buildInfo = info["IU"]!!.channels[0].builds[0]
assertEquals("162.100.1", buildInfo.number.asString())
assertEquals("162.99.2", buildInfo.patches[0].fromBuild.asString())
}
private fun load(text: String) = UpdatesInfo(loadElement(text))
} | apache-2.0 | aafe568badf8d2d665c6d7fd8e89ef48 | 35.971223 | 155 | 0.648696 | 3.916159 | false | true | false | false |
lare96/luna | plugins/world/player/skill/firemaking/Log.kt | 1 | 842 | package world.player.skill.firemaking
/**
* An enum representing logs that can be burned.
*/
enum class Log(val id: Int, val level: Int, val exp: Double) {
NORMAL(id = 1511,
level = 1,
exp = 40.0),
OAK(id = 1521,
level = 15,
exp = 60.0),
WILLOW(id = 1519,
level = 30,
exp = 90.0),
TEAK(id = 6333,
level = 35,
exp = 105.0),
MAPLE(id = 1517,
level = 45,
exp = 135.0),
MAHOGANY(id = 6332,
level = 50,
exp = 157.5),
YEW(id = 1515,
level = 60,
exp = 202.5),
MAGIC(id = 1513,
level = 75,
exp = 303.8);
companion object {
/**
* Log item ID -> Log instance
*/
val ID_TO_LOG = values().associateBy { it.id }
}
}
| mit | 2074e30f0c8959e972ab39bc4eb61fb0 | 20.589744 | 62 | 0.445368 | 3.328063 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/map/viewmodel/MapViewModel.kt | 1 | 21734 | package com.telenav.osv.map.viewmodel
import android.annotation.SuppressLint
import android.location.Location
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.mapbox.mapboxsdk.module.http.HttpRequestUtil
import com.telenav.osv.application.ApplicationPreferences
import com.telenav.osv.application.PreferenceTypes
import com.telenav.osv.common.Injection
import com.telenav.osv.common.model.KVLatLng
import com.telenav.osv.data.location.datasource.LocationLocalDataSource
import com.telenav.osv.data.user.datasource.UserDataSource
import com.telenav.osv.event.EventBus
import com.telenav.osv.event.SdkEnabledEvent
import com.telenav.osv.event.network.matcher.KVBoundingBox
import com.telenav.osv.event.ui.UserTypeChangedEvent
import com.telenav.osv.item.network.TrackCollection
import com.telenav.osv.listener.network.NetworkResponseDataListener
import com.telenav.osv.manager.network.GeometryRetriever
import com.telenav.osv.manager.playback.OnlinePlaybackManager
import com.telenav.osv.manager.playback.PlaybackManager
import com.telenav.osv.manager.playback.SafePlaybackManager
import com.telenav.osv.manager.playback.VideoPlayerManager
import com.telenav.osv.map.MapFragment
import com.telenav.osv.map.model.*
import com.telenav.osv.map.model.MapModes
import com.telenav.osv.map.render.mapbox.grid.loader.GridsLoader
import com.telenav.osv.ui.fragment.camera.controls.viewmodel.RecordingViewModel
import com.telenav.osv.utils.Log
import com.telenav.osv.utils.StringUtils
import com.telenav.osv.utils.Utils
import com.telenav.osv.utils.getMapMode
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
/**
* The view model related to Map functionality. Holds the logic to switch the map between modes by using the [switchMode] which will change the state of the map.
*/
class MapViewModel(private val locationLocalDataSource: LocationLocalDataSource,
private val userDataSource: UserDataSource,
private val gridsLoader: GridsLoader,
private val geometryRetriever: GeometryRetriever,
private val appPrefs: ApplicationPreferences,
private val recordingViewModel: RecordingViewModel) : ViewModel(), PlaybackManager.PlaybackListener {
private var mutableRecordingEnable: MutableLiveData<Boolean> = MutableLiveData()
private var mutableLocationEnable: MutableLiveData<Boolean> = MutableLiveData()
private var mutableMapRender: MutableLiveData<MapRenderMode> = MutableLiveData()
private var mutableMapUpdate: MutableLiveData<MapUpdateBase> = MutableLiveData()
private var mutableNearby: MutableLiveData<TrackCollection?> = MutableLiveData()
private var mutableEnableProgress: MutableLiveData<Boolean> = MutableLiveData()
private var mutableEnableMyTasks: MutableLiveData<Boolean> = MutableLiveData()
private val mutableShouldReLogin: MutableLiveData<Boolean> = MutableLiveData()
private var disposables: CompositeDisposable = CompositeDisposable()
private var playbackManager: PlaybackManager? = null
private var boundingBoxUS = KVBoundingBox(KVLatLng(49.034, -125.041), KVLatLng(24.519, -68.701))
private var jarvisUserId: Int? = null
init {
TAG = MapViewModel::class.java.simpleName
}
/**
* Observable for changing the state of driving.
*/
val recordingEnable: LiveData<Boolean> = mutableRecordingEnable
/**
* Observable for changing the state of the rendering of points.
*/
val locationEnable: LiveData<Boolean> = mutableLocationEnable
/**
* Observable for updating the the values of the renders on the map.
*/
val mapRenderUpdate: LiveData<MapUpdateBase> = mutableMapUpdate
/**
* Observable for changing the state of the map rendering.
*/
val mapRender: LiveData<MapRenderMode> = mutableMapRender
/**
* Observable for changing the state of the rendering of points.
*/
val nearbySequences: LiveData<TrackCollection?> = mutableNearby
/**
* Observable for changing the state of the rendering of points.
*/
val enableProgress: LiveData<Boolean> = mutableEnableProgress
/**
* Observable for changing the state of the grid request.
*/
val enableMyTasks: LiveData<Boolean> = mutableEnableMyTasks
/**
* Observable for changing the state of re-login dialog
*/
val shouldReLogin: LiveData<Boolean> = mutableShouldReLogin
/**
* The current render mode.
*/
private var currentRenderMode = MapRenderMode.DEFAULT
/**
* The status representing if the zoom is between threshold values.
*/
private var isCurrentZoomBetweenGivenValues: Boolean = false
private var mapBoxJarvisOkHttpClient: OkHttpClient? = null
/**
* Function which switches the UI for different map modes. Available modes are based on [MapModes] enum, based on that:
* * [MapModes.IDLE] - this will enable all the controls on the map (recording button, center CCP) and request for the current persisted local sequences by using the internal [displayAllLocalSequences]
* * [MapModes.PREVIEW_MAP] - this will disable all the controls on the map, set the player in order to have access to the played local sequence and request for the current local sequence used in it by the internal method [displayPlayerSequence]
* * [MapModes.DISABLED] - this will disable the center CCP control on the map and disable the map. The recording control is still available since you can record without a map displayed.
* * [MapModes.PREVIEW_MAP_DISABLED] - this will disabled all the controls and the map.
* * [MapModes.RECORDING] - this will enable the map similar with [MapModes.IDLE] but with focus/control elements off
* * [MapModes.GRID] - this will enable map similiar with [MapModes.IDLE] with added grids to display the available tasks for the user.
* @param mapMode the map mode for which the UI will be switched and specific functionality will be called for that switch
* @param playbackManager this is required for [MapModes.PREVIEW_MAP] mode otherwise it should not be set.
*/
fun switchMode(mapMode: MapModes, playbackManager: PlaybackManager? = null) {
Log.d(TAG, "switch map Mode: ${mapMode.mode}")
when (mapMode) {
MapModes.IDLE -> {
currentRenderMode = MapRenderMode.DEFAULT
mutableMapRender.postValue(currentRenderMode)
enableMapButtons(true)
mutableEnableMyTasks.postValue(isJarvisUser())
displayAllLocalSequences(MapUpdateDefault())
}
MapModes.PREVIEW_MAP -> {
currentRenderMode = MapRenderMode.PREVIEW
mutableMapRender.postValue(currentRenderMode)
mutableEnableMyTasks.postValue(false)
enableMapButtons(false)
disposables.clear()
this.playbackManager = playbackManager
playbackManager?.addPlaybackListener(this)
if (playbackManager is SafePlaybackManager || playbackManager is VideoPlayerManager) {
displayPlayerSequence()
}
}
MapModes.PREVIEW_MAP_DISABLED -> {
currentRenderMode = MapRenderMode.DISABLED
mutableMapRender.postValue(currentRenderMode)
enableMapButtons(false)
mutableEnableMyTasks.postValue(false)
disposables.clear()
}
MapModes.DISABLED -> {
currentRenderMode = MapRenderMode.DISABLED
mutableMapRender.postValue(currentRenderMode)
enableLocationButton(false)
enableRecordingButton(true)
mutableEnableMyTasks.postValue(isJarvisUser())
disposables.clear()
}
MapModes.RECORDING -> {
currentRenderMode = MapRenderMode.RECORDING
mutableMapRender.postValue(currentRenderMode)
enableMapButtons(false)
mutableEnableMyTasks.postValue(false)
displayAllLocalSequences(MapUpdateRecording())
}
MapModes.RECORDING_MAP_DISABLED -> {
currentRenderMode = MapRenderMode.DISABLED
mutableMapRender.postValue(currentRenderMode)
enableMapButtons(false)
mutableEnableMyTasks.postValue(false)
disposables.clear()
}
MapModes.GRID -> {
currentRenderMode = MapRenderMode.DEFAULT_WITH_GRID
mutableMapRender.postValue(currentRenderMode)
enableMapButtons(true)
mutableEnableMyTasks.postValue(isJarvisUser())
}
}
}
override fun onCleared() {
super.onCleared()
disposables.clear()
geometryRetriever.destroy()
gridsLoader.clear()
}
/**
* Method for subscribe/unsubscribe to EventBus
*/
fun enableEventBus(enable: Boolean) {
if (enable) {
EventBus.register(this)
} else {
EventBus.unregister(this)
}
}
/**
* This will check if there is a jarvis user logged in and if the current zoom is between [MIN_ZOOM_LEVEL] and [MAX_ZOOM_LEVEL]. If true the request for grids will be made which will be based on the current given bounding box.
*
* The grids request will be performed by [GridsLoader] class.
*
*/
fun onGridsLoadIfAvailable(currentZoom: Double, boundingBox: LatLngBounds, currentLocation: LatLng, forceLoad: Boolean) {
val isJarvisUser = isJarvisUser()
//logic for when to active the grids based on the current zoom level
if (isJarvisUser) {
if (currentZoom < MIN_ZOOM_LEVEL_THRESHOLD) {
Log.d(TAG, "onGridsLoadIfAvailable. Status: Zoom smaller than min threshold. Message: Ignoring request. Current zoom: $currentZoom. Min threshold: $MIN_ZOOM_LEVEL_THRESHOLD")
} else {
val isCurrentZoomBetweenGivenValues = currentZoom >= MIN_ZOOM_LEVEL && currentZoom < MAX_ZOOM_LEVEL
var bypassForceLoad = forceLoad
if (!bypassForceLoad) {
bypassForceLoad = this.isCurrentZoomBetweenGivenValues != isCurrentZoomBetweenGivenValues
}
this.isCurrentZoomBetweenGivenValues = isCurrentZoomBetweenGivenValues
gridsLoader.loadIfNecessary(
boundingBox,
currentLocation,
{
Log.d(TAG, "onGridsLoadIfAvailable. Status: success. Grids szie: ${it.size}. Include labels: $isCurrentZoomBetweenGivenValues. Current Zoom: $currentZoom.")
displayAllLocalSequences(MapUpdateGrid(it, jarvisUserId!!, isCurrentZoomBetweenGivenValues))
},
{
Log.d(TAG, "onGridsLoadHandleError. Status: error. Message: ${it.message}.")
displayAllLocalSequences(MapUpdateGrid())
mutableShouldReLogin.value = true
},
bypassForceLoad)
}
} else {
Log.d(TAG, "onGridsLoadIfAvailable. Status: Jarvis user not found. Message: Ignoring request.")
}
}
fun setupMapResource(mapBoxJarvisOkHttpClient: OkHttpClient) {
disposables.add(userDataSource.user
.subscribeOn(Schedulers.io())
.subscribe(
{
if (it.jarvisUserId != 0) {
Log.d(TAG, "setupMapResources. Status: setting OkHttpClient for Jarvis authorization.")
this.jarvisUserId = it.jarvisUserId
HttpRequestUtil.setOkHttpClient(mapBoxJarvisOkHttpClient)
} else {
Log.d(TAG, "setupMapResources. Status: removing OkHttpClient for Jarvis authorization.")
HttpRequestUtil.setOkHttpClient(null)
}
},
{
Timber.d("error while getting the user type. Error: ${it.message}.")
}
))
}
/**
* Logic which handles the nearby sequence logic by making a network request to the [geometryRetriever] which will either return the nearby sequences or empty.
*/
fun onNearbySequencesClick(point: LatLng): Boolean {
mutableEnableProgress.postValue(true)
geometryRetriever.nearby(object : NetworkResponseDataListener<TrackCollection> {
override fun requestFailed(status: Int, details: TrackCollection) {
Log.d(TAG, "onMapClick. Nearby error: $details")
mutableEnableProgress.postValue(false)
}
override fun requestFinished(status: Int, collection: TrackCollection) {
Log.d(TAG, "onMapClick. Nearby success. Collection size: ${collection.trackList.size}")
mutableEnableProgress.postValue(false)
if (collection.trackList.size > 0) {
mutableNearby.postValue(collection)
} else {
mutableNearby.postValue(null)
}
}
}, point.latitude.toString(), point.longitude.toString())
return true
}
override fun onPaused() {
}
override fun onStopped() {
}
override fun onPrepared() {
if (playbackManager != null && playbackManager is OnlinePlaybackManager && playbackManager!!.track != null) {
displayPlayerSequence()
}
}
override fun onProgressChanged(index: Int) {
//ToDo: Remove this abomination once Player is rewritten FROM SCRATCH
val sequenceLocations = playbackManager!!.track!!.map { LatLng(it) }.toList()
var ccp: LatLng? = null
if (index < sequenceLocations.size) {
ccp = sequenceLocations[index]
}
mutableMapUpdate.postValue(MapUpdatePreview(sequenceLocations, ccp))
}
override fun onExit() {
Log.d(TAG, "onExit. Removed playback manager listener.")
playbackManager = null
}
override fun onPlaying() {
}
private fun displayPlayerSequence() {
val sequenceLocations = playbackManager!!.track!!.map { LatLng(it) }.toList()
mutableMapUpdate.postValue(MapUpdatePreview(sequenceLocations, if (sequenceLocations.isEmpty()) null else sequenceLocations[0]))
}
@Subscribe(sticky = true, threadMode = ThreadMode.BACKGROUND)
fun onSdkEnabled(event: SdkEnabledEvent) {
Log.d(TAG, "Evenbus onSdkEnabled.")
switchMode(if (event.enabled) MapModes.IDLE else MapModes.DISABLED, null)
EventBus.clear(SdkEnabledEvent::class.java)
}
//ToDo: remove this abomination once the EventBus is removed from the project, I am sorry for the workaround fix and the technical depth added
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
fun onUserTypeChanged(event: UserTypeChangedEvent) {
//for now this is the only way to check if a user has been logged out
if (event.type == PreferenceTypes.USER_TYPE_UNKNOWN) {
Log.d(MapFragment.TAG, "onUserTypeChanged. Status: unknown user type. Message: Clearing grids.")
jarvisUserId = null
HttpRequestUtil.setOkHttpClient(null)
switchMode(appPrefs.getMapMode(), null)
displayAllLocalSequences(MapUpdateDefault())
mutableEnableMyTasks.postValue(false)
} else {
disposables.add(userDataSource.user
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
if (it.jarvisUserId != 0) {
mapBoxJarvisOkHttpClient = Injection.provideMapBoxOkHttpClient(appPrefs)
this.jarvisUserId = it.jarvisUserId
HttpRequestUtil.setOkHttpClient(mapBoxJarvisOkHttpClient)
Log.d(TAG, "onUserTypeChanged. Status: Jarvis user loaded. Message: Clearing previous coverages.")
if (currentRenderMode != MapRenderMode.RECORDING) {
switchMode(mapMode = MapModes.GRID)
}
}
},
{
Log.d(TAG, "onUserTypeChanged. Status: Could not get user. Error: ${it.message}.")
}
))
}
}
/**
* @return true if the jarvis id is set, false otherwise
*/
private fun isJarvisUser(): Boolean {
return jarvisUserId != null && jarvisUserId != 0
}
/**
* Enables/disables the recording button.
* @param enable `true` if the button should be visible, `false` otherwise.
*/
private fun enableRecordingButton(enable: Boolean) {
Log.d(TAG, "enableRecordingButton: $enable")
mutableRecordingEnable.postValue(enable)
}
/**
* This will enable/disable the metric/imperial system based on the current location if it is inside a specific bounding box.
*/
fun initMetricBasedOnCcp(location: Location): Boolean {
return (Utils.isInsideBoundingBox(
location.latitude,
location.longitude,
boundingBoxUS.topLeft.lat,
boundingBoxUS.topLeft.lon,
boundingBoxUS.bottomRight.lat,
boundingBoxUS.bottomRight.lon))
}
/**
* Enables/disables the location button.
* @param enable `true` if the button should be visible, `false` otherwise.
*/
private fun enableLocationButton(enable: Boolean) {
Log.d(TAG, "enableLocationButton: $enable")
mutableLocationEnable.postValue(enable)
}
private fun displayAllLocalSequences(mapRenderBaseSequences: MapUpdateBaseSequences) {
disposables.add(
locationLocalDataSource
.locations
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ locations ->
val sequences = mutableListOf<List<LatLng>>()
if (locations.isEmpty()) {
Log.d(TAG, "displayAllLocalSequences. Status: abort. Message: Empty sequences.")
mapRenderBaseSequences.sequences = mutableListOf()
mutableMapUpdate.postValue(mapRenderBaseSequences)
return@subscribe
}
val sequencesGrouped = locations.filter { location ->
location.sequenceId != (recordingViewModel.currentSequenceIdIfSet
?: StringUtils.EMPTY_STRING)
}.groupBy { it.sequenceId }
Log.d(TAG, "displayAllLocalSequences. Locations size: ${sequencesGrouped.size}")
for ((_, value) in sequencesGrouped) {
sequences.add(value.map { LatLng(it.location) })
}
mapRenderBaseSequences.sequences = sequences
mutableMapUpdate.postValue(mapRenderBaseSequences)
},
//onError
{ throwable ->
Log.d(TAG, String.format("displayLocalSequencesRunnable. Status: error. Message: %s.", throwable.localizedMessage))
}))
}
/**
* Enables/disables the map buttons, i.e. record and position.
*
* The lint suppress is due to restriction of the api. While the recommendation is to use hide/show methods, that means those methods will use internally animators sets
* which have issues when called on fragments which do not have callbacks of lifecycle when the view is changed/resized.
* @param enable `true` will display the buttons, otherwise hide them.
*/
@SuppressLint("RestrictedApi")
fun enableMapButtons(enable: Boolean) {
Log.d(TAG, "enableMapButtons: $enable")
enableRecordingButton(enable)
mutableLocationEnable.postValue(enable)
}
private companion object {
private lateinit var TAG: String
private const val MIN_ZOOM_LEVEL: Double = 13.2
private const val MAX_ZOOM_LEVEL: Double = 16.2
private const val MIN_ZOOM_LEVEL_THRESHOLD: Double = 9.1
}
} | lgpl-3.0 | 214488afb2eeec88a5d519120d50d5c8 | 45.442308 | 249 | 0.625104 | 5.177227 | false | false | false | false |
cjkent/osiris | core/src/main/kotlin/ws/osiris/core/Api.kt | 1 | 18939 | package ws.osiris.core
import org.slf4j.LoggerFactory
import java.util.regex.Pattern
import kotlin.reflect.KClass
private val log = LoggerFactory.getLogger("ws.osiris.core")
/**
* The MIME types that are treated as binary by default.
*
* The user can specify additional types that should be treated as binary using `binaryMimeTypes` in
* the API definition.
*/
val STANDARD_BINARY_MIME_TYPES = setOf(
"application/octet-steam",
"image/png",
"image/apng",
"image/webp",
"image/jpeg",
"image/gif",
"audio/mpeg",
"video/mpeg",
"application/pdf",
"multipart/form-data"
)
/**
* A model describing an API; it contains the routes to the API endpoints and the code executed
* when the API receives requests.
*/
data class Api<T : ComponentsProvider>(
/**
* The routes defined by the API.
*
* Each route consists of:
* * An HTTP method
* * A path
* * The code that is executed when a request is received for the endpoint
* * The authorisation required to invoke the endpoint.
*/
val routes: List<Route<T>>,
/** Filters applied to requests before they are passed to a handler. */
val filters: List<Filter<T>>,
/**
* The type of the object available to the code in the API definition that handles the HTTP requests.
*
* The code in the API definition runs with the components provider class as the implicit receiver
* and can directly access its properties and methods.
*
* For example, if a data store is needed to handle a request, it would be provided by
* the `ComponentsProvider` implementation:
*
* class Components(val dataStore: DataStore) : ComponentsProvider
*
* ...
*
* get("/orders/{orderId}") { req ->
* val orderId = req.pathParams["orderId"]
* dataStore.loadOrderDetails(orderId)
* }
*/
val componentsClass: KClass<in T>,
/** True if this API serves static files. */
val staticFiles: Boolean,
/** The MIME types that are treated by API Gateway as binary; these are encoded in the JSON using Base64. */
val binaryMimeTypes: Set<String>
) {
companion object {
/**
* Merges multiple APIs into a single API.
*
* The APIs must not defines any endpoints with the same path and method.
*
* This is intended to allow large APIs to be defined across multiple files:
*
* val api1 = api<Foo> {
* get("/bar") {
* ...
* }
* }
*
* val api2 = api<Foo> {
* get("/baz") {
* ...
* }
* }
*
* // An API containing all the endpoints and filters from `api1` and `api2`
* val api = Api.merge(api1, api2)
*/
inline fun <reified T : ComponentsProvider> merge(api1: Api<T>, api2: Api<T>, vararg rest: Api<T>): Api<T> {
val apis = listOf(api1, api2) + rest
val routes = apis.map { it.routes }.reduce { allRoutes, apiRoutes -> allRoutes + apiRoutes }
val filters = apis.map { it.filters }.reduce { allFilters, apiFilters -> allFilters + apiFilters }
val staticFiles = apis.map { it.staticFiles }.reduce { sf1, sf2 -> sf1 || sf2}
val binaryMimeTypes = apis.flatMap { it.binaryMimeTypes }.toSet()
return Api(routes, filters, T::class, staticFiles, binaryMimeTypes)
}
}
}
/**
* This function is the entry point to the DSL used for defining an API.
*
* It is used to populate a top-level property named `api`. For example
*
* val api = api<ExampleComponents> {
* get("/foo") { req ->
* ...
* }
* }
*
* The type parameter is the type of the implicit receiver of the handler code. This means the properties and
* functions of that type are available to be used by the handler code. See [ComponentsProvider] for details.
*/
inline fun <reified T : ComponentsProvider> api(cors: Boolean = false, body: RootApiBuilder<T>.() -> Unit): Api<T> {
// This needs to be local because this function is inline and can only access public members of this package
val log = LoggerFactory.getLogger("ws.osiris.core")
log.debug("Creating the Api")
val builder = RootApiBuilder(T::class, cors)
log.debug("Running the RootApiBuilder")
builder.body()
log.debug("Building the Api from the builder")
val api = buildApi(builder)
log.debug("Created the Api")
return api
}
/**
* The type of the lambdas in the DSL containing the code that runs when a request is received.
*/
internal typealias Handler<T> = T.(Request) -> Any
// This causes the compiler to crash
//typealias FilterHandler<T> = T.(Request, Handler<T>) -> Any
// This is equivalent to the line above but doesn't make the compiler crash
internal typealias FilterHandler<T> = T.(Request, T.(Request) -> Response) -> Any
/**
* The type of lambda in the DSL passed to the `cors` function.
*
* This lambda receives a request (for any endpoint where `cors = true`) and populates the fields
* used to build the CORS headers.
*/
internal typealias CorsHandler<T> = CorsHeadersBuilder<T>.(Request) -> Unit
/**
* The type of the handler passed to a [Filter].
*
* Handlers and filters can return objects of any type (see [Handler]). If the returned value is
* not a [Response] the library wraps it in a `Response` before returning it to the caller. This
* ensures that the objects returned to a `Filter` implementation is guaranteed to be a `Response`.
*/
typealias RequestHandler<T> = T.(Request) -> Response
/**
* Pattern matching resource paths; matches regular segments like `/foo` and variable segments like `/{foo}` and
* any combination of the two.
*/
internal val pathPattern = Pattern.compile("/|(?:(?:/[a-zA-Z0-9_\\-~.()]+)|(?:/\\{[a-zA-Z0-9_\\-~.()]+}))+")
/**
* Marks the DSL implicit receivers to avoid scoping problems.
*/
@DslMarker
@Target(AnnotationTarget.CLASS)
internal annotation class OsirisDsl
/**
* This is an internal class that is part of the DSL implementation and should not be used by user code.
*/
@OsirisDsl
open class ApiBuilder<T : ComponentsProvider> internal constructor(
internal val componentsClass: KClass<T>,
private val prefix: String,
private val auth: Auth?,
private val cors: Boolean
) {
internal var staticFilesBuilder: StaticFilesBuilder? = null
internal var corsHandler: CorsHandler<T>? = null
set(handler) {
if (field == null) {
field = handler
} else {
throw IllegalStateException("There must be only one cors block")
}
}
internal val routes: MutableList<LambdaRoute<T>> = arrayListOf()
internal val filters: MutableList<Filter<T>> = arrayListOf()
private val children: MutableList<ApiBuilder<T>> = arrayListOf()
/** Defines an endpoint that handles GET requests to the path. */
fun get(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.GET, path, handler, cors)
/** Defines an endpoint that handles POST requests to the path. */
fun post(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.POST, path, handler, cors)
/** Defines an endpoint that handles PUT requests to the path. */
fun put(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.PUT, path, handler, cors)
/** Defines an endpoint that handles UPDATE requests to the path. */
fun update(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.UPDATE, path, handler, cors)
/** Defines an endpoint that handles OPTIONS requests to the path. */
fun options(path: String, handler: Handler<T>): Unit =
addRoute(HttpMethod.OPTIONS, path, handler, null)
/** Defines an endpoint that handles PATCH requests to the path. */
fun patch(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.PATCH, path, handler, cors)
/** Defines an endpoint that handles DELETE requests to the path. */
fun delete(path: String, cors: Boolean? = null, handler: Handler<T>): Unit =
addRoute(HttpMethod.DELETE, path, handler, cors)
fun filter(path: String, handler: FilterHandler<T>): Unit {
filters.add(Filter(prefix, path, handler))
}
fun filter(handler: FilterHandler<T>): Unit = filter("/*", handler)
fun path(path: String, cors: Boolean? = null, body: ApiBuilder<T>.() -> Unit) {
val child = ApiBuilder(componentsClass, prefix + path, auth, cors ?: this.cors)
children.add(child)
child.body()
}
fun auth(auth: Auth, body: ApiBuilder<T>.() -> Unit) {
// not sure about this. the alternative is to allow nesting and the inner block applies.
// this seems misleading to me. common sense says that nesting an endpoint inside multiple
// auth blocks means it would be subject to multiple auth strategies. which isn't true
// and wouldn't make sense.
// if I did that then the auth fields could be non-nullable and default to None
if (this.auth != null) throw IllegalStateException("auth blocks cannot be nested")
val child = ApiBuilder(componentsClass, prefix, auth, cors)
children.add(child)
child.body()
}
fun staticFiles(body: StaticFilesBuilder.() -> Unit) {
val staticFilesBuilder = StaticFilesBuilder(prefix, auth)
staticFilesBuilder.body()
this.staticFilesBuilder = staticFilesBuilder
}
fun cors(corsHandler: CorsHandler<T>) {
this.corsHandler = corsHandler
}
//--------------------------------------------------------------------------------------------------
private fun addRoute(method: HttpMethod, path: String, handler: Handler<T>, routeCors: Boolean?) {
val cors = routeCors ?: cors
routes.add(LambdaRoute(method, prefix + path, requestHandler(handler), auth ?: NoAuth, cors))
}
internal fun descendants(): List<ApiBuilder<T>> = children + children.flatMap { it.descendants() }
companion object {
private fun <T : ComponentsProvider> requestHandler(handler: Handler<T>): RequestHandler<T> = { req ->
val returnVal = handler(this, req)
returnVal as? Response ?: req.responseBuilder().build(returnVal)
}
}
}
@OsirisDsl
class RootApiBuilder<T : ComponentsProvider> internal constructor(
componentsClass: KClass<T>,
prefix: String,
auth: Auth?,
cors: Boolean
) : ApiBuilder<T>(componentsClass, prefix, auth, cors) {
constructor(componentsType: KClass<T>, cors: Boolean) : this(componentsType, "", null, cors)
var globalFilters: List<Filter<T>> = StandardFilters.create()
var binaryMimeTypes: Set<String>? = null
set(value) {
if (field != null) {
throw IllegalStateException("Binary MIME types must only be set once. Current values: $binaryMimeTypes")
}
field = value
}
get() = field?.let { it + STANDARD_BINARY_MIME_TYPES } ?: STANDARD_BINARY_MIME_TYPES
/**
* Returns the static files configuration.
*
* This can be specified in any `ApiBuilder` in the API definition, but it must only be specified once.
*/
internal fun effectiveStaticFiles(): StaticFiles? {
val allStaticFiles = descendants().map { it.staticFilesBuilder } + staticFilesBuilder
val nonNullStaticFiles = allStaticFiles.filterNotNull()
if (nonNullStaticFiles.size > 1) {
throw IllegalArgumentException("staticFiles must only be specified once")
}
return nonNullStaticFiles.firstOrNull()?.build()
}
}
/**
* Builds the API defined by the builder.
*
* This function is an implementation detail and not intended to be called by users.
*/
fun <T : ComponentsProvider> buildApi(builder: RootApiBuilder<T>): Api<T> {
val filters = builder.globalFilters + builder.filters + builder.descendants().flatMap { it.filters }
// TODO validate that there's a CORS handler if anything has cors = true?
val corsHandler = builder.corsHandler
val corsFilters = if (corsHandler != null) listOf(corsFilter(corsHandler)) + filters else filters
val lambdaRoutes = builder.routes + builder.descendants().flatMap { it.routes }
val allLambdaRoutes = addOptionsMethods(lambdaRoutes)
// TODO the explicit type is needed to make type inference work. remove in future
val wrappedRoutes: List<Route<T>> = allLambdaRoutes.map { if (it.cors) it.wrap(corsFilters) else it.wrap(filters) }
val effectiveStaticFiles = builder.effectiveStaticFiles()
val allRoutes = when (effectiveStaticFiles) {
null -> wrappedRoutes
else -> wrappedRoutes + StaticRoute(
effectiveStaticFiles.path,
effectiveStaticFiles.indexFile,
effectiveStaticFiles.auth
)
}
if (effectiveStaticFiles != null && !staticFilesPattern.matcher(effectiveStaticFiles.path).matches()) {
throw IllegalArgumentException("Static files path is illegal: $effectiveStaticFiles")
}
val authTypes = allRoutes.map { it.auth }.filter { it != NoAuth }.toSet()
if (authTypes.size > 1) throw IllegalArgumentException("Only one auth type is supported but found $authTypes")
val binaryMimeTypes = builder.binaryMimeTypes ?: setOf()
return Api(allRoutes, filters, builder.componentsClass, effectiveStaticFiles != null, binaryMimeTypes)
}
private fun <T : ComponentsProvider> addOptionsMethods(routes: List<LambdaRoute<T>>): List<LambdaRoute<T>> {
// group the routes by path, ignoring any paths with no CORS routes and any that already have an OPTIONS method
val routesByPath = routes.groupBy { it.path }
.filterValues { pathRoutes -> pathRoutes.any { it.cors } }
.filterValues { pathRoutes -> pathRoutes.none { it.method == HttpMethod.OPTIONS } }
// the options method provides a CORS response for all other methods for the same path.
// if they all have the same auth then the OPTIONS method should probably have it too.
// if they don't all have the same auth then it's impossible to say what the OPTIONS auth
// should be. NoAuth seems reasonable. an OPTIONS request should be harmless.
val authByPath = routesByPath
.mapValues { (_, pathRoutes) -> pathRoutes.map { it.auth }.filter { it != NoAuth }.toSet() }
.mapValues { (_, authSet) -> if (authSet.size == 1) authSet.first() else NoAuth }
// the default handler added for OPTIONS methods doesn't do anything exception build the response.
// the response builder will have been initialised with the CORS headers so this will build a
// CORS-compliant response
val optionsHandler: RequestHandler<T> = { req -> req.responseBuilder().build() }
val optionsRoutes = authByPath.map { (path, auth) -> LambdaRoute(HttpMethod.OPTIONS, path, optionsHandler, auth, true) }
log.debug("Adding routes for OPTIONS methods: {}", optionsRoutes)
return routes + optionsRoutes
}
/**
* Returns a filter that passes the request to the [corsHandler] and adds the returned headers to the default
* response headers.
*
* This filter is used as the first filter for any endpoint where `cors=true`.
*/
private fun <T : ComponentsProvider> corsFilter(corsHandler: CorsHandler<T>): Filter<T> =
defineFilter { req, handler ->
val corsHeadersBuilder = CorsHeadersBuilder<T>()
corsHandler(corsHeadersBuilder, req)
val corHeaders = corsHeadersBuilder.build()
val defaultResponseHeaders = req.defaultResponseHeaders + corHeaders.headerMap
val newReq = req.copy(defaultResponseHeaders = defaultResponseHeaders)
handler(newReq)
}
private val staticFilesPattern = Pattern.compile("/|(?:/[a-zA-Z0-9_\\-~.()]+)+")
class CorsHeadersBuilder<T : ComponentsProvider> {
var allowMethods: Set<HttpMethod>? = null
var allowHeaders: Set<String>? = null
var allowOrigin: Set<String>? = null
internal fun build(): Headers {
val headerMap = mapOf(
"Access-Control-Allow-Methods" to allowMethods?.joinToString(","),
"Access-Control-Allow-Headers" to allowHeaders?.joinToString(","),
"Access-Control-Allow-Origin" to allowOrigin?.joinToString(",")
)
@Suppress("UNCHECKED_CAST")
return Headers(headerMap.filterValues { it != null } as Map<String, String>)
}
}
class StaticFilesBuilder(
private val prefix: String,
private val auth: Auth?
) {
var path: String? = null
var indexFile: String? = null
internal fun build(): StaticFiles {
val localPath = path ?: throw IllegalArgumentException("Must specify the static files path")
return StaticFiles(prefix + localPath, indexFile, auth ?: NoAuth)
}
}
data class StaticFiles internal constructor(val path: String, val indexFile: String?, val auth: Auth)
/**
* Provides all the components used by the implementation of the API.
*
* The code in the API runs with the components provider class as the implicit receiver
* and can directly access its properties and methods.
*
* For example, if a data store is needed to handle a request, it would be provided by
* the `ComponentsProvider` implementation:
*
* class Components(val dataStore: DataStore) : ComponentsProvider
*
* ...
*
* get("/orders/{orderId}") { req ->
* val orderId = req.pathParams["orderId"]
* dataStore.loadOrderDetails(orderId)
* }
*/
@OsirisDsl
interface ComponentsProvider
/**
* The authorisation strategy that should be applied to an endpoint in the API.
*/
interface Auth {
/** The name of the authorisation strategy. */
val name: String
}
/**
* Authorisation strategy that allows anyone to call an endpoint in the API without authenticating.
*/
object NoAuth : Auth {
override val name: String = "NONE"
}
/**
* Base class for exceptions that should be automatically mapped to HTTP status codes.
*/
abstract class HttpException(val httpStatus: Int, message: String) : RuntimeException(message)
/**
* Exception indicating that data could not be found at the specified location.
*
* This is thrown when a path doesn't match a resource and is translated to a
* status of 404 (not found) by default.
*/
class DataNotFoundException(message: String = "Not Found") : HttpException(404, message)
/**
* Exception indicating the caller is not authorised to access the resource.
*
* This is translated to a status of 403 (forbidden) by default.
*/
class ForbiddenException(message: String = "Forbidden") : HttpException(403, message)
| apache-2.0 | f1b26e4847511fa515fa61a32a5f7a78 | 38.955696 | 124 | 0.662179 | 4.259784 | false | false | false | false |
BilledTrain380/sporttag-psa | app/desktop-starter/src/main/kotlin/ch/schulealtendorf/psa/desktop/PsaApplicationContext.kt | 1 | 898 | package ch.schulealtendorf.psa.desktop
import ch.schulealtendorf.psa.PsaApplication
import ch.schulealtendorf.psa.setup.AppDirsApplicationDirectory
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.context.ConfigurableApplicationContext
import java.nio.file.Path
object PsaApplicationContext {
val logsDirectory: Path = AppDirsApplicationDirectory().path.resolve("logs")
private var context: ConfigurableApplicationContext? = null
fun start(args: Array<String>) {
val properties = HashMap<String, Any>().apply {
put("psa.logging.path", logsDirectory.toString())
}
context = SpringApplicationBuilder(PsaApplication::class.java)
.profiles("standalone")
.properties(properties)
.run(*args)
}
fun stop() {
context?.close()
context = null
}
}
| gpl-3.0 | ead1f8a1edca8f262c15a84e3ac9c186 | 29.965517 | 80 | 0.709354 | 4.776596 | false | true | false | false |
ioc1778/incubator | incubator-quant/src/main/java/com/riaektiv/quant/options/OneStepBinomialModel.kt | 2 | 1827 | package com.riaektiv.quant.options
/**
* Coding With Passion Since 1991
* Created: 8/20/2016, 9:09 PM Eastern Time
* @author Sergey Chuykov
*/
class OneStepBinomialModel(val strike: Double, val months: Double,
val S0: Double, val u: Double, val d: Double,
val rate: Double) {
// John C. Hull
// Options, Futures and Other Derivatives, 9th edition
// page 274-277
fun payoff(price: Double, strike: Double): Double {
return Math.max(0.0, price - strike)
}
fun shares(S1u: Double, S1d: Double, strike: Double): Double {
return (payoff(S1u, strike) - payoff(S1d, strike)) / (S1u - S1d)
}
fun future(shares: Double, price: Double, strike: Double): Double {
return shares * price - payoff(price, strike)
}
fun present(fv: Double, rate: Double, months: Double): Double {
return fv * Math.pow(Math.E, -(rate * months / 12.0))
}
fun calculate1(): Double {
val S1u = S0 * u
val S1d = S0 * d
val shares = shares(S1u, S1d, strike)
val fv = future(shares, S1u, strike)
val pv = present(fv, rate, months)
return shares * S0 - pv
}
fun p(u: Double, d: Double, rate: Double, time: Double): Double {
return (Math.pow(Math.E, (rate * (time / 12.0))) - d) / (u - d) // (13.3)
}
fun f(p: Double, fu: Double, fd: Double, rate: Double, months: Double): Double {
return Math.pow(Math.E, -(rate * months / 12.0)) * (p * fu + (1 - p) * fd) // (13.2)
}
fun calculate2(): Double {
val S1u = S0 * u
val S1d = S0 * d
val fu = payoff(S1u, strike)
val fd = payoff(S1d, strike)
val p = p(u, d, rate, months)
val f = f(p, fu, fd, rate, months)
return f
}
}
| bsd-3-clause | 4ab22e6d94a03266ad20c0e7522f5946 | 27.107692 | 92 | 0.550629 | 3.19965 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/rest/ScriptsRestClient.kt | 1 | 2499 | package com.github.jk1.ytplugin.rest
import com.github.jk1.ytplugin.issues.model.Workflow
import com.github.jk1.ytplugin.issues.model.WorkflowRule
import com.github.jk1.ytplugin.logger
import com.github.jk1.ytplugin.rest.MulticatchException.Companion.multicatchException
import com.github.jk1.ytplugin.tasks.YouTrackServer
import com.github.jk1.ytplugin.timeTracker.TrackerNotification
import com.google.gson.JsonObject
import com.intellij.notification.NotificationType
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.utils.URIBuilder
import org.apache.http.conn.HttpHostConnectException
import java.net.UnknownHostException
class ScriptsRestClient(override val repository: YouTrackServer) : RestClientTrait, ResponseLoggerTrait {
fun getScriptsWithRules(): List<Workflow> {
val builder = URIBuilder("${repository.url}/api/admin/workflows")
builder.setParameter("\$top", "-1")
.setParameter("fields", "name,id,rules(id,name)")
.setParameter("query", "language:JS")
.setParameter("debug", "true")
val method = HttpGet(builder.build())
val scriptsList = mutableListOf<Workflow>()
return try {
method.execute { element ->
val jsonArray = element.asJsonArray
for (json in jsonArray) {
scriptsList.add(Workflow(json as JsonObject))
}
scriptsList
}
} catch (e: Exception) {
e.multicatchException(UnknownHostException::class.java, HttpHostConnectException::class.java,
RuntimeException::class.java) {
logger.debug("Unable to load YouTrack Scripts: ${e.message}")
val trackerNote = TrackerNotification()
trackerNote.notify("Connection to the YouTrack might be lost", NotificationType.WARNING)
emptyList()
}
}
}
fun getScriptsContent(workflow: Workflow, rule: WorkflowRule) {
val builder = URIBuilder("${repository.url}/api/admin/workflows/${workflow.id}/rules/${rule.id}")
builder.setParameter("\$top", "-1")
.setParameter("fields", "script")
val method = HttpGet(builder.build())
return method.execute { element ->
rule.content = element.asJsonObject.get("script").asString
}
// logger.warn("Unable to get workFlow content $status: ${method.responseBodyAsLoggedString()}")
}
}
| apache-2.0 | 67cb0378edb49cd37b70a5e2926c6f34 | 39.967213 | 105 | 0.667067 | 4.551913 | false | false | false | false |
liuche/focus-android | app/src/main/java/org/mozilla/focus/autocomplete/UrlAutoCompleteFilter.kt | 3 | 5855 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.autocomplete
import android.content.Context
import android.util.Log
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import org.mozilla.focus.locale.Locales
import org.mozilla.focus.utils.Settings
import org.mozilla.focus.widget.InlineAutocompleteEditText
import org.mozilla.focus.widget.InlineAutocompleteEditText.AutocompleteResult
import java.io.IOException
import java.util.Locale
class UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {
companion object {
private val LOG_TAG = "UrlAutoCompleteFilter"
}
object AutocompleteSource {
const val DEFAULT_LIST = "default"
const val CUSTOM_LIST = "custom"
}
private var settings: Settings? = null
private var customDomains: List<String> = emptyList()
private var preInstalledDomains: List<String> = emptyList()
override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {
if (view == null) {
return
}
// Search terms are all lowercase already, we just need to lowercase the search text
val searchText = rawSearchText.toLowerCase(Locale.US)
settings?.let {
if (it.shouldAutocompleteFromCustomDomainList()) {
val autocomplete = tryToAutocomplete(searchText, customDomains)
if (autocomplete != null) {
view.onAutocomplete(prepareAutocompleteResult(
rawSearchText,
autocomplete,
AutocompleteSource.CUSTOM_LIST,
customDomains.size))
return
}
}
if (it.shouldAutocompleteFromShippedDomainList()) {
val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)
if (autocomplete != null) {
view.onAutocomplete(prepareAutocompleteResult(
rawSearchText,
autocomplete,
AutocompleteSource.DEFAULT_LIST,
preInstalledDomains.size))
return
}
}
}
view.onAutocomplete(AutocompleteResult.emptyResult())
}
private fun tryToAutocomplete(searchText: String, domains: List<String>): String? {
domains.forEach {
val wwwDomain = "www." + it
if (wwwDomain.startsWith(searchText)) {
return wwwDomain
}
if (it.startsWith(searchText)) {
return it
}
}
return null
}
internal fun onDomainsLoaded(domains: List<String>, customDomains: List<String>) {
this.preInstalledDomains = domains
this.customDomains = customDomains
}
fun load(context: Context, loadDomainsFromDisk: Boolean = true) {
settings = Settings.getInstance(context)
if (loadDomainsFromDisk) {
launch(UI) {
val domains = async(CommonPool) { loadDomains(context) }
val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }
onDomainsLoaded(domains.await(), customDomains.await())
}
}
}
private suspend fun loadDomains(context: Context): List<String> {
val domains = LinkedHashSet<String>()
val availableLists = getAvailableDomainLists(context)
// First load the country specific lists following the default locale order
Locales.getCountriesInDefaultLocaleList()
.asSequence()
.filter { availableLists.contains(it) }
.forEach { loadDomainsForLanguage(context, domains, it) }
// And then add domains from the global list
loadDomainsForLanguage(context, domains, "global")
return domains.toList()
}
private fun getAvailableDomainLists(context: Context): Set<String> {
val availableDomains = LinkedHashSet<String>()
val assetManager = context.assets
try {
availableDomains.addAll(assetManager.list("domains"))
} catch (e: IOException) {
Log.w(LOG_TAG, "Could not list domain list directory")
}
return availableDomains
}
private fun loadDomainsForLanguage(context: Context, domains: MutableSet<String>, country: String) {
val assetManager = context.assets
try {
domains.addAll(
assetManager.open("domains/" + country).bufferedReader().readLines())
} catch (e: IOException) {
Log.w(LOG_TAG, "Could not load domain list: " + country)
}
}
/**
* Our autocomplete list is all lower case, however the search text might be mixed case.
* Our autocomplete EditText code does more string comparison, which fails if the suggestion
* doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion
* that exactly matches the search text - which is what this method is for:
*/
private fun prepareAutocompleteResult(
rawSearchText: String,
lowerCaseResult: String,
source: String,
totalCount: Int
) =
AutocompleteResult(
rawSearchText + lowerCaseResult.substring(rawSearchText.length),
source,
totalCount)
}
| mpl-2.0 | 3430e477dcfd0cd5a1d7a7d98c48d82b | 35.141975 | 115 | 0.622032 | 5.195209 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/okhttp/LoggingInterceptor.kt | 1 | 3677 | package com.exyui.android.debugbottle.components.okhttp
import android.util.Log
import com.squareup.okhttp.*
import com.exyui.android.debugbottle.components.DTSettings
import java.io.IOException
import okio.Buffer
/**
* Created by yuriel on 8/18/16.
*/
internal class LoggingInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
val response = chain.proceed(request)
val t2 = System.nanoTime()
var contentType: MediaType? = null
var bodyString: String? = null
if (response.body() != null) {
contentType = response.body().contentType()
bodyString = response.body().string()
}
var requestBody = ""
var responseBody = ""
val time: Double = (t2 - t1) / 1e6
when(request.method()) {
"GET" -> {
responseBody = stringifyResponseBody(bodyString!!)
println(String.format("GET $F_REQUEST_WITHOUT_BODY$F_RESPONSE_WITH_BODY",
request.url(), time, request.headers(),
response.code(), response.headers(), responseBody))
}
"POST" -> {
requestBody = stringifyRequestBody(request)
responseBody = stringifyResponseBody(bodyString!!)
println(String.format("POST $F_REQUEST_WITH_BODY$F_RESPONSE_WITH_BODY",
request.url(), time, request.headers(), requestBody,
response.code(), response.headers(), responseBody))
}
"PUT" -> {
requestBody = request.body().toString()
responseBody = stringifyResponseBody(bodyString!!)
println(String.format("PUT $F_REQUEST_WITH_BODY$F_RESPONSE_WITH_BODY",
request.url(), time, request.headers(), requestBody,
response.code(), response.headers(), responseBody))
}
"DELETE" -> {
println(String.format("DELETE $F_REQUEST_WITHOUT_BODY$F_RESPONSE_WITHOUT_BODY",
request.url(), time, request.headers(),
response.code(), response.headers()))
}
}
val block = HttpBlock.newInstance(
url = request.url().toString(),
method = request.method(),
timeStart = t1,
timeEnd = t2,
requestHeader = request.headers().toString(),
responseCode = response.code().toString(),
responseHeader = response.headers().toString(),
requestBody = requestBody,
responseBody = responseBody
)
if (DTSettings.networkSniff) {
HttpBlockFileMgr.saveLog(block.toString())
}
if (response.body() != null) {
val body = ResponseBody.create(contentType, bodyString)
return response.newBuilder().body(body).build()
} else {
return response
}
}
private fun stringifyResponseBody(responseBody: String): String {
return responseBody
}
private fun stringifyRequestBody(request: Request): String {
try {
val copy = request.newBuilder().build()
val buffer = Buffer()
copy.body().writeTo(buffer)
return buffer.readUtf8()
} catch (e: IOException) {
return "did not work"
}
}
private fun println(line: String) {
Log.d("DEBUG-BOTTLE", line)
}
} | apache-2.0 | 10c186fecdfa801beb41672e8e90366c | 34.708738 | 95 | 0.55344 | 4.896138 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/snapping/LazyListSnappingDemos.kt | 3 | 5847 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.demos.snapping
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider
import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.integration.demos.common.ComposableDemo
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
val LazyListSnappingDemos = listOf(
ComposableDemo("Single Page - Same Size Pages") { SamePageSizeDemo() },
ComposableDemo("Single Page - Multi-Size Pages") { MultiSizePageDemo() },
ComposableDemo("Single Page - Large Pages") { LargePageSizeDemo() },
ComposableDemo("Single Page - List with Content padding") { DifferentContentPaddingDemo() },
ComposableDemo("Multi Page - Animation Based Offset") { MultiPageSnappingDemo() },
ComposableDemo("Multi Page - View Port Based Offset") { ViewPortBasedSnappingDemo() },
)
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SamePageSizeDemo() {
val lazyListState = rememberLazyListState()
val layoutInfoProvider = rememberNextPageSnappingLayoutInfoProvider(lazyListState)
val flingBehavior = rememberSnapFlingBehavior(layoutInfoProvider)
SnappingDemoMainLayout(
lazyListState = lazyListState,
flingBehavior = flingBehavior
) {
DefaultSnapDemoItem(it)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MultiSizePageDemo() {
val lazyListState = rememberLazyListState()
val layoutInfoProvider = rememberNextPageSnappingLayoutInfoProvider(lazyListState)
val flingBehavior = rememberSnapFlingBehavior(layoutInfoProvider)
SnappingDemoMainLayout(lazyListState = lazyListState, flingBehavior = flingBehavior) {
ResizableSnapDemoItem(
width = PagesSizes[it],
height = 500.dp,
position = it
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun LargePageSizeDemo() {
val lazyListState = rememberLazyListState()
val layoutInfoProvider = rememberNextPageSnappingLayoutInfoProvider(lazyListState)
val flingBehavior = rememberSnapFlingBehavior(layoutInfoProvider)
SnappingDemoMainLayout(lazyListState = lazyListState, flingBehavior = flingBehavior) {
ResizableSnapDemoItem(
width = 350.dp,
height = 500.dp,
position = it
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun DifferentContentPaddingDemo() {
val lazyListState = rememberLazyListState()
val layoutInfoProvider =
remember(lazyListState) { SnapLayoutInfoProvider(lazyListState) }
val flingBehavior = rememberSnapFlingBehavior(layoutInfoProvider)
SnappingDemoMainLayout(
lazyListState = lazyListState,
flingBehavior = flingBehavior,
contentPaddingValues = PaddingValues(start = 20.dp, end = 50.dp)
) {
DefaultSnapDemoItem(position = it)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MultiPageSnappingDemo() {
val lazyListState = rememberLazyListState()
val flingBehavior = rememberSnapFlingBehavior(lazyListState)
SnappingDemoMainLayout(lazyListState = lazyListState, flingBehavior = flingBehavior) {
DefaultSnapDemoItem(position = it)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ViewPortBasedSnappingDemo() {
val lazyListState = rememberLazyListState()
val layoutInfoProvider = rememberViewPortSnappingLayoutInfoProvider(lazyListState)
val flingBehavior = rememberSnapFlingBehavior(layoutInfoProvider)
SnappingDemoMainLayout(lazyListState = lazyListState, flingBehavior = flingBehavior) {
DefaultSnapDemoItem(position = it)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun rememberNextPageSnappingLayoutInfoProvider(
state: LazyListState
): SnapLayoutInfoProvider {
return remember(state) {
val basedSnappingLayoutInfoProvider = SnapLayoutInfoProvider(lazyListState = state)
object : SnapLayoutInfoProvider by basedSnappingLayoutInfoProvider {
override fun Density.calculateApproachOffset(initialVelocity: Float): Float {
return 0f
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun rememberViewPortSnappingLayoutInfoProvider(
state: LazyListState
): SnapLayoutInfoProvider {
val decayAnimationSpec: DecayAnimationSpec<Float> = rememberSplineBasedDecay()
return remember(state) {
ViewPortBasedSnappingLayoutInfoProvider(
SnapLayoutInfoProvider(lazyListState = state),
decayAnimationSpec,
) { state.layoutInfo.viewportSize.width.toFloat() }
}
}
private val PagesSizes = (0..ItemNumber).toList().map { (50..500).random().dp } | apache-2.0 | 58809476bee686577b616b191db58f9a | 36.248408 | 96 | 0.759364 | 5.183511 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/ScrollerTestCase.kt | 3 | 2750 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.benchmark
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.ToggleableTestCase
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.runBlocking
/**
* Test case that puts a large number of boxes in a column in a vertical scroller to force scrolling.
*/
class ScrollerTestCase : LayeredComposeTestCase(), ToggleableTestCase {
private lateinit var scrollState: ScrollState
@Composable
override fun MeasuredContent() {
scrollState = rememberScrollState()
Column(Modifier.verticalScroll(scrollState)) {
Column(Modifier.fillMaxHeight()) {
for (green in 0..0xFF) {
ColorStripe(0xFF, green, 0)
}
for (red in 0xFF downTo 0) {
ColorStripe(red, 0xFF, 0)
}
for (blue in 0..0xFF) {
ColorStripe(0, 0xFF, blue)
}
for (green in 0xFF downTo 0) {
ColorStripe(0, green, 0xFF)
}
for (red in 0..0xFF) {
ColorStripe(red, 0, 0xFF)
}
for (blue in 0xFF downTo 0) {
ColorStripe(0xFF, 0, blue)
}
}
}
}
override fun toggleState() {
runBlocking { scrollState.scrollTo(if (scrollState.value == 0) 10 else 0) }
}
@Composable
fun ColorStripe(red: Int, green: Int, blue: Int) {
Canvas(Modifier.size(45.dp, 5.dp)) {
drawRect(Color(red = red, green = green, blue = blue))
}
}
} | apache-2.0 | 5b6f9baf847a8d58092ae376e36e1cf7 | 34.727273 | 101 | 0.651636 | 4.537954 | false | true | false | false |
google/ide-perf | src/main/java/com/google/idea/perf/cvtracer/CachedValueTable.kt | 1 | 5773 | /*
* Copyright 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.cvtracer
import com.google.idea.perf.util.formatNsInMs
import com.google.idea.perf.util.formatNum
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.JBUI
import java.awt.Font
import javax.swing.ListSelectionModel
import javax.swing.SortOrder
import javax.swing.SwingConstants
import javax.swing.table.AbstractTableModel
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.JTableHeader
import javax.swing.table.TableRowSorter
// Table columns.
private const val NAME = 0
private const val COMPUTE_TIME = 1
private const val HITS = 2
private const val MISSES = 3
private const val HIT_MISS_RATIO = 4
private const val COL_COUNT = 5
class CachedValueTableModel: AbstractTableModel() {
private var data: List<CachedValueStats>? = null
fun setData(newData: List<CachedValueStats>?) {
data = newData
fireTableDataChanged()
}
override fun getColumnCount(): Int = COL_COUNT
override fun getColumnName(column: Int): String = when (column) {
NAME -> "name"
COMPUTE_TIME -> "compute time"
HITS -> "hits"
MISSES -> "misses"
HIT_MISS_RATIO -> "hit ratio"
else -> error(column)
}
override fun getColumnClass(columnIndex: Int): Class<*> = when (columnIndex) {
NAME -> String::class.java
COMPUTE_TIME, HITS, MISSES -> Long::class.javaObjectType
HIT_MISS_RATIO -> Double::class.javaObjectType
else -> error(columnIndex)
}
override fun getRowCount(): Int = data?.size ?: 0
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
val stats = data!![rowIndex]
return when (columnIndex) {
NAME -> stats.description
COMPUTE_TIME -> stats.computeTimeNs
HITS -> stats.hits
MISSES -> stats.misses
HIT_MISS_RATIO -> stats.hitRatio
else -> error(columnIndex)
}
}
override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean = false
}
class CachedValueTable(private val model: CachedValueTableModel): JBTable(model) {
init {
font = JBUI.Fonts.create(Font.MONOSPACED, font.size)
setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
setShowGrid(false)
// Column rendering.
val tableColumns = columnModel.columns.toList()
for (tableColumn in tableColumns) {
val col = tableColumn.modelIndex
// Column widths.
tableColumn.minWidth = 100
tableColumn.preferredWidth = when (col) {
NAME -> Int.MAX_VALUE
COMPUTE_TIME, HITS, MISSES, HIT_MISS_RATIO -> 100
else -> tableColumn.preferredWidth
}
// Locale-aware and unit-aware rendering for numbers.
when (col) {
COMPUTE_TIME, HITS, MISSES, HIT_MISS_RATIO -> {
tableColumn.cellRenderer = object: DefaultTableCellRenderer() {
init {
horizontalAlignment = SwingConstants.RIGHT
}
override fun setValue(value: Any?) {
if (value == null) return super.setValue(value)
val formatted = when (col) {
COMPUTE_TIME -> formatNsInMs(value as Long)
HITS, MISSES -> formatNum(value as Long)
HIT_MISS_RATIO -> formatNum(value as Double)
else -> error("Unhandled column")
}
super.setValue(formatted)
}
}
}
}
}
// Limit sorting directions.
rowSorter = object: TableRowSorter<CachedValueTableModel>(model) {
override fun toggleSortOrder(col: Int) {
val alreadySorted = sortKeys.any {
it.column == col && it.sortOrder != SortOrder.UNSORTED
}
if (alreadySorted) return
val order = when (col) {
NAME, HIT_MISS_RATIO -> SortOrder.ASCENDING
else -> SortOrder.DESCENDING
}
sortKeys = listOf(SortKey(col, order))
}
}
rowSorter.toggleSortOrder(COMPUTE_TIME)
}
override fun createDefaultTableHeader(): JTableHeader {
return object: JBTableHeader() {
init {
// Override the renderer that JBTableHeader sets.
// The default, center-aligned renderer looks better.
defaultRenderer = createDefaultRenderer()
}
}
}
fun setStats(newStats: List<CachedValueStats>?) {
// Changing the table clears the current row selection, so we have to restore it manually.
val selection = selectionModel.leadSelectionIndex
model.setData(newStats)
if (selection != -1 && selection < model.rowCount) {
selectionModel.setSelectionInterval(selection, selection)
}
}
}
| apache-2.0 | 835db38166f65a36b288cd92c770be28 | 35.08125 | 98 | 0.596917 | 4.728092 | false | false | false | false |
raxden/square | square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/floatingactionbutton/HasFloatingActionButtonFragmentInterceptor.kt | 2 | 2945 | package com.raxdenstudios.square.interceptor.commons.floatingactionbutton
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.view.View
import com.raxdenstudios.square.interceptor.HasInterceptor
/**
* Created by Ángel Gómez on 29/12/2016.
*
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_view"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Toolbar" />
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="@+id/container_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar_view" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/floating_action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
app:backgroundTint="@color/colorPrimary"
app:rippleColor="@android:color/white"
app:fabSize="normal"
app:srcCompat="@drawable/ic_add_white_24dp"
app:layout_constraintBottom_toBottomOf="@+id/container_view"
app:layout_constraintEnd_toEndOf="parent"
app:useCompatPadding="true" />
</android.support.constraint.ConstraintLayout>
*/
interface HasFloatingActionButtonFragmentInterceptor<TFragment : Fragment> : HasInterceptor {
fun onLoadFloatingActionButton(): FloatingActionButton
fun onCreateToolbarView(): Toolbar
fun onToolbarViewCreated(toolbar: Toolbar)
fun onLoadFragmentContainer(): View
fun onCreateFragment(type: FragmentType): TFragment
fun onFragmentLoaded(type: FragmentType, fragment: TFragment)
}
| apache-2.0 | 619dc637a5007a52400f9c842110d962 | 38.24 | 93 | 0.674822 | 4.315249 | false | false | false | false |
JavaEden/Orchid | plugins/OrchidPluginDocs/src/main/kotlin/com/eden/orchid/plugindocs/controllers/AdminController.kt | 2 | 2415 | package com.eden.orchid.plugindocs.controllers
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.Descriptive
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.server.OrchidController
import com.eden.orchid.api.server.OrchidRequest
import com.eden.orchid.api.server.OrchidResponse
import com.eden.orchid.api.server.OrchidView
import com.eden.orchid.api.server.annotations.AdminPage
import com.eden.orchid.api.server.annotations.Get
import com.eden.orchid.utilities.SuppressedWarnings
import java.net.URLEncoder
import javax.inject.Inject
@JvmSuppressWildcards
class AdminController
@Inject
constructor(
val context: OrchidContext
) : OrchidController(1000) {
@Get(path = "/admin")
fun index(@Suppress(SuppressedWarnings.UNUSED_PARAMETER) request: OrchidRequest): OrchidResponse {
val view = OrchidView(context, this, "admin")
return OrchidResponse(context).view(view)
}
class DescribeParams : OptionsHolder {
@Option lateinit var className: String
}
@Get(path = "/admin/describe", params = DescribeParams::class)
fun describeClass(@Suppress(SuppressedWarnings.UNUSED_PARAMETER) request: OrchidRequest, params: DescribeParams): OrchidResponse {
if (params.className.isNotBlank()) {
val data = HashMap<String, Any>()
data.putAll(request.all().toMap())
try {
val classType = Class.forName(params.className)
val view = OrchidView(context, this, "${params.className} Description", data, "describe")
view.title = Descriptive.getDescriptiveName(classType)
view.breadcrumbs = arrayOf("describe", classType.`package`.name)
view.params = params
return OrchidResponse(context).view(view)
}
catch (e: Exception) {
}
}
return OrchidResponse(context).status(404).content("Class ${params.className} not found")
}
private fun getDescriptionLink(o: Any): String {
val className = o as? Class<*> ?: o.javaClass
try {
return context.baseUrl + "/admin/describe?className=" + URLEncoder.encode(className.name, "UTF-8")
}
catch (e: Exception) {
e.printStackTrace()
return ""
}
}
}
| lgpl-3.0 | 60c01288a5ce65a9e12fde2d656019e1 | 34.514706 | 134 | 0.676605 | 4.343525 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/notifications/HabiticaLocalNotification.kt | 1 | 3037 | package com.habitrpg.android.habitica.helpers.notifications
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import androidx.annotation.CallSuper
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.withImmutableFlag
import com.habitrpg.android.habitica.ui.activities.MainActivity
import java.util.Date
/**
* Created by keithholliday on 6/28/16.
*/
abstract class HabiticaLocalNotification(
protected var context: Context,
protected var identifier: String?
) {
protected var data: Map<String, String>? = null
protected var title: String? = null
protected var message: String? = null
protected var notificationBuilder = NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_gryphon_white)
.setAutoCancel(true)
open fun configureNotificationBuilder(data: MutableMap<String, String>): NotificationCompat.Builder {
val path = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
return notificationBuilder
.setSound(path)
}
@CallSuper
open fun notifyLocally(title: String?, message: String?, data: MutableMap<String, String>) {
this.title = title
this.message = message
var notificationBuilder = configureNotificationBuilder(data)
if (this.title != null) {
notificationBuilder = notificationBuilder.setContentTitle(title)
}
if (this.message != null) {
notificationBuilder = notificationBuilder.setContentText(message)
}
val notificationId = getNotificationID(data)
this.setNotificationActions(notificationId, data)
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(notificationId, notificationBuilder.build())
}
fun setExtras(data: Map<String, String>) {
this.data = data
}
protected open fun setNotificationActions(notificationId: Int, data: Map<String, String>) {
val intent = Intent(context, MainActivity::class.java)
configureMainIntent(intent)
intent.putExtra("NOTIFICATION_ID", notificationId)
val pendingIntent = PendingIntent.getActivity(
context,
3000,
intent,
withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT)
)
notificationBuilder.setContentIntent(pendingIntent)
}
protected open fun configureMainIntent(intent: Intent) {
intent.putExtra("notificationIdentifier", identifier)
intent.putExtra("notificationTimeStamp", Date().time)
if (data?.containsKey("openURL") == true) {
intent.putExtra("openURL", data?.get("openURL"))
}
}
protected open fun getNotificationID(data: MutableMap<String, String>): Int {
return Date().time.toInt()
}
}
| gpl-3.0 | aea22ad7b7ef68f4b59193e5c34747ea | 34.313953 | 105 | 0.708265 | 4.954323 | false | false | false | false |
sz-piotr/pik-projekt | backend/src/main/kotlin/app/result/Result.kt | 1 | 735 | package app.result
import app.test.Test
import app.user.User
import com.fasterxml.jackson.annotation.JsonIgnore
import javax.persistence.*
/**
* Created by michal on 23/05/2017.
*/
@Entity
@Table(name="\"Result\"")
data class Result ( @ManyToOne @JoinColumn(name = "test_id")
var test: Test? = null,
@ManyToOne @JoinColumn(name = "user_id") @JsonIgnore
var user: User? = null,
@OneToMany(mappedBy = "result", cascade = arrayOf(CascadeType.ALL))
var questions: List<QuestionResult>? = null,
var result : Int? = null,
@Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long? = null) | mit | 0d35647c9274d33aae3c2439e873aacb | 34.047619 | 93 | 0.587755 | 4.176136 | false | true | false | false |
Cypher121/discordplayer | src/main/kotlin/coffee/cypher/discordplayer/commands/general.kt | 1 | 2531 | package coffee.cypher.discordplayer.commands
import coffee.cypher.discordplayer.*
import coffee.cypher.discordplayer.model.MusicFile
import sx.blah.discord.handle.obj.IMessage
import java.io.File
fun printAvailable(context: CommandContext) {
val list = context.client.musicList.sortedBy(MusicFile::index).joinToString("\n").run {
if (isEmpty())
"No music available"
else
this
}
if (list.length < context.client.config.get("message.maxsize", 500)) {
context.message.respond(list)
} else {
val url = createGist("list.txt", list)
if (url == null) {
context.message.respond("List too long and failed to create gist")
} else {
context.message.respond("List too long, created gist: $url")
}
}
}
fun deleteTrack(context: CommandContext, index: Int) {
context.client.musicList.findIndex(index)?.let {
context.client.removeFile(it)
context.client.playlists.forEach { p -> p.tracks -= it.index }
File(context.client.musicFolder, it.path).delete()
}
context.client.db.commit()
}
fun findTracks(context: CommandContext, query: String) {
val key = query.toLowerCase()
if (key.isBlank()) {
context.message.respond("No search query provided")
}
val found = context.client.musicList.filter { key in it.toString().toLowerCase() }
if (found.isEmpty()) {
context.message.respond("No matching tracks found")
} else {
val list = found.joinToString("\n")
if (list.length < context.client.config.get("message.maxsize", 500)) {
context.message.respond(
"${found.size} match${if (found.size > 1) "es" else ""} found:```${list.prependIndent(" ")}```"
)
} else {
val url = createGist("found.txt", list)
if (url != null) {
context.message.respond("${found.size} match${if (found.size > 1) "es" else ""} found, list too long: $url")
} else {
context.message.respond("List too long and failed to create gist")
}
}
}
}
data class CommandContext(val client: DiscordPlayer, val message: IMessage) {
val guild = message.guild!!
val player = message.player
val caller = message.author!!
val voiceChannel = caller.connectedVoiceChannels.firstOrNull {
it.guild == message.guild
}
fun respond(text: String, mention: Boolean = false) = message.respond(text, mention)
} | mit | 10cb388115875ad897ea355fd2a65bc4 | 31.883117 | 124 | 0.618333 | 4.011094 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/lesson/ui/dialog/SectionUnavailableDialogFragment.kt | 2 | 8412 | package org.stepik.android.view.lesson.ui.dialog
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.stepic.droid.R
import org.stepic.droid.util.DateTimeHelper
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.model.Section
import org.stepik.android.view.course_content.model.RequiredSection
import org.stepik.android.view.step.model.SectionUnavailableAction
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.resolveAttribute
import java.util.TimeZone
import kotlin.math.roundToInt
class SectionUnavailableDialogFragment : DialogFragment() {
companion object {
const val TAG = "SectionUnavailableDialogFragment"
fun newInstance(sectionUnavailableAction: SectionUnavailableAction): DialogFragment =
SectionUnavailableDialogFragment()
.apply {
this.sectionUnavailableAction = sectionUnavailableAction
}
}
private var sectionUnavailableAction: SectionUnavailableAction by argument()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
when (val action = sectionUnavailableAction) {
is SectionUnavailableAction.RequiresSection ->
createRequiresSectionDialog(action, MaterialAlertDialogBuilder(requireContext()))
is SectionUnavailableAction.RequiresExam ->
createRequiresExamDialog(action, MaterialAlertDialogBuilder(requireContext()))
is SectionUnavailableAction.RequiresDate ->
createRequiresDateDialog(action, MaterialAlertDialogBuilder(requireContext()))
}
/**
* SectionUnavailableAction.RequiresSection
*/
private fun createRequiresSectionDialog(requiresSectionAction: SectionUnavailableAction.RequiresSection, materialAlertDialogBuilder: MaterialAlertDialogBuilder): Dialog {
val title = getString(R.string.unavailable_section_title, requiresSectionAction.currentSection.title)
val requiredPoints = (requiresSectionAction.requiredSection.progress.cost * requiresSectionAction.targetSection.requiredPercent / 100f).roundToInt()
val message = getString(
R.string.unavailable_section_required_section_message,
requiresSectionAction.targetSection.title,
resources.getQuantityString(R.plurals.points, requiredPoints.toInt(), requiredPoints),
requiresSectionAction.requiredSection.section.title
)
return with(materialAlertDialogBuilder) {
setTitle(title)
setMessage(message)
setNegativeButton(R.string.unavailable_section_to_content_action) { _, _ ->
(parentFragment as? Callback)?.onSyllabusAction(CourseViewSource.SectionUnavailableDialog)
}
setPositiveButton(R.string.unavailable_section_to_tasks_action) { _, _ ->
dismiss()
}
create()
}.apply {
setOnShowListener {
val negativeColor = context
.resolveAttribute(R.attr.colorPrimary)
?.data
?: return@setOnShowListener
val positiveColor = ContextCompat
.getColor(context, R.color.color_overlay_green)
getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(negativeColor)
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(positiveColor)
}
}
}
/**
* SectionUnavailableAction.RequiresExam
*/
private fun createRequiresExamDialog(requiresExamAction: SectionUnavailableAction.RequiresExam, materialAlertDialogBuilder: MaterialAlertDialogBuilder): Dialog {
val (currentSection, targetSection, requiredSection) = requiresExamAction
return if (requiredSection == null) {
createRequiresExamWithoutRequirementsDialog(currentSection, targetSection, materialAlertDialogBuilder)
} else {
createRequiresExamWithRequirementsDialog(currentSection, targetSection, requiredSection, materialAlertDialogBuilder)
}
}
private fun createRequiresExamWithoutRequirementsDialog(currentSection: Section, targetSection: Section, materialAlertDialogBuilder: MaterialAlertDialogBuilder): Dialog {
val title = getString(R.string.unavailable_section_title, currentSection.title)
val message = getString(R.string.unavailable_section_required_exam_message, targetSection.title)
return with(materialAlertDialogBuilder) {
setTitle(title)
setMessage(message)
setPositiveButton(R.string.unavailable_section_to_content_action) { _, _ ->
(parentFragment as? Callback)?.onSyllabusAction(CourseViewSource.SectionUnavailableDialog)
}
create()
}.apply {
setOnShowListener {
val positiveColor = ContextCompat
.getColor(context, R.color.color_overlay_green)
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(positiveColor)
}
}
}
private fun createRequiresExamWithRequirementsDialog(
currentSection: Section,
targetSection: Section,
requiredSection: RequiredSection,
materialAlertDialogBuilder: MaterialAlertDialogBuilder
): Dialog {
val title = getString(R.string.unavailable_section_title, currentSection.title)
val requiredPoints = (requiredSection.progress.cost * targetSection.requiredPercent / 100f).roundToInt()
val message = getString(
R.string.unavailable_section_required_exam_message_with_requirements,
targetSection.title,
resources.getQuantityString(R.plurals.points, requiredPoints.toInt(), requiredPoints),
requiredSection.section.title
)
return with(materialAlertDialogBuilder) {
setTitle(title)
setMessage(message)
setNegativeButton(R.string.unavailable_section_to_content_action) { _, _ ->
(parentFragment as? Callback)?.onSyllabusAction(CourseViewSource.SectionUnavailableDialog)
}
setPositiveButton(R.string.unavailable_section_to_tasks_action) { _, _ -> }
create()
}.apply {
setOnShowListener {
val negativeColor = context
.resolveAttribute(R.attr.colorPrimary)
?.data
?: return@setOnShowListener
val positiveColor = ContextCompat
.getColor(context, R.color.color_overlay_green)
getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(negativeColor)
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(positiveColor)
}
}
}
/**
* SectionUnavailableAction.RequiresDate
*/
private fun createRequiresDateDialog(requiresDateAction: SectionUnavailableAction.RequiresDate, materialAlertDialogBuilder: MaterialAlertDialogBuilder): Dialog {
val title = getString(R.string.unavailable_section_title, requiresDateAction.currentSection.title)
val message = getString(
R.string.unavailable_section_required_date_message,
requiresDateAction.nextLesson.title,
DateTimeHelper.getPrintableDate(requiresDateAction.date, DateTimeHelper.DISPLAY_DATETIME_PATTERN, TimeZone.getDefault())
)
return with(materialAlertDialogBuilder) {
setTitle(title)
setMessage(message)
setPositiveButton(R.string.unavailable_section_to_content_action) { _, _ ->
(parentFragment as? Callback)?.onSyllabusAction(CourseViewSource.SectionUnavailableDialog)
}
create()
}.apply {
setOnShowListener {
val positiveColor = ContextCompat
.getColor(context, R.color.color_overlay_green)
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(positiveColor)
}
}
}
interface Callback {
fun onSyllabusAction(courseViewSource: CourseViewSource)
}
} | apache-2.0 | b56493e5f3ca7f61b06a4d9676147a62 | 44.231183 | 174 | 0.683785 | 5.434109 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/transactions/TransactionRecyclerAdapter.kt | 1 | 1833 | package org.walleth.transactions
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import org.walleth.R
import org.walleth.data.AppDatabase
import org.walleth.data.config.Settings
import org.walleth.data.exchangerate.ExchangeRateProvider
import org.walleth.chains.ChainInfoProvider
import org.walleth.data.transactions.TransactionEntity
enum class TransactionAdapterDirection {
INCOMING, OUTGOING
}
class TransactionDiffCallback : DiffUtil.ItemCallback<TransactionEntity>() {
override fun areItemsTheSame(oldItem: TransactionEntity, newItem: TransactionEntity): Boolean {
return oldItem.hash == newItem.hash
}
override fun areContentsTheSame(oldItem: TransactionEntity, newItem: TransactionEntity): Boolean {
return oldItem == newItem
}
}
class TransactionRecyclerAdapter(val appDatabase: AppDatabase,
private val direction: TransactionAdapterDirection,
val chainInfoProvider: ChainInfoProvider,
private val exchangeRateProvider: ExchangeRateProvider,
val settings: Settings
) : PagingDataAdapter<TransactionEntity, TransactionViewHolder>(TransactionDiffCallback()) {
override fun onBindViewHolder(holder: TransactionViewHolder, position: Int) = holder.bind(getItem(position), appDatabase)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TransactionViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.transaction_item, parent, false)
return TransactionViewHolder(itemView, direction, chainInfoProvider, exchangeRateProvider, settings)
}
} | gpl-3.0 | 48f6938af960795b42623b8a8cfff4f7 | 39.755556 | 125 | 0.755592 | 5.40708 | false | false | false | false |
UCSoftworks/LeafDb | leafdb-jdbc/src/main/java/com/ucsoftworks/leafdb/jdbc/ReadableLeafDbJdbc.kt | 1 | 1256 | package com.ucsoftworks.leafdb.jdbc
import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor
import com.ucsoftworks.leafdb.wrapper.ILeafDbReadableDatabase
import java.sql.Statement
/**
* Created by Pasenchuk Victor on 25/08/2017
*/
internal class ReadableLeafDbJdbc(private val readableDatabase: Statement) : ILeafDbReadableDatabase {
val FIRST_COLUMN_ID = 1
override fun close() {
readableDatabase.close()
}
override fun selectQuery(query: String): ILeafDbCursor = LeafDbJdbcCursor(readableDatabase.executeQuery(query))
override fun stringQuery(query: String): String? {
val cursor = LeafDbJdbcCursor(readableDatabase.executeQuery(query))
if (cursor.empty)
return null
return cursor.getString(FIRST_COLUMN_ID)
}
override fun longQuery(query: String): Long? {
val cursor = LeafDbJdbcCursor(readableDatabase.executeQuery(query))
if (cursor.empty)
return null
return cursor.getLong(FIRST_COLUMN_ID)
}
override fun doubleQuery(query: String): Double? {
val cursor = LeafDbJdbcCursor(readableDatabase.executeQuery(query))
if (cursor.empty)
return null
return cursor.getDouble(FIRST_COLUMN_ID)
}
}
| lgpl-3.0 | 99d7707a714765ce5916d563e617a76e | 28.904762 | 115 | 0.703025 | 4.376307 | false | false | false | false |
da1z/intellij-community | plugins/stream-debugger/test/com/intellij/debugger/streams/exec/streamex/ConcatenateOperationsTest.kt | 4 | 761 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.exec.streamex
/**
* @author Vitaliy.Bibaev
*/
class ConcatenateOperationsTest : StreamExTestCase() {
override val packageName: String = "concatenate"
fun testAppendToEmpty() = doStreamExWithResultTest()
fun testAppendNone() = doStreamExWithResultTest()
fun testAppendOne() = doStreamExWithResultTest()
fun testAppendMany() = doStreamExWithResultTest()
fun testPrependToEmpty() = doStreamExWithResultTest()
fun testPrependNone() = doStreamExWithResultTest()
fun testPrependOne() = doStreamExWithResultTest()
fun testPrependMany() = doStreamExWithResultTest()
} | apache-2.0 | 5b91c7370ed85c36eef62d503c932698 | 39.105263 | 140 | 0.779238 | 4.275281 | false | true | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/interfaces/TraceableDBEntry.kt | 1 | 788 | package info.nightscout.androidaps.database.interfaces
import info.nightscout.androidaps.database.embedments.InterfaceIDs
interface TraceableDBEntry: DBEntry {
var version: Int
var dateCreated: Long
var isValid: Boolean
var referenceId: Long?
@Suppress("PropertyName") var interfaceIDs_backing: InterfaceIDs?
val historic: Boolean get() = referenceId != null
val foreignKeysValid: Boolean get() = referenceId != 0L
var interfaceIDs: InterfaceIDs
get() {
var value = this.interfaceIDs_backing
if (value == null) {
value = InterfaceIDs()
interfaceIDs_backing = value
}
return value
}
set(value) {
interfaceIDs_backing = value
}
} | agpl-3.0 | d272800804589a1fea071aebfe370aac | 27.178571 | 69 | 0.628173 | 5.083871 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt | 1 | 9753 | package info.nightscout.androidaps.plugins.aps.openAPSAMA
import android.content.Context
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.interfaces.*
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.interfaces.ResourceHelper
import org.json.JSONException
import javax.inject.Inject
import javax.inject.Singleton
@OpenForTesting
@Singleton
class OpenAPSAMAPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker,
rh: ResourceHelper,
private val profileFunction: ProfileFunction,
private val context: Context,
private val activePlugin: ActivePlugin,
private val iobCobCalculator: IobCobCalculator,
private val hardLimits: HardLimits,
private val profiler: Profiler,
private val fabricPrivacy: FabricPrivacy,
private val dateUtil: DateUtil,
private val repository: AppRepository,
private val glucoseStatusProvider: GlucoseStatusProvider
) : PluginBase(PluginDescription()
.mainType(PluginType.APS)
.fragmentClass(OpenAPSAMAFragment::class.java.name)
.pluginIcon(R.drawable.ic_generic_icon)
.pluginName(R.string.openapsama)
.shortName(R.string.oaps_shortname)
.preferencesId(R.xml.pref_openapsama)
.description(R.string.description_ama),
aapsLogger, rh, injector
), APS {
// last values
override var lastAPSRun: Long = 0
override var lastAPSResult: DetermineBasalResultAMA? = null
override var lastDetermineBasalAdapter: DetermineBasalAdapterInterface? = null
override var lastAutosensResult: AutosensResult = AutosensResult()
override fun specialEnableCondition(): Boolean {
return try {
val pump = activePlugin.activePump
pump.pumpDescription.isTempBasalCapable
} catch (ignored: Exception) {
// may fail during initialization
true
}
}
override fun specialShowInListCondition(): Boolean {
val pump = activePlugin.activePump
return pump.pumpDescription.isTempBasalCapable
}
override fun invoke(initiator: String, tempBasalFallback: Boolean) {
aapsLogger.debug(LTag.APS, "invoke from $initiator tempBasalFallback: $tempBasalFallback")
lastAPSResult = null
val determineBasalAdapterAMAJS = DetermineBasalAdapterAMAJS(ScriptReader(context), injector)
val glucoseStatus = glucoseStatusProvider.glucoseStatusData
val profile = profileFunction.getProfile()
val pump = activePlugin.activePump
if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset))
return
}
if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return
}
if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return
}
val inputConstraints = Constraint(0.0) // fake. only for collecting all results
val maxBasal = constraintChecker.getMaxBasalAllowed(profile).also {
inputConstraints.copyReasons(it)
}.value()
var start = System.currentTimeMillis()
var startPart = System.currentTimeMillis()
val iobArray = iobCobCalculator.calculateIobArrayInDia(profile)
profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart)
startPart = System.currentTimeMillis()
val mealData = iobCobCalculator.getMealDataWithWaitingForCalculationFinish()
profiler.log(LTag.APS, "getMealData()", startPart)
val maxIob = constraintChecker.getMaxIOBAllowed().also { maxIOBAllowedConstraint ->
inputConstraints.copyReasons(maxIOBAllowedConstraint)
}.value()
var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1])
var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1])
var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1])
var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) {
isTempTarget = true
minBg = hardLimits.verifyHardLimits(tempTarget.value.lowTarget, R.string.temp_target_low_target, HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1].toDouble())
maxBg = hardLimits.verifyHardLimits(tempTarget.value.highTarget, R.string.temp_target_high_target, HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1].toDouble())
targetBg = hardLimits.verifyHardLimits(tempTarget.value.target(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1].toDouble())
}
if (!hardLimits.checkHardLimits(profile.dia, R.string.profile_dia, hardLimits.minDia(), hardLimits.maxDia())) return
if (!hardLimits.checkHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), R.string.profile_carbs_ratio_value, hardLimits.minIC(), hardLimits.maxIC())) return
if (!hardLimits.checkHardLimits(profile.getIsfMgdl(), R.string.profile_sensitivity_value, HardLimits.MIN_ISF, HardLimits.MAX_ISF)) return
if (!hardLimits.checkHardLimits(profile.getMaxDailyBasal(), R.string.profile_max_daily_basal_value, 0.02, hardLimits.maxBasal())) return
if (!hardLimits.checkHardLimits(pump.baseBasalRate, R.string.current_basal_value, 0.01, hardLimits.maxBasal())) return
startPart = System.currentTimeMillis()
if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return
}
lastAutosensResult = autosensData.autosensResult
} else {
lastAutosensResult.sensResult = "autosens disabled"
}
profiler.log(LTag.APS, "detectSensitivityAndCarbAbsorption()", startPart)
profiler.log(LTag.APS, "AMA data gathering", start)
start = System.currentTimeMillis()
try {
determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, activePlugin.activePump.baseBasalRate, iobArray, glucoseStatus, mealData,
lastAutosensResult.ratio,
isTempTarget
)
} catch (e: JSONException) {
fabricPrivacy.logException(e)
return
}
val determineBasalResultAMA = determineBasalAdapterAMAJS.invoke()
profiler.log(LTag.APS, "AMA calculation", start)
// Fix bug determine basal
if (determineBasalResultAMA == null) {
aapsLogger.error(LTag.APS, "SMB calculation returned null")
lastDetermineBasalAdapter = null
lastAPSResult = null
lastAPSRun = 0
} else {
if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) == null) determineBasalResultAMA.tempBasalRequested = false
determineBasalResultAMA.iob = iobArray[0]
val now = System.currentTimeMillis()
determineBasalResultAMA.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultAMA.inputConstraints = inputConstraints
lastDetermineBasalAdapter = determineBasalAdapterAMAJS
lastAPSResult = determineBasalResultAMA as DetermineBasalResultAMA
lastAPSRun = now
}
rxBus.send(EventOpenAPSUpdateGui())
//deviceStatus.suggested = determineBasalResultAMA.json;
}
} | agpl-3.0 | 9c213bb93272425fdd3b702c09bbb5a2 | 53.797753 | 227 | 0.729212 | 4.451392 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/entry/EntryDetailActivity.kt | 1 | 5771 | package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.view.Menu
import android.view.MenuItem
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.api.entries.TypedInputStream
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.ui.adapters.decorators.EntryCommentItemDecoration
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.EntryDetailAdapter
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.ExitConfirmationDialog
import io.github.feelfreelinux.wykopmobilny.ui.widgets.InputToolbarListener
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity
import io.github.feelfreelinux.wykopmobilny.utils.api.getWpisId
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import kotlinx.android.synthetic.main.activity_entry.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.openEntryActivity(entryId : Int) {
val intent = Intent(this, EntryActivity::class.java)
intent.putExtra(EntryActivity.EXTRA_ENTRY_ID, entryId)
startActivity(intent)
}
class EntryActivity : BaseActivity(), EntryDetailView, InputToolbarListener, SwipeRefreshLayout.OnRefreshListener {
var entryId = 0
companion object {
val EXTRA_ENTRY_ID = "ENTRY_ID"
val EXTRA_FRAGMENT_KEY = "ENTRY_ACTIVITY_#"
}
@Inject lateinit var presenter : EntryDetailPresenter
private lateinit var entryFragmentData : DataFragment<Entry>
private val adapter by lazy { EntryDetailAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_entry)
setSupportActionBar(toolbar)
entryId = intent.data?.getWpisId() ?: intent.getIntExtra(EXTRA_ENTRY_ID, -1)
supportActionBar?.apply {
title = null
setDisplayHomeAsUpEnabled(true)
}
WykopApp.uiInjector.inject(this)
presenter.entryId = entryId
presenter.subscribe(this)
// Prepare RecyclerView
recyclerView.apply {
prepare()
// Set adapter
this.adapter = this@EntryActivity.adapter
}
// Prepare InputToolbar
inputToolbar.inputToolbarListener = this
swiperefresh.setOnRefreshListener(this)
entryFragmentData = supportFragmentManager.getDataFragmentInstance(EXTRA_FRAGMENT_KEY + entryId)
if (entryFragmentData.data != null)
adapter.entry = entryFragmentData.data
else {
// Trigger data loading
loadingView.isVisible = true
presenter.loadData()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater?.inflate(R.menu.entry_fragment_menu, menu)
return true
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
entryFragmentData.data = adapter.entry
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(entryFragmentData)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> onBackPressed()
}
return true
}
override fun onRefresh() {
presenter.loadData()
}
override fun showEntry(entry: Entry) {
adapter.entry = entry
inputToolbar.setDefaultAddressant(entry.author.nick)
inputToolbar.isVisible = true
loadingView.isVisible = false
swiperefresh.isRefreshing = false
adapter.notifyDataSetChanged()
}
override fun hideInputToolbar() {
inputToolbar.isVisible = false
}
override fun hideInputbarProgress() {
inputToolbar.showProgress(false)
}
override fun resetInputbarState() {
inputToolbar.resetState()
}
override fun openGalleryImageChooser() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent,
getString(R.string.insert_photo_galery)), BaseInputActivity.USER_ACTION_INSERT_PHOTO)
}
override fun onBackPressed() {
if (inputToolbar.hasUserEditedContent()) {
ExitConfirmationDialog(this, {
finish()
})?.show()
} else finish()
}
override fun sendPhoto(photo: String?, body: String) {
presenter.addComment(body, photo)
}
override fun sendPhoto(photo: TypedInputStream, body: String) {
presenter.addComment(body, photo)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
BaseInputActivity.USER_ACTION_INSERT_PHOTO -> {
inputToolbar.setPhoto(data?.data)
}
}
}
}
} | mit | 316ac5bd78ae2744ac7fe1dccf20dda5 | 32.952941 | 115 | 0.700225 | 4.957904 | false | false | false | false |
elsiff/MoreFish | src/main/kotlin/me/elsiff/morefish/util/InventoryExtension.kt | 1 | 483 | package me.elsiff.morefish.util
import org.bukkit.Material
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemStack
/**
* Created by elsiff on 2019-01-07.
*/
fun Inventory.isEmptyAt(slot: Int): Boolean {
val item = getItem(slot)
return item == null || item.type == Material.AIR
}
fun Inventory.itemAt(slot: Int): ItemStack {
return getItem(slot) ?: ItemStack(Material.AIR)
}
fun Inventory.slots(): List<Int> {
return (0 until size).toList()
} | mit | 530b50e7ec8345b1e4400332fcf1e4ec | 22.047619 | 52 | 0.712215 | 3.47482 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/expression/Expression.kt | 1 | 20849 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data.expression
import arcs.core.util.BigInt
import arcs.core.util.toBigInt
/**
* A DSL for expressions used by queries, refinements, and adapters. Instances can be constructed
* directly, from protos or deserialization, and eventually, from a Kotlin implementation of
* the Arcs Manifest Parser. A number of operator overloads exist to make hand construction
* terse and ergonomic, see Builders.kt.
*
* @param T the resulting type of the expression.
*/
sealed class Expression<out T> {
/**
* Implementors denote sub-properties that may be looked up. This is not necessarily limited
* to entities, but could also be used for coercions, e.g. 'numberField.integerPart'.
*/
interface Scope {
/** Used to construct new immutable scopes as children of the current [Scope]. */
interface Builder {
/** Set's the parameter to the given entry. */
fun set(param: String, value: Any?): Builder
/** builds a new [Scope] as a child of this [Scope] with entries collected via [set] */
fun build(): Scope
}
/** The name of the scope, used for debugging and stringification */
val scopeName: String
/** Lookup an entry in a given scope. */
fun <T> lookup(param: String): T
/** Return a builder used to create a new immutable scope. */
fun builder(subName: String? = null): Builder
/** Return a new scope with the given entry. */
fun set(param: String, value: Any?) = builder().set(param, value).build()
/** Return a set of all property names in the scope. */
fun properties(): Set<String>
}
/**
* Visitor pattern for traversing expressions. Implementations of visitor are used for
* evaluation, serialization, and type flow.
* @param Result type returned from processing a visitation of an [Expression]
* @param Context a user defined context for any evaluation or traversal
*/
interface Visitor<Result, Context> {
/** Called when [UnaryExpression] encountered. */
fun <E, T> visit(expr: UnaryExpression<E, T>, ctx: Context): Result
/** Called when [BinaryExpression] encountered. */
fun <L, R, T> visit(expr: BinaryExpression<L, R, T>, ctx: Context): Result
/** Called when [FieldExpression] encountered. */
fun <T> visit(expr: FieldExpression<T>, ctx: Context): Result
/** Called when [QueryParameterExpression] encountered. */
fun <T> visit(expr: QueryParameterExpression<T>, ctx: Context): Result
/** Called when [NumberLiteralExpression] encountered. */
fun visit(expr: NumberLiteralExpression, ctx: Context): Result
/** Called when [TextLiteralExpression] encountered. */
fun visit(expr: TextLiteralExpression, ctx: Context): Result
/** Called when [BooleanLiteralExpression] encountered. */
fun visit(expr: BooleanLiteralExpression, ctx: Context): Result
/** Called when [NullLiteralExpression] encountered. */
fun visit(expr: NullLiteralExpression, ctx: Context): Result
/** Called when [FromExpression] encountered. */
fun visit(expr: FromExpression, ctx: Context): Result
/** Called when [WhereExpression] encountered. */
fun visit(expr: WhereExpression, ctx: Context): Result
/** Called when [SelectExpression] encountered. */
fun <T> visit(expr: SelectExpression<T>, ctx: Context): Result
/** Called when [LetExpression] encountered. */
fun visit(expr: LetExpression, ctx: Context): Result
/** Called when [FunctionExpression] encountered. */
fun <T> visit(expr: FunctionExpression<T>, ctx: Context): Result
/** Called when [NewExpression] encountered. */
fun visit(expr: NewExpression, ctx: Context): Result
/** Called when [OrderByExpression] encountered. */
fun <T> visit(expr: OrderByExpression<T>, ctx: Context): Result
}
/** Accepts a visitor and invokes the appropriate [Visitor.visit] method. */
abstract fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context): Result
override fun toString() = this.stringify()
/**
* Type that represents all supported binary operations of the [BinaryExpression] node.
* @param L the left side type of the binary op
* @param R the right side type of the binary op
* @param T the result of applying the binary op to [L] and [R]
*/
sealed class BinaryOp<L, R, T> {
/** Apply the binary operation to the left and right arguments. */
abstract operator fun invoke(l: L, r: R): T
abstract val token: String
/** Boolean AND of two Boolean values. */
object And : BinaryOp<Boolean, Boolean, Boolean>() {
override operator fun invoke(l: Boolean, r: Boolean): Boolean = l && r
override val token = "and"
}
/** Boolean OR of two Boolean values. */
object Or : BinaryOp<Boolean, Boolean, Boolean>() {
override operator fun invoke(l: Boolean, r: Boolean): Boolean = l || r
override val token = "or"
}
/** Numeric 'less than' comparison of two numeric arguments, returning Boolean. */
object LessThan : BinaryOp<Number, Number, Boolean>() {
override operator fun invoke(l: Number, r: Number): Boolean = l < r
override val token = "<"
}
/** Numeric 'greater than' comparison of two numeric arguments, returning Boolean. */
object GreaterThan : BinaryOp<Number, Number, Boolean>() {
override operator fun invoke(l: Number, r: Number): Boolean = l > r
override val token = ">"
}
/** Numeric 'less than equals' comparison of two numeric arguments, returning Boolean. */
object LessThanOrEquals : BinaryOp<Number, Number, Boolean>() {
override operator fun invoke(l: Number, r: Number): Boolean = l <= r
override val token = "<="
}
/** Numeric 'greater than equals' comparison of two numeric arguments, returning Boolean. */
object GreaterThanOrEquals : BinaryOp<Number, Number, Boolean>() {
override operator fun invoke(l: Number, r: Number): Boolean = l >= r
override val token = ">="
}
/** Numeric addition (Double Precision). */
object Add : BinaryOp<Number, Number, Number>() {
override operator fun invoke(l: Number, r: Number): Number = l + r
override val token = "+"
}
/** Numeric subtraction (Double Precision). */
object Subtract : BinaryOp<Number, Number, Number>() {
override operator fun invoke(l: Number, r: Number): Number = l - r
override val token = "-"
}
/** Numeric multiplication (Double Precision). */
object Multiply : BinaryOp<Number, Number, Number>() {
override operator fun invoke(l: Number, r: Number): Number = l * r
override val token = "*"
}
/** Numeric division (Double Precision). */
object Divide : BinaryOp<Number, Number, Number>() {
override operator fun invoke(l: Number, r: Number): Number = l / r
override val token = "/"
}
/** Equality of two arguments (default equality operator) */
object Equals : BinaryOp<Any?, Any?, Boolean>() {
override operator fun invoke(l: Any?, r: Any?): Boolean = l == r
override val token = "=="
}
/** Non-Equality of two arguments (default equality operator) */
object NotEquals : BinaryOp<Any?, Any?, Boolean>() {
override operator fun invoke(l: Any?, r: Any?): Boolean = l != r
override val token = "!="
}
object IfNull : BinaryOp<Any?, Any?, Any?>() {
override operator fun invoke(l: Any?, r: Any?): Any? = l ?: r
override val token = "?:"
}
companion object {
val allOps: List<BinaryOp<*, *, *>> by lazy {
listOf(
And,
Or,
Add,
Subtract,
Multiply,
Divide,
Equals,
NotEquals,
LessThan,
LessThanOrEquals,
GreaterThan,
GreaterThanOrEquals,
IfNull
)
}
/** Given a [BinaryOp]'s string token, return the associated [BinaryOp] */
fun fromToken(token: String): BinaryOp<*, *, *>? {
return allOps.find {
it.token == token
}
}
}
}
/**
* Type that represents all operations supported by [UnaryExpression].
* @param E the type of the expression before invoking the op
* @param T the resulting type of the expression after invoking the op
*/
sealed class UnaryOp<E, T> {
/** Apply the unary operation to the expression. */
abstract operator fun invoke(expression: E): T
abstract val token: String
/** Boolean negation. */
object Not : UnaryOp<Boolean, Boolean>() {
override operator fun invoke(expression: Boolean): Boolean = !expression
override val token = "not"
}
/** Numeric negation. */
object Negate : UnaryOp<Number, Number>() {
override operator fun invoke(expression: Number): Number = -expression
override val token = "-"
}
companion object {
/** Given a [UnaryOp]'s token, return the associated [UnaryOp] */
fun fromToken(token: String): UnaryOp<*, *>? = when (token) {
Not.token -> Not
Negate.token -> Negate
else -> null
}
}
}
/**
* Represents a binary operation between two expressions.
* @param L the type of the left side expression
* @param R the type of the right side expression
* @param T the resulting type of the expression
*/
data class BinaryExpression<L, R, T>(
val op: BinaryOp<L, R, T>,
val left: Expression<L>,
val right: Expression<R>
) : Expression<T>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Represents a unary operation on an expression.
* @param E the type of the expression to apply the [UnaryOp] to
* @param T the result type of the expression after applying the [UnaryOp]
*/
data class UnaryExpression<E, T>(
val op: UnaryOp<E, T>,
val expr: Expression<E>
) : Expression<T>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Represents a lookup of a field on a [Scope] by [field] name.
* [nullSafe] specifies if nulls should be propagated - signifying the '?.' operator.
* @param T the type of the expression yielded by looking up the field
*/
data class FieldExpression<T>(
val qualifier: Expression<Scope?>?,
val field: String,
val nullSafe: Boolean
) : Expression<T>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Represents a query parameter (supplied during execution) identified by [paramIdentifier].
* @param T the type of the resulting query parameter
*/
data class QueryParameterExpression<T>(val paramIdentifier: String) : Expression<T>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Base class for all simple immutable values in an expression.
* @param T the type of the literal value
*/
abstract class LiteralExpression<T>(val value: T) : Expression<T>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LiteralExpression<*>) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value?.hashCode() ?: 0
}
}
/** A reference to a literal [Number] value, e.g. 42.0 */
class NumberLiteralExpression(number: Number) : LiteralExpression<Number>(number) {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
}
/** A reference to a literal text value, e.g. "Hello" */
class TextLiteralExpression(text: String) : LiteralExpression<String>(text) {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
}
/** A reference to a literal boolean value, e.g. true/false */
class BooleanLiteralExpression(boolean: Boolean) : LiteralExpression<Boolean>(boolean) {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
}
/** A reference to a literal null */
class NullLiteralExpression() : LiteralExpression<Any?>(null) {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
}
/** Subtypes represent a [Expression]s that operate over the result of the [qualifier]. */
interface QualifiedExpression {
val qualifier: Expression<Sequence<Scope>>?
fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression
}
/**
* Represents an iteration over a [Sequence] in the current scope under the identifier [source],
* placing each member of the sequence in a scope under [iterationVar] and returning
* a new sequence.
*/
data class FromExpression(
override val qualifier: Expression<Sequence<Scope>>?,
val source: Expression<Sequence<Any>>,
val iterationVar: String
) : QualifiedExpression, Expression<Sequence<Scope>>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
@Suppress("UNCHECKED_CAST")
override fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression =
this.copy(qualifier = qualifier as? Expression<Sequence<Scope>>)
override fun toString() = this.stringify()
}
/**
* Represents a filter expression that returns true or false.
*/
data class WhereExpression(
override val qualifier: Expression<Sequence<Scope>>,
val expr: Expression<Boolean>
) : QualifiedExpression, Expression<Sequence<Scope>>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
@Suppress("UNCHECKED_CAST")
override fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression =
qualifier?.let { this.copy(qualifier = qualifier as Expression<Sequence<Scope>>) }
?: this
override fun toString() = this.stringify()
}
/**
* Represents introducing a new identifier into the scope.
*/
data class LetExpression(
override val qualifier: Expression<Sequence<Scope>>,
val variableExpr: Expression<*>,
val variableName: String
) : QualifiedExpression, Expression<Sequence<Scope>>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
@Suppress("UNCHECKED_CAST")
override fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression =
qualifier?.let { this.copy(qualifier = qualifier as Expression<Sequence<Scope>>) }
?: this
override fun toString() = this.stringify()
}
/**
* Represents an expression that outputs a value.
*
* @param T the type of the new elements in the sequence
*/
data class SelectExpression<T>(
override val qualifier: Expression<Sequence<Scope>>,
val expr: Expression<T>
) : QualifiedExpression, Expression<Sequence<T>>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
@Suppress("UNCHECKED_CAST")
override fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression =
qualifier?.let { this.copy(qualifier = qualifier as Expression<Sequence<Scope>>) }
?: this
override fun toString() = this.stringify()
}
/**
* Represents an expression that constructs a new value corresponding to the given
* [schemaName] with a field for each declared (name, expression) in [fields].
*/
data class NewExpression(
val schemaName: Set<String>,
val fields: List<Pair<String, Expression<*>>>
) : Expression<Scope>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Represents an expression that invokes a builtin function by name.
*
* @param T the type of the result of the [FunctionExpression]
*/
data class FunctionExpression<T>(
val function: GlobalFunction,
val arguments: List<Expression<*>>
) : Expression<T>() {
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
}
/**
* Represents an expression that sorts a sequence to produce a new sequence. Note that this
* operator can be expensive, and must traverse its qualifying sequence entirely.
*
* [selectors] is a non-empty list of expressions that return values to be used for ordering.
*/
data class OrderByExpression<T>(
override val qualifier: Expression<Sequence<Scope>>,
val selectors: List<Selector>
) : QualifiedExpression, Expression<Sequence<T>>() {
/** the orderby [expr] and a boolean whether it is a descending sort. */
data class Selector(val expr: Expression<Any>, val descending: Boolean)
init {
require(!selectors.isEmpty()) {
"OrderBy expressions must have at least 1 selector."
}
}
override fun <Result, Context> accept(visitor: Visitor<Result, Context>, ctx: Context) =
visitor.visit(this, ctx)
override fun toString() = this.stringify()
@Suppress("UNCHECKED_CAST")
override fun withQualifier(qualifier: QualifiedExpression?): QualifiedExpression =
qualifier?.let { this.copy(qualifier = qualifier as Expression<Sequence<Scope>>) }
?: this
}
}
/**
* Although this function looks weird, it exists to overcome a shortcoming in Kotlin's numeric
* type hierarchy, namely that operator overloads don't exist on [Number], and [BigInt]
* doesn't have them either. This function also widens types to the nearest compatible type
* for the operation (e.g. Double, Long, Int, or BigInt) and then narrows the type afterwards.
* Currently, Double + BigInt and Float + BigInt will not return the right answer,
* unless * we either round the Double, or truncate the BigInt, at least until we perhaps
* support [BigDecimal].
* TODO: Write out own BigInt facade that is multiplatform and works on JS/JVM/WASM.
*/
private fun widenAndApply(
l: Number,
r: Number,
floatBlock: (Double, Double) -> Number,
longBlock: (Long, Long) -> Number,
intBlock: (Int, Int) -> Number,
bigBlock: (BigInt, BigInt) -> Number
): Number {
if (l is Double || r is Double) return floatBlock(l.toDouble(), r.toDouble())
if (l is Float || r is Float) return floatBlock(l.toDouble(), r.toDouble()).toFloat()
if (l is BigInt || r is BigInt) return bigBlock(l.toBigInt(), r.toBigInt())
if (l is Long || r is Long) return longBlock(l.toLong(), r.toLong())
if (l is Int || r is Int) return intBlock(l.toInt(), r.toInt())
if (l is Short || r is Short) return intBlock(l.toInt(), r.toInt()).toShort()
if (l is Byte || r is Byte) return intBlock(l.toInt(), r.toInt()).toByte()
throw IllegalArgumentException("Unable to widenType for ${l::class}, ${r::class}")
}
@Suppress("UNCHECKED_CAST")
private operator fun Number.compareTo(other: Number) = widenAndApply(
this,
other,
{ l, r -> l.compareTo(r) },
{ l, r -> l.compareTo(r) },
{ l, r -> l.compareTo(r) },
{ l, r -> l.compareTo(r) }
).toInt()
private operator fun Number.plus(other: Number): Number {
return widenAndApply(this, other,
{ l, r -> l + r },
{ l, r -> l + r },
{ l, r -> l + r },
{ l, r -> l.add(r) }
)
}
private operator fun Number.minus(other: Number): Number {
return widenAndApply(this, other,
{ l, r -> l - r },
{ l, r -> l - r },
{ l, r -> l - r },
{ l, r -> l.subtract(r) }
)
}
private operator fun Number.times(other: Number): Number {
return widenAndApply(this, other,
{ l, r -> l * r },
{ l, r -> l * r },
{ l, r -> l * r },
{ l, r -> l.multiply(r) }
)
}
private operator fun Number.div(other: Number): Number {
return widenAndApply(this, other,
{ l, r -> l / r },
{ l, r -> l / r },
{ l, r -> l / r },
{ l, r -> l.divide(r) }
)
}
operator fun Number.unaryMinus() = this * -1
| bsd-3-clause | 1380a854b13d262d71a0710b7010f840 | 34.761578 | 98 | 0.660032 | 4.173974 | false | false | false | false |
hpost/kommon | app/src/main/java/cc/femto/kommon/ui/recyclerview/InsetItemDecoration.kt | 1 | 977 | package cc.femto.kommon.ui.recyclerview
import android.graphics.Rect
import android.support.annotation.Dimension
import android.support.annotation.LayoutRes
import android.support.v7.widget.RecyclerView
import android.view.View
class InsetItemDecoration(@LayoutRes private val itemLayoutId: Int,
@Dimension private val paddingHorizontal: Int,
@Dimension private val paddingVertical: Int) : RecyclerView.ItemDecoration() {
fun isDecoratedItem(child: View, parent: RecyclerView): Boolean
= parent.layoutManager.getItemViewType(child) == itemLayoutId
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
if (!isDecoratedItem(view, parent)) {
return
}
outRect.left = paddingHorizontal
outRect.top = paddingVertical
outRect.right = paddingHorizontal
outRect.bottom = paddingVertical
}
}
| apache-2.0 | d6f56987aa1fd1540a399f8a81674712 | 36.576923 | 110 | 0.704197 | 5.062176 | false | false | false | false |
ismail-s/JTime | JTime-android/src/main/kotlin/com/ismail_s/jtime/android/fragment/MasjidFragment.kt | 1 | 4173 | package com.ismail_s.jtime.android.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.ismail_s.jtime.android.CalendarFormatter.formatCalendarAsDate
import com.ismail_s.jtime.android.CalendarFormatter.formatCalendarAsTime
import com.ismail_s.jtime.android.Constants
import com.ismail_s.jtime.android.R
import com.ismail_s.jtime.android.RestClient
import com.ismail_s.jtime.android.SharedPreferencesWrapper
import nl.komponents.kovenant.ui.failUi
import nl.komponents.kovenant.ui.successUi
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.act
import org.jetbrains.anko.support.v4.longToast
import org.jetbrains.anko.support.v4.withArguments
import java.util.*
/**
* A fragment that displays salaah times for a particular masjid, for a particular day. Used within
* [MasjidsFragment].
*/
class MasjidFragment : BaseFragment() {
lateinit private var editButton: Button
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_masjid, container, false)
val textView = rootView.find<TextView>(R.id.section_label)
val date = arguments.getSerializable(ARG_DATE) as GregorianCalendar
textView.text = getString(R.string.section_format, formatCalendarAsDate(date))
// TODO-instead of 1, what should the default value be here?
val masjidId = arguments.getInt(Constants.MASJID_ID)
editButton = rootView.find<Button>(R.id.edit_button)
editButton.setOnClickListener {
val masjidName = arguments.getString(Constants.MASJID_NAME)
if (activity != null)
mainAct.switchToChangeMasjidTimesFragment(masjidId, masjidName, date)
}
if (SharedPreferencesWrapper(act).persistedLoginExists()) {
onLogin()
} else {
onLogout()
}
cancelPromiseOnFragmentDestroy {
RestClient(act).getMasjidTimes(masjidId, date) successUi {
ifAttachedToAct {
if (it.fajrTime != null) {
val fTime = formatCalendarAsTime(it.fajrTime as GregorianCalendar)
rootView.find<TextView>(R.id.fajr_date).text = fTime
}
if (it.zoharTime != null) {
val zTime = formatCalendarAsTime(it.zoharTime as GregorianCalendar)
rootView.find<TextView>(R.id.zohar_date).text = zTime
}
if (it.asrTime != null) {
val aTime = formatCalendarAsTime(it.asrTime as GregorianCalendar)
rootView.find<TextView>(R.id.asr_date).text = aTime
}
if (it.magribTime != null) {
val mTime = formatCalendarAsTime(it.magribTime as GregorianCalendar)
rootView.find<TextView>(R.id.magrib_date).text = mTime
}
if (it.eshaTime != null) {
val eTime = formatCalendarAsTime(it.eshaTime as GregorianCalendar)
rootView.find<TextView>(R.id.esha_date).text = eTime
}
}
} failUi {
ifAttachedToAct {
longToast(getString(R.string.get_masjid_times_failure_toast, it.message))
}
}
}
return rootView
}
override fun onLogin() {
editButton.visibility = View.VISIBLE
}
override fun onLogout() {
editButton.visibility = View.INVISIBLE
}
companion object {
private val ARG_DATE = "date"
fun newInstance(masjidId: Int, masjidName: String, date: GregorianCalendar): MasjidFragment =
MasjidFragment().withArguments(
ARG_DATE to date, Constants.MASJID_ID to masjidId,
Constants.MASJID_NAME to masjidName)
}
}
| gpl-2.0 | 00b2fd7e37522ebf53cf1de90eb22640 | 41.151515 | 101 | 0.623772 | 4.288798 | false | false | false | false |
DiUS/pact-jvm | core/support/src/main/kotlin/au/com/dius/pact/core/support/KotlinLanguageSupport.kt | 1 | 1589 | package au.com.dius.pact.core.support
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.UnwrapException
import java.lang.Integer.max
import java.net.URL
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
public fun String?.isNotEmpty(): Boolean = !this.isNullOrEmpty()
public fun String?.contains(other: String): Boolean = this?.contains(other, ignoreCase = false) ?: false
public fun <E> List<E>.zipAll(otherList: List<E>): List<Pair<E?, E?>> {
return (0 until max(this.size, otherList.size)).map {
this.getOrNull(it) to otherList.getOrNull(it)
}
}
public fun Any?.hasProperty(name: String) = this != null && this::class.memberProperties.any { it.name == name }
public fun Any?.property(name: String) = if (this != null) {
this::class.memberProperties.find { it.name == name } as KProperty1<Any, Any?>?
} else null
public fun String?.toUrl() = if (this.isNullOrEmpty()) {
null
} else {
URL(this)
}
public fun <F> handleWith(f: () -> Any?): Result<F, Exception> {
return try {
val result = f()
if (result is Result<*, *>) result as Result<F, Exception> else Ok(result as F)
} catch (ex: Exception) {
Err(ex)
} catch (ex: Throwable) {
Err(RuntimeException(ex))
}
}
public fun <A, B> Result<A, B>.unwrap(): A {
when (this) {
is Err<*> -> when (error) {
is Throwable -> throw error as Throwable
else -> throw UnwrapException(error.toString())
}
is Ok<*> -> return value as A
}
}
| apache-2.0 | 7cf2fc125c3d8ab6b758db4bc8b83614 | 28.981132 | 112 | 0.683449 | 3.409871 | false | false | false | false |
mdaniel/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/DaemonBoundCodeVisionProvider.kt | 4 | 2741 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.codeVision
import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering
import com.intellij.codeInsight.codeVision.CodeVisionPlaceholderCollector
import com.intellij.codeInsight.codeVision.ui.model.CodeVisionPredefinedActionEntry
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
/**
* Almost the same thing as [com.intellij.codeInsight.codeVision.CodeVisionProvider], but run in the [com.intellij.codeInsight.daemon.DaemonCodeAnalyzer]
* and that's why it has built-in support of interruption.
*/
interface DaemonBoundCodeVisionProvider {
companion object {
const val EP_NAME = "com.intellij.codeInsight.daemonBoundCodeVisionProvider"
val extensionPoint = ExtensionPointName.create<DaemonBoundCodeVisionProvider>(EP_NAME)
}
@JvmDefault
fun preparePreview(editor: Editor, file: PsiFile) {
}
/**
* Computes code lens data in read action in background for a given editor.
*/
@Deprecated("Use overload with file")
fun computeForEditor(editor: Editor): List<Pair<TextRange, CodeVisionEntry>> = emptyList()
/**
* Computes code lens data in read action in background for a given editor.
*/
@Suppress("DEPRECATION")
@JvmDefault
fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> = emptyList()
fun handleClick(editor: Editor, textRange: TextRange, entry: CodeVisionEntry){
if (entry is CodeVisionPredefinedActionEntry) entry.onClick(editor)
}
/**
* Calls on background BEFORE editor opening
* Returns ranges where placeholders should be when editor opens
*/
@JvmDefault
@Deprecated("use getPlaceholderCollector")
fun collectPlaceholders(editor: Editor): List<TextRange> = emptyList()
@JvmDefault
fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? = null
/**
* Name in settings.
*/
@get:Nls
val name: String
val relativeOrderings: List<CodeVisionRelativeOrdering>
val defaultAnchor: CodeVisionAnchorKind
/**
* Unique identifier (among all instances of [DaemonBoundCodeVisionProvider] and [com.intellij.codeInsight.codeVision.CodeVisionProvider])
*/
@get:NonNls
val id: String
val groupId: String
get() = id
} | apache-2.0 | 0d48189d7b3342e4a09d3b769568f924 | 34.61039 | 158 | 0.779642 | 4.630068 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/IncompleteDestructuringInspection.kt | 1 | 5608 | // 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.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.destructuringDeclarationVisitor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class IncompleteDestructuringInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return destructuringDeclarationVisitor(fun(destructuringDeclaration) {
val lPar = destructuringDeclaration.lPar ?: return
val rPar = destructuringDeclaration.rPar ?: return
val primaryParameters = destructuringDeclaration.primaryParameters() ?: return
if (destructuringDeclaration.entries.size < primaryParameters.size) {
val highlightRange =
TextRange(lPar.textRangeIn(destructuringDeclaration).startOffset, rPar.textRangeIn(destructuringDeclaration).endOffset)
holder.registerProblem(
destructuringDeclaration,
highlightRange,
KotlinBundle.message("incomplete.destructuring.declaration.text"),
IncompleteDestructuringQuickfix()
)
}
})
}
}
private fun KtDestructuringDeclaration.primaryParameters(): List<ValueParameterDescriptor>? {
val initializer = this.initializer
val parameter = this.parent as? KtParameter
val type = when {
initializer != null -> initializer.getType(analyze(BodyResolveMode.PARTIAL))
parameter != null -> analyze(BodyResolveMode.PARTIAL)[BindingContext.VALUE_PARAMETER, parameter]?.type
else -> null
} ?: return null
val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return null
return classDescriptor.constructors.firstOrNull { it.isPrimary }?.valueParameters
}
class IncompleteDestructuringQuickfix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("incomplete.destructuring.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val destructuringDeclaration = descriptor.psiElement as? KtDestructuringDeclaration ?: return
addMissingEntries(destructuringDeclaration)
}
companion object {
fun addMissingEntries(destructuringDeclaration: KtDestructuringDeclaration) {
val primaryParameters = destructuringDeclaration.primaryParameters() ?: return
val nameValidator = CollectingNameValidator(
filter = Fe10KotlinNewDeclarationNameValidator(
destructuringDeclaration.parent,
null,
KotlinNameSuggestionProvider.ValidatorTarget.PARAMETER
)
)
val psiFactory = KtPsiFactory(destructuringDeclaration)
val currentEntries = destructuringDeclaration.entries
val hasType = currentEntries.any { it.typeReference != null }
val additionalEntries = primaryParameters
.drop(currentEntries.size)
.map {
val name = Fe10KotlinNameSuggester.suggestNameByName(it.name.asString(), nameValidator)
if (hasType) {
val type = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it.type)
"$name: $type"
} else {
name
}
}
.let { psiFactory.createDestructuringDeclaration("val (${it.joinToString()}) = TODO()").entries }
val rPar = destructuringDeclaration.rPar
val hasTrailingComma = destructuringDeclaration.trailingComma != null
val currentEntriesIsEmpty = currentEntries.isEmpty()
additionalEntries.forEachIndexed { index, entry ->
if (index != 0 || (!hasTrailingComma && !currentEntriesIsEmpty)) {
destructuringDeclaration.addBefore(psiFactory.createComma(), rPar)
}
destructuringDeclaration.addBefore(entry, rPar)
}
}
}
}
| apache-2.0 | 403efad917d01d7cc633257c57d69e32 | 50.449541 | 158 | 0.713445 | 5.775489 | false | false | false | false |
andrewoma/kommon | src/main/kotlin/com/github/andrewoma/kommon/lang/ObjectExtensions.kt | 1 | 1614 | /*
* Copyright (c) 2016 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kommon.lang
import kotlin.reflect.KProperty1
inline fun <reified T> equals(t: T, other: Any?, equate: (t1: T, t2: T) -> Boolean): Boolean {
if (t === other) return true
if (other !is T) return false
return equate(t, other)
}
inline fun <reified T> equals(t: T, other: Any?, vararg properties: KProperty1<T, *>): Boolean {
if (t === other) return true
if (other !is T) return false
return properties.none { it.get(t) != it.get(other) }
} | mit | 9b3bca93cf8c6b4bc60a8999623d4c22 | 41.5 | 96 | 0.728005 | 4.014925 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-15/app/src/main/java/dev/mfazio/pennydrop/game/AI.kt | 1 | 1198 | package dev.mfazio.pennydrop.game
import dev.mfazio.pennydrop.types.Player
import dev.mfazio.pennydrop.types.Slot
import dev.mfazio.pennydrop.types.fullSlots
data class AI(
val aiId: Int = 0,
val name: String,
val rollAgain: (slots: List<Slot>) -> Boolean
) {
override fun toString() = name
fun toPlayer() = Player(
playerName = name,
isHuman = false,
selectedAI = this
)
companion object {
@JvmStatic
val basicAI = listOf(
AI(1, "TwoFace") { slots ->
slots.fullSlots() < 3 || (slots.fullSlots() == 3 && coinFlipIsHeads())
},
AI(2, "No Go Noah") { slots -> slots.fullSlots() == 0 },
AI(3, "Bail Out Beulah") { slots -> slots.fullSlots() <= 1 },
AI(4, "Fearful Fred") { slots -> slots.fullSlots() <= 2 },
AI(5, "Even Steven") { slots -> slots.fullSlots() <= 3 },
AI(6, "Riverboat Ron") { slots -> slots.fullSlots() <= 4 },
AI(7, "Sammy Sixes") { slots -> slots.fullSlots() <= 5 },
AI(8, "Random Rachael") { coinFlipIsHeads() }
)
}
}
fun coinFlipIsHeads() = (Math.random() * 2).toInt() == 0 | apache-2.0 | 00913e49f6fbdf45f10d4b1dc76dffc7 | 30.552632 | 86 | 0.542571 | 3.482558 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/listeners/antispam/DuplicateMessageListener.kt | 1 | 2617 | package me.aberrantfox.hotbot.listeners.antispam
import me.aberrantfox.hotbot.commandframework.commands.administration.SecurityLevelState
import me.aberrantfox.hotbot.extensions.jda.descriptor
import me.aberrantfox.hotbot.extensions.jda.fullName
import me.aberrantfox.hotbot.extensions.jda.isImagePost
import me.aberrantfox.hotbot.logging.BotLogger
import me.aberrantfox.hotbot.services.*
import me.aberrantfox.hotbot.utility.permMuteMember
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.core.hooks.ListenerAdapter
import org.joda.time.DateTime
object MutedRaiders {
val set = PersistentSet(configPath("raiders.json"))
}
class DuplicateMessageListener (val config: Configuration, val log: BotLogger, val tracker: MessageTracker) : ListenerAdapter() {
override fun onGuildMessageReceived(event: GuildMessageReceivedEvent) {
if(event.message.isImagePost()) return
val time = DateTime.now()
if((event.member?.roles?.size ?: 0) > 0) return
if(event.author.isBot) return
val id = event.author.id
val matches = tracker.addMessage(AccurateMessage(time, event.message))
checkDuplicates(id, event, matches)
checkSpeed(id, event)
}
private fun checkDuplicates(id: String, event: GuildMessageReceivedEvent, matches: Int) {
if(tracker.count(id) < SecurityLevelState.alertLevel.waitPeriod) return
if(matches < SecurityLevelState.alertLevel.matchCount) return
MutedRaiders.set.add(id)
val reason = "Automatic mute for duplicate-spam detection due to security level ${SecurityLevelState.alertLevel.name}"
punish(event, reason, id)
}
private fun checkSpeed(id: String, event: GuildMessageReceivedEvent) {
if(MutedRaiders.set.contains(id)) return
val maxAmount = SecurityLevelState.alertLevel.maxAmount
val amount = tracker.list(id)
?.count { it.time.isAfter(DateTime.now().minusSeconds(5)) }
?: return
if(maxAmount <= amount) {
MutedRaiders.set.add(id)
val reason = "Automatic mute for repeat-spam detection due to security level ${SecurityLevelState.alertLevel.name}"
punish(event, reason, id)
}
}
private fun punish(event: GuildMessageReceivedEvent, reason: String, id: String) {
permMuteMember(event.guild, event.author, reason, config)
tracker.list(id)?.forEach { it.message.delete().queue() }
log.warning("${event.author.descriptor()} was muted for $reason")
tracker.removeUser(id)
}
}
| mit | 09e912ace2cd5c78a2d6ddd5ce9b6688 | 37.485294 | 129 | 0.716087 | 4.101881 | false | true | false | false |
austinv11/D4JBot | src/main/kotlin/com/austinv11/d4j/bot/command/impl/KotlinEvalCommand.kt | 1 | 2690 | package com.austinv11.d4j.bot.command.impl
import com.austinv11.d4j.bot.command.CommandExecutor
import com.austinv11.d4j.bot.command.Executor
import com.austinv11.d4j.bot.command.Parameter
import com.austinv11.d4j.bot.command.context
import com.austinv11.d4j.bot.extensions.embed
import com.austinv11.d4j.bot.scripting.KotlinScriptCompiler
import com.austinv11.d4j.bot.util.MessageReader
import org.apache.commons.io.input.ReaderInputStream
import org.apache.commons.io.output.WriterOutputStream
import sx.blah.discord.util.EmbedBuilder
import java.io.PrintStream
import java.io.PrintWriter
import java.io.Reader
import java.io.StringWriter
import java.nio.charset.Charset
class KotlinEvalCommand : CommandExecutor() {
override val name: String = "eval"
override val aliases: Array<String> = arrayOf("evaluate", "kotlin", "kotlinc")
@Executor("Compiles and runs the provided kotlin snippet.", requiresOwner = true)
fun execute(@Parameter("The code to attempt to run.") code: String): EmbedBuilder {
val code = context.raw.substringAfter(' ')
val context = context
context.channel.typingStatus = true
val compiled = KotlinScriptCompiler.compile(code.removeSurrounding("```").removePrefix("kotlin").removeSurrounding("`"))
val builder = context.embed.withTitle("Kotlin Evaluation Results").withThumbnail("https://avatars2.githubusercontent.com/u/1446536?v=3&s=400") //Kotlin's icon
val writer = StringWriter()
val reader: Reader = MessageReader(context.channel.longID)
val ris = ReaderInputStream(reader, Charset.defaultCharset())
val wos = PrintStream(WriterOutputStream(writer, Charset.defaultCharset()))
compiled.setIn(ris)
compiled.setOut(wos)
compiled.setErr(wos)
compiled.bind("context", context)
try {
val result = compiled.execute()
builder.appendField("Output", "```\n$result```", false)
} catch (e: Throwable) {
val stacktraceWriter = StringWriter()
e.printStackTrace(PrintWriter(stacktraceWriter))
val stacktraceLines = stacktraceWriter.toString().lines()
val stacktrace = stacktraceLines.subList(0, Math.min(10, stacktraceLines.size)).joinToString("\n")
stacktraceWriter.close()
builder.appendField("Thrown Exception", "```\n$stacktrace```", false)
} finally {
wos.close()
ris.close()
val log = writer.toString()
builder.appendField("Log", "```\n$log```", false)
context.channel.typingStatus = false
}
return builder
}
}
| gpl-3.0 | 030c4a13d77a7a2340ac8cdb2129645e | 43.098361 | 166 | 0.683271 | 4.269841 | false | false | false | false |
vickychijwani/kotlin-koans-android | app/src/main/code/me/vickychijwani/kotlinkoans/features/common/TabLayoutWithFonts.kt | 1 | 1301 | package me.vickychijwani.kotlinkoans.features.common
import android.content.Context
import android.graphics.Typeface
import android.support.design.widget.TabLayout
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.TextView
class TabLayoutWithFonts : TabLayout {
private var mTypeface: Typeface? = null
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
mTypeface = Typeface.createFromAsset(context.assets, "fonts/bold.ttf")
}
override fun addTab(tab: Tab, position: Int, setSelected: Boolean) {
super.addTab(tab, position, setSelected)
val mainView = getChildAt(0) as ViewGroup
val tabView = mainView.getChildAt(tab.position) as ViewGroup
val tabChildCount = tabView.childCount
for (i in 0..tabChildCount - 1) {
val tabViewChild = tabView.getChildAt(i)
if (tabViewChild is TextView) {
tabViewChild.setTypeface(mTypeface, Typeface.NORMAL)
}
}
}
}
| mit | a19e1489992a735772f6c1cbc28472ca | 27.911111 | 113 | 0.675634 | 4.365772 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/DefaultArgumentsConversion.kt | 2 | 9261 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.symbols.JKSymbol
import org.jetbrains.kotlin.nj2k.symbols.JKUniverseMethodSymbol
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKNoType
class DefaultArgumentsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
private fun JKMethod.canNotBeMerged(): Boolean =
modality == Modality.ABSTRACT
|| hasOtherModifier(OtherModifier.OVERRIDE)
|| hasOtherModifier(OtherModifier.NATIVE)
|| hasOtherModifier(OtherModifier.SYNCHRONIZED)
|| psi<PsiMethod>()?.let { context.converter.converterServices.oldServices.referenceSearcher.hasOverrides(it) } == true
|| annotationList.annotations.isNotEmpty()
|| name.value.canBeGetterOrSetterName()
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClassBody) return recurse(element)
val methods = element.declarations.filterIsInstance<JKMethod>().sortedBy { it.parameters.size }
checkMethod@ for (method in methods) {
val block = method.block as? JKBlock ?: continue
val singleStatement = block.statements.singleOrNull() ?: continue
if (method.canNotBeMerged()) continue
val call = lookupCall(singleStatement) ?: continue
val callee = call.identifier as? JKUniverseMethodSymbol ?: continue
val calledMethod = callee.target
if (calledMethod.parent != method.parent
|| callee.name != method.name.value
|| calledMethod.returnType.type != method.returnType.type
|| call.arguments.arguments.size <= method.parameters.size
|| call.arguments.arguments.size < calledMethod.parameters.size //calledMethod has varargs param or call expr has errors
|| calledMethod.parameters.any(JKParameter::isVarArgs)
) {
continue
}
if (calledMethod.visibility != method.visibility) continue@checkMethod
if (calledMethod.canNotBeMerged()) continue
for (i in method.parameters.indices) {
val parameter = method.parameters[i]
val targetParameter = calledMethod.parameters[i]
val argument = call.arguments.arguments[i].value
if (parameter.name.value != targetParameter.name.value) continue@checkMethod
if (parameter.type.type != targetParameter.type.type) continue@checkMethod
if (argument !is JKFieldAccessExpression || argument.identifier.target != parameter) continue@checkMethod
if (parameter.initializer !is JKStubExpression
&& targetParameter.initializer !is JKStubExpression
&& !areTheSameExpressions(targetParameter.initializer, parameter.initializer)
) continue@checkMethod
}
for (i in method.parameters.indices) {
val parameter = method.parameters[i]
val targetParameter = calledMethod.parameters[i]
if (parameter.initializer !is JKStubExpression
&& targetParameter.initializer is JKStubExpression
) {
targetParameter.initializer = parameter.initializer.copyTreeAndDetach()
}
}
for (index in (method.parameters.lastIndex + 1)..calledMethod.parameters.lastIndex) {
val calleeExpression = call.arguments.arguments[index].value
val defaultArgument = calledMethod.parameters[index].initializer.takeIf { it !is JKStubExpression } ?: continue
if (!areTheSameExpressions(calleeExpression, defaultArgument)) continue@checkMethod
}
call.arguments.invalidate()
val defaults = call.arguments.arguments
.map { it::value.detached() }
.zip(calledMethod.parameters)
.drop(method.parameters.size)
fun JKSymbol.isNeedThisReceiver(): Boolean {
val parameters = defaults.map { it.second }
val declarations = element.declarations
val propertyNameByGetMethodName = propertyNameByGetMethodName(Name.identifier(this.name))?.asString()
return parameters.any { it.name.value == this.name || it.name.value == propertyNameByGetMethodName }
&& declarations.any { it == this.target }
}
fun remapParameterSymbol(on: JKTreeElement): JKTreeElement {
if (on is JKQualifiedExpression && on.receiver is JKThisExpression) {
return on
}
if (on is JKFieldAccessExpression) {
val target = on.identifier.target
if (target is JKParameter && target.parent == method) {
val newSymbol =
symbolProvider.provideUniverseSymbol(calledMethod.parameters[method.parameters.indexOf(target)])
return JKFieldAccessExpression(newSymbol)
}
if (on.identifier.isNeedThisReceiver()) {
return JKQualifiedExpression(JKThisExpression(JKLabelEmpty(), JKNoType), JKFieldAccessExpression(on.identifier))
}
}
if (on is JKCallExpression && on.identifier.isNeedThisReceiver()) {
return JKQualifiedExpression(JKThisExpression(JKLabelEmpty(), JKNoType), applyRecursive(on, ::remapParameterSymbol))
}
return applyRecursive(on, ::remapParameterSymbol)
}
for ((defaultValue, parameter) in defaults) {
parameter.initializer = remapParameterSymbol(defaultValue) as JKExpression
}
element.declarations -= method
calledMethod.withFormattingFrom(method)
}
if (element.parentOfType<JKClass>()?.classKind != JKClass.ClassKind.ANNOTATION) {
for (method in element.declarations) {
if (method !is JKMethod) continue
if (method.hasParametersWithDefaultValues()
&& (method.visibility == Visibility.PUBLIC || method.visibility == Visibility.INTERNAL)
) {
method.annotationList.annotations += jvmAnnotation("JvmOverloads", symbolProvider)
}
}
}
return recurse(element)
}
private fun areTheSameExpressions(first: JKElement, second: JKElement): Boolean {
if (first::class != second::class) return false
if (first is JKNameIdentifier && second is JKNameIdentifier) return first.value == second.value
if (first is JKLiteralExpression && second is JKLiteralExpression) return first.literal == second.literal
if (first is JKFieldAccessExpression && second is JKFieldAccessExpression && first.identifier != second.identifier) return false
if (first is JKCallExpression && second is JKCallExpression && first.identifier != second.identifier) return false
return if (first is JKTreeElement && second is JKTreeElement) {
first.children.zip(second.children) { childOfFirst, childOfSecond ->
when {
childOfFirst is JKTreeElement && childOfSecond is JKTreeElement -> {
areTheSameExpressions(
childOfFirst,
childOfSecond
)
}
childOfFirst is List<*> && childOfSecond is List<*> -> {
childOfFirst.zip(childOfSecond) { child1, child2 ->
areTheSameExpressions(
child1 as JKElement,
child2 as JKElement
)
}.fold(true, Boolean::and)
}
else -> false
}
}.fold(true, Boolean::and)
} else false
}
private fun JKMethod.hasParametersWithDefaultValues() =
parameters.any { it.initializer !is JKStubExpression }
private fun lookupCall(statement: JKStatement): JKCallExpression? {
val expression = when (statement) {
is JKExpressionStatement -> statement.expression
is JKReturnStatement -> statement.expression
else -> null
}
return when (expression) {
is JKCallExpression -> expression
is JKQualifiedExpression -> {
if (expression.receiver !is JKThisExpression) return null
expression.selector as? JKCallExpression
}
else -> null
}
}
}
| apache-2.0 | 18fb9405947c9f7d67b2b49956c2afbb | 47.742105 | 136 | 0.606306 | 5.650397 | false | false | false | false |
google/accompanist | pager/src/sharedTest/kotlin/com/google/accompanist/pager/PagerStateUnitTest.kt | 1 | 3632 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.pager
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.junit4.StateRestorationTester
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalPagerApi::class) // Pager is currently experimental
@RunWith(AndroidJUnit4::class)
class PagerStateUnitTest {
@get:Rule
val composeTestRule = createComposeRule()
@OptIn(ExperimentalCoroutinesApi::class)
@Ignore // Not currently working after migration to Lazy
@Suppress("DEPRECATION")
@Test
fun store_restore_state() = runBlockingTest {
val stateRestoration = StateRestorationTester(composeTestRule)
lateinit var state: PagerState
stateRestoration.setContent {
state = rememberPagerState()
HorizontalPager(count = 10, state = state) { page ->
BasicText(text = "Page:$page")
}
}
composeTestRule.awaitIdle()
// Now scroll to page 4
state.scrollToPage(4)
// Emulator a state save + restore
stateRestoration.emulateSavedInstanceStateRestore()
// And assert that everything was restored
assertThat(state.currentPage).isEqualTo(4)
assertThat(state.pageCount).isEqualTo(10)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun change_pager_count() {
val pagerState = PagerState()
var count by mutableStateOf(10)
composeTestRule.setContent {
HorizontalPager(count = count, state = pagerState) { page ->
BasicText(text = "Page:$page")
}
}
composeTestRule.waitForIdle()
// Now scroll to page 8
composeTestRule.runOnIdle {
runBlocking {
pagerState.scrollToPage(8)
}
}
// And assert that currentPage and pageCount are correct
assertThat(pagerState.currentPage).isEqualTo(8)
assertThat(pagerState.pageCount).isEqualTo(10)
// Change page count to 4
count = 4
composeTestRule.waitForIdle()
// And assert that currentPage and pageCount are correct
assertThat(pagerState.currentPage).isEqualTo(3)
assertThat(pagerState.pageCount).isEqualTo(4)
// Change page count to 0
count = 0
composeTestRule.waitForIdle()
// And assert that currentPage and pageCount are correct
assertThat(pagerState.currentPage).isEqualTo(0)
assertThat(pagerState.pageCount).isEqualTo(0)
}
}
| apache-2.0 | df03a7205084c0aa7914012fef2bdf70 | 32.62963 | 75 | 0.697137 | 4.894879 | false | true | false | false |
marius-m/wt4 | components/src/main/java/lt/markmerkk/tickets/TicketInfoLoader.kt | 1 | 1816 | package lt.markmerkk.tickets
import lt.markmerkk.Tags
import lt.markmerkk.TicketStorage
import lt.markmerkk.entities.Ticket
import lt.markmerkk.entities.TicketCode
import org.slf4j.LoggerFactory
import rx.Observable
import rx.Scheduler
import rx.Subscription
import rx.subjects.BehaviorSubject
import java.util.concurrent.TimeUnit
/**
* Responsible for finding [Ticket] by input code
*/
class TicketInfoLoader(
private val listener: Listener,
private val ticketStorage: TicketStorage,
private val waitScheduler: Scheduler,
private val ioScheduler: Scheduler,
private val uiScheduler: Scheduler
) {
private var searchSubscription: Subscription? = null
fun onAttach() { }
fun onDetach() {
searchSubscription?.unsubscribe()
}
fun findTicket(inputCode: String) {
val ticketCode = TicketCode.new(inputCode)
if (ticketCode.isEmpty()) {
listener.onNoTicket(inputCode)
return
}
searchSubscription?.unsubscribe()
searchSubscription = ticketStorage.findTicketsByCode(ticketCode.code)
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.subscribe({ tickets ->
if (tickets.isNotEmpty()) {
listener.onTicketFound(tickets.first())
} else {
listener.onNoTicket(inputCode)
}
}, {
listener.onNoTicket(inputCode)
})
}
interface Listener {
fun onTicketFound(ticket: Ticket)
fun onNoTicket(searchTicket: String)
}
companion object {
const val INPUT_THROTTLE_MILLIS = 500L
private val logger = LoggerFactory.getLogger(Tags.TICKETS)
}
} | apache-2.0 | 66b7bc1224fd45f6fb20c90ec8f507fa | 27.390625 | 77 | 0.627753 | 4.948229 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/swift/SwiftServiceBuilder.kt | 1 | 1648 | package org.roylance.yaclib.core.services.swift
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.StringUtilities
import org.roylance.yaclib.core.utilities.SwiftUtilities
class SwiftServiceBuilder(
private val mainDependency: YaclibModel.Dependency,
private val controller: YaclibModel.Controller) : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val workspace = StringBuilder()
val interfaceName = StringUtilities.convertServiceNameToInterfaceName(controller)
val initialTemplate = """${CommonTokens.DoNotAlterMessage}
import Foundation
public protocol $interfaceName {
"""
workspace.append(initialTemplate)
controller.actionsList.forEach { action ->
val colonSeparatedInputs = action.inputsList.map { input ->
"${input.argumentName}: ${SwiftUtilities.buildSwiftFullName(input)}"
}.joinToString()
val actionTemplate = "\tfunc ${action.name}($colonSeparatedInputs, onSuccess: @escaping (_ response: ${SwiftUtilities.buildSwiftFullName(
action.output).trim()}) -> Void, onError: @escaping (_ response: String) -> Void)\n"
workspace.append(actionTemplate)
}
workspace.append("}")
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(workspace.toString())
.setFileExtension(YaclibModel.FileExtension.SWIFT_EXT)
.setFileName(interfaceName)
.setFullDirectoryLocation("${mainDependency.name}${CommonTokens.SwiftSuffix}/Source")
.build()
return returnFile
}
} | mit | a6978bfafc0c66f20e30febbd0e38731 | 38.261905 | 143 | 0.745146 | 4.708571 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-jetty/jvm/src/io/ktor/client/engine/jetty/JettyResponseListener.kt | 1 | 4994 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.jetty
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.HttpMethod
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import org.eclipse.jetty.http.*
import org.eclipse.jetty.http2.*
import org.eclipse.jetty.http2.api.*
import org.eclipse.jetty.http2.client.*
import org.eclipse.jetty.http2.frames.*
import org.eclipse.jetty.util.*
import java.io.*
import java.nio.*
import java.nio.channels.*
import kotlin.coroutines.*
internal data class StatusWithHeaders(val statusCode: HttpStatusCode, val headers: Headers)
private data class JettyResponseChunk(val buffer: ByteBuffer, val callback: Callback)
internal class JettyResponseListener(
private val request: HttpRequestData,
private val session: HTTP2ClientSession,
private val channel: ByteWriteChannel,
private val callContext: CoroutineContext
) : Stream.Listener {
private val headersBuilder: HeadersBuilder = HeadersBuilder()
private val onHeadersReceived = CompletableDeferred<HttpStatusCode?>()
private val backendChannel = Channel<JettyResponseChunk>(Channel.UNLIMITED)
init {
runResponseProcessing()
}
override fun onPush(stream: Stream, frame: PushPromiseFrame): Stream.Listener {
stream.reset(ResetFrame(frame.promisedStreamId, ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP)
return Ignore
}
override fun onIdleTimeout(stream: Stream, cause: Throwable): Boolean {
channel.close(cause)
return true
}
override fun onReset(stream: Stream, frame: ResetFrame) {
val error = when (frame.error) {
0 -> null
ErrorCode.CANCEL_STREAM_ERROR.code -> ClosedChannelException()
else -> {
val code = ErrorCode.from(frame.error)
IOException("Connection reset ${code?.name ?: "with unknown error code ${frame.error}"}")
}
}
error?.let { backendChannel.close(it) }
onHeadersReceived.complete(null)
}
override fun onData(stream: Stream, frame: DataFrame, callback: Callback) {
val data = frame.data!!
try {
if (!backendChannel.trySend(JettyResponseChunk(data, callback)).isSuccess) {
throw IOException("backendChannel.offer() failed")
}
if (frame.isEndStream) backendChannel.close()
} catch (cause: Throwable) {
backendChannel.close(cause)
callback.failed(cause)
}
}
override fun onFailure(stream: Stream?, error: Int, reason: String?, failure: Throwable?, callback: Callback?) {
callback?.succeeded()
val messagePrefix = reason ?: "HTTP/2 failure"
val message = when (error) {
0 -> messagePrefix
else -> "$messagePrefix, code $error"
}
val cause = IOException(message, failure)
backendChannel.close(cause)
onHeadersReceived.completeExceptionally(cause)
}
override fun onHeaders(stream: Stream, frame: HeadersFrame) {
frame.metaData.fields.forEach { field ->
headersBuilder.append(field.name, field.value)
}
if (frame.isEndStream || request.method == HttpMethod.Head) {
backendChannel.close()
}
onHeadersReceived.complete(
(frame.metaData as? MetaData.Response)?.let {
val (status, reason) = it.status to it.reason
reason?.let { text -> HttpStatusCode(status, text) } ?: HttpStatusCode.fromValue(status)
}
)
}
suspend fun awaitHeaders(): StatusWithHeaders {
val statusCode = onHeadersReceived.await() ?: throw IOException("Connection reset")
return StatusWithHeaders(statusCode, headersBuilder.build())
}
@OptIn(DelicateCoroutinesApi::class)
private fun runResponseProcessing() = GlobalScope.launch(callContext) {
while (true) {
val (buffer, callback) = backendChannel.receiveCatching().getOrNull() ?: break
try {
if (buffer.remaining() > 0) channel.writeFully(buffer)
callback.succeeded()
} catch (cause: ClosedWriteChannelException) {
callback.failed(cause)
session.endPoint.close()
break
} catch (cause: Throwable) {
callback.failed(cause)
session.endPoint.close()
throw cause
}
}
}.invokeOnCompletion { cause ->
channel.close(cause)
backendChannel.close()
GlobalScope.launch {
for ((_, callback) in backendChannel) {
callback.succeeded()
}
}
}
companion object {
private val Ignore = Stream.Listener.Adapter()
}
}
| apache-2.0 | fd6a68d4e8f0a2b1cd634e9ed7ed8b0b | 32.972789 | 118 | 0.636964 | 4.684803 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/setting/search/SettingsSearchHelper.kt | 2 | 5763 | package eu.kanade.tachiyomi.ui.setting.search
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceGroup
import androidx.preference.PreferenceManager
import eu.kanade.tachiyomi.ui.setting.SettingsAdvancedController
import eu.kanade.tachiyomi.ui.setting.SettingsAppearanceController
import eu.kanade.tachiyomi.ui.setting.SettingsBackupController
import eu.kanade.tachiyomi.ui.setting.SettingsBrowseController
import eu.kanade.tachiyomi.ui.setting.SettingsController
import eu.kanade.tachiyomi.ui.setting.SettingsDownloadController
import eu.kanade.tachiyomi.ui.setting.SettingsGeneralController
import eu.kanade.tachiyomi.ui.setting.SettingsLibraryController
import eu.kanade.tachiyomi.ui.setting.SettingsReaderController
import eu.kanade.tachiyomi.ui.setting.SettingsSecurityController
import eu.kanade.tachiyomi.ui.setting.SettingsTrackingController
import eu.kanade.tachiyomi.util.lang.launchNow
import eu.kanade.tachiyomi.util.system.isLTR
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
object SettingsSearchHelper {
private var prefSearchResultList: MutableList<SettingsSearchResult> = mutableListOf()
/**
* All subclasses of `SettingsController` should be listed here, in order to have their preferences searchable.
*/
private val settingControllersList: List<KClass<out SettingsController>> = listOf(
SettingsAdvancedController::class,
SettingsAppearanceController::class,
SettingsBackupController::class,
SettingsBrowseController::class,
SettingsDownloadController::class,
SettingsGeneralController::class,
SettingsLibraryController::class,
SettingsReaderController::class,
SettingsSecurityController::class,
SettingsTrackingController::class
)
/**
* Must be called to populate `prefSearchResultList`
*/
@SuppressLint("RestrictedApi")
fun initPreferenceSearchResultCollection(context: Context) {
val preferenceManager = PreferenceManager(context)
prefSearchResultList.clear()
launchNow {
settingControllersList.forEach { kClass ->
val ctrl = kClass.createInstance()
val settingsPrefScreen = ctrl.setupPreferenceScreen(preferenceManager.createPreferenceScreen(context))
val prefCount = settingsPrefScreen.preferenceCount
for (i in 0 until prefCount) {
val rootPref = settingsPrefScreen.getPreference(i)
if (rootPref.title == null) continue // no title, not a preference. (note: only info notes appear to not have titles)
getSettingSearchResult(ctrl, rootPref, "${settingsPrefScreen.title}")
}
}
}
}
fun getFilteredResults(query: String): List<SettingsSearchResult> {
return prefSearchResultList.filter {
val inTitle = it.title.contains(query, true)
val inSummary = it.summary.contains(query, true)
val inBreadcrumb = it.breadcrumb.contains(query, true)
return@filter inTitle || inSummary || inBreadcrumb
}
}
/**
* Extracts the data needed from a `Preference` to create a `SettingsSearchResult`, and then adds it to `prefSearchResultList`
* Future enhancement: make bold the text matched by the search query.
*/
private fun getSettingSearchResult(
ctrl: SettingsController,
pref: Preference,
breadcrumbs: String = ""
) {
when {
pref is PreferenceGroup -> {
val breadcrumbsStr = addLocalizedBreadcrumb(breadcrumbs, "${pref.title}")
for (x in 0 until pref.preferenceCount) {
val subPref = pref.getPreference(x)
getSettingSearchResult(ctrl, subPref, breadcrumbsStr) // recursion
}
}
pref is PreferenceCategory -> {
val breadcrumbsStr = addLocalizedBreadcrumb(breadcrumbs, "${pref.title}")
for (x in 0 until pref.preferenceCount) {
val subPref = pref.getPreference(x)
getSettingSearchResult(ctrl, subPref, breadcrumbsStr) // recursion
}
}
(pref.title != null && pref.isVisible) -> {
// Is an actual preference
val title = pref.title.toString()
// ListPreferences occasionally run into ArrayIndexOutOfBoundsException issues
val summary = try { pref.summary?.toString() ?: "" } catch (e: Throwable) { "" }
val breadcrumbsStr = addLocalizedBreadcrumb(breadcrumbs, "${pref.title}")
prefSearchResultList.add(
SettingsSearchResult(
key = pref.key,
title = title,
summary = summary,
breadcrumb = breadcrumbsStr,
searchController = ctrl
)
)
}
}
}
private fun addLocalizedBreadcrumb(path: String, node: String): String {
return if (Resources.getSystem().isLTR) {
// This locale reads left to right.
"$path > $node"
} else {
// This locale reads right to left.
"$node < $path"
}
}
data class SettingsSearchResult(
val key: String?,
val title: String,
val summary: String,
val breadcrumb: String,
val searchController: SettingsController
)
}
| apache-2.0 | 6cc1789c150fbcf495d5b5c6deffd212 | 40.164286 | 137 | 0.651917 | 5.205962 | false | false | false | false |
cmzy/okhttp | okhttp/src/test/java/okhttp3/RecordingExecutor.kt | 2 | 2186 | /*
* 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
import java.util.concurrent.AbstractExecutorService
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit
import okhttp3.internal.connection.RealCall
import okhttp3.internal.finishedAccessor
import org.assertj.core.api.Assertions.assertThat
internal class RecordingExecutor(
private val dispatcherTest: DispatcherTest
) : AbstractExecutorService() {
private var shutdown: Boolean = false
private val calls = mutableListOf<RealCall.AsyncCall>()
override fun execute(command: Runnable) {
if (shutdown) throw RejectedExecutionException()
calls.add(command as RealCall.AsyncCall)
}
fun assertJobs(vararg expectedUrls: String) {
val actualUrls = calls.map { it.request.url.toString() }
assertThat(actualUrls).containsExactly(*expectedUrls)
}
fun finishJob(url: String) {
val i = calls.iterator()
while (i.hasNext()) {
val call = i.next()
if (call.request.url.toString() == url) {
i.remove()
dispatcherTest.dispatcher.finishedAccessor(call)
return
}
}
throw AssertionError("No such job: $url")
}
override fun shutdown() {
shutdown = true
}
override fun shutdownNow(): List<Runnable> {
throw UnsupportedOperationException()
}
override fun isShutdown(): Boolean {
throw UnsupportedOperationException()
}
override fun isTerminated(): Boolean {
throw UnsupportedOperationException()
}
override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean {
throw UnsupportedOperationException()
}
}
| apache-2.0 | 38fd4b084b71a710a3d7cb06991e168e | 28.945205 | 75 | 0.729186 | 4.407258 | false | false | false | false |
meik99/CoffeeList | app/src/main/java/rynkbit/tk/coffeelist/db/facade/BaseFacade.kt | 1 | 2137 | package rynkbit.tk.coffeelist.db.facade
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import io.reactivex.schedulers.Schedulers
import org.koin.core.KoinComponent
import org.koin.core.inject
import rynkbit.tk.coffeelist.db.AppDatabase
import rynkbit.tk.coffeelist.db.dao.BaseDao
import java.lang.IllegalStateException
import java.util.*
abstract class BaseFacade<DatabaseEntity : Entity, Entity> : KoinComponent{
protected val appDatabase by inject<AppDatabase>()
private fun findDao(entityClass: Class<Entity>): BaseDao<DatabaseEntity> {
val daoMethod = appDatabase::class.java.declaredMethods.find {
it.name.toLowerCase(Locale.ROOT).contains(
entityClass.simpleName.toLowerCase(Locale.ROOT))
}
return daoMethod?.invoke(appDatabase) as BaseDao<DatabaseEntity>
}
protected fun findAll(entityClass: Class<Entity>): LiveData<List<Entity>>{
val liveData = MutableLiveData<List<Entity>>()
val dao = findDao(entityClass)
dao.findAll().map {
val entities = mutableListOf<Entity>()
it.forEach {
entities.add(it)
}
liveData.postValue(entities)
return@map it
}
.subscribe()
return liveData
}
protected fun delete(entity: DatabaseEntity, entityClass: Class<Entity>): LiveData<Unit> {
val liveData = MutableLiveData<Unit>()
findDao(entityClass)
.delete(entity)
.subscribeOn(Schedulers.newThread())
.map {
liveData.postValue(Unit)
}
.subscribe()
return liveData
}
protected fun update(entity: DatabaseEntity, entityClass: Class<Entity>): LiveData<Unit> {
val liveData = MutableLiveData<Unit>()
findDao(entityClass)
.update(entity)
.subscribeOn(Schedulers.newThread())
.map {
liveData.postValue(Unit)
}
.subscribe()
return liveData
}
} | mit | e1455d416b7d94b628b833f0a12f531a | 30.441176 | 94 | 0.620028 | 5.063981 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/AddAnotherBookmarkAction.kt | 4 | 1142 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.LineBookmark
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
internal class AddAnotherBookmarkAction : DumbAwareAction(BookmarkBundle.messagePointer("bookmark.add.another.action.text")) {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = process(event, false)
}
override fun actionPerformed(event: AnActionEvent) {
process(event, true)
}
private fun process(event: AnActionEvent, perform: Boolean): Boolean {
val manager = event.bookmarksManager ?: return false
val bookmark = event.contextBookmark ?: return false
if (bookmark is LineBookmark) return false
val type = manager.getType(bookmark) ?: return false
if (perform) manager.add(bookmark, type)
return true
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | ec48a02aa4aed6d3c47242f4b35c6b24 | 35.83871 | 158 | 0.769702 | 4.531746 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToStringWithStringTemplateInspection.kt | 2 | 1656 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible
import org.jetbrains.kotlin.idea.intentions.isToString
import org.jetbrains.kotlin.psi.*
class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression !is KtReferenceExpression) return false
if (element.parent is KtBlockStringTemplateEntry) return false
return element.isToString()
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val variable = element.receiverExpression.text
val replaced = element.replace(KtPsiFactory(element).createExpression("\"\${$variable}\""))
val blockStringTemplateEntry = (replaced as? KtStringTemplateExpression)?.entries?.firstOrNull() as? KtBlockStringTemplateEntry
blockStringTemplateEntry?.dropCurlyBracketsIfPossible()
}
override fun inspectionText(element: KtDotQualifiedExpression) =
KotlinBundle.message("inspection.replace.to.string.with.string.template.display.name")
override val defaultFixText get() = KotlinBundle.message("replace.tostring.with.string.template")
} | apache-2.0 | 0b0d7b7efca2370f3f0f4e6bd1ab6a2e | 50.78125 | 158 | 0.788647 | 5.273885 | false | false | false | false |
atfox7/KotlinSealedUnions | src/main/kotlin/io/andyfox/unions/Union6.kt | 1 | 3659 | /*
* Copyright (c) andyfox 2016
*
* 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.andyfox.unions
sealed class Union6<out First, out Second, out Third, out Fourth, out Fifth, out Sixth> {
companion object {
@JvmStatic
fun <First> first(value: First): Union6<First, Nothing, Nothing, Nothing, Nothing, Nothing> = Union6First(value)
@JvmStatic
fun <Second> second(value: Second): Union6<Nothing, Second, Nothing, Nothing, Nothing, Nothing> = Union6Second(value)
@JvmStatic
fun <Third> third(value: Third): Union6<Nothing, Nothing, Third, Nothing, Nothing, Nothing> = Union6Third(value)
@JvmStatic
fun <Fourth> fourth(value: Fourth): Union6<Nothing, Nothing, Nothing, Fourth, Nothing, Nothing> = Union6Fourth(value)
@JvmStatic
fun <Fifth> fifth(value: Fifth): Union6<Nothing, Nothing, Nothing, Nothing, Fifth, Nothing> = Union6Fifth(value)
@JvmStatic
fun <Sixth> sixth(value: Sixth): Union6<Nothing, Nothing, Nothing, Nothing, Nothing, Sixth> = Union6Sixth(value)
}
inline fun <R> join(mapFirst: (First) -> R,
mapSecond: (Second) -> R,
mapThird: (Third) -> R,
mapFourth: (Fourth) -> R,
mapFifth: (Fifth) -> R,
mapSixth: (Sixth) -> R): R =
when (this) {
is Union6First -> mapFirst(value)
is Union6Second -> mapSecond(value)
is Union6Third -> mapThird(value)
is Union6Fourth -> mapFourth(value)
is Union6Fifth -> mapFifth(value)
is Union6Sixth -> mapSixth(value)
}
inline fun continued(continuationFirst: (First) -> Unit,
continuationSecond: (Second) -> Unit,
continuationThird: (Third) -> Unit,
continuationFourth: (Fourth) -> Unit,
continuationFifth: (Fifth) -> Unit,
continuationSixth: (Sixth) -> Unit) {
when (this) {
is Union6First -> continuationFirst(value)
is Union6Second -> continuationSecond(value)
is Union6Third -> continuationThird(value)
is Union6Fourth -> continuationFourth(value)
is Union6Fifth -> continuationFifth(value)
is Union6Sixth -> continuationSixth(value)
}
}
data class Union6First<out First>(@PublishedApi internal val value: First) : Union6<First, Nothing, Nothing, Nothing, Nothing, Nothing>()
data class Union6Second<out Second>(@PublishedApi internal val value: Second) : Union6<Nothing, Second, Nothing, Nothing, Nothing, Nothing>()
data class Union6Third<out Third>(@PublishedApi internal val value: Third) : Union6<Nothing, Nothing, Third, Nothing, Nothing, Nothing>()
data class Union6Fourth<out Fourth>(@PublishedApi internal val value: Fourth) : Union6<Nothing, Nothing, Nothing, Fourth, Nothing, Nothing>()
data class Union6Fifth<out Fifth>(@PublishedApi internal val value: Fifth) : Union6<Nothing, Nothing, Nothing, Nothing, Fifth, Nothing>()
data class Union6Sixth<out Sixth>(@PublishedApi internal val value: Sixth) : Union6<Nothing, Nothing, Nothing, Nothing, Nothing, Sixth>()
} | apache-2.0 | c110aebdd24f2de3b6b9291714a71c12 | 42.058824 | 143 | 0.665756 | 4.003282 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/data/CollegeRoleServiceImpl.kt | 1 | 2155 | package top.zbeboy.isy.service.data
import org.jooq.DSLContext
import org.jooq.Record
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import top.zbeboy.isy.domain.tables.daos.CollegeRoleDao
import javax.annotation.Resource
import top.zbeboy.isy.domain.Tables.COLLEGE_ROLE
import top.zbeboy.isy.domain.tables.pojos.CollegeRole
import top.zbeboy.isy.domain.tables.records.CollegeRoleRecord
import java.util.*
/**
* Created by zbeboy 2017-12-02 .
**/
@Service("collegeRoleService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class CollegeRoleServiceImpl @Autowired constructor(dslContext: DSLContext) : CollegeRoleService{
private val create: DSLContext = dslContext
@Resource
open lateinit var collegeRoleDao: CollegeRoleDao
override fun findByCollegeId(collegeId: Int): List<CollegeRoleRecord> {
return create.selectFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.COLLEGE_ID.eq(collegeId))
.fetch()
}
override fun findByCollegeIdAndAllowAgent(collegeId: Int, allowAgent: Byte?): List<CollegeRoleRecord> {
return create.selectFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.COLLEGE_ID.eq(collegeId).and(COLLEGE_ROLE.ALLOW_AGENT.eq(allowAgent)))
.fetch()
}
override fun findByRoleId(roleId: String): Optional<Record> {
return create.select()
.from(COLLEGE_ROLE)
.where(COLLEGE_ROLE.ROLE_ID.eq(roleId))
.fetchOptional()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(collegeRole: CollegeRole) {
collegeRoleDao.insert(collegeRole)
}
override fun update(collegeRole: CollegeRole) {
collegeRoleDao.update(collegeRole)
}
override fun deleteByRoleId(roleId: String) {
create.deleteFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.ROLE_ID.eq(roleId))
.execute()
}
} | mit | 4b00f143798539f3bb2b168651234899 | 33.222222 | 107 | 0.715545 | 4.217221 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/execution/filters/ArgumentFileFilter.kt | 3 | 1338 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.filters
import java.io.File
import java.nio.charset.Charset
/**
* A console filter which looks for a given path in an output and creates a link for viewing a content of that file.
*/
class ArgumentFileFilter() : Filter {
@Volatile private var filePath: String? = null
@Volatile private var fileText: String? = null
private var triggered = false
constructor(filePath: String?, fileText: String?) : this() {
this.filePath = filePath
this.fileText = fileText
}
@JvmOverloads
fun setPath(path: String, charset: Charset = Charsets.UTF_8) {
filePath = path
fileText = File(path).readText(charset)
}
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
if (!triggered) {
val path = this.filePath
val text = this.fileText
if (path == null || text == null) {
triggered = true
}
else {
val p = line.indexOf(path)
if (p > 0) {
triggered = true
val offset = entireLength - line.length + p
return Filter.Result(offset, offset + path.length, ShowTextPopupHyperlinkInfo(path, text))
}
}
}
return null
}
} | apache-2.0 | ee9800a2b98d559ad738650c1c6ebe5a | 28.755556 | 140 | 0.656951 | 4.104294 | false | false | false | false |
paplorinc/intellij-community | plugins/git4idea/src/git4idea/rebase/GitRewordAction.kt | 2 | 6574 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.rebase
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil.DEFAULT_HGAP
import com.intellij.util.ui.UIUtil.DEFAULT_VGAP
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsShortCommitDetails
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.VcsCommitMetadataImpl
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.VcsUserUtil.getShortPresentation
import git4idea.findProtectedRemoteBranch
import git4idea.repo.GitRepository
private val LOG: Logger = logger<GitRewordAction>()
class GitRewordAction : GitCommitEditingAction() {
override fun update(e: AnActionEvent) {
super.update(e)
prohibitRebaseDuringRebase(e, "reword", true)
}
override fun actionPerformedAfterChecks(e: AnActionEvent) {
val commit = getSelectedCommit(e)
val project = e.project!!
val repository = getRepository(e)
val details = getOrLoadDetails(project, getLogData(e), commit)
RewordDialog(project, getLogData(e), details, repository).show()
}
private fun getOrLoadDetails(project: Project, data: VcsLogData, commit: VcsShortCommitDetails): VcsCommitMetadata {
return commit as? VcsCommitMetadata
?: getCommitDataFromCache(data, commit)
?: loadCommitData(project, data, commit)
?: throw ProcessCanceledException()
}
override fun getFailureTitle(): String = "Couldn't Reword Commit"
private fun getCommitDataFromCache(data: VcsLogData, commit: VcsShortCommitDetails): VcsCommitMetadata? {
val commitIndex = data.getCommitIndex(commit.id, commit.root)
val commitData = data.commitDetailsGetter.getCommitDataIfAvailable(commitIndex)
if (commitData != null) return commitData
val message = data.index.dataGetter?.getFullMessage(commitIndex)
if (message != null) return VcsCommitMetadataImpl(commit.id, commit.parents, commit.commitTime, commit.root, commit.subject,
commit.author, message, commit.committer, commit.authorTime)
return null
}
private fun loadCommitData(project: Project, data: VcsLogData, commit: VcsShortCommitDetails): VcsCommitMetadata? {
var commitData: VcsCommitMetadata? = null
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
try {
commitData = VcsLogUtil.getDetails(data, commit.root, commit.id)
}
catch (e: VcsException) {
val error = "Couldn't load changes of " + commit.id.asString()
LOG.warn(error, e)
val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(
"", error, NotificationType.ERROR, null)
VcsNotifier.getInstance(project).notify(notification)
}
}, "Loading Commit Message", true, project)
return commitData
}
private fun rewordInBackground(project: Project, commit: VcsCommitMetadata, repository: GitRepository, newMessage: String) {
object : Task.Backgroundable(project, "Rewording") {
override fun run(indicator: ProgressIndicator) {
GitRewordOperation(repository, commit, newMessage).execute()
}
}.queue()
}
private inner class RewordDialog(val project: Project, val data: VcsLogData, val commit: VcsCommitMetadata, val repository: GitRepository)
: DialogWrapper(project, true) {
val originalHEAD = repository.info.currentRevision
val commitEditor = createCommitEditor()
init {
init()
isModal = false
title = "Reword Commit"
}
override fun createCenterPanel() =
JBUI.Panels.simplePanel(DEFAULT_HGAP, DEFAULT_VGAP)
.addToTop(JBLabel("Edit message for commit ${commit.id.toShortString()} by ${getShortPresentation(commit.author)}"))
.addToCenter(commitEditor)
override fun getPreferredFocusedComponent() = commitEditor.editorField
override fun getDimensionServiceKey() = "GitRewordDialog"
private fun createCommitEditor(): CommitMessage {
val editor = CommitMessage(project, false, false, true)
editor.setText(commit.fullMessage)
editor.editorField.setCaretPosition(0)
editor.editorField.addSettingsProvider { editor ->
// display at least several rows for one-line messages
val MIN_ROWS = 3
if ((editor as EditorImpl).visibleLineCount < MIN_ROWS) {
verticalStretch = 1.5F
}
}
return editor
}
override fun doValidate(): ValidationInfo? {
if (repository.info.currentRevision != originalHEAD ||
Disposer.isDisposed(data)) {
return ValidationInfo("Can't reword commit: repository state was changed")
}
val branches = findContainingBranches(data, commit.root, commit.id)
val protectedBranch = findProtectedRemoteBranch(repository, branches)
if (protectedBranch != null) {
return ValidationInfo("Can't reword commit: " + commitPushedToProtectedBranchError(protectedBranch))
}
return null
}
override fun doOKAction() {
super.doOKAction()
rewordInBackground(project, commit, repository, commitEditor.comment)
}
}
} | apache-2.0 | b212ce462f51a6e3898fac55c8339875 | 38.608434 | 140 | 0.735929 | 4.574809 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/chain/AbstractCallChainHintsProvider.kt | 1 | 7923 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.chain
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.hints.*
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.layout.panel
import com.intellij.util.asSafely
import com.intellij.util.ui.JBUI
import javax.swing.JPanel
import javax.swing.JSpinner
import javax.swing.text.DefaultFormatter
abstract class AbstractCallChainHintsProvider<DotQualifiedExpression : PsiElement, ExpressionType, TypeComputationContext> :
InlayHintsProvider<AbstractCallChainHintsProvider.Settings> {
protected data class ExpressionWithType<ExpressionType>(val expression: PsiElement, val type: ExpressionType)
override fun getCollectorFor(file: PsiFile, editor: Editor, settings: Settings, sink: InlayHintsSink): InlayHintsCollector? {
if (file.project.isDefault) return null
return object : FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (file.project.service<DumbService>().isDumb) return true
processInlayElements(element, settings, sink, factory)
return true
}
}
}
protected open fun addInlayElementsAdapter(context: TypeComputationContext,
elements: List<ExpressionWithType<ExpressionType>>,
sink: InlayHintsSink,
factory: PresentationFactory,
offset: Int = 0) {
addInlayElementsToSink(context, elements, sink, factory, offset)
}
protected fun processInlayElements(element: PsiElement,
settings: Settings,
sink: InlayHintsSink,
factory: PresentationFactory,
offset: Int = 0) {
val topmostDotQualifiedExpression = element.safeCastUsing(dotQualifiedClass)
// We will process the whole chain using topmost DotQualifiedExpression.
// If the current one has parent then it means that it's not topmost DotQualifiedExpression
?.takeIf { it.getParentDotQualifiedExpression() == null }
?: return
val context = getTypeComputationContext(topmostDotQualifiedExpression)
val reversedChain = topmostDotQualifiedExpression.assembleChainCall(context)
if (reversedChain == null) return
if (reversedChain.asSequence().distinctBy { it.type }.count() < settings.uniqueTypeCount) return
addInlayElementsAdapter(context, reversedChain, sink, factory, offset)
}
protected fun addInlayElementsToSink(context: TypeComputationContext,
elements: List<ExpressionWithType<ExpressionType>>,
sink: InlayHintsSink,
factory: PresentationFactory,
offset: Int = 0) {
if (elements.isEmpty()) return
val project = elements.first().expression.project
for ((expression, type) in elements) {
sink.addInlineElement(
expression.textRange.endOffset + offset,
true,
type.getInlayPresentation(expression, factory, project, context),
false
)
}
}
override val name: String
get() = CodeInsightBundle.message("inlay.hints.chain.call.chain")
final override fun createConfigurable(settings: Settings): ImmediateConfigurable = object : ImmediateConfigurable {
val uniqueTypeCountName = CodeInsightBundle.message("inlay.hints.chain.minimal.unique.type.count.to.show.hints")
private val uniqueTypeCount = JBIntSpinner(1, 1, 10)
override fun createComponent(listener: ChangeListener): JPanel {
reset()
// Workaround to get immediate change, not only when focus is lost. To be changed after moving to polling model
val formatter = (uniqueTypeCount.editor as JSpinner.NumberEditor).textField.formatter as DefaultFormatter
formatter.commitsOnValidEdit = true
uniqueTypeCount.addChangeListener {
handleChange(listener)
}
val panel = panel {
row {
label(uniqueTypeCountName)
uniqueTypeCount(pushX)
}
}
panel.border = JBUI.Borders.empty(5)
return panel
}
override fun reset() {
uniqueTypeCount.value = settings.uniqueTypeCount
}
private fun handleChange(listener: ChangeListener) {
settings.uniqueTypeCount = uniqueTypeCount.number
listener.settingsChanged()
}
}
private fun DotQualifiedExpression.assembleChainCall(context: TypeComputationContext): List<ExpressionWithType<ExpressionType>>? {
var someTypeIsUnknown = false
val reversedChain =
generateSequence<PsiElement>(this) {
it.skipParenthesesAndPostfixOperatorsDown()?.safeCastUsing(dotQualifiedClass)?.getReceiver()
}
.drop(1) // Except last to avoid builder.build() which has obvious type
.filter { it.nextSibling.asSafely<PsiWhiteSpace>()?.textContains('\n') == true }
.map { it to it.getType(context) }
.takeWhile { (_, type) -> (type != null).also { if (!it) someTypeIsUnknown = true } }
.map { (expression, type) -> ExpressionWithType<ExpressionType>(expression, type!!) }
.windowed(2, partialWindows = true) { it.first() to it.getOrNull(1) }
.filter { (expressionWithType, prevExpressionWithType) ->
if (prevExpressionWithType == null) {
// Show type for expression in call chain on the first line only if it's dot qualified
dotQualifiedClass.isInstance(expressionWithType.expression.skipParenthesesAndPostfixOperatorsDown())
}
else {
expressionWithType.type != prevExpressionWithType.type ||
!dotQualifiedClass.isInstance(prevExpressionWithType.expression.skipParenthesesAndPostfixOperatorsDown())
}
}
.map { it.first }
.toList()
return if (someTypeIsUnknown) null else reversedChain
}
protected abstract fun ExpressionType.getInlayPresentation(
expression: PsiElement,
factory: PresentationFactory,
project: Project,
context: TypeComputationContext
): InlayPresentation
protected abstract fun PsiElement.getType(context: TypeComputationContext): ExpressionType?
protected abstract val dotQualifiedClass: Class<DotQualifiedExpression>
/**
* Implementation must NOT skip parentheses and postfix operators
*/
protected abstract fun DotQualifiedExpression.getReceiver(): PsiElement?
protected abstract fun DotQualifiedExpression.getParentDotQualifiedExpression(): DotQualifiedExpression?
protected abstract fun PsiElement.skipParenthesesAndPostfixOperatorsDown(): PsiElement?
protected abstract fun getTypeComputationContext(topmostDotQualifiedExpression: DotQualifiedExpression): TypeComputationContext
private fun <T> Any.safeCastUsing(clazz: Class<T>) = if (clazz.isInstance(this)) clazz.cast(this) else null
final override fun createSettings() = Settings()
data class Settings(var uniqueTypeCount: Int) {
constructor() : this(2)
}
}
| apache-2.0 | 9fe73a3b830daa0812bc89cf4b761c7c | 43.511236 | 158 | 0.689638 | 5.289052 | false | false | false | false |
JetBrains/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemComponentFactory.kt | 1 | 12381 | // 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 org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.collaboration.ui.codereview.onHyperlinkActivated
import com.intellij.collaboration.ui.codereview.setHtmlBody
import com.intellij.collaboration.ui.codereview.timeline.StatusMessageComponentFactory
import com.intellij.collaboration.ui.codereview.timeline.StatusMessageType
import com.intellij.collaboration.ui.codereview.timeline.TimelineItemComponentFactory
import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.newui.HorizontalLayout
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.util.text.buildChildren
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.text.JBDateFormat
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GHActor
import org.jetbrains.plugins.github.api.data.GHIssueComment
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewState.*
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.comment.convertToHtml
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadComponent
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRCommentsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDetailsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider
import org.jetbrains.plugins.github.pullrequest.ui.GHEditableHtmlPaneHandle
import org.jetbrains.plugins.github.pullrequest.ui.GHTextActions
import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRSuggestedChangeHelper
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import java.util.*
import javax.swing.JComponent
import javax.swing.JPanel
class GHPRTimelineItemComponentFactory(private val project: Project,
private val detailsDataProvider: GHPRDetailsDataProvider,
private val commentsDataProvider: GHPRCommentsDataProvider,
private val reviewDataProvider: GHPRReviewDataProvider,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val reviewsThreadsModelsProvider: GHPRReviewsThreadsModelsProvider,
private val reviewDiffComponentFactory: GHPRReviewThreadDiffComponentFactory,
private val selectInToolWindowHelper: GHPRSelectInToolWindowHelper,
private val suggestedChangeHelper: GHPRSuggestedChangeHelper,
private val ghostUser: GHUser,
private val prAuthor: GHActor?,
private val currentUser: GHUser) : TimelineItemComponentFactory<GHPRTimelineItem> {
private val eventComponentFactory = GHPRTimelineEventComponentFactoryImpl(avatarIconsProvider, ghostUser)
override fun createComponent(item: GHPRTimelineItem): JComponent {
try {
return when (item) {
is GHPullRequestCommitShort -> createComponent(listOf(item))
is GHPRTimelineGroupedCommits -> createComponent(item.items)
is GHIssueComment -> createComponent(item)
is GHPullRequestReview -> createComponent(item)
is GHPRTimelineEvent -> eventComponentFactory.createComponent(item)
is GHPRTimelineItem.Unknown -> throw IllegalStateException("Unknown item type: " + item.__typename)
else -> error("Undefined item type")
}
}
catch (e: Exception) {
LOG.warn(e)
return createItem(prAuthor, null, HtmlEditorPane(GithubBundle.message("cannot.display.item", e.message ?: "")))
}
}
private fun createComponent(commits: List<GHPullRequestCommitShort>): JComponent {
val commitsPanels = commits.asSequence()
.map { it.commit }
.map {
val builder = HtmlBuilder()
.append(HtmlChunk.p()
.children(
HtmlChunk.link("$COMMIT_HREF_PREFIX${it.abbreviatedOid}", it.abbreviatedOid),
HtmlChunk.nbsp(),
HtmlChunk.raw(it.messageHeadlineHTML)
))
val author = it.author
if (author != null) {
val actor = author.user ?: ghostUser
val date = author.date
val chunk = HtmlChunk.p().buildChildren {
append(HtmlChunk.link(actor.url, actor.getPresentableName()))
if (date != null) {
append(HtmlChunk.nbsp())
append(JBDateFormat.getFormatter().formatPrettyDateTime(date))
}
}
builder.append(chunk)
}
builder.toString()
}.map { text ->
HtmlEditorPane(text).apply {
removeHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
onHyperlinkActivated {
val href = it.description
if (href.startsWith(COMMIT_HREF_PREFIX)) {
selectInToolWindowHelper.selectCommit(href.removePrefix(COMMIT_HREF_PREFIX))
}
else {
BrowserUtil.browse(href)
}
}
}
}.fold(JPanel(VerticalLayout(4)).apply { isOpaque = false }) { panel, commitPane ->
panel.apply {
add(commitPane)
}
}
val commitsCount = commits.size
val contentPanel = JPanel(VerticalLayout(4)).apply {
isOpaque = false
val titleText = if (commitsCount == 1) {
GithubBundle.message("pull.request.timeline.commit.added")
}
else {
GithubBundle.message("pull.request.timeline.commits.added", commitsCount)
}
add(HtmlEditorPane(titleText))
add(StatusMessageComponentFactory.create(commitsPanels))
}
val actor = commits.singleOrNull()?.commit?.author?.user ?: prAuthor ?: ghostUser
return createItem(actor, commits.singleOrNull()?.commit?.author?.date, contentPanel)
}
fun createComponent(details: GHPullRequestShort): JComponent {
val contentPanel: JPanel?
val actionsPanel: JPanel?
if (details is GHPullRequest) {
val textPane = HtmlEditorPane(details.body.convertToHtml(project))
val panelHandle = GHEditableHtmlPaneHandle(project, textPane, details::body) { newText ->
detailsDataProvider.updateDetails(EmptyProgressIndicator(), description = newText)
.successOnEdt { textPane.setHtmlBody(it.body.convertToHtml(project)) }
}
contentPanel = panelHandle.panel
actionsPanel = if (details.viewerCanUpdate) NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
add(GHTextActions.createEditButton(panelHandle))
}
else null
}
else {
contentPanel = null
actionsPanel = null
}
return createItem(details.author, details.createdAt, contentPanel ?: JPanel(null), actionsPanel)
}
private fun createComponent(comment: GHIssueComment): JComponent {
val textPane = HtmlEditorPane(comment.body.convertToHtml(project))
val panelHandle = GHEditableHtmlPaneHandle(project, textPane, comment::body) { newText ->
commentsDataProvider.updateComment(EmptyProgressIndicator(), comment.id, newText)
.successOnEdt { textPane.setHtmlBody(it.convertToHtml(project)) }
}
val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
if (comment.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle))
if (comment.viewerCanDelete) add(GHTextActions.createDeleteButton {
commentsDataProvider.deleteComment(EmptyProgressIndicator(), comment.id)
})
}
return createItem(comment.author, comment.createdAt, panelHandle.panel, actionsPanel)
}
private fun createComponent(review: GHPullRequestReview): JComponent {
val reviewThreadsModel = reviewsThreadsModelsProvider.getReviewThreadsModel(review.id)
val panelHandle: GHEditableHtmlPaneHandle?
if (review.body.isNotEmpty()) {
val textPane = HtmlEditorPane(review.body.convertToHtml(project))
panelHandle =
GHEditableHtmlPaneHandle(project, textPane, review::body, { newText ->
reviewDataProvider.updateReviewBody(EmptyProgressIndicator(), review.id, newText)
.successOnEdt { textPane.setHtmlBody(it.convertToHtml(project)) }
})
}
else {
panelHandle = null
}
val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
if (panelHandle != null && review.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle))
}
val stateText = when (review.state) {
APPROVED -> GithubBundle.message("pull.request.timeline.approved.changes")
CHANGES_REQUESTED -> GithubBundle.message("pull.request.timeline.requested.changes")
PENDING -> GithubBundle.message("pull.request.timeline.started.review")
COMMENTED, DISMISSED -> GithubBundle.message("pull.request.timeline.reviewed")
}
val stateType = when (review.state) {
APPROVED -> StatusMessageType.SUCCESS
CHANGES_REQUESTED -> StatusMessageType.ERROR
PENDING -> StatusMessageType.SECONDARY_INFO
COMMENTED, DISMISSED -> StatusMessageType.INFO
}
val contentPanel = JPanel(null).apply {
isOpaque = false
layout = MigLayout(LC()
.fillX()
.flowY()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
if (panelHandle != null) {
val commentPanel = panelHandle.panel
add(commentPanel, CC().grow().push()
.minWidth("0").maxWidth("${GHPRTimelineItemUIUtil.maxTimelineItemTextWidth}"))
}
add(StatusMessageComponentFactory.create(HtmlEditorPane(stateText), stateType), CC().grow().push()
.minWidth("0").maxWidth("${GHPRTimelineItemUIUtil.maxTimelineItemTextWidth}"))
val threadsPanel = GHPRReviewThreadsPanel.create(reviewThreadsModel) {
GHPRReviewThreadComponent.createWithDiff(project, it,
reviewDataProvider, avatarIconsProvider,
reviewDiffComponentFactory,
selectInToolWindowHelper, suggestedChangeHelper,
currentUser)
}
add(threadsPanel, CC().grow().push()
.minWidth("0")
.gapTop("${JBUIScale.scale(8)}"))
}
return GHPRTimelineItemUIUtil.createItem(avatarIconsProvider, review.author ?: ghostUser, review.createdAt,
contentPanel, Int.MAX_VALUE, actionsPanel)
}
private fun createItem(actor: GHActor?, date: Date?, content: JComponent, actionsPanel: JComponent? = null): JComponent =
GHPRTimelineItemUIUtil.createItem(avatarIconsProvider, actor ?: ghostUser, date, content, actionsPanel)
companion object {
private val LOG = logger<GHPRTimelineItemComponentFactory>()
private const val COMMIT_HREF_PREFIX = "commit://"
}
} | apache-2.0 | 2434707193e5ed6f66d0a04dc70abf18 | 46.623077 | 140 | 0.695097 | 5.145885 | false | false | false | false |
allotria/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeFileTracker.kt | 1 | 6065 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.schemeManager
import com.intellij.configurationStore.LOG
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.configurationStore.StoreReloadManagerImpl
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.io.systemIndependentPath
internal class SchemeFileTracker(private val schemeManager: SchemeManagerImpl<Any, Any>, private val project: Project) : BulkFileListener {
private val applicator = SchemeChangeApplicator(schemeManager)
override fun after(events: List<VFileEvent>) {
val list = SmartList<SchemeChangeEvent>()
for (event in events) {
if (event.requestor is SchemeManagerImpl<*, *>) {
continue
}
when (event) {
is VFileContentChangeEvent -> {
val file = event.file
if (isMyFileWithoutParentCheck(file) && file.parent != null && isMyDirectory(file.parent)) {
LOG.debug { "CHANGED ${file.path}" }
list.add(UpdateScheme(file))
}
}
is VFileCreateEvent -> {
if (event.isDirectory) {
handleDirectoryCreated(event, list)
}
else if (schemeManager.canRead(event.childName) && isMyDirectory(event.parent)) {
val virtualFile = event.file
LOG.debug { "CREATED ${event.path} (virtualFile: ${if (virtualFile == null) "not " else ""}found)" }
virtualFile?.let {
list.add(AddScheme(it))
}
}
}
is VFileDeleteEvent -> {
val file = event.file
if (file.isDirectory) {
handleDirectoryDeleted(file, list)
}
else if (isMyFileWithoutParentCheck(file) && isMyDirectory(file.parent)) {
LOG.debug { "DELETED ${file.path}" }
list.add(RemoveScheme(file.name))
}
}
}
}
if (list.isNotEmpty()) {
(StoreReloadManager.getInstance() as StoreReloadManagerImpl).registerChangedSchemes(list, applicator, project)
}
}
private fun isMyFileWithoutParentCheck(file: VirtualFile) = schemeManager.canRead(file.nameSequence)
@Suppress("MoveVariableDeclarationIntoWhen")
private fun isMyDirectory(parent: VirtualFile): Boolean {
val virtualDirectory = schemeManager.cachedVirtualDirectory
return when (virtualDirectory) {
null -> schemeManager.ioDirectory.systemIndependentPath == parent.path
else -> virtualDirectory == parent
}
}
private fun handleDirectoryDeleted(file: VirtualFile, list: SmartList<SchemeChangeEvent>) {
if (!StringUtil.equals(file.nameSequence, schemeManager.ioDirectory.fileName.toString())) {
return
}
LOG.debug { "DIR DELETED ${file.path}" }
if (file == schemeManager.getVirtualDirectory(StateStorageOperation.READ)) {
list.add(RemoveAllSchemes())
}
}
private fun handleDirectoryCreated(event: VFileCreateEvent, list: MutableList<SchemeChangeEvent>) {
if (event.childName != schemeManager.ioDirectory.fileName.toString()) {
return
}
val dir = schemeManager.getVirtualDirectory(StateStorageOperation.READ)
val virtualFile = event.file
if (virtualFile != dir) {
return
}
LOG.debug { "DIR CREATED ${virtualFile?.path}" }
for (file in dir!!.children) {
if (isMyFileWithoutParentCheck(file)) {
list.add(AddScheme(file))
}
}
}
}
internal data class UpdateScheme(override val file: VirtualFile) : SchemeChangeEvent, SchemeAddOrUpdateEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
}
}
private data class AddScheme(override val file: VirtualFile) : SchemeChangeEvent, SchemeAddOrUpdateEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
if (!file.isValid) {
return
}
val readScheme = readSchemeFromFile(file, schemaLoader.value, schemeManager) ?: return
val readSchemeKey = schemeManager.processor.getSchemeKey(readScheme)
val existingScheme = schemeManager.findSchemeByName(readSchemeKey) ?: return
if (schemeManager.schemeListManager.readOnlyExternalizableSchemes.get(
schemeManager.processor.getSchemeKey(existingScheme)) !== existingScheme) {
LOG.warn("Ignore incorrect VFS create scheme event: schema $readSchemeKey is already exists")
return
}
}
}
internal data class RemoveScheme(val fileName: String) : SchemeChangeEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
LOG.assertTrue(!schemaLoader.isInitialized())
// do not schedule scheme file removing because file was already removed
val scheme = schemeManager.removeFirstScheme(isScheduleToDelete = false) {
fileName == getSchemeFileName(schemeManager, it)
} ?: return
schemeManager.processor.onSchemeDeleted(scheme)
}
}
internal class RemoveAllSchemes : SchemeChangeEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
LOG.assertTrue(!schemaLoader.isInitialized())
schemeManager.cachedVirtualDirectory = null
// do not schedule scheme file removing because files were already removed
schemeManager.removeExternalizableSchemesFromRuntimeState()
}
} | apache-2.0 | 7f7c260a7f55aea23f2b6f788fdee9c8 | 38.38961 | 140 | 0.71789 | 4.708851 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/view/OtherAlertListItem.kt | 1 | 1474 | package jp.cordea.mackerelclient.view
import android.content.Context
import com.xwray.groupie.databinding.BindableItem
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.databinding.ListItemOtherAlertBinding
import jp.cordea.mackerelclient.model.DisplayableAlert
import jp.cordea.mackerelclient.navigator.OtherAlertNavigator
import jp.cordea.mackerelclient.toRelativeTime
import javax.inject.Inject
class OtherAlertListItem @Inject constructor(
private val navigator: OtherAlertNavigator
) : BindableItem<ListItemOtherAlertBinding>() {
private lateinit var model: OtherAlertListItemModel
fun update(model: OtherAlertListItemModel) = apply {
this.model = model
}
override fun getLayout(): Int = R.layout.list_item_other_alert
override fun bind(binding: ListItemOtherAlertBinding, position: Int) {
binding.model = model
binding.statusView.char = model.statusChar
binding.root.setOnClickListener {
navigator.navigateToDetail(model.alert)
}
}
}
class OtherAlertListItemModel(
val alert: DisplayableAlert
) {
fun getName(context: Context) =
"${alert.hostName} - ${alert.openedAt.toRelativeTime(context, System.currentTimeMillis())}"
val statusChar get() = alert.status.first()
val availableState get() = alert.value != null
val state get() = "${alert.value} ${alert.operator} ${alert.warning}"
val type get() = alert.monitorName ?: alert.type
}
| apache-2.0 | 2df45572a9133f7166394ce3f0ed8958 | 34.095238 | 99 | 0.746269 | 4.360947 | false | false | false | false |
zdary/intellij-community | plugins/git4idea/src/git4idea/revert/GitRevertOperation.kt | 2 | 2524 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.revert
import com.intellij.openapi.project.Project
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsFullCommitDetails
import git4idea.GitApplyChangesProcess
import git4idea.commands.Git
import git4idea.commands.GitCommandResult
import git4idea.commands.GitLineHandlerListener
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
/**
* Commits should be provided in the "UI" order, i.e. as if `git log --date-order` is called, i.e. in reverse-chronological order.
*/
class GitRevertOperation(private val project: Project,
private val commits: List<VcsFullCommitDetails>,
private val autoCommit: Boolean) {
private val git = Git.getInstance()
fun execute() {
GitApplyChangesProcess(project, commits, autoCommit, GitBundle.message("revert.operation.name"),
GitBundle.message("revert.operation.applied"),
command = { repository, commit, autoCommit, listeners ->
doRevert(autoCommit, repository, commit, listeners)
},
emptyCommitDetector = { result -> result.outputAsJoinedString.contains("nothing to commit") },
defaultCommitMessageGenerator = { _, commit ->
"""
Revert "${commit.subject}"
This reverts commit ${commit.id.toShortString()}""".trimIndent()
},
preserveCommitMetadata = false).execute()
}
private fun doRevert(autoCommit: Boolean,
repository: GitRepository,
hash: Hash,
listeners: List<GitLineHandlerListener>): GitCommandResult {
return git.revert(repository, hash.asString(), autoCommit, *listeners.toTypedArray())
}
} | apache-2.0 | f8217292254b49cf62a18f5e17e6e989 | 42.534483 | 130 | 0.641442 | 4.988142 | false | false | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/query/CaseCondition.kt | 1 | 2023 | package com.dbflow5.query
import com.dbflow5.query.property.IProperty
import com.dbflow5.sql.Query
/**
* Description: Represents an individual condition inside a CASE.
*/
class CaseCondition<TReturn> : Query {
private val caze: Case<TReturn>
private val whenValue: TReturn?
private val sqlOperator: SQLOperator?
private var thenValue: TReturn? = null
private val property: IProperty<*>?
private var thenProperty: IProperty<*>? = null
private var isThenPropertySet: Boolean = false
override val query: String
get() = buildString {
append(" WHEN ")
if (caze.isEfficientCase) {
append(BaseOperator.convertValueToString(property ?: whenValue, false))
} else {
sqlOperator?.appendConditionToQuery(this)
}
append(" THEN ")
append(BaseOperator.convertValueToString(
if (isThenPropertySet) thenProperty else thenValue, false))
}
internal constructor(caze: Case<TReturn>, sqlOperator: SQLOperator) {
this.caze = caze
this.sqlOperator = sqlOperator
this.whenValue = null
this.property = null
}
internal constructor(caze: Case<TReturn>, whenValue: TReturn?) {
this.caze = caze
this.whenValue = whenValue
this.sqlOperator = null
this.property = null
}
internal constructor(caze: Case<TReturn>, property: IProperty<*>) {
this.caze = caze
this.property = property
this.whenValue = null
this.sqlOperator = null
}
/**
* THEN part of this query, the value that gets set on column if condition is true.
*/
infix fun then(value: TReturn?): Case<TReturn> = caze.apply { thenValue = value }
infix fun then(value: IProperty<*>): Case<TReturn> = caze.apply {
thenProperty = value
// in case values are null in some sense.
isThenPropertySet = true
}
override fun toString(): String = query
}
| mit | cab047bbd939173824b58b6e6e6a6a85 | 29.651515 | 87 | 0.630746 | 4.258947 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/Product.kt | 1 | 1237 | @file:JvmName("ProductUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.enums.BillingPeriodType
import com.vimeo.networking2.enums.asEnum
/**
* Product data.
*
* @param billingPeriod The monthly or yearly billing period of the product. See [Product.billingPeriodType].
* @param description Product description.
* @param metadata Metadata about the product.
* @param name Product name.
* @param productId Product ID.
* @param uri The unique identifier you can use to access the product.
*/
@JsonClass(generateAdapter = true)
data class Product(
@Json(name = "billing_period")
val billingPeriod: String? = null,
@Json(name = "description")
val description: String? = null,
@Json(name = "metadata")
val metadata: MetadataInteractions<ProductInteractions>? = null,
@Json(name = "name")
val name: String? = null,
@Json(name = "product_id")
val productId: String? = null,
@Json(name = "uri")
val uri: String? = null
)
/**
* @see Product.billingPeriod
* @see BillingPeriodType
*/
val Product.billingPeriodType: BillingPeriodType
get() = billingPeriod.asEnum(BillingPeriodType.UNKNOWN)
| mit | 60a4ee06905e8753ff1afc72651ab935 | 24.770833 | 109 | 0.717057 | 3.841615 | false | false | false | false |
AndroidX/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/ExerciseRouteRecord.kt | 3 | 4409 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.annotation.FloatRange
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Length
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the user's route during exercise, e.g. during running or cycling. Each record represents
* a series of location points.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class ExerciseRouteRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
override val samples: List<Location>,
override val metadata: Metadata = Metadata.EMPTY,
) : SeriesRecord<ExerciseRouteRecord.Location> {
init {
require(!startTime.isAfter(endTime)) { "startTime must not be after endTime." }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExerciseRouteRecord) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (samples != other.samples) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = startTime.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + samples.hashCode()
result = 31 * result + metadata.hashCode()
return result
}
/**
* Represents a single location in an exercise route.
*
* @param time The point in time when the measurement was taken.
* @param latitude Latitude of a location represented as a float, in degrees. Valid
* range: -180 - 180 degrees.
* @param longitude Longitude of a location represented as a float, in degrees. Valid
* range: -180 - 180 degrees.
* @param horizontalAccuracy The radius of uncertainty for the location, in [Length] unit.
* @param altitude An altitude of a location represented as a float, in [Length] unit above sea
* level.
* @param verticalAccuracy The validity of the altitude values, and their estimated uncertainty,
* in [Length] unit.
*
* @see ExerciseRouteRecord
*/
public class Location(
val time: Instant,
@FloatRange(from = MIN_COORDINATE, to = MAX_COORDINATE) val latitude: Float,
@FloatRange(from = MIN_COORDINATE, to = MAX_COORDINATE) val longitude: Float,
val horizontalAccuracy: Length? = null,
val altitude: Length? = null,
val verticalAccuracy: Length? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Location) return false
if (time != other.time) return false
if (latitude != other.latitude) return false
if (longitude != other.longitude) return false
if (horizontalAccuracy != other.horizontalAccuracy) return false
if (altitude != other.altitude) return false
if (verticalAccuracy != other.verticalAccuracy) return false
return true
}
override fun hashCode(): Int {
var result = time.hashCode()
result = 31 * result + latitude.hashCode()
result = 31 * result + longitude.hashCode()
result = 31 * result + horizontalAccuracy.hashCode()
result = 31 * result + altitude.hashCode()
result = 31 * result + verticalAccuracy.hashCode()
return result
}
}
private companion object {
private const val MIN_COORDINATE = -180.0
private const val MAX_COORDINATE = 180.0
}
}
| apache-2.0 | a5f3c8d7d67a12baf55624a733c38a25 | 35.139344 | 100 | 0.704695 | 4.326791 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt | 4 | 7915 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("LoopToCallChain")
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager.getCachedValue
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyProperty
import org.jetbrains.plugins.groovy.lang.resolve.imports.importedNameKey
import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind
val log: Logger = Logger.getInstance("#org.jetbrains.plugins.groovy.lang.resolve")
@JvmField
val NON_CODE: Key<Boolean?> = Key.create("groovy.process.non.code.members")
@JvmField
val sorryCannotKnowElementKind: Key<Boolean> = Key.create("groovy.skip.kind.check.please")
fun initialState(processNonCodeMembers: Boolean): ResolveState = ResolveState.initial().put(NON_CODE, processNonCodeMembers)
fun ResolveState.processNonCodeMembers(): Boolean = get(NON_CODE).let { it == null || it }
fun treeWalkUp(place: PsiElement, processor: PsiScopeProcessor, state: ResolveState): Boolean {
return ResolveUtil.treeWalkUp(place, place, processor, state)
}
fun GrStatementOwner.processStatements(lastParent: PsiElement?, processor: (GrStatement) -> Boolean): Boolean {
var run = if (lastParent == null) lastChild else lastParent.prevSibling
while (run != null) {
if (run is GrStatement && !processor(run)) return false
run = run.prevSibling
}
return true
}
fun GrStatementOwner.processLocals(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean {
return !processor.shouldProcessLocals() || processStatements(lastParent) {
it.processDeclarations(processor, state, null, place)
}
}
fun PsiScopeProcessor.checkName(name: String, state: ResolveState): Boolean {
val expectedName = getName(state) ?: return true
return expectedName == name
}
fun PsiScopeProcessor.getName(state: ResolveState): String? = getHint(NameHint.KEY)?.getName(state)
fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean {
return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false
}
fun PsiScopeProcessor.shouldProcessDynamicProperties(): Boolean {
return getHint(DynamicMembersHint.KEY)?.shouldProcessProperties() ?: false
}
fun PsiScopeProcessor.shouldProcessLocals(): Boolean = shouldProcess(GroovyResolveKind.VARIABLE)
fun PsiScopeProcessor.shouldProcessFields(): Boolean = shouldProcess(GroovyResolveKind.FIELD)
fun PsiScopeProcessor.shouldProcessMethods(): Boolean = shouldProcess(GroovyResolveKind.METHOD)
fun PsiScopeProcessor.shouldProcessProperties(): Boolean = shouldProcess(GroovyResolveKind.PROPERTY)
fun PsiScopeProcessor.shouldProcessClasses(): Boolean {
return ResolveUtil.shouldProcessClasses(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessMembers(): Boolean {
val hint = getHint(ElementClassHint.KEY) ?: return true
return hint.shouldProcess(DeclarationKind.CLASS) ||
hint.shouldProcess(DeclarationKind.FIELD) ||
hint.shouldProcess(DeclarationKind.METHOD)
}
fun PsiScopeProcessor.shouldProcessTypeParameters(): Boolean {
if (shouldProcessClasses()) return true
val groovyKindHint = getHint(GroovyResolveKind.HINT_KEY) ?: return true
return groovyKindHint.shouldProcess(GroovyResolveKind.TYPE_PARAMETER)
}
private fun PsiScopeProcessor.shouldProcess(kind: GroovyResolveKind): Boolean {
val resolveKindHint = getHint(GroovyResolveKind.HINT_KEY)
if (resolveKindHint != null) return resolveKindHint.shouldProcess(kind)
val elementClassHint = getHint(ElementClassHint.KEY) ?: return true
return kind.declarationKinds.any(elementClassHint::shouldProcess)
}
fun getDefaultConstructor(clazz: PsiClass): PsiMethod {
return getCachedValue(clazz) {
Result.create(DefaultConstructor(clazz), clazz)
}
}
fun GroovyFileBase.processClassesInFile(processor: PsiScopeProcessor, state: ResolveState): Boolean {
if (!processor.shouldProcessClasses()) return true
val scriptClass = scriptClass
if (scriptClass != null && !ResolveUtil.processElement(processor, scriptClass, state)) return false
for (definition in typeDefinitions) {
if (!ResolveUtil.processElement(processor, definition, state)) return false
}
return true
}
fun GroovyFileBase.processClassesInPackage(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement = this): Boolean {
if (!processor.shouldProcessClasses()) return true
val aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName) ?: return true
return aPackage.processDeclarations(PackageSkippingProcessor(processor), state, null, place)
}
val PsiScopeProcessor.annotationHint: AnnotationHint? get() = getHint(AnnotationHint.HINT_KEY)
fun PsiScopeProcessor.isAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return hint.isAnnotationResolve
}
fun PsiScopeProcessor.isNonAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return !hint.isAnnotationResolve
}
fun GrCodeReferenceElement.isAnnotationReference(): Boolean {
val (possibleAnnotation, _) = skipSameTypeParents()
return possibleAnnotation is GrAnnotation
}
fun getName(state: ResolveState, element: PsiNamedElement): String? {
return state[importedNameKey] ?: element.name
}
fun <T : GroovyResolveResult> valid(allCandidates: Collection<T>): List<T> = allCandidates.filter {
it.isValidResult
}
fun singleOrValid(allCandidates: List<GroovyResolveResult>): List<GroovyResolveResult> {
return if (allCandidates.size <= 1) allCandidates else valid(allCandidates)
}
fun getResolveKind(element: PsiNamedElement): GroovyResolveKind? {
return when (element) {
is PsiClass -> GroovyResolveKind.CLASS
is PsiPackage -> GroovyResolveKind.PACKAGE
is PsiMethod -> GroovyResolveKind.METHOD
is PsiField -> GroovyResolveKind.FIELD
is GrBindingVariable -> GroovyResolveKind.BINDING
is PsiVariable -> GroovyResolveKind.VARIABLE
is GroovyProperty -> GroovyResolveKind.PROPERTY
else -> null
}
}
fun GroovyResolveResult?.asJavaClassResult(): PsiClassType.ClassResolveResult {
if (this == null) return PsiClassType.ClassResolveResult.EMPTY
val clazz = element as? PsiClass ?: return PsiClassType.ClassResolveResult.EMPTY
return object : PsiClassType.ClassResolveResult {
override fun getElement(): PsiClass? = clazz
override fun getSubstitutor(): PsiSubstitutor = this@asJavaClassResult.substitutor
override fun isPackagePrefixPackageReference(): Boolean = false
override fun isAccessible(): Boolean = true
override fun isStaticsScopeCorrect(): Boolean = true
override fun getCurrentFileResolveScope(): PsiElement? = null
override fun isValidResult(): Boolean = true
}
}
| apache-2.0 | 49b131dd44eb053ce72d184d9147682a | 42.251366 | 140 | 0.799747 | 4.639508 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/InferenceProcess.kt | 12 | 3855 | // 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 org.jetbrains.plugins.groovy.intentions.style.inference
import com.intellij.psi.PsiTypeParameter
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.plugins.groovy.intentions.style.inference.driver.*
import org.jetbrains.plugins.groovy.intentions.style.inference.graph.InferenceUnitGraph
import org.jetbrains.plugins.groovy.intentions.style.inference.graph.createGraphFromInferenceVariables
import org.jetbrains.plugins.groovy.intentions.style.inference.graph.determineDependencies
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
/**
* Performs full substitution for non-typed parameters of [method]
* Inference is performed in 3 phases:
* 1. Creating a type parameter for each of existing non-typed parameters
* 2. Inferring new parameters signature cause of possible generic types. Creating new type parameters.
* 3. Inferring dependencies between new type parameters and instantiating them.
*/
fun runInferenceProcess(method: GrMethod, options: SignatureInferenceOptions): GrMethod {
val originalMethod = getOriginalMethod(method)
val overridableMethod = findOverridableMethod(originalMethod)
if (overridableMethod != null) {
return convertToGroovyMethod(overridableMethod) ?: method
}
val searchScope = getSearchScope(method, options.shouldUseReducedScope) ?: return method
val environment = SignatureInferenceEnvironment(originalMethod, searchScope, options.signatureInferenceContext)
val driver = createDriver(originalMethod, environment)
val signatureSubstitutor = driver.collectSignatureSubstitutor().removeForeignTypeParameters(method)
val virtualMethodPointer: SmartPsiElementPointer<GrMethod> = createVirtualMethod(method) ?: return method
val parameterizedDriver = run {
val virtualMethod = virtualMethodPointer.element ?: return method
driver.createParameterizedDriver(ParameterizationManager(method), virtualMethod, signatureSubstitutor)
}
val typeUsage = parameterizedDriver.collectInnerConstraints()
val graph = run {
val virtualMethod = virtualMethodPointer.element ?: return method
setUpGraph(virtualMethod, method.typeParameters.asList(), typeUsage)
}
val inferredGraph = determineDependencies(graph)
return instantiateTypeParameters(parameterizedDriver, inferredGraph, method, typeUsage)
}
private val forbiddenAnnotations =
setOf(GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO,
GroovyCommonClassNames.GROOVY_TRANSFORM_STC_CLOSURE_PARAMS)
internal fun GrParameter.eligibleForExtendedInference(): Boolean =
typeElement == null //|| (type.isClosureType() && (annotations.map { it.qualifiedName } intersect forbiddenAnnotations).isEmpty())
private fun createDriver(method: GrMethod, environment: SignatureInferenceEnvironment): InferenceDriver {
val virtualMethodPointer: SmartPsiElementPointer<GrMethod> = createVirtualMethod(method) ?: return EmptyDriver
val generator = NameGenerator("_START" + method.hashCode(), context = method)
return CommonDriver.createFromMethod(method, virtualMethodPointer, generator, environment)
}
private fun setUpGraph(virtualMethod: GrMethod,
constantTypes: List<PsiTypeParameter>,
typeUsage: TypeUsageInformation): InferenceUnitGraph {
val inferenceSession = CollectingGroovyInferenceSession(virtualMethod.typeParameters, context = virtualMethod)
typeUsage.fillSession(inferenceSession)
inferenceSession.infer()
return createGraphFromInferenceVariables(inferenceSession, virtualMethod, typeUsage, constantTypes)
} | apache-2.0 | ba9354b68a15acf0839a55813f2441a3 | 58.323077 | 140 | 0.814008 | 4.917092 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/models/Checkout.kt | 1 | 2416 | package com.kickstarter.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class Checkout private constructor(
private val id: Long?,
private val backing: Backing,
) : Parcelable {
fun id() = this.id
fun backing() = this.backing
@Parcelize
data class Builder(
private var id: Long? = null,
private var backing: Backing = Backing.builder().build()
) : Parcelable {
fun id(id: Long?) = apply { this.id = id }
fun backing(backing: Backing) = apply { this.backing = backing }
fun build() = Checkout(
id = id,
backing = backing
)
}
fun toBuilder() = Builder(
id = id,
backing = backing
)
companion object {
@JvmStatic
fun builder() = Builder()
}
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is Checkout) {
equals = id() == obj.id() &&
backing() == obj.backing()
}
return equals
}
@Parcelize
data class Backing private constructor(
private val clientSecret: String?,
private val requiresAction: Boolean,
) : Parcelable {
fun clientSecret() = this.clientSecret
fun requiresAction() = this.requiresAction
@Parcelize
data class Builder(
private var clientSecret: String? = null,
private var requiresAction: Boolean = false,
) : Parcelable {
fun clientSecret(clientSecret: String?) = apply { this.clientSecret = clientSecret }
fun requiresAction(requiresAction: Boolean) = apply { this.requiresAction = requiresAction }
fun build() = Backing(
clientSecret = clientSecret,
requiresAction = requiresAction
)
}
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is Backing) {
equals = clientSecret() == obj.clientSecret() &&
requiresAction() == obj.requiresAction()
}
return equals
}
fun toBuilder() = Builder(
clientSecret = clientSecret,
requiresAction = requiresAction
)
companion object {
@JvmStatic
fun builder() = Builder()
}
}
}
| apache-2.0 | 676fd552c7fd5568a22fc3bf489b1aa1 | 26.770115 | 104 | 0.554636 | 5.033333 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt | 1 | 9555 | package info.nightscout.androidaps.plugins.general.nsclient.data
import android.content.Context
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
/*
{
"status": "ok",
"name": "Nightscout",
"version": "0.10.0-dev-20170423",
"versionNum": 1000,
"serverTime": "2017-06-12T07:46:56.006Z",
"apiEnabled": true,
"careportalEnabled": true,
"boluscalcEnabled": true,
"head": "96ee154",
"settings": {
"units": "mmol",
"timeFormat": 24,
"nightMode": false,
"editMode": true,
"showRawbg": "always",
"customTitle": "Bara's CGM",
"theme": "colors",
"alarmUrgentHigh": true,
"alarmUrgentHighMins": [30, 60, 90, 120],
"alarmHigh": true,
"alarmHighMins": [30, 60, 90, 120],
"alarmLow": true,
"alarmLowMins": [15, 30, 45, 60],
"alarmUrgentLow": true,
"alarmUrgentLowMins": [15, 30, 45],
"alarmUrgentMins": [30, 60, 90, 120],
"alarmWarnMins": [30, 60, 90, 120],
"alarmTimeagoWarn": true,
"alarmTimeagoWarnMins": 15,
"alarmTimeagoUrgent": true,
"alarmTimeagoUrgentMins": 30,
"language": "cs",
"scaleY": "linear",
"showPlugins": "careportal boluscalc food bwp cage sage iage iob cob basal ar2 delta direction upbat rawbg",
"showForecast": "ar2",
"focusHours": 3,
"heartbeat": 60,
"baseURL": "http:\/\/barascgm.sysop.cz:82",
"authDefaultRoles": "readable",
"thresholds": {
"bgHigh": 252,
"bgTargetTop": 180,
"bgTargetBottom": 72,
"bgLow": 71
},
"DEFAULT_FEATURES": ["bgnow", "delta", "direction", "timeago", "devicestatus", "upbat", "errorcodes", "profile"],
"alarmTypes": ["predict"],
"enable": ["careportal", "boluscalc", "food", "bwp", "cage", "sage", "iage", "iob", "cob", "basal", "ar2", "rawbg", "pushover", "bgi", "pump", "openaps", "pushover", "treatmentnotify", "bgnow", "delta", "direction", "timeago", "devicestatus", "upbat", "profile", "ar2"]
},
"extendedSettings": {
"pump": {
"fields": "reservoir battery clock",
"urgentBattP": 26,
"warnBattP": 51
},
"openaps": {
"enableAlerts": true
},
"cage": {
"alerts": true,
"display": "days",
"urgent": 96,
"warn": 72
},
"sage": {
"alerts": true,
"urgent": 336,
"warn": 168
},
"iage": {
"alerts": true,
"urgent": 150,
"warn": 120
},
"basal": {
"render": "default"
},
"profile": {
"history": true,
"multiple": true
},
"devicestatus": {
"advanced": true
}
},
"activeProfile": "2016 +30%"
}
*/
@Singleton
class NSSettingsStatus @Inject constructor(
private val aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper,
private val rxBus: RxBusWrapper,
private val defaultValueHelper: DefaultValueHelper,
private val sp: SP,
private val config: Config
) {
var nightscoutVersionName = ""
// ***** PUMP STATUS ******
var data: JSONObject? = null
fun handleNewData(nightscoutVersionName: String, nightscoutVersionCode: Int, status: JSONObject) {
this.nightscoutVersionName = nightscoutVersionName
aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: $nightscoutVersionName")
if (nightscoutVersionCode < config.SUPPORTEDNSVERSION) {
val notification = Notification(Notification.OLD_NS, resourceHelper.gs(R.string.unsupportednsversion), Notification.NORMAL)
rxBus.send(EventNewNotification(notification))
} else {
rxBus.send(EventDismissNotification(Notification.OLD_NS))
}
data = status
aapsLogger.debug(LTag.NSCLIENT, "Received status: $status")
val targetHigh = getSettingsThreshold("bgTargetTop")
val targetlow = getSettingsThreshold("bgTargetBottom")
if (targetHigh != null) defaultValueHelper.bgTargetHigh = targetHigh
if (targetlow != null) defaultValueHelper.bgTargetLow = targetlow
if (config.NSCLIENT) copyStatusLightsNsSettings(null)
}
fun getName(): String? =
JsonHelper.safeGetStringAllowNull(data, "name", null)
fun getVersion(): String? =
JsonHelper.safeGetStringAllowNull(data, "version", null)
fun getVersionNum(): Int =
JsonHelper.safeGetInt(data, "versionNum")
private fun getSettings() =
JsonHelper.safeGetJSONObject(data, "settings", null)
private fun getExtendedSettings(): JSONObject? =
JsonHelper.safeGetJSONObject(data, "extendedSettings", null)
// valid property is "warn" or "urgent"
// plugings "iage" "sage" "cage" "pbage"
fun getExtendedWarnValue(plugin: String, property: String): Double? {
val extendedSettings = getExtendedSettings() ?: return null
val pluginJson = extendedSettings.optJSONObject(plugin) ?: return null
try {
return pluginJson.getDouble(property)
} catch (e: Exception) {
return null
}
}
// "bgHigh": 252,
// "bgTargetTop": 180,
// "bgTargetBottom": 72,
// "bgLow": 71
fun getSettingsThreshold(what: String): Double? {
val threshold = JsonHelper.safeGetJSONObject(getSettings(), "thresholds", null)
return JsonHelper.safeGetDoubleAllowNull(threshold, what)
}
/*
, warnClock: sbx.extendedSettings.warnClock || 30
, urgentClock: sbx.extendedSettings.urgentClock || 60
, warnRes: sbx.extendedSettings.warnRes || 10
, urgentRes: sbx.extendedSettings.urgentRes || 5
, warnBattV: sbx.extendedSettings.warnBattV || 1.35
, urgentBattV: sbx.extendedSettings.urgentBattV || 1.3
, warnBattP: sbx.extendedSettings.warnBattP || 30
, urgentBattP: sbx.extendedSettings.urgentBattP || 20
, enableAlerts: sbx.extendedSettings.enableAlerts || false
*/
fun extendedPumpSettings(setting: String?): Double {
try {
val pump = extendedPumpSettings()
return when (setting) {
"warnClock" -> JsonHelper.safeGetDouble(pump, setting, 30.0)
"urgentClock" -> JsonHelper.safeGetDouble(pump, setting, 60.0)
"warnRes" -> JsonHelper.safeGetDouble(pump, setting, 10.0)
"urgentRes" -> JsonHelper.safeGetDouble(pump, setting, 5.0)
"warnBattV" -> JsonHelper.safeGetDouble(pump, setting, 1.35)
"urgentBattV" -> JsonHelper.safeGetDouble(pump, setting, 1.3)
"warnBattP" -> JsonHelper.safeGetDouble(pump, setting, 30.0)
"urgentBattP" -> JsonHelper.safeGetDouble(pump, setting, 20.0)
else -> 0.0
}
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return 0.0
}
private fun extendedPumpSettings(): JSONObject? =
JsonHelper.safeGetJSONObject(getExtendedSettings(), "pump", null)
fun pumpExtendedSettingsEnabledAlerts(): Boolean =
JsonHelper.safeGetBoolean(extendedPumpSettings(), "enableAlerts")
fun pumpExtendedSettingsFields(): String =
JsonHelper.safeGetString(extendedPumpSettings(), "fields", "")
fun openAPSEnabledAlerts(): Boolean {
val openaps = JsonHelper.safeGetJSONObject(getExtendedSettings(), "openaps", null)
return JsonHelper.safeGetBoolean(openaps, "enableAlerts")
}
fun copyStatusLightsNsSettings(context: Context?) {
val action = Runnable {
getExtendedWarnValue("cage", "warn")?.let { sp.putDouble(R.string.key_statuslights_cage_warning, it) }
getExtendedWarnValue("cage", "urgent")?.let { sp.putDouble(R.string.key_statuslights_cage_critical, it) }
getExtendedWarnValue("iage", "warn")?.let { sp.putDouble(R.string.key_statuslights_iage_warning, it) }
getExtendedWarnValue("iage", "urgent")?.let { sp.putDouble(R.string.key_statuslights_iage_critical, it) }
getExtendedWarnValue("sage", "warn")?.let { sp.putDouble(R.string.key_statuslights_sage_warning, it) }
getExtendedWarnValue("sage", "urgent")?.let { sp.putDouble(R.string.key_statuslights_sage_critical, it) }
getExtendedWarnValue("bage", "warn")?.let { sp.putDouble(R.string.key_statuslights_bage_warning, it) }
getExtendedWarnValue("bage", "urgent")?.let { sp.putDouble(R.string.key_statuslights_bage_critical, it) }
}
if (context != null) OKDialog.showConfirmation(context, resourceHelper.gs(R.string.statuslights), resourceHelper.gs(R.string.copyexistingvalues), action)
else action.run()
}
} | agpl-3.0 | 9a11e87483fbfbbd43d1c3bba30ddcec | 38.651452 | 274 | 0.649084 | 3.928865 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/fragments/RewardsFragment.kt | 1 | 7197 | package com.kickstarter.ui.fragments
import android.os.Bundle
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import androidx.recyclerview.widget.LinearLayoutManager
import com.kickstarter.R
import com.kickstarter.databinding.FragmentRewardsBinding
import com.kickstarter.libs.BaseFragment
import com.kickstarter.libs.qualifiers.RequiresFragmentViewModel
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.NumberUtils
import com.kickstarter.libs.utils.RewardDecoration
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.selectPledgeFragment
import com.kickstarter.models.Reward
import com.kickstarter.ui.adapters.RewardsAdapter
import com.kickstarter.ui.data.PledgeData
import com.kickstarter.ui.data.PledgeReason
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.viewmodels.RewardsFragmentViewModel
@RequiresFragmentViewModel(RewardsFragmentViewModel.ViewModel::class)
class RewardsFragment : BaseFragment<RewardsFragmentViewModel.ViewModel>(), RewardsAdapter.Delegate {
private var rewardsAdapter = RewardsAdapter(this)
private lateinit var dialog: AlertDialog
private var binding: FragmentRewardsBinding? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentRewardsBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
createDialog()
this.viewModel.outputs.projectData()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { rewardsAdapter.populateRewards(it) }
this.viewModel.outputs.backedRewardPosition()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { scrollToReward(it) }
this.viewModel.outputs.showPledgeFragment()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
dialog.dismiss()
showPledgeFragment(it.first, it.second, it.third)
}
this.viewModel.outputs.showAddOnsFragment()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
dialog.dismiss()
showAddonsFragment(it)
}
this.viewModel.outputs.rewardsCount()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setRewardsCount(it) }
this.viewModel.outputs.showAlert()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
showAlert()
}
context?.apply {
binding?.rewardsCount?.isGone = ViewUtils.isLandscape(this)
}
}
private fun createDialog() {
context?.let { context ->
dialog = AlertDialog.Builder(context, R.style.AlertDialog)
.setCancelable(false)
.setTitle(getString(R.string.Continue_with_this_reward))
.setMessage(getString(R.string.It_may_not_offer_some_or_all_of_your_add_ons))
.setNegativeButton(getString(R.string.No_go_back)) { _, _ -> {} }
.setPositiveButton(getString(R.string.Yes_continue)) { _, _ ->
this.viewModel.inputs.alertButtonPressed()
}.create()
}
}
private fun showAlert() {
if (this.isVisible)
dialog.show()
}
private fun scrollToReward(position: Int) {
if (position != 0) {
val recyclerWidth = (binding?.rewardsRecycler?.width ?: 0)
val linearLayoutManager = binding?.rewardsRecycler?.layoutManager as LinearLayoutManager
val rewardWidth = resources.getDimensionPixelSize(R.dimen.item_reward_width)
val rewardMargin = resources.getDimensionPixelSize(R.dimen.reward_margin)
val center = (recyclerWidth - rewardWidth - rewardMargin) / 2
linearLayoutManager.scrollToPositionWithOffset(position, center)
}
}
private fun setRewardsCount(count: Int) {
val rewardsCountString = requireNotNull(this.viewModel.environment.ksString()).format(
"Rewards_count_rewards", count,
"rewards_count", NumberUtils.format(count)
)
binding?.rewardsCount?.text = rewardsCountString
}
override fun onDetach() {
super.onDetach()
binding?.rewardsRecycler?.adapter = null
this.viewModel = null
}
override fun rewardClicked(reward: Reward) {
this.viewModel.inputs.rewardClicked(reward)
}
fun configureWith(projectData: ProjectData) {
this.viewModel.inputs.configureWith(projectData)
}
private fun addItemDecorator() {
val margin = resources.getDimension(R.dimen.reward_margin).toInt()
binding?.rewardsRecycler?.addItemDecoration(RewardDecoration(margin))
}
private fun setupRecyclerView() {
binding?.rewardsRecycler?.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding?.rewardsRecycler?.adapter = rewardsAdapter
addItemDecorator()
}
private fun showPledgeFragment(
pledgeData: PledgeData,
pledgeReason: PledgeReason,
shouldShowPaymentSheet: Boolean
) {
val fragment = this.selectPledgeFragment(pledgeData, pledgeReason, shouldShowPaymentSheet)
if (this.isVisible && this.parentFragmentManager.findFragmentByTag(fragment::class.java.simpleName) == null) {
this.parentFragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, 0, 0, R.anim.slide_out_right)
.add(
R.id.fragment_container,
fragment,
fragment::class.java.simpleName
)
.addToBackStack(fragment::class.java.simpleName)
.commit()
}
}
private fun showAddonsFragment(pledgeDataAndReason: Pair<PledgeData, PledgeReason>) {
if (this.isVisible && this.parentFragmentManager.findFragmentByTag(BackingAddOnsFragment::class.java.simpleName) == null) {
val addOnsFragment = BackingAddOnsFragment.newInstance(pledgeDataAndReason)
this.parentFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, 0, 0, R.anim.slide_out_right)
.add(
R.id.fragment_container,
addOnsFragment,
BackingAddOnsFragment::class.java.simpleName
)
.addToBackStack(BackingAddOnsFragment::class.java.simpleName)
.commit()
}
}
}
| apache-2.0 | 9a2217eeb2c26098a37a499ceb79b9cc | 37.902703 | 131 | 0.660831 | 5.097025 | false | false | false | false |
RedEpicness/redis-messenger | src/test/kotlin/me/redepicness/redismsg/tests/RedisDataTest.kt | 1 | 4251 | /*
* Copyright 2017 Red_Epicness
*
* 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 me.redepicness.redismsg.tests
import me.redepicness.redismsg.RedisData
import me.redepicness.redismsg.deserializeData
import org.junit.Test
import java.time.Duration
import java.util.*
/**
* @author Red_Epicness
*/
class RedisDataTest {
@Test
fun testWithoutSerialization() {
val rand = Random()
val a: Double = rand.nextDouble()
val b: Float = rand.nextFloat()
val c: Long = rand.nextLong()
val d: Int = rand.nextInt()
val e: Short = rand.nextInt(Short.MAX_VALUE.toInt()).toShort()
val f: Byte = rand.nextInt(Byte.MAX_VALUE.toInt()).toByte()
val g: String = "This is a test string"
val h: Char = '?'
val i: Boolean = rand.nextBoolean()
val j: Duration = Duration.ofSeconds(rand.nextLong())
val id = "Testing ID"
val data = RedisData(id)
data.addDouble("a", a)
data.addFloat("b", b)
data.addLong("c", c)
data.addInt("d", d)
data.addShort("e", e)
data.addByte("f", f)
data.addString("g", g)
data.addChar("h", h)
data.addBoolean("i", i)
data.addObject("j", j)
val a_: Double = data.getData("a")
val b_: Float = data.getData("b")
val c_: Long = data.getData("c")
val d_: Int = data.getData("d")
val e_: Short = data.getData("e")
val f_: Byte = data.getData("f")
val g_: String = data.getData("g")
val h_: Char = data.getData("h")
val i_: Boolean = data.getData("i")
val j_: Duration = data.getData("j")
val id_ = data.id
assert(id == id_)
assert(a == a_)
assert(b == b_)
assert(c == c_)
assert(d == d_)
assert(e == e_)
assert(f == f_)
assert(g == g_)
assert(h == h_)
assert(i == i_)
assert(j == j_)
assert(j === j_)
}
@Test
fun testWithSerialization() {
val rand = Random()
val a: Double = rand.nextDouble()
val b: Float = rand.nextFloat()
val c: Long = rand.nextLong()
val d: Int = rand.nextInt()
val e: Short = rand.nextInt(Short.MAX_VALUE.toInt()).toShort()
val f: Byte = rand.nextInt(Byte.MAX_VALUE.toInt()).toByte()
val g: String = "This is a test string"
val h: Char = '?'
val i: Boolean = rand.nextBoolean()
val j: Duration = Duration.ofSeconds(rand.nextLong())
val id = "Testing ID"
val data = RedisData(id)
data.addDouble("a", a)
data.addFloat("b", b)
data.addLong("c", c)
data.addInt("d", d)
data.addShort("e", e)
data.addByte("f", f)
data.addString("g", g)
data.addChar("h", h)
data.addBoolean("i", i)
data.addObject("j", j)
val data_ = deserializeData(data.serialize())
val a_: Double = data_.getData("a")
val b_: Float = data_.getData("b")
val c_: Long = data_.getData("c")
val d_: Int = data_.getData("d")
val e_: Short = data_.getData("e")
val f_: Byte = data_.getData("f")
val g_: String = data_.getData("g")
val h_: Char = data_.getData("h")
val i_: Boolean = data_.getData("i")
val j_: Duration = data_.getData("j")
val id_ = data_.id
assert(id == id_)
assert(a == a_)
assert(b == b_)
assert(c == c_)
assert(d == d_)
assert(e == e_)
assert(f == f_)
assert(g == g_)
assert(h == h_)
assert(i == i_)
assert(j == j_)
}
}
| apache-2.0 | 1afc96fc0c13a44dd44800120171ed92 | 27.34 | 78 | 0.537285 | 3.648927 | false | true | false | false |
EnricSala/RxSSE | src/main/kotlin/com/saladevs/rxsse/RxSSE.kt | 1 | 1544 | package com.saladevs.rxsse
import io.reactivex.Flowable
import io.reactivex.Single
import okhttp3.OkHttpClient
import okhttp3.Request
class RxSSE(private val client: OkHttpClient = OkHttpClient()) {
fun connectTo(url: String) = start(prepare(url))
fun connectTo(request: Request) = start(prepare(request))
private fun prepare(url: String) = Request.Builder().url(url)
.header(ACCEPT_HEADER, SSE_MIME_TYPE).build()
private fun prepare(request: Request) = request.newBuilder()
.header(ACCEPT_HEADER, SSE_MIME_TYPE).build()
private fun start(request: Request): Flowable<ServerSentEvent> =
execute(request).flatMapPublisher { it.events() }
private fun execute(request: Request): Single<Connection> =
Single.create { emitter ->
val call = client.newCall(request)
emitter.setCancellable { call.cancel() }
try {
val response = call.execute()
if (response.isSuccessful) {
emitter.onSuccess(Connection(call, response))
} else {
val error = "HTTP ${response.code()}"
emitter.tryOnError(RuntimeException(error))
}
} catch (t: Throwable) {
emitter.tryOnError(t)
}
}
companion object {
private const val ACCEPT_HEADER = "Accept"
private const val SSE_MIME_TYPE = "text/event-stream"
}
}
| apache-2.0 | be684251d11f5013fe950e6e2a62c365 | 33.311111 | 69 | 0.580311 | 4.636637 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/commit/CommitDetailsPanel.kt | 1 | 8326 | // 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.ui.details.commit
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.ui.FontUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.HtmlPanel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsRef
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil.*
import com.intellij.vcs.log.util.VcsLogUiUtil
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JPanel
import javax.swing.event.HyperlinkEvent
open class CommitDetailsPanel(private val project: Project, navigate: (CommitId) -> Unit) : JPanel() {
companion object {
const val SIDE_BORDER = 14
const val INTERNAL_BORDER = 10
const val EXTERNAL_BORDER = 14
}
data class RootColor(val root: VirtualFile, val color: Color)
private val hashAndAuthorPanel = HashAndAuthorPanel()
private val messagePanel = CommitMessagePanel(navigate)
private val branchesPanel = ReferencesPanel()
private val tagsPanel = ReferencesPanel()
private val rootPanel = RootColorPanel(hashAndAuthorPanel)
private val containingBranchesPanel = ContainingBranchesPanel()
init {
layout = VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)
isOpaque = false
val metadataPanel = BorderLayoutPanel().apply {
isOpaque = false
border = JBUI.Borders.empty(INTERNAL_BORDER, SIDE_BORDER)
addToLeft(rootPanel)
addToCenter(hashAndAuthorPanel)
}
add(messagePanel)
add(metadataPanel)
add(branchesPanel)
add(tagsPanel)
add(containingBranchesPanel)
}
final override fun add(comp: Component?): Component = super.add(comp)
protected open fun setCommit(commit: CommitId, presentation: CommitPresentation) {
messagePanel.updateMessage(presentation)
hashAndAuthorPanel.updateHashAndAuthor(presentation)
}
fun setCommit(commit: VcsCommitMetadata) {
val presentation = buildPresentation(project, commit, mutableSetOf())
setCommit(CommitId(commit.id, commit.root), presentation)
}
fun setRefs(references: List<VcsRef>?) {
references ?: return
branchesPanel.setReferences(references.filter { it.type.isBranch })
tagsPanel.setReferences(references.filter { !it.type.isBranch })
if (tagsPanel.isVisible) {
branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, 0, SIDE_BORDER)
tagsPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, SIDE_BORDER)
}
else if (branchesPanel.isVisible) {
branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, SIDE_BORDER)
}
update()
}
fun setRoot(rootColor: RootColor?) {
rootPanel.setRoot(rootColor)
}
fun setBranches(branches: List<String>?) {
containingBranchesPanel.setBranches(branches)
}
fun update() {
messagePanel.update()
rootPanel.update()
hashAndAuthorPanel.update()
branchesPanel.update()
tagsPanel.update()
containingBranchesPanel.update()
}
override fun getBackground(): Color = getCommitDetailsBackground()
}
private class CommitMessagePanel(private val navigate: (CommitId) -> Unit) : HtmlPanel() {
private var presentation: CommitPresentation? = null
override fun hyperlinkUpdate(e: HyperlinkEvent) {
presentation?.let { presentation ->
if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isGoToHash(e)) {
val commitId = presentation.parseTargetCommit(e) ?: return
navigate(commitId)
}
else {
BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e)
}
}
}
init {
border = JBUI.Borders.empty(CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.INTERNAL_BORDER,
CommitDetailsPanel.SIDE_BORDER)
}
fun updateMessage(message: CommitPresentation?) {
presentation = message
update()
}
override fun getBody() = presentation?.text ?: ""
override fun getBackground(): Color = getCommitDetailsBackground()
override fun update() {
isVisible = presentation != null
super.update()
}
}
private class ContainingBranchesPanel : HtmlPanel() {
private var branches: List<String>? = null
private var expanded = false
init {
border = JBUI.Borders.empty(0, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER)
isVisible = false
}
override fun setBounds(x: Int, y: Int, w: Int, h: Int) {
val oldWidth = width
super.setBounds(x, y, w, h)
if (w != oldWidth) {
update()
}
}
override fun hyperlinkUpdate(e: HyperlinkEvent) {
if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isShowHideBranches(e)) {
expanded = !expanded
update()
}
}
fun setBranches(branches: List<String>?) {
this.branches = branches
expanded = false
isVisible = true
update()
}
override fun getBody(): String {
val insets = insets
val text = getBranchesText(branches, expanded, width - insets.left - insets.right, getFontMetrics(bodyFont))
return if (expanded) text else "<nobr>$text</nobr>"
}
override fun getBackground(): Color = getCommitDetailsBackground()
override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont()
}
private class HashAndAuthorPanel : HtmlPanel() {
private var presentation: CommitPresentation? = null
override fun getBody(): String = presentation?.hashAndAuthor ?: ""
init {
border = JBUI.Borders.empty()
}
fun updateHashAndAuthor(commitAndAuthorPresentation: CommitPresentation?) {
presentation = commitAndAuthorPresentation
update()
}
public override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont()
override fun update() {
isVisible = presentation != null
super.update()
}
}
private class RootColorPanel(private val parent: HashAndAuthorPanel) : Wrapper(parent) {
companion object {
private const val ROOT_ICON_SIZE = 13
private const val ROOT_GAP = 4
}
private var icon: ColorIcon? = null
private var tooltipText: String? = null
private val mouseMotionListener = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent?) {
if (IdeTooltipManager.getInstance().hasCurrent()) {
IdeTooltipManager.getInstance().hideCurrent(e)
return
}
icon?.let { icon ->
tooltipText?.let { tooltipText ->
VcsLogUiUtil.showTooltip(this@RootColorPanel, Point(icon.iconWidth / 2, 0), Balloon.Position.above, tooltipText)
}
}
}
}
init {
setVerticalSizeReferent(parent)
addMouseMotionListener(mouseMotionListener)
}
override fun getPreferredSize(): Dimension = icon?.let { icon ->
val size = super.getPreferredSize()
Dimension(icon.iconWidth + JBUIScale.scale(ROOT_GAP), size.height)
} ?: Dimension(0, 0)
fun setRoot(rootColor: CommitDetailsPanel.RootColor?) {
if (rootColor != null) {
icon = JBUI.scale(ColorIcon(ROOT_ICON_SIZE, rootColor.color))
tooltipText = rootColor.root.path
}
else {
icon = null
tooltipText = null
}
}
fun update() {
isVisible = icon != null
revalidate()
repaint()
}
override fun getBackground(): Color = getCommitDetailsBackground()
override fun paintComponent(g: Graphics) {
icon?.let { icon ->
val h = FontUtil.getStandardAscent(parent.bodyFont, g)
val metrics = getFontMetrics(parent.bodyFont)
icon.paintIcon(this, g, 0, metrics.maxAscent - h + (h - icon.iconHeight - 1) / 2)
}
}
}
fun getCommitDetailsBackground(): Color = UIUtil.getTreeBackground() | apache-2.0 | 7dcff1a5b258e8e718764e1081a56fe2 | 30.070896 | 140 | 0.717511 | 4.352326 | false | false | false | false |
JetBrains/xodus | openAPI/src/main/kotlin/jetbrains/exodus/crypto/StreamCipherInputStream.kt | 1 | 2372 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.crypto
import jetbrains.exodus.kotlin.notNull
import java.io.BufferedInputStream
import java.io.FilterInputStream
import java.io.InputStream
val InputStream.asBuffered: InputStream get() = this as? BufferedInputStream ?: BufferedInputStream(this)
class StreamCipherInputStream(input: InputStream, private val cipherGetter: () -> StreamCipher) : FilterInputStream(input) {
private var cipher: StreamCipher = cipherGetter()
private var position = 0
private var savedPosition = 0
override fun read(): Int {
val b = super.read()
if (b == -1) {
return -1
}
return cipher.cryptAsInt(b.toByte()).apply { ++position }
}
override fun read(bytes: ByteArray?): Int {
val b = bytes.notNull { "Can't read into null array" }
return read(b, 0, b.size)
}
override fun read(bytes: ByteArray?, off: Int, len: Int): Int {
val b = bytes.notNull { "Can't read into null array" }
val read = super.read(b, off, len)
if (read > 0) {
for (i in off until read + off) {
b[i] = cipher.crypt(b[i])
}
position += read
}
return read
}
override fun reset() {
super.reset()
cipher = cipherGetter()
// skip savedPosition bytes
repeat(savedPosition) {
cipher.crypt(0)
}
position = savedPosition
}
override fun mark(readlimit: Int) {
super.mark(readlimit)
savedPosition = position
}
val source: InputStream
get() {
var result = `in`
while (result is FilterInputStream) {
result = `in`
}
return result
}
} | apache-2.0 | e4bbe8b285931b36a8af323a694cd7be | 29.037975 | 124 | 0.618465 | 4.281588 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/vcs/BunchCheckinHandler.kt | 1 | 5844 | // 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.vcs
import com.intellij.BundleBase.replaceMnemonicAmpersand
import com.intellij.CommonBundle
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Messages.NO
import com.intellij.openapi.ui.Messages.YES
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.NonFocusableCheckBox
import com.intellij.util.PairConsumer
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.psi.NotNullableUserDataProperty
import java.awt.GridLayout
import java.nio.file.Path
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.io.path.*
private val BUNCH_PLUGIN_ID = PluginId.getId("org.jetbrains.bunch.tool.idea.plugin")
private var Project.bunchFileCheckEnabled: Boolean
by NotNullableUserDataProperty(
Key.create("IS_BUNCH_FILE_CHECK_ENABLED_KOTLIN"),
!PluginManagerCore.isPluginInstalled(BUNCH_PLUGIN_ID)
)
class BunchFileCheckInHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return BunchCheckInHandler(panel)
}
class BunchCheckInHandler(private val checkInProjectPanel: CheckinProjectPanel) : CheckinHandler() {
private val project get() = checkInProjectPanel.project
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent? {
if (PluginManagerCore.isPluginInstalled(BUNCH_PLUGIN_ID)) return null
BunchFileUtils.bunchFile(project) ?: return null
val bunchFilesCheckBox = NonFocusableCheckBox(replaceMnemonicAmpersand(KotlinJvmBundle.message("check.bunch.files")))
return object : RefreshableOnComponent {
override fun getComponent(): JComponent {
val panel = JPanel(GridLayout(1, 0))
panel.add(bunchFilesCheckBox)
return panel
}
override fun refresh() {}
override fun saveState() {
project.bunchFileCheckEnabled = bunchFilesCheckBox.isSelected
}
override fun restoreState() {
bunchFilesCheckBox.isSelected = project.bunchFileCheckEnabled
}
}
}
override fun beforeCheckin(
executor: CommitExecutor?,
additionalDataConsumer: PairConsumer<Any, Any>?
): ReturnResult {
if (!project.bunchFileCheckEnabled) return ReturnResult.COMMIT
val extensions = BunchFileUtils.bunchExtension(project)?.toSet() ?: return ReturnResult.COMMIT
val forgottenFiles = HashSet<Path>()
val commitFiles = checkInProjectPanel.files.mapNotNull { file -> file.toPath().takeIf { it.isRegularFile() } }.toSet()
for (file in commitFiles) {
if (file.extension in extensions) continue
val parent = file.parent ?: continue
val name = file.name
for (extension in extensions) {
val bunchFile = parent.resolve("$name.$extension")
if (bunchFile !in commitFiles && bunchFile.exists()) {
forgottenFiles.add(bunchFile)
}
}
}
if (forgottenFiles.isEmpty()) return ReturnResult.COMMIT
val paths = project.basePath?.let(::Path)?.let { projectBasePath ->
forgottenFiles.map { it.relativeTo(projectBasePath) }
} ?: forgottenFiles
var filePaths = paths.map(Path::pathString).sorted()
if (filePaths.size > 15) {
filePaths = filePaths.take(15) + "..."
}
when (Messages.showYesNoCancelDialog(
project,
KotlinJvmBundle.message(
"several.bunch.files.haven.t.been.updated.0.do.you.want.to.review.them.before.commit",
filePaths.joinToString("\n")
),
KotlinJvmBundle.message("button.text.forgotten.bunch.files"),
KotlinJvmBundle.message("button.text.review"),
KotlinJvmBundle.message("button.text.commit"),
CommonBundle.getCancelButtonText(),
Messages.getWarningIcon()
)) {
YES -> {
return ReturnResult.CLOSE_WINDOW
}
NO -> return ReturnResult.COMMIT
}
return ReturnResult.CANCEL
}
}
}
object BunchFileUtils {
fun bunchFile(project: Project): VirtualFile? {
val baseDir = project.baseDir ?: return null
return baseDir.findChild(".bunch")
}
fun bunchExtension(project: Project): List<String>? {
val bunchFile: VirtualFile = bunchFile(project) ?: return null
val file = bunchFile.toNioPath()
if (file.notExists()) return null
val lines = file.readLines().map { it.trim() }.filter { it.isNotEmpty() }
if (lines.size <= 1) return null
return lines.drop(1).map { it.split('_').first() }
}
}
| apache-2.0 | bbbfc74260b509ef5a73aef327dbe7e7 | 39.867133 | 158 | 0.648186 | 4.931646 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/completion/keywords/DefaultCompletionKeywordHandlerProvider.kt | 6 | 4019 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.completion.keywords
import com.intellij.codeInsight.completion.CompletionParameters
import org.jetbrains.kotlin.idea.completion.breakOrContinueExpressionItems
import org.jetbrains.kotlin.idea.completion.handlers.createKeywordConstructLookupElement
import org.jetbrains.kotlin.idea.completion.handlers.withLineIndentAdjuster
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
@OptIn(ExperimentalStdlibApi::class)
object DefaultCompletionKeywordHandlerProvider : CompletionKeywordHandlerProvider<CompletionKeywordHandler.NO_CONTEXT>() {
private val BREAK_HANDLER =
completionKeywordHandler<CompletionKeywordHandler.NO_CONTEXT>(KtTokens.BREAK_KEYWORD) { _, expression, _, _ ->
if (expression != null) {
breakOrContinueExpressionItems(expression, KtTokens.BREAK_KEYWORD.value)
} else emptyList()
}
private val CONTINUE_HANDLER =
completionKeywordHandler<CompletionKeywordHandler.NO_CONTEXT>(KtTokens.CONTINUE_KEYWORD) { _, expression, _, _ ->
if (expression != null) {
breakOrContinueExpressionItems(expression, KtTokens.CONTINUE_KEYWORD.value)
} else emptyList()
}
private val CONTRACT_HANDLER = completionKeywordHandler<CompletionKeywordHandler.NO_CONTEXT>(KtTokens.CONTRACT_KEYWORD) { _, _, _, _ ->
emptyList()
}
private val GETTER_HANDLER =
completionKeywordHandler<CompletionKeywordHandler.NO_CONTEXT>(KtTokens.GET_KEYWORD) { parameters, _, lookupElement, project ->
buildList {
add(lookupElement.withLineIndentAdjuster())
if (!parameters.isUseSiteAnnotationTarget) {
add(
createKeywordConstructLookupElement(
project,
KtTokens.GET_KEYWORD.value,
"val v:Int get()=caret",
adjustLineIndent = true,
)
)
add(
createKeywordConstructLookupElement(
project,
KtTokens.GET_KEYWORD.value,
"val v:Int get(){caret}",
trimSpacesAroundCaret = true,
adjustLineIndent = true,
)
)
}
}
}
private val SETTER_HANDLER =
completionKeywordHandler<CompletionKeywordHandler.NO_CONTEXT>(KtTokens.SET_KEYWORD) { parameters, _, lookupElement, project ->
buildList {
add(lookupElement.withLineIndentAdjuster())
if (!parameters.isUseSiteAnnotationTarget) {
add(
createKeywordConstructLookupElement(
project,
KtTokens.SET_KEYWORD.value,
"var v:Int set(value)=caret",
adjustLineIndent = true,
)
)
add(
createKeywordConstructLookupElement(
project,
KtTokens.SET_KEYWORD.value,
"var v:Int set(value){caret}",
trimSpacesAroundCaret = true,
adjustLineIndent = true,
)
)
}
}
}
override val handlers = CompletionKeywordHandlers(
BREAK_HANDLER, CONTINUE_HANDLER,
GETTER_HANDLER, SETTER_HANDLER,
CONTRACT_HANDLER,
)
}
private val CompletionParameters.isUseSiteAnnotationTarget
get() = position.prevLeaf()?.node?.elementType == KtTokens.AT | apache-2.0 | 52a6b7b315ee966593f8816351aeece8 | 41.765957 | 139 | 0.565066 | 5.892962 | false | false | false | false |
jwren/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogExtension.kt | 1 | 6133 | // 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 org.jetbrains.plugins.github.ui.cloneDialog
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.UIUtil.ComponentStyle
import com.intellij.util.ui.UIUtil.getRegularPanelInsets
import com.intellij.util.ui.cloneDialog.AccountMenuItem
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.authentication.accounts.isGHAccount
import org.jetbrains.plugins.github.i18n.GithubBundle.message
import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader
import org.jetbrains.plugins.github.util.GithubUtil
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel
private fun getGHAccounts(): Collection<GithubAccount> =
GithubAuthenticationManager.getInstance().getAccounts().filter { it.isGHAccount }
class GHCloneDialogExtension : BaseCloneDialogExtension() {
override fun getName() = GithubUtil.SERVICE_DISPLAY_NAME
override fun getAccounts(): Collection<GithubAccount> = getGHAccounts()
override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent =
GHCloneDialogExtensionComponent(project)
}
private class GHCloneDialogExtensionComponent(project: Project) : GHCloneDialogExtensionComponentBase(
project,
GithubAuthenticationManager.getInstance(),
GithubApiRequestExecutorManager.getInstance(),
GithubAccountInformationProvider.getInstance(),
CachingGHUserAvatarLoader.getInstance()
) {
init {
service<GHAccountManager>().addListener(this, this)
setup()
}
override fun getAccounts(): Collection<GithubAccount> = getGHAccounts()
override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) {
super.onAccountListChanged(old.filter { it.isGHAccount }, new.filter { it.isGHAccount })
}
override fun onAccountCredentialsChanged(account: GithubAccount) {
if (account.isGHAccount) super.onAccountCredentialsChanged(account)
}
override fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent =
GHCloneDialogLoginPanel(account).apply {
val chooseLoginUiHandler = { setChooseLoginUi() }
loginPanel.setCancelHandler(if (getAccounts().isEmpty()) chooseLoginUiHandler else cancelHandler)
}.also {
Disposer.register(this, it)
}
override fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action> =
listOf(createLoginAction(account), createLoginWithTokenAction(account))
private fun createLoginAction(account: GithubAccount?): AccountMenuItem.Action {
val isExistingAccount = account != null
return AccountMenuItem.Action(
message("login.via.github.action"),
{
switchToLogin(account)
getLoginPanel()?.setOAuthLoginUi()
},
showSeparatorAbove = !isExistingAccount
)
}
private fun createLoginWithTokenAction(account: GithubAccount?): AccountMenuItem.Action =
AccountMenuItem.Action(
message("login.with.token.action"),
{
switchToLogin(account)
getLoginPanel()?.setTokenUi()
}
)
private fun getLoginPanel(): GHCloneDialogLoginPanel? = content as? GHCloneDialogLoginPanel
}
private class GHCloneDialogLoginPanel(account: GithubAccount?) :
JBPanel<GHCloneDialogLoginPanel>(VerticalLayout(0)),
Disposable {
private val titlePanel =
simplePanel().apply {
val title = JBLabel(message("login.to.github"), ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) }
addToLeft(title)
}
private val contentPanel = Wrapper()
private val chooseLoginUiPanel: JPanel =
JPanel(HorizontalLayout(0)).apply {
border = JBEmptyBorder(getRegularPanelInsets())
val loginViaGHButton = JButton(message("login.via.github.action")).apply { addActionListener { setOAuthLoginUi() } }
val useTokenLink = ActionLink(message("link.label.use.token")) { setTokenUi() }
add(loginViaGHButton)
add(JBLabel(message("label.login.option.separator")).apply { border = empty(0, 6, 0, 4) })
add(useTokenLink)
}
val loginPanel = CloneDialogLoginPanel(account).apply {
setServer(GithubServerPath.DEFAULT_HOST, false)
}.also {
Disposer.register(this, it)
}
init {
add(titlePanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { bottom = 0 }) })
add(contentPanel)
setChooseLoginUi()
}
fun setChooseLoginUi() = setContent(chooseLoginUiPanel)
fun setOAuthLoginUi() {
setContent(loginPanel)
loginPanel.setOAuthUi()
}
fun setTokenUi() {
setContent(loginPanel)
loginPanel.setTokenUi() // after `loginPanel` is set as content to ensure correct focus behavior
}
private fun setContent(content: JComponent) {
contentPanel.setContent(content)
revalidate()
repaint()
}
override fun dispose() = Unit
} | apache-2.0 | 6e41d1cb21dc5d4854d11fb74e69a509 | 36.631902 | 140 | 0.776618 | 4.587135 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinFragmentContentRootsCreator.kt | 1 | 3144 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ContentRootData
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ContentRootsCreator
import org.jetbrains.kotlin.idea.gradleJava.configuration.kpm.KotlinKPMGradleProjectResolver.Companion.getIdeaKotlinProjectModel
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
@Order(ExternalSystemConstants.UNORDERED)
class KotlinFragmentContentRootsCreator : ContentRootsCreator {
override fun populateContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, resolverCtx: ProjectResolverContext) {
val sourceSetsMap = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY).filter {
ExternalSystemApiUtil.find(it, KotlinFragmentData.KEY) != null
}.associateBy { it.data.id }
val model = resolverCtx.getIdeaKotlinProjectModel(gradleModule)!!
for (fragment in model.modules.flatMap { it.fragments }) {
val moduleId = calculateKotlinFragmentModuleId(gradleModule, fragment.coordinates, resolverCtx)
val moduleDataNode = sourceSetsMap[moduleId] ?: continue
createContentRootData(
fragment.sourceDirs.toSet(),
fragment.computeSourceType(),
KotlinKPMGradleProjectResolver.extractPackagePrefix(fragment),
moduleDataNode
)
createContentRootData(
fragment.resourceDirs.toSet(),
fragment.computeResourceType(),
null,
moduleDataNode
)
}
}
companion object {
private fun createContentRootData(
sourceDirs: Set<File>,
sourceType: ExternalSystemSourceType,
packagePrefix: String?,
parentNode: DataNode<*>
) {
for (sourceDir in sourceDirs) {
val contentRootData = ContentRootData(GradleConstants.SYSTEM_ID, sourceDir.absolutePath)
packagePrefix?.also {
contentRootData.storePath(sourceType, sourceDir.absolutePath, it)
} ?: contentRootData.storePath(sourceType, sourceDir.absolutePath)
parentNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
}
}
} | apache-2.0 | bdc9637eda0e52bae25f3415c163e653 | 48.140625 | 135 | 0.728053 | 5.328814 | false | false | false | false |
androidx/androidx | collection/collection/src/commonTest/kotlin/androidx/collection/ArraySetTest.kt | 3 | 7048 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import androidx.collection.internal.Lock
import androidx.collection.internal.synchronized
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
internal class ArraySetTest {
private val set = ArraySet<String>()
/**
* Attempt to generate a ConcurrentModificationException in ArraySet.
*
*
* ArraySet is explicitly documented to be non-thread-safe, yet it's easy to accidentally screw
* this up; ArraySet should (in the spirit of the core Java collection types) make an effort to
* catch this and throw ConcurrentModificationException instead of crashing somewhere in its
* internals.
*/
@Suppress("UnnecessaryOptInAnnotation")
@OptIn(
ExperimentalCoroutinesApi::class, // newFixedThreadPoolContext is experimental in common
DelicateCoroutinesApi::class, // newFixedThreadPoolContext is delicate in jvm
)
@Test
fun testConcurrentModificationException() {
var error: Throwable? = null
val nThreads = 20
var nActiveThreads = 0
val lock = Lock()
val dispatcher = newFixedThreadPoolContext(nThreads = nThreads, name = "ArraySetTest")
val scope = CoroutineScope(dispatcher)
repeat(nThreads) {
scope.launch {
lock.synchronized { nActiveThreads++ }
while (isActive) {
val add = Random.nextBoolean()
try {
if (add) {
set.add(Random.nextLong().toString())
} else {
set.clear()
}
} catch (e: IndexOutOfBoundsException) {
if (!add) {
error = e
throw e
} // Expected exception otherwise
} catch (e: ClassCastException) {
error = e
throw e
} catch (ignored: ConcurrentModificationException) {
// Expected exception
}
}
}
}
runBlocking(Dispatchers.Default) {
// Wait until all worker threads are started
for (i in 0 until 100) {
if (lock.synchronized { nActiveThreads == nThreads }) {
break
} else {
delay(timeMillis = 10L)
}
}
// Allow the worker threads to run concurrently for some time
delay(timeMillis = 100L)
}
scope.cancel()
dispatcher.close()
error?.also { throw it }
}
/**
* Check to make sure the same operations behave as expected in a single thread.
*/
@Test
fun testNonConcurrentAccesses() {
repeat(100_000) { i ->
set.add("key $i")
if (i % 200 == 0) {
print(".")
}
if (i % 500 == 0) {
set.clear()
}
}
}
@Test
fun testCanNotIteratePastEnd() {
val set = ArraySet<String>()
set.add("value")
val iterator: Iterator<String> = set.iterator()
assertTrue(iterator.hasNext())
assertEquals("value", iterator.next())
assertFalse(iterator.hasNext())
assertTrue(runCatching { iterator.next() }.exceptionOrNull() is NoSuchElementException)
}
@Test
fun addAllTypeProjection() {
val set1 = ArraySet<Any>()
val set2 = ArraySet<String>()
set2.add("Foo")
set2.add("Bar")
set1.addAll(set2)
assertEquals(set1.asIterable().toSet(), setOf("Bar", "Foo"))
}
/**
* Test for implementation correction. This makes sure that all branches in ArraySet's
* backstore shrinking code gets exercised.
*/
@Test
fun addAllThenRemoveOneByOne() {
val sourceList = (0 until 10).toList()
val set = ArraySet(sourceList)
assertEquals(sourceList.size, set.size)
for (e in sourceList) {
assertTrue(set.contains(e))
set.remove(e)
}
assertTrue(set.isEmpty())
}
/**
* Test for implementation correction of indexOf.
*/
@Test
fun addObjectsWithSameHashCode() {
@Suppress("EqualsOrHashCode") // Testing for hash code collisions
class Value {
override fun hashCode(): Int = 42
}
val sourceList = (0 until 10).map { Value() }
val set = ArraySet(sourceList)
assertEquals(sourceList.size, set.size)
for (e in sourceList) {
assertEquals(e, set.valueAt(set.indexOf(e)))
}
}
@Test
fun constructWithArray() {
val strings: Array<String> = arrayOf("a", "b", "c")
val set = ArraySet(strings)
assertEquals(3, set.size)
assertTrue(set.contains("a"))
assertFalse(set.contains("d"))
}
@Test
fun arraySetEqualsAndHashCode() {
val set3 = ArraySet(listOf(1, 2, 3))
val set3b = ArraySet(listOf(1, 2, 3))
val set4 = ArraySet(listOf(1, 2, 3, 4))
assertEquals(set3, set3)
assertEquals(set3.hashCode(), set3.hashCode())
assertEquals(set3, set3b)
assertEquals(set3.hashCode(), set3b.hashCode())
assertNotEquals(set3, set4)
assertNotEquals(set3.hashCode(), set4.hashCode())
}
@Test
fun testToString() {
val set3 = ArraySet(listOf(1, 2, 3))
val set4 = ArraySet(listOf(1, 2, 3, 4))
assertEquals("{1, 2, 3}", set3.toString())
assertEquals("{1, 2, 3, 4}", set4.toString())
val set5 = ArraySet<Any>()
set5.add(1)
set5.add("one")
set5.add(set5)
assertEquals("{1, one, (this Set)}", set5.toString())
}
} | apache-2.0 | 41323b6cc7f8b23cf33afe58e7d96f35 | 31.040909 | 99 | 0.585982 | 4.689288 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceTypeExtractor.kt | 4 | 2460 | // 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.debugger.sequence.psi.sequence
import com.intellij.debugger.streams.trace.impl.handler.type.ClassTypeImpl
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.idea.debugger.sequence.psi.CallTypeExtractor
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinSequenceTypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
class SequenceTypeExtractor : CallTypeExtractor.Base() {
private companion object {
val LOG = Logger.getInstance(SequenceTypeExtractor::class.java)
}
override fun extractItemsType(type: KotlinType?): GenericType {
if (type == null) return KotlinSequenceTypes.NULLABLE_ANY
return tryToFindElementType(type) ?: defaultType(type)
}
override fun getResultType(type: KotlinType): GenericType {
val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type)
return KotlinSequenceTypes.primitiveTypeByName(typeName)
?: KotlinSequenceTypes.primitiveArrayByName(typeName)
?: ClassTypeImpl(KotlinPsiUtil.getTypeName(type))
}
private fun tryToFindElementType(type: KotlinType): GenericType? {
val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type)
if (typeName == "kotlin.sequences.Sequence") {
if (type.arguments.isEmpty()) return KotlinSequenceTypes.NULLABLE_ANY
val itemsType = type.arguments.single().type
if (itemsType.isMarkedNullable) return KotlinSequenceTypes.NULLABLE_ANY
val primitiveType = KotlinSequenceTypes.primitiveTypeByName(KotlinPsiUtil.getTypeWithoutTypeParameters(itemsType))
return primitiveType ?: KotlinSequenceTypes.ANY
}
return type.supertypes().asSequence()
.map(this::tryToFindElementType)
.firstOrNull()
}
private fun defaultType(type: KotlinType): GenericType {
LOG.warn("Could not find type of items for type ${KotlinPsiUtil.getTypeName(type)}")
return if (type.isMarkedNullable) KotlinSequenceTypes.NULLABLE_ANY else KotlinSequenceTypes.ANY
}
} | apache-2.0 | e872eb3342758346e6cb1e7672c8102f | 47.254902 | 158 | 0.750407 | 4.880952 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/CompileStdlib.kt | 1 | 2093 | package phizdets.compiler
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.ObjectMapper
import org.jetbrains.kotlin.cli.js.K2PhizdetsCompiler
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.facade.K2JSTranslator
import org.jetbrains.kotlin.js.translate.utils.jsAstUtils.array
import org.jetbrains.kotlin.js.translate.utils.jsAstUtils.index
import vgrechka.*
import java.io.File
import java.io.StringWriter
import java.util.*
import javax.xml.bind.JAXB
import javax.xml.bind.JAXBContext
import javax.xml.bind.annotation.*
import kotlin.properties.Delegates.notNull
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlin.system.exitProcess
import jdk.nashorn.internal.ir.*
import jdk.nashorn.internal.ir.visitor.NodeVisitor
import jdk.nashorn.internal.parser.Parser
import jdk.nashorn.internal.parser.TokenType
import jdk.nashorn.internal.runtime.Context
import jdk.nashorn.internal.runtime.ErrorManager
import jdk.nashorn.internal.runtime.Source
import jdk.nashorn.internal.runtime.options.Options
import org.jetbrains.kotlin.js.sourceMap.PhizdetsSourceGenerationVisitor
import org.jetbrains.kotlin.js.util.TextOutputImpl
object CompileStdlib {
val adaptedKotlinJSFilePath = "E:/fegh/phizdets/phizdetsc/src/phizdets/php/kotlin--adapted.js"
val stdlibPHPFilePath = "E:/fegh/phizdets/phizdetsc/src/phizdets/php/phizdets-stdlib.php"
@JvmStatic
fun main(args: Array<String>) {
print("Compiling stdlib...")
Barbos(inputFilePath = adaptedKotlinJSFilePath,
outputFilePath = stdlibPHPFilePath,
copyPhiEngine = false,
copyPhiStdlib = false,
useMap = false,
phpifierOpts = Phpifier.Opts(skipDebuggingOptionInExpressionStatements = true))
.ignite()
println(" OK, strange")
}
}
| apache-2.0 | b6a38e474c8d11def424498bae308303 | 37.054545 | 98 | 0.789298 | 4.103922 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectView/KtDeclarationTreeNode.kt | 5 | 4000 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.projectView
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.psi.*
internal class KtDeclarationTreeNode(
project: Project?,
ktDeclaration: KtDeclaration?,
viewSettings: ViewSettings?
) : AbstractPsiBasedNode<KtDeclaration?>(project, ktDeclaration!!, viewSettings) {
override fun extractPsiFromValue(): PsiElement? = value
override fun getChildrenImpl(): Collection<AbstractTreeNode<*>> = emptyList()
override fun updateImpl(data: PresentationData) {
val declaration = value ?: return
data.presentableText = tryGetRepresentableText(declaration)
}
override fun isDeprecated(): Boolean = value?.let { KtPsiUtil.isDeprecated(it) } ?: false
companion object {
private val CLASS_INITIALIZER = "<" + KotlinBundle.message("project.view.class.initializer") + ">"
private val ERROR_NAME = "<" + KotlinBundle.message("project.view.class.error.name") + ">"
private fun String?.orErrorName() = if (!isNullOrBlank()) this else ERROR_NAME
@NlsSafe
fun tryGetRepresentableText(declaration: KtDeclaration): String {
val settings = declaration.containingKtFile.kotlinCustomSettings
fun StringBuilder.appendColon() {
if (settings.SPACE_BEFORE_TYPE_COLON) append(" ")
append(":")
if (settings.SPACE_AFTER_TYPE_COLON) append(" ")
}
fun KtProperty.presentableText() = buildString {
append(name.orErrorName())
typeReference?.text?.let { reference ->
appendColon()
append(reference)
}
}
fun KtFunction.presentableText() = buildString {
receiverTypeReference?.text?.let { receiverReference ->
append(receiverReference)
append('.')
}
append(name.orErrorName())
append("(")
val valueParameters = valueParameters
valueParameters.forEachIndexed { index, parameter ->
parameter.name?.let { parameterName ->
append(parameterName)
appendColon()
}
parameter.typeReference?.text?.let { typeReference ->
append(typeReference)
}
if (index != valueParameters.size - 1) {
append(", ")
}
}
append(")")
typeReference?.text?.let { returnTypeReference ->
appendColon()
append(returnTypeReference)
}
}
fun KtObjectDeclaration.presentableText(): String = buildString {
if (isCompanion()) {
append("companion object")
} else {
append(name.orErrorName())
}
}
return when (declaration) {
is KtProperty -> declaration.presentableText()
is KtFunction -> declaration.presentableText()
is KtObjectDeclaration -> declaration.presentableText()
is KtAnonymousInitializer -> CLASS_INITIALIZER
else -> declaration.name.orErrorName()
}
}
}
}
| apache-2.0 | 74413257edf876d9fef4bd2ce4485000 | 38.60396 | 120 | 0.58775 | 5.763689 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/online/english/Mangahere.kt | 1 | 9986 | package eu.kanade.tachiyomi.source.online.english
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
class Mangahere : ParsedHttpSource() {
override val id: Long = 2
override val name = "Mangahere"
override val baseUrl = "http://www.mangahere.cc"
override val lang = "en"
override val supportsLatest = true
private val trustManager = object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
}
}
private val sslContext = SSLContext.getInstance("SSL").apply {
init(null, arrayOf(trustManager), SecureRandom())
}
override val client = super.client.newBuilder()
.sslSocketFactory(sslContext.socketFactory, trustManager)
.build()
override fun popularMangaSelector() = "div.directory_list > ul > li"
override fun latestUpdatesSelector() = "div.directory_list > ul > li"
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/directory/$page.htm?views.za", headers)
}
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/directory/$page.htm?last_chapter_time.za", headers)
}
private fun mangaFromElement(query: String, element: Element): SManga {
val manga = SManga.create()
element.select(query).first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = if (it.hasAttr("title")) it.attr("title") else if (it.hasAttr("rel")) it.attr("rel") else it.text()
}
return manga
}
override fun popularMangaFromElement(element: Element): SManga {
return mangaFromElement("div.title > a", element)
}
override fun latestUpdatesFromElement(element: Element): SManga {
return popularMangaFromElement(element)
}
override fun popularMangaNextPageSelector() = "div.next-page > a.next"
override fun latestUpdatesNextPageSelector() = "div.next-page > a.next"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = HttpUrl.parse("$baseUrl/search.php?name_method=cw&author_method=cw&artist_method=cw&advopts=1")!!.newBuilder().addQueryParameter("name", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is Status -> url.addQueryParameter("is_completed", arrayOf("", "1", "0")[filter.state])
is GenreList -> filter.state.forEach { genre -> url.addQueryParameter(genre.id, genre.state.toString()) }
is TextField -> url.addQueryParameter(filter.key, filter.state)
is Type -> url.addQueryParameter("direction", arrayOf("", "rl", "lr")[filter.state])
is OrderBy -> {
url.addQueryParameter("sort", arrayOf("name", "rating", "views", "total_chapters", "last_chapter_time")[filter.state!!.index])
url.addQueryParameter("order", if (filter.state?.ascending == true) "az" else "za")
}
}
}
url.addQueryParameter("page", page.toString())
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "div.result_search > dl:has(dt)"
override fun searchMangaFromElement(element: Element): SManga {
return mangaFromElement("a.manga_info", element)
}
override fun searchMangaNextPageSelector() = "div.next-page > a.next"
override fun mangaDetailsParse(document: Document): SManga {
val detailElement = document.select(".manga_detail_top").first()
val infoElement = detailElement.select(".detail_topText").first()
val licensedElement = document.select(".mt10.color_ff00.mb10").first()
val manga = SManga.create()
manga.author = infoElement.select("a[href*=author/]").first()?.text()
manga.artist = infoElement.select("a[href*=artist/]").first()?.text()
manga.genre = infoElement.select("li:eq(3)").first()?.text()?.substringAfter("Genre(s):")
manga.description = infoElement.select("#show").first()?.text()?.substringBeforeLast("Show less")
manga.thumbnail_url = detailElement.select("img.img").first()?.attr("src")
if (licensedElement?.text()?.contains("licensed") == true) {
manga.status = SManga.LICENSED
} else {
manga.status = infoElement.select("li:eq(6)").first()?.text().orEmpty().let { parseStatus(it) }
}
return manga
}
private fun parseStatus(status: String) = when {
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = ".detail_list > ul:not([class]) > li"
override fun chapterFromElement(element: Element): SChapter {
val parentEl = element.select("span.left").first()
val urlElement = parentEl.select("a").first()
var volume = parentEl.select("span.mr6")?.first()?.text()?.trim() ?: ""
if (volume.length > 0) {
volume = " - " + volume
}
var title = parentEl?.textNodes()?.last()?.text()?.trim() ?: ""
if (title.length > 0) {
title = " - " + title
}
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text() + volume + title
chapter.date_upload = element.select("span.right").first()?.text()?.let { parseChapterDate(it) } ?: 0
return chapter
}
private fun parseChapterDate(date: String): Long {
return if ("Today" in date) {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else if ("Yesterday" in date) {
Calendar.getInstance().apply {
add(Calendar.DATE, -1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else {
try {
SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH).parse(date).time
} catch (e: ParseException) {
0L
}
}
}
override fun pageListParse(document: Document): List<Page> {
val licensedError = document.select(".mangaread_error > .mt10").first()
if (licensedError != null) {
throw Exception(licensedError.text())
}
val pages = mutableListOf<Page>()
document.select("select.wid60").first()?.getElementsByTag("option")?.forEach {
if (!it.attr("value").contains("featured.html")) {
pages.add(Page(pages.size, "http:" + it.attr("value")))
}
}
pages.getOrNull(0)?.imageUrl = imageUrlParse(document)
return pages
}
override fun imageUrlParse(document: Document) = document.getElementById("image").attr("src")
private class Status : Filter.TriState("Completed")
private class Genre(name: String, val id: String = "genres[$name]") : Filter.TriState(name)
private class TextField(name: String, val key: String) : Filter.Text(name)
private class Type : Filter.Select<String>("Type", arrayOf("Any", "Japanese Manga (read from right to left)", "Korean Manhwa (read from left to right)"))
private class OrderBy : Filter.Sort("Order by",
arrayOf("Series name", "Rating", "Views", "Total chapters", "Last chapter"),
Filter.Sort.Selection(2, false))
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres)
override fun getFilterList() = FilterList(
TextField("Author", "author"),
TextField("Artist", "artist"),
Type(),
Status(),
OrderBy(),
GenreList(getGenreList())
)
// [...document.querySelectorAll("select[id^='genres'")].map((el,i) => `Genre("${el.nextSibling.nextSibling.textContent.trim()}", "${el.getAttribute('name')}")`).join(',\n')
// http://www.mangahere.co/advsearch.htm
private fun getGenreList() = listOf(
Genre("Action"),
Genre("Adventure"),
Genre("Comedy"),
Genre("Doujinshi"),
Genre("Drama"),
Genre("Ecchi"),
Genre("Fantasy"),
Genre("Gender Bender"),
Genre("Harem"),
Genre("Historical"),
Genre("Horror"),
Genre("Josei"),
Genre("Martial Arts"),
Genre("Mature"),
Genre("Mecha"),
Genre("Mystery"),
Genre("One Shot"),
Genre("Psychological"),
Genre("Romance"),
Genre("School Life"),
Genre("Sci-fi"),
Genre("Seinen"),
Genre("Shoujo"),
Genre("Shoujo Ai"),
Genre("Shounen"),
Genre("Shounen Ai"),
Genre("Slice of Life"),
Genre("Sports"),
Genre("Supernatural"),
Genre("Tragedy"),
Genre("Yaoi"),
Genre("Yuri")
)
} | apache-2.0 | 3f6d854fc9750ef566e7f9b545fa3e31 | 37.559846 | 177 | 0.601142 | 4.547359 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | python/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt | 1 | 5020 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.typing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.TYPING
import com.jetbrains.python.packaging.PyPIPackageUtil
import com.jetbrains.python.packaging.PyPackageManagers
import com.jetbrains.python.packaging.PyPackageUtil
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.PythonSdkType
import java.io.File
/**
* Utilities for managing the local copy of the typeshed repository.
*
* The original Git repo is located [here](https://github.com/JetBrains/typeshed).
*
* @author vlan
*/
object PyTypeShed {
private val ONLY_SUPPORTED_PY2_MINOR = 7
private val SUPPORTED_PY3_MINORS = 2..7
val WHITE_LIST = setOf(TYPING, "six", "__builtin__", "builtins", "exceptions", "types", "datetime", "functools", "shutil", "re", "time",
"argparse", "uuid", "threading", "signal")
private val BLACK_LIST = setOf<String>()
/**
* Returns true if we allow to search typeshed for a stub for [name].
*/
fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean {
val topLevelPackage = name.firstComponent ?: return false
if (topLevelPackage in BLACK_LIST) {
return false
}
if (topLevelPackage !in WHITE_LIST) {
return false
}
if (isInStandardLibrary(root)) {
return true
}
if (isInThirdPartyLibraries(root)) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val pyPIPackages = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: emptyList()
val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true
return PyPackageUtil.findPackage(packages, topLevelPackage) != null ||
pyPIPackages.any { PyPackageUtil.findPackage(packages, it) != null }
}
return false
}
/**
* Returns the list of roots in typeshed for the Python language level of [sdk].
*/
fun findRootsForSdk(sdk: Sdk): List<VirtualFile> {
val level = PythonSdkType.getLanguageLevelForSdk(sdk)
val dir = directory ?: return emptyList()
return findRootsForLanguageLevel(level)
.asSequence()
.map { dir.findFileByRelativePath(it) }
.filterNotNull()
.toList()
}
/**
* Returns the list of roots in typeshed for the specified Python language [level].
*/
fun findRootsForLanguageLevel(level: LanguageLevel): List<String> {
val minors = when (level.major) {
2 -> listOf(ONLY_SUPPORTED_PY2_MINOR)
3 -> SUPPORTED_PY3_MINORS.reversed().filter { it <= level.minor }
else -> return emptyList()
}
return minors.map { "stdlib/${level.major}.$it" } +
listOf("stdlib/${level.major}",
"stdlib/2and3",
"third_party/${level.major}",
"third_party/2and3")
}
/**
* Checks if the [file] is located inside the typeshed directory.
*/
fun isInside(file: VirtualFile): Boolean {
val dir = directory
return dir != null && VfsUtilCore.isAncestor(dir, file, true)
}
/**
* The actual typeshed directory.
*/
val directory: VirtualFile? by lazy {
val path = directoryPath ?: return@lazy null
StandardFileSystems.local().findFileByPath(path)
}
val directoryPath: String?
get() {
val paths = listOf("${PathManager.getConfigPath()}/typeshed",
"${PathManager.getConfigPath()}/../typeshed",
PythonHelpersLocator.getHelperPath("typeshed"))
return paths.asSequence()
.filter { File(it).exists() }
.firstOrNull()
}
/**
* A shallow check for a [file] being located inside the typeshed third-party stubs.
*/
fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path
fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path
private val LanguageLevel.major: Int
get() = this.version / 10
private val LanguageLevel.minor: Int
get() = this.version % 10
}
| apache-2.0 | 0711127be06d6d836edc9b1fae8f9dd9 | 34.602837 | 138 | 0.688446 | 4.320138 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/sob/SOBShipCombatFragment.kt | 1 | 5126 | package pt.joaomneto.titancompanion.adventure.impl.fragments.sob
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.Adventure
import pt.joaomneto.titancompanion.adventure.AdventureFragment
import pt.joaomneto.titancompanion.adventure.impl.SOBAdventure
import pt.joaomneto.titancompanion.util.DiceRoller
class SOBShipCombatFragment : AdventureFragment() {
internal var starshipCrewStrikeValue: TextView? = null
internal var starshipCrewStrengthValue: TextView? = null
internal var enemyCrewStrikeValue: TextView? = null
internal var enemyCrewStrengthValue: TextView? = null
internal var attackButton: Button? = null
var enemyCrewStrike = 0
var enemyCrewStrength = 0
internal var combatResult: TextView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
val rootView = inflater.inflate(R.layout.fragment_16sob_adventure_shipcombat, container, false)
val adv = activity as SOBAdventure
starshipCrewStrikeValue = rootView.findViewById<View>(R.id.starshipCrewStrikeValue) as TextView
starshipCrewStrengthValue = rootView.findViewById<View>(R.id.starshipCrewStrengthValue) as TextView
enemyCrewStrikeValue = rootView.findViewById<View>(R.id.enemyCrewStrikeValue) as TextView
enemyCrewStrengthValue = rootView.findViewById<View>(R.id.enemyCrewStrengthValue) as TextView
starshipCrewStrikeValue!!.text = "" + adv.currentCrewStrike
starshipCrewStrengthValue!!.text = "" + adv.currentCrewStrength
combatResult = rootView.findViewById<View>(R.id.combatResult) as TextView
setupIncDecButton(
rootView,
R.id.plusCrewStrikeButton,
R.id.minusCrewStrikeButton,
adv,
SOBAdventure::currentCrewStrike,
adv.initialCrewStrike
)
setupIncDecButton(
rootView,
R.id.plusCrewStrengthButton,
R.id.minusCrewStrengthButton,
adv,
SOBAdventure::currentCrewStrength,
adv.initialCrewStrength
)
setupIncDecButton(
rootView,
R.id.plusEnemyCrewStrikeButton,
R.id.minusEnemyCrewStrikeButton,
::enemyCrewStrike,
99
)
setupIncDecButton(
rootView,
R.id.plusEnemyCrewStrengthButton,
R.id.minusEnemyCrewStrengthButton,
::enemyCrewStrength,
99
)
attackButton = rootView.findViewById<View>(R.id.buttonAttack) as Button
attackButton!!.setOnClickListener(
OnClickListener {
if (enemyCrewStrength == 0 || adv.currentCrewStrength == 0)
return@OnClickListener
combatResult!!.text = ""
if (enemyCrewStrength > 0) {
val attackStrength = DiceRoller.roll2D6().sum + adv.currentCrewStrike
val enemyStrength = DiceRoller.roll2D6().sum + enemyCrewStrike
if (attackStrength > enemyStrength) {
val damage = 2
enemyCrewStrength -= damage
if (enemyCrewStrength <= 0) {
enemyCrewStrength = 0
Adventure.showAlert(R.string.ffDirectHitDefeat, adv)
} else {
combatResult!!.setText(R.string.sobDirectHit)
}
} else if (attackStrength < enemyStrength) {
val damage = 2
adv.currentCrewStrength = adv.currentCrewStrength - damage
if (adv.currentCrewStrength <= 0) {
adv.currentCrewStrength = 0
Adventure.showAlert(R.string.enemyDestroyedShip, adv)
} else {
combatResult!!.text = combatResult!!.text.toString() + "\n" + getString(R.string.sobEnemyHitYourShip)
}
} else {
combatResult!!.setText(R.string.bothShipsMissed)
}
} else {
return@OnClickListener
}
refreshScreensFromResume()
}
)
refreshScreensFromResume()
return rootView
}
override fun refreshScreensFromResume() {
val adv = activity as SOBAdventure
enemyCrewStrengthValue!!.text = "" + enemyCrewStrength
enemyCrewStrikeValue!!.text = "" + enemyCrewStrike
starshipCrewStrengthValue!!.text = "" + adv.currentCrewStrength
starshipCrewStrikeValue!!.text = "" + adv.currentCrewStrike
}
}
| lgpl-3.0 | fe657caec21ad35b844c63979f81fafd | 36.144928 | 129 | 0.611198 | 4.962246 | false | false | false | false |
scp504677840/Widget | Floating/app/src/main/java/com/scp/floating/MainService.kt | 1 | 4104 | package com.scp.floating
import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Binder
import android.os.IBinder
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
/**
* Created by scp on 18-4-16.
*/
class MainService : Service() {
private lateinit var windowManager: WindowManager
private lateinit var params: WindowManager.LayoutParams
private lateinit var toucherLayout: LinearLayout
private var statusBarHeight: Int = 0
private var buttonIV: ImageView? = null
override fun onCreate() {
super.onCreate()
//生成悬浮窗
createToucher()
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
//用imageButton检查悬浮窗还在不在,这里可以不要。优化悬浮窗时要用到。
if (buttonIV != null) {
windowManager.removeView(toucherLayout)
}
super.onDestroy()
}
/**
* 创建悬浮窗
*/
private fun createToucher() {
//配置WindowManager¶ms
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
params = WindowManager.LayoutParams()
//设置type.系统提示型窗口,一般都在应用程序窗口之上
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
//设置效果为背景透明
params.format = PixelFormat.RGBA_8888
//设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//设置窗口初始停靠位置
params.gravity = Gravity.START or Gravity.TOP
params.x = 0
params.y = 0
//设置悬浮窗口长宽数据
//注意,这里的width和height均使用px而非dp
//如果你想完全对应布局设置,需要先获取到机器的dpi
//px与dp的换算为px = dp * (dpi / 160)
params.width = 300
params.height = 300
val inflater = LayoutInflater.from(application)
//获取浮动窗口视图所在布局
toucherLayout = inflater.inflate(R.layout.view_floating, null) as LinearLayout
//添加toucherlayout
windowManager.addView(toucherLayout, params)
Log.e("MainActivity", "toucherlayout-->left:" + toucherLayout.left)
Log.e("MainActivity", "toucherlayout-->right:" + toucherLayout.right)
Log.e("MainActivity", "toucherlayout-->top:" + toucherLayout.top)
Log.e("MainActivity", "toucherlayout-->bottom:" + toucherLayout.bottom)
//主动计算出当前View的宽高信息
toucherLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
//用于检测状态栏高度
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
statusBarHeight = resources.getDimensionPixelSize(resourceId)
Log.e("MainActivity", "statusBarHeight:" + statusBarHeight)
}
//配置悬浮按钮
buttonIV = toucherLayout.findViewById(R.id.view_floating_toucher_iv) as ImageView
buttonIV!!.setOnClickListener {
Toast.makeText(application, "我被点击了", Toast.LENGTH_SHORT).show()
val intent = Intent(application,MainActivity::class.java)
startActivity(intent)
}
buttonIV!!.setOnTouchListener { v, event ->
//ImageButton我放在了布局中心,布局一共300dp
params.x = event.rawX.toInt() - 150
//这就是状态栏偏移量用的地方
params.y = event.rawY.toInt() - 150 - statusBarHeight
windowManager.updateViewLayout(toucherLayout, params)
false
}
}
} | apache-2.0 | aee8586a018da1c964c879cadfff8bcb | 31.380531 | 89 | 0.664297 | 3.984749 | false | false | false | false |
BastiaanOlij/godot | platform/android/java/lib/src/org/godotengine/godot/io/file/DataAccess.kt | 12 | 6118 | /*************************************************************************/
/* DataAccess.kt */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.io.file
import android.content.Context
import android.os.Build
import android.util.Log
import org.godotengine.godot.io.StorageScope
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import kotlin.math.max
/**
* Base class for file IO operations.
*
* Its derived instances provide concrete implementations to handle regular file access, as well
* as file access through the media store API on versions of Android were scoped storage is enabled.
*/
internal abstract class DataAccess(private val filePath: String) {
companion object {
private val TAG = DataAccess::class.java.simpleName
fun generateDataAccess(
storageScope: StorageScope,
context: Context,
filePath: String,
accessFlag: FileAccessFlags
): DataAccess? {
return when (storageScope) {
StorageScope.APP -> FileData(filePath, accessFlag)
StorageScope.SHARED -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStoreData(context, filePath, accessFlag)
} else {
null
}
StorageScope.UNKNOWN -> null
}
}
fun fileExists(storageScope: StorageScope, context: Context, path: String): Boolean {
return when(storageScope) {
StorageScope.APP -> FileData.fileExists(path)
StorageScope.SHARED -> MediaStoreData.fileExists(context, path)
StorageScope.UNKNOWN -> false
}
}
fun fileLastModified(storageScope: StorageScope, context: Context, path: String): Long {
return when(storageScope) {
StorageScope.APP -> FileData.fileLastModified(path)
StorageScope.SHARED -> MediaStoreData.fileLastModified(context, path)
StorageScope.UNKNOWN -> 0L
}
}
fun removeFile(storageScope: StorageScope, context: Context, path: String): Boolean {
return when(storageScope) {
StorageScope.APP -> FileData.delete(path)
StorageScope.SHARED -> MediaStoreData.delete(context, path)
StorageScope.UNKNOWN -> false
}
}
fun renameFile(storageScope: StorageScope, context: Context, from: String, to: String): Boolean {
return when(storageScope) {
StorageScope.APP -> FileData.rename(from, to)
StorageScope.SHARED -> MediaStoreData.rename(context, from, to)
StorageScope.UNKNOWN -> false
}
}
}
protected abstract val fileChannel: FileChannel
internal var endOfFile = false
fun close() {
try {
fileChannel.close()
} catch (e: IOException) {
Log.w(TAG, "Exception when closing file $filePath.", e)
}
}
fun flush() {
try {
fileChannel.force(false)
} catch (e: IOException) {
Log.w(TAG, "Exception when flushing file $filePath.", e)
}
}
fun seek(position: Long) {
try {
fileChannel.position(position)
endOfFile = position >= fileChannel.size()
} catch (e: Exception) {
Log.w(TAG, "Exception when seeking file $filePath.", e)
}
}
fun seekFromEnd(positionFromEnd: Long) {
val positionFromBeginning = max(0, size() - positionFromEnd)
seek(positionFromBeginning)
}
fun position(): Long {
return try {
fileChannel.position()
} catch (e: IOException) {
Log.w(
TAG,
"Exception when retrieving position for file $filePath.",
e
)
0L
}
}
fun size() = try {
fileChannel.size()
} catch (e: IOException) {
Log.w(TAG, "Exception when retrieving size for file $filePath.", e)
0L
}
fun read(buffer: ByteBuffer): Int {
return try {
val readBytes = fileChannel.read(buffer)
endOfFile = readBytes == -1 || (fileChannel.position() >= fileChannel.size())
if (readBytes == -1) {
0
} else {
readBytes
}
} catch (e: IOException) {
Log.w(TAG, "Exception while reading from file $filePath.", e)
0
}
}
fun write(buffer: ByteBuffer) {
try {
val writtenBytes = fileChannel.write(buffer)
if (writtenBytes > 0) {
endOfFile = false
}
} catch (e: IOException) {
Log.w(TAG, "Exception while writing to file $filePath.", e)
}
}
}
| mit | 6ba371cbc25fbc261e2820945f61fce5 | 32.431694 | 100 | 0.602975 | 4.092308 | false | false | false | false |
JayNewstrom/json | tests/integration-tests/src/test/java/com/jaynewstrom/jsonDelight/sample/custom/LenientTest.kt | 1 | 1141 | package com.jaynewstrom.jsonDelight.sample.custom
import com.jaynewstrom.jsonDelight.sample.JsonTestHelper
import org.fest.assertions.api.Assertions.assertThat
import org.junit.Test
class LenientTest {
@Test fun testLenientSerializerTrue() {
val testHelper = JsonTestHelper()
val serialized = testHelper.serialize(Lenient(true), Lenient::class.java)
assertThat(serialized).isEqualTo("{\"foo\":\"true\"}")
}
@Test fun testLenientSerializerFalse() {
val testHelper = JsonTestHelper()
val serialized = testHelper.serialize(Lenient(false), Lenient::class.java)
assertThat(serialized).isEqualTo("{\"foo\":\"false\"}")
}
@Test fun testLenientDeserializerTrue() {
val testHelper = JsonTestHelper()
val (foo) = testHelper.deserializeString(Lenient::class.java, "{\"foo\":\"true\"}")
assertThat(foo).isEqualTo(true)
}
@Test fun testLenientDeserializerFalse() {
val testHelper = JsonTestHelper()
val (foo) = testHelper.deserializeString(Lenient::class.java, "{\"foo\":\"false\"}")
assertThat(foo).isEqualTo(false)
}
}
| apache-2.0 | b9f0433a9adac177e8e55473e210c0aa | 35.806452 | 92 | 0.679229 | 4.600806 | false | true | false | false |
Goyatuzo/LurkerBot | plyd/plyd-core/src/main/kotlin/com/lurkerbot/core/response/RecentlyPlayed.kt | 1 | 1471 | package com.lurkerbot.core.response
import com.lurkerbot.core.gameTime.TimeRecord
import java.time.Duration
import java.time.LocalDateTime
@kotlinx.serialization.Serializable
data class RecentlyPlayed(
val gameName: String,
val gameDetail: String?,
val gameState: String?,
val smallAssetText: String?,
val largeAssetText: String?,
val timePlayed: Double,
val playedAgo: String
) {
companion object {
fun from(timeRecord: TimeRecord): RecentlyPlayed {
val timePlayed =
Duration.between(timeRecord.sessionBegin, timeRecord.sessionEnd)
.toMinutes()
.toDouble()
val timePlayedAgo =
Duration.between(timeRecord.sessionEnd, LocalDateTime.now()).toSeconds()
return RecentlyPlayed(
gameName = timeRecord.gameName,
gameDetail = timeRecord.gameDetail,
gameState = timeRecord.gameState,
smallAssetText = timeRecord.smallAssetText,
largeAssetText = timeRecord.largeAssetText,
timePlayed = timePlayed / 60,
playedAgo =
when {
timePlayedAgo < 60 -> "$timePlayedAgo second(s)"
timePlayedAgo < 3600 -> "${timePlayedAgo / 60} minute(s)"
else -> "${timePlayedAgo / 3600} hour(s)"
}
)
}
}
}
| apache-2.0 | 43c004fac72950d645f5340e79d351d6 | 34.02381 | 88 | 0.575119 | 4.870861 | false | false | false | false |
AlexandrDrinov/kotlin-koans-edu | src/ii_collections/_22_Fold_.kt | 1 | 530 | package ii_collections
fun example9() {
val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult })
result == 24
}
// The same as
fun whatFoldDoes(): Int {
var result = 1
listOf(1, 2, 3, 4).forEach { element -> result = element * result}
return result
}
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> =
customers.fold(allOrderedProducts, {orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }) }).toSet()
| mit | cf0aa86b756967b1c16bca6cda600be4 | 28.444444 | 92 | 0.664151 | 3.81295 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/jsonarray/WmJsonArrayRest.kt | 1 | 1207 | package com.foo.rest.examples.spring.openapi.v3.wiremock.jsonarray
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.BufferedReader
import java.net.URL
@RestController
@RequestMapping(path = ["/api/wm/jsonarray"])
class WmJsonArrayRest {
@GetMapping
fun getObject() : ResponseEntity<String> {
val url = URL("http://json.array:10877/api/foo")
val connection = url.openConnection()
connection.setRequestProperty("accept", "application/json")
val mapper = ObjectMapper()
val list = mapper.readValue(connection.getInputStream(), ArrayList::class.java)
val dto = mapper.convertValue(list[0], WmJsonArrayDto::class.java)
return if (dto.x!! > 0 && dto.cycle != null){
if ((dto.cycle!!.y ?: 0) > 0)
ResponseEntity.ok("OK X and Y")
else
ResponseEntity.ok("OK X")
} else{
ResponseEntity.status(500).build()
}
}
} | lgpl-3.0 | f3b953baa6af8388937cab856723cc02 | 31.648649 | 87 | 0.67937 | 4.22028 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/dsl-verification/src/main/java/com/example/dsl_verification/constraint/Rtl.kt | 2 | 2802 | /*
* Copyright (C) 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.
*/
@file:JvmName("DslVerificationKt")
@file:JvmMultifileClass
package com.example.dsl_verification.constraint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import com.example.dsl_verification.constraint.DslVerification.TwoBoxConstraintSet
@Preview
@Composable
fun Test1() {
val constraintSet = ConstraintSet(TwoBoxConstraintSet) {
val box1 = createRefFor("box1")
val box2 = createRefFor("box2")
constrain(box1) {
// TODO: Add a way to specify if this is LTR only
centerHorizontallyTo(parent, 0.2f)
}
constrain(box2) {
clearHorizontal()
absoluteLeft.linkTo(box1.start, 8.dp)
}
}
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Column {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = true), constraintSet = constraintSet
) {
Box(
modifier = Modifier
.background(Color.Red)
.layoutId("box1")
)
Box(
modifier = Modifier
.background(Color.Blue)
.layoutId("box2")
)
}
Button(onClick = { }) {
Text(text = "Run")
}
}
}
} | apache-2.0 | 87beb2ffe20b113869ca1af8a13ba24a | 34.481013 | 82 | 0.665953 | 4.765306 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/listener/SignChangeListener.kt | 1 | 3774 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.auctions.bukkit.listener
import com.rpkit.auctions.bukkit.RPKAuctionsBukkit
import com.rpkit.auctions.bukkit.auction.RPKAuctionId
import com.rpkit.auctions.bukkit.auction.RPKAuctionService
import com.rpkit.auctions.bukkit.bid.RPKBid
import com.rpkit.core.service.Services
import org.bukkit.ChatColor.GREEN
import org.bukkit.block.Sign
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.SignChangeEvent
/**
* Sign change listener for auction signs.
*/
class SignChangeListener(private val plugin: RPKAuctionsBukkit) : Listener {
@EventHandler
fun onSignChange(event: SignChangeEvent) {
if (event.getLine(0).equals("[auction]", ignoreCase = true)) {
event.setLine(0, "$GREEN[auction]")
if (!event.player.hasPermission("rpkit.auctions.sign.auction")) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages.noPermissionAuctionSignCreate)
return
}
try {
val auctionService = Services[RPKAuctionService::class.java]
if (auctionService == null) {
event.player.sendMessage(plugin.messages.noAuctionService)
return
}
val auctionId = event.getLine(1)?.toInt()
if (auctionId == null) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages.auctionSignInvalidIdNotANumber)
return
}
auctionService.getAuction(RPKAuctionId(auctionId)).thenAccept { auction ->
if (auction == null) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages.auctionSignInvalidAuctionDoesNotExist)
return@thenAccept
} else {
auction.bids.thenAccept { bids ->
plugin.server.scheduler.runTask(plugin, Runnable {
val data = event.block.state
if (data is Sign) {
data.setLine(2,
auction.item.amount.toString() + " x " + auction.item.type.toString()
.lowercase().replace('_', ' ')
)
data.setLine(
3, ((bids.maxByOrNull(RPKBid::amount)
?.amount ?: auction.startPrice) + auction.minimumBidIncrement).toString()
)
data.update()
}
})
}
}
}
} catch (exception: NumberFormatException) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages.auctionSignInvalidIdNotANumber)
return
}
}
}
}
| apache-2.0 | b3dbf9955435489c93bf23ba1f7d03d8 | 42.37931 | 117 | 0.550609 | 5.32299 | false | false | false | false |
google/summit-ast | src/main/java/com/google/summit/ast/traversal/DfsWalker.kt | 1 | 4042 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.summit.ast.traversal
import com.google.summit.ast.Node
import java.util.function.Supplier
import java.util.stream.Stream
typealias NodePredicate = (Node) -> Boolean
/**
* This depth-first search walker enables AST traversal as a stream of nodes.
*
* Given a [start] node, its subtree is walked in depth-first order. The visited nodes can be
* orderded in either pre- or post- visitation ordering.
*
* The [stream] method returns a [Stream<Node>] that allows the nodes to be filtered or processed as
* they are traversed. A typical usage might be: `DfsWalker(node).stream().filter(...).forEach(...)`
*
* The class is a [Supplier] of pairs of a [Node] and a "done" flags. The latter provides an
* indication to terminate a stream after all nodes have been visited, as is done internally in
* [stream].
*
* @property start the root of the subtree to walk
* @property ordering whether the nodes are in pre- or post-order visitation
* @property skipBelow should return `true` to skip the children/subtree of a node
*/
class DfsWalker(
val start: Node,
val ordering: Ordering = Ordering.POST_ORDER,
val skipBelow: NodePredicate = { _ -> false }
) : Supplier<DfsWalker.NodeAndDoneFlag> {
enum class Ordering {
PRE_ORDER, // a parent is visited before all its children
POST_ORDER, // a parent is visited after all its children
}
/** Returns a finite stream of [Node] objects from walking the AST. */
fun stream(): Stream<Node> = Stream.generate(this).takeWhile { !it.done }.map { it.node }
/** Pairing of a [Node] and a `Boolean` to indicate stream termination. */
data class NodeAndDoneFlag(val node: Node, val done: Boolean)
/** A node and its DFS traversal status. */
private data class NodeAndStatus(val node: Node, val status: Status)
private enum class Status {
/** When a node is UNVISITED, we have yet to push its children onto the stack. */
UNVISITED,
/**
* When a node is IN_PROGRESS, we have pushed its children onto the stack and are in the process
* of traversing its subtree.
*/
IN_PROGRESS,
}
/** Stack of current DFS traversal path. Initialized with [start] node. */
private val stack = mutableListOf(NodeAndStatus(start, Status.UNVISITED))
/** Pushes the children of a node onto the stack, unless [skipBelow] is `true`. */
private fun pushChildrenUnlessSkipped(parent: Node) {
if (!skipBelow(parent)) {
stack.addAll(parent.getChildren().asReversed().map { NodeAndStatus(it, Status.UNVISITED) })
}
}
/**
* Gets the next [Node] and whether the traversal is done.
*
* When the return value has the "done" flag set, the [Node] can be ignored.
*/
override fun get(): NodeAndDoneFlag {
while (!stack.isEmpty()) {
val element = stack.removeLast()
when (ordering) {
Ordering.PRE_ORDER -> {
pushChildrenUnlessSkipped(element.node)
return NodeAndDoneFlag(element.node, false)
}
Ordering.POST_ORDER -> {
if (element.status == Status.IN_PROGRESS) {
return NodeAndDoneFlag(element.node, false)
} else {
stack.add(NodeAndStatus(element.node, Status.IN_PROGRESS))
pushChildrenUnlessSkipped(element.node)
}
}
}
}
// When the stack is empty, the traversal is finished. Indicate via the "done" flag.
return NodeAndDoneFlag(start /*unused*/, true)
}
}
| apache-2.0 | 55e941eb43e80c4bbfbcd99120b6e28f | 36.775701 | 100 | 0.688273 | 3.958864 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/action/TranslateAction.kt | 1 | 4548 | package cn.yiiguxing.plugin.translate.action
import cn.yiiguxing.plugin.translate.service.TranslationUIManager
import cn.yiiguxing.plugin.translate.ui.BalloonPositionTracker
import cn.yiiguxing.plugin.translate.util.SelectionMode
import cn.yiiguxing.plugin.translate.util.createCaretRangeMarker
import cn.yiiguxing.plugin.translate.util.processBeforeTranslate
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.editor.markup.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
/**
* 翻译动作
*
* @param checkSelection 指定是否检查手动选择的文本。`true` - 如果有手动选择文本, 则忽略`autoSelectionMode`, `false` - 将忽略手动选择的文本。
*/
open class TranslateAction(checkSelection: Boolean = false) : AutoSelectAction(checkSelection), DumbAware {
override val selectionMode
get() = SelectionMode.INCLUSIVE
override fun onActionPerformed(event: AnActionEvent, editor: Editor, selectionRange: TextRange) {
val project = editor.project ?: CommonDataKeys.PROJECT.getData(event.dataContext)
val markupModel = editor.markupModel
val selectionModel = editor.selectionModel
val isColumnSelectionMode = editor.caretModel.caretCount > 1
val text: String
val starts: IntArray
val ends: IntArray
if (selectionModel.hasSelection(true) && isColumnSelectionMode) {
starts = selectionModel.blockSelectionStarts
ends = selectionModel.blockSelectionEnds
text = selectionModel.getSelectedText(true)?.processBeforeTranslate() ?: return
} else {
starts = intArrayOf(selectionRange.startOffset)
ends = intArrayOf(selectionRange.endOffset)
text = editor.document.getText(selectionRange).processBeforeTranslate() ?: return
}
//this logic is also used in ShowTranslationDialogAction
val currentNewTD = TranslationUIManager.instance(project).currentNewTranslationDialog()
if (currentNewTD != null) {
currentNewTD.translate(text)
return
}
val startLine by lazy { editor.offsetToVisualPosition(selectionRange.startOffset).line }
val endLine by lazy { editor.offsetToVisualPosition(selectionRange.endOffset).line }
val highlightAttributes = if (starts.size > 1 || startLine == endLine) {
HIGHLIGHT_ATTRIBUTES
} else {
MULTILINE_HIGHLIGHT_ATTRIBUTES
}
val highlighters = ArrayList<RangeHighlighter>(starts.size)
try {
for (i in starts.indices) {
highlighters += markupModel.addRangeHighlighter(
starts[i],
ends[i],
HighlighterLayer.SELECTION - 1,
highlightAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val caretRangeMarker = editor.createCaretRangeMarker(selectionRange)
val tracker = BalloonPositionTracker(editor, caretRangeMarker)
val balloon = TranslationUIManager.showBalloon(editor, text, tracker)
if (balloon.disposed) {
markupModel.removeHighlighters(highlighters)
} else {
Disposer.register(balloon) { markupModel.removeHighlighters(highlighters) }
}
} catch (thr: Throwable) {
markupModel.removeHighlighters(highlighters)
}
}
private companion object {
val EFFECT_COLOR = JBColor(0xFFEE6000.toInt(), 0xFFCC7832.toInt())
val HIGHLIGHT_ATTRIBUTES: TextAttributes = TextAttributes().apply {
effectType = EffectType.LINE_UNDERSCORE
effectColor = EFFECT_COLOR
}
val MULTILINE_HIGHLIGHT_ATTRIBUTES: TextAttributes = TextAttributes().apply {
effectType = EffectType.BOXED
effectColor = EFFECT_COLOR
}
private fun MarkupModel.removeHighlighters(highlighters: Collection<RangeHighlighter>) {
for (highlighter in highlighters) {
removeHighlighter(highlighter)
highlighter.dispose()
}
}
}
}
| mit | 20b538556dc4b42c6edcfb3d1212e84f | 39.6 | 107 | 0.677788 | 5.06924 | false | false | false | false |
danirod/rectball | app/src/main/java/es/danirod/rectball/scene2d/input/DragBoardSelectionListener.kt | 1 | 2349 | package es.danirod.rectball.scene2d.input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import es.danirod.rectball.model.Bounds
import es.danirod.rectball.model.Coordinate
import es.danirod.rectball.scene2d.game.BallActor
import es.danirod.rectball.scene2d.game.BoardActor
import java.lang.Math.min
class DragBoardSelectionListener(val board: BoardActor) : InputListener() {
private var active: Boolean = false
private var startX: Int = 0
private var startY: Int = 0
private var minX: Int = 0
private var minY: Int = 0
private var maxX: Int = 0
private var maxY: Int = 0
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
val touched = board.hit(x, y, true)
return if (pointer == 0 && button == 0 && touched is BallActor) {
startX = touched.ball.x
startY = touched.ball.y
true
} else {
super.touchDown(event, x, y, pointer, button)
}
}
override fun touchDragged(event: InputEvent?, x: Float, y: Float, pointer: Int) {
val touched = board.hit(x, y, true)
if (touched is BallActor) {
if (active) {
tintSelection(Color.WHITE)
}
computeBounds(touched)
tintSelection(Color.GRAY)
}
}
override fun touchUp(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int) {
val touched = board.hit(x, y, true)
if (touched is BallActor) {
computeBounds(touched)
}
if (active) {
tintSelection(Color.WHITE)
board.select(Bounds(minX, minY, maxX, maxY))
active = false
}
}
private fun computeBounds(touched: BallActor) {
val endX: Int = touched.ball.x
val endY: Int = touched.ball.y
minX = startX.coerceAtMost(endX)
maxX = startX.coerceAtLeast(endX)
minY = startY.coerceAtMost(endY)
maxY = startY.coerceAtLeast(endY)
active = true
}
private fun tintSelection(color: Color) {
for (x in minX..maxX) {
for (y in minY..maxY) {
board.getBall(x, y).color = color
}
}
}
} | gpl-3.0 | 0917d12fcca6a11e60d8fbb0b617f139 | 28.746835 | 104 | 0.604513 | 3.857143 | false | false | false | false |
a642500/Ybook | app/src/main/kotlin/com/ybook/app/ui/detail/BookDetailActivity.kt | 1 | 8505 | /*
Copyright 2015 Carlos
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.ybook.app.ui.detail
import com.ybook.app.id
import com.ybook.app.swipebacklayout.SwipeBackActivity
import android.view.View
import com.melnykov.fab.FloatingActionButton
import com.ybook.app.bean.SearchResponse
import com.ybook.app.bean.BookItem
import android.os.Bundle
import android.support.v7.widget.Toolbar
import com.ybook.app.bean.BookListResponse
import android.widget.TextView
import android.widget.ImageView
import android.support.v4.view.ViewPager
import com.ybook.app.viewpagerindicator.TabPageIndicator
import android.view.MenuItem
import com.ybook.app.bean.DetailResponse
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import com.ybook.app.util.BooksListUtil
import com.ybook.app.R
import com.ybook.app.ui.home
import com.umeng.analytics.MobclickAgent
import com.squareup.picasso.Picasso
import android.widget.Toast
import de.keyboardsurfer.android.widget.crouton.Style
import de.keyboardsurfer.android.widget.crouton.Crouton
import com.ybook.app
import com.ybook.app.bean
import com.ybook.app.net
import com.ybook.app.net.PostHelper
import com.ybook.app.ui
import android.app.Activity
import com.ybook.app.net.DetailRequest
/**
* This activity is to display the detail of book of the search results.
* Created by Carlos on 2014/8/1.
*/
public class BookDetailActivity : SwipeBackActivity(), View.OnClickListener {
var mMarkFAB: FloatingActionButton? = null
private var mSearchObject: SearchResponse.SearchObject? = null
private var mBookItem: BookItem? = null
private var mUtil = BooksListUtil.getInstance(this)
//http://ftp.lib.hust.edu.cn/record=b2673698~S0*chx
override fun onCreate(savedInstanceState: Bundle?) {
super<SwipeBackActivity>.onCreate(savedInstanceState)
setContentView(R.layout.book_details_activity)
setSupportActionBar(this.id(R.id.toolBar) as Toolbar)
setResult(RESULT_CODE_UNCHANGED, getIntent())
val o = getIntent() getSerializableExtra INTENT_SEARCH_OBJECT ?: getIntent().getSerializableExtra(home.KEY_BOOK_LIST_RESPONSE_EXTRA)
when (o) {
is SearchResponse.SearchObject -> mSearchObject = o
is BookItem -> mBookItem = o
is BookListResponse.BookListObject -> mSearchObject = o.toSearchObject()
else -> this.finish()
}
initViews()
}
override fun onResume() {
super<SwipeBackActivity>.onResume()
MobclickAgent.onResume(this);
}
override fun onPause() {
super<SwipeBackActivity>.onPause()
MobclickAgent.onPause(this);
}
var titleView: TextView ? = null
private fun initViews() {
mMarkFAB = id(R.id.fab) as FloatingActionButton
val imageView = id(R.id.image_view_book_cover) as ImageView
titleView = id(R.id.text_view_book_title) as TextView
val viewPager = id(R.id.detail_viewPager) as ViewPager
val indicator = id(R.id.detail_viewPager_indicator) as TabPageIndicator
var title: String?
if (mSearchObject == null) {
Picasso.with(this).load(mBookItem!!.detailResponse.coverImageUrl).error(getResources().getDrawable(R.drawable.ic_error)).resizeDimen(R.dimen.cover_height, R.dimen.cover_width).into(imageView)
title = mBookItem!!.detailResponse.title.trim()
viewPager setAdapter MyDetailPagerAdapter(getSupportFragmentManager(), null, mBookItem!!)
if (mBookItem!! isMarked mUtil) mMarkFAB!! setImageResource R.drawable.fab_star_unlike
else mMarkFAB!! setImageResource R.drawable.fab_drawable_star_like
} else {
Picasso.with(this).load(mSearchObject!!.coverImgUrl).error(getResources().getDrawable(R.drawable.ic_error)).resizeDimen(R.dimen.cover_height, R.dimen.cover_width).into(imageView)
title = mSearchObject!!.title.trim()
viewPager.setAdapter(MyDetailPagerAdapter(getSupportFragmentManager(), mSearchObject!!, null))
if (mSearchObject!! isMarked mUtil ) mMarkFAB!! setImageResource R.drawable.fab_star_unlike
else mMarkFAB!! setImageResource R.drawable.fab_drawable_star_like
}
indicator setViewPager viewPager
indicator setBackgroundResource R.drawable.indicator_bg_selector
if (title!!.trim().length() == 0) title = getString(R.string.noTitleHint)
titleView!! setText title
setupActionBar()
}
private fun setupActionBar() {
val bar = getSupportActionBar()
bar.setTitle(mSearchObject?.title ?: mBookItem?.detailResponse?.title)
bar.setDisplayShowTitleEnabled(true)
bar setDisplayHomeAsUpEnabled true
bar setDisplayUseLogoEnabled false
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.getItemId()) {
android.R.id.home -> onBackPressed()
}
return super<SwipeBackActivity>.onOptionsItemSelected(item)
}
override fun onClick(v: View) {
when (v.getId()) {
R.id.fab -> {
if (mBookItem == null) Toast.makeText(this, "loading, please try again when loaded.", Toast.LENGTH_SHORT).show()
else {
mBookItem!!.markOrCancelMarked(mUtil)
setResult(RESULT_CODE_CHANGED, getIntent())
if (mBookItem!!.isMarked(mUtil)) {
Crouton.makeText(this, getResources().getString(R.string.toastMarked), Style.INFO).show()
mMarkFAB!! setImageResource R.drawable.fab_star_unlike
MobclickAgent.onEvent(this, app.util.EVENT_ADD_FROM_DETAIL)
} else {
Crouton.makeText(this, getResources().getString(R.string.toastCancelMark), Style.INFO).show()
mMarkFAB!! setImageResource R.drawable.fab_drawable_star_like
MobclickAgent.onEvent(this, app.util.EVENT_DELETE_FROM_DETAIL)
}
}
}
}
}
fun onRefresh(detail: DetailResponse) {
titleView!! setText detail.title
}
// R.id.button_addToList -> {
// }
inner class MyDetailPagerAdapter(fm: FragmentManager, searchObject: SearchResponse.SearchObject?, bookItem: BookItem?) : FragmentPagerAdapter(fm) {
{
if (searchObject != null) PostHelper.detail(DetailRequest(searchObject.id, searchObject.idType, bean.getLibCode()), object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
net.MSG_SUCCESS -> (msg.obj as DetailResponse).let {
mBookItem = it.toBookItem()
pagers.forEach { p -> p.onRefresh(it) }
this@BookDetailActivity.onRefresh(it)
}
net.MSG_ERROR -> pagers.forEach { p -> p.onError() }
}
}
})
}
val pagers = array(DetailInfoFragment(searchObject, bookItem), DetailStoreFragment(searchObject, bookItem))
val titleResId = array(R.string.detailTabTitleInfo, R.string.detailTabTitleStatus)
override fun getItem(i: Int) = pagers[i]
override fun getCount() = 2
override fun getPageTitle(position: Int) = getResources().getString(titleResId[position])
}
class object {
public val INTENT_SEARCH_OBJECT: String = "searchObject"
public val RESULT_CODE_UNCHANGED: Int = Activity.RESULT_FIRST_USER
public val RESULT_CODE_CHANGED: Int = Activity.RESULT_FIRST_USER + 1
}
trait OnDetail : Fragment {
public fun onRefresh(detail: DetailResponse)
public fun onError()
}
} | apache-2.0 | 682a0b6f413d140b6845ecdc7a81897e | 41.53 | 203 | 0.669371 | 4.271723 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/RoleInfoExecutor.kt | 1 | 5312 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord
import dev.kord.common.Color
import dev.kord.rest.Image
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.discordinteraktions.common.utils.thumbnailUrl
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.GuildApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.declarations.ServerCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.loritta.cinnamon.discord.utils.RawToFormated.toLocalized
import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor
import net.perfectdreams.loritta.common.utils.LorittaColors
class RoleInfoExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val role = role("role", ServerCommand.I18N_PREFIX.Role.Info.Options.Role)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
if (context !is GuildApplicationCommandContext)
context.fail {
content = context.i18nContext.get(I18nKeysData.Commands.CommandOnlyAvailableInGuilds)
}
val role = args[options.role]
val iconUrl = role.icon?.cdnUrl?.toUrl {
this.size = Image.Size.Size2048
}
// If the color is not 0, then it means that it has a color set!
val hasColor = role.data.color != 0
context.sendMessage {
embed {
title = "${Emotes.BriefCase.asMention} ${role.name}"
color = if (hasColor)
Color(role.data.color)
else
LorittaColors.DiscordBlurple.toKordColor()
if (role.icon != null)
thumbnailUrl = iconUrl
field {
name = "${Emotes.Eyes} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Mention)
value = "`<@&${role.id}>`"
inline = true
}
field {
name = "${Emotes.LoriId} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.RoleId)
value = "`${role.id}`"
inline = true
}
field {
name = "${Emotes.Eyes} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Hoisted)
value = context.i18nContext.get(role.hoisted.toLocalized())
inline = true
}
field {
name = "${Emotes.BotTag} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Managed)
value = context.i18nContext.get(role.managed.toLocalized())
inline = true
}
field {
name = "${Emotes.LoriPing} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Mentionable)
value = context.i18nContext.get(role.mentionable.toLocalized())
inline = true
}
if (hasColor) {
field {
name = "${Emotes.Art} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Color)
value = "`#${Integer.toHexString(role.data.color).uppercase()}`"
inline = true
}
}
field {
name = "${Emotes.LoriCalendar} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.CreatedAt)
value = "<t:${role.id.timestamp.toEpochMilliseconds() / 1000}:D>"
inline = true
}
val rolePermissionsLocalized = role.permissions.values.toLocalized()?.joinToString(
", ",
transform = { "`${context.i18nContext.get(it)}`" }
)
field {
name = "${Emotes.Shield} " + context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.Permissions)
value = rolePermissionsLocalized ?: context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.NoPermissions)
}
}
if (iconUrl != null)
actionRow {
linkButton(iconUrl) {
label = context.i18nContext.get(ServerCommand.I18N_PREFIX.Role.Info.OpenRoleIconInBrowser)
}
}
}
}
} | agpl-3.0 | 601e337aac97a1f59c3eddfb868552c4 | 41.846774 | 130 | 0.610316 | 4.751342 | false | false | false | false |
simonorono/pradera_baja | asistencia/src/main/kotlin/pb/asistencia/controller/Control.kt | 1 | 2885 | /*
* Copyright 2016 Simón Oroño
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pb.asistencia.controller
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.TableView
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import pb.asistencia.data.DB
import pb.asistencia.data.Persona
import pb.asistencia.window.PersonaForm
@Suppress("UNUSED_PARAMETER")
class Control {
@FXML private var tablaPersonas: TableView<Persona>? = null
@FXML private var searchBar: TextField? = null
fun initialize() {
update()
}
fun update(p: List<Persona>? = null) {
tablaPersonas?.let {
val personas = p ?: DB.personas()
val i = it.selectionModel.selectedIndex
it.items.clear()
it.items.addAll(*personas.toTypedArray())
it.selectionModel.select(i)
}
}
fun buscar() {
val qry = searchBar?.text ?: ""
when (qry) {
"" -> update()
else -> {
val personas = DB.buscar(qry)
update(personas)
}
}
}
@FXML
fun agregarOnAction(event: ActionEvent) {
val edit = PersonaForm(null)
edit.showAndWait()
if (edit.isDone()) {
update()
}
}
@FXML
fun eliminarOnAction(event: ActionEvent) {
tablaPersonas?.let {
val p = it.selectionModel.selectedItem
if (p != null) {
DB.deletePersona(p.getId())
DB.deleteEventoFromPersona(p.getId())
}
update()
}
}
@FXML
fun editarOnAction(event: ActionEvent) {
tablaPersonas?.let {
val p = it.selectionModel.selectedItem
if (p != null) {
val edit = PersonaForm(p)
edit.showAndWait()
if (edit.isDone()) {
update()
}
}
}
}
@FXML
fun busquedaKeyPressed(event: KeyEvent) {
if (event.code == KeyCode.ENTER) {
buscar()
}
}
@FXML
fun buscarOnAction(event: ActionEvent) {
buscar()
}
@FXML
fun restablecerOnAction(event: ActionEvent) {
searchBar?.clear()
update()
}
}
| apache-2.0 | f8789c5b62ef5afa402e92e563a31f8b | 24.289474 | 75 | 0.579951 | 4.100996 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/utils/KotlinUtils.kt | 1 | 3666 | package com.sampsonjoliver.firestarter.utils
import android.content.Context
import android.location.Location
import android.os.Handler
import android.os.SystemClock
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import com.firebase.geofire.GeoLocation
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
val <T : Any> T.TAG: String
get() = this.javaClass.name
fun ViewGroup.inflate(@LayoutRes layoutId: Int, attachToParent: Boolean): View {
return LayoutInflater.from(this.context).inflate(layoutId, this, attachToParent)
}
inline fun <T, R: Comparable<R>> MutableCollection<T>.insertSorted(obj: T, crossinline selector: (T) -> R?): Int {
this.add(obj)
this.sortedBy(selector)
return this.indexOf(obj)
}
var View.visible: Boolean
get() = this.visibility == View.VISIBLE
set(value) {
this.visibility = if (value) View.VISIBLE else View.INVISIBLE
}
var View.appear: Boolean
get() = this.visibility == View.VISIBLE
set(value) {
this.visibility = if (value) View.VISIBLE else View.GONE
}
fun Any?.exists():Boolean = this != null
inline fun consume(func: () -> Unit): Boolean { func(); return true }
inline fun <T> T.whenEqual(that: T, block: (T) -> Unit) {
if (this == that) block.invoke(this)
}
inline fun <T> T.whenNotEqual(that: T, block: (T) -> Unit) {
if (this != that) block.invoke(this)
}
fun View.setBackgroundResourcePreservePadding(@LayoutRes res: Int) {
val padBottom = paddingBottom
val padTop = paddingTop
val padLeft = paddingLeft
val padRight = paddingRight
val padStart = paddingStart
val padEnd = paddingEnd
this.setBackgroundResource(res)
setPadding(padLeft, padTop, padRight, padBottom)
setPaddingRelative(padStart, padTop, padEnd, padBottom)
}
fun Context.copyToClipboard(key: String, obj: String) {
// Backwards compatible clipboard service
val sdk = android.os.Build.VERSION.SDK_INT
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
clipboard.text = obj
} else {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
val clip = android.content.ClipData.newPlainText(key, obj)
clipboard.primaryClip = clip
}
}
// Animation handler for old APIs without animation support
fun Marker.animateMarkerTo(lat: Double, lng: Double) {
val handler = Handler()
val start = SystemClock.uptimeMillis()
val DURATION_MS = 3000f
val interpolator = AccelerateDecelerateInterpolator()
val startPosition = position
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t = elapsed / DURATION_MS
val v = interpolator.getInterpolation(t)
val currentLat = (lat - startPosition.latitude) * v + startPosition.latitude
val currentLng = (lng - startPosition.longitude) * v + startPosition.longitude
position = LatLng(currentLat, currentLng)
// if animation is not finished yet, repeat
if (t < 1) {
handler.postDelayed(this, 16)
}
}
})
}
fun Location?.latLng(): LatLng {
return LatLng(this?.latitude ?: 0.0, this?.longitude ?: 0.0)
}
fun GeoLocation?.latLng(): LatLng {
return LatLng(this?.latitude ?: 0.0, this?.longitude ?: 0.0)
} | apache-2.0 | 7e89aa73ff96c63d5dbb607582268a77 | 32.036036 | 114 | 0.694763 | 4.059801 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/toolWindow/log/UnityLogPanelToolbarBuilder.kt | 1 | 5457 | package com.jetbrains.rider.plugins.unity.toolWindow.log
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.jetbrains.rider.plugins.unity.UnityBundle
import com.jetbrains.rider.plugins.unity.model.LogEventMode
import com.jetbrains.rider.plugins.unity.model.LogEventType
import com.jetbrains.rider.plugins.unity.toolWindow.UnityToolWindowFactory
import com.jetbrains.rider.ui.RiderAction
import icons.UnityIcons
import java.awt.BorderLayout
import javax.swing.JPanel
object UnityLogPanelToolbarBuilder {
private fun create(actionGroup: ActionGroup, layout: String, horizontal: Boolean): JPanel {
val component = ActionManager.getInstance()
.createActionToolbar(UnityToolWindowFactory.ACTION_PLACE, actionGroup, horizontal)
.component
return JPanel(BorderLayout()).apply { add(component, layout) }
}
fun createTopToolbar(): JPanel {
return create(ActionGroup.EMPTY_GROUP, BorderLayout.NORTH, true)
}
fun createLeftToolbar(model: UnityLogPanelModel): JPanel {
fun getLocalizedName(eventType: LogEventType):String {
return when (eventType) {
LogEventType.Error -> UnityBundle.message("logEventType.errors")
LogEventType.Warning -> UnityBundle.message("logEventType.warning")
LogEventType.Message -> UnityBundle.message("logEventType.messages")
}
}
fun createType(type: LogEventType) = object : ToggleAction(UnityBundle.message("show.hide", getLocalizedName(type)), "", type.getIcon()) {
override fun isSelected(e: AnActionEvent) = model.typeFilters.getShouldBeShown(type)
override fun setSelected(e: AnActionEvent, value: Boolean) = model.typeFilters.setShouldBeShown(type, value)
override fun update(e: AnActionEvent) {
if (isSelected(e))
e.presentation.text = UnityBundle.message("hide", getLocalizedName(type))
else
e.presentation.text = UnityBundle.message("show", getLocalizedName(type))
super.update(e)
}
}
fun createMode(mode: LogEventMode) = object : ToggleAction(UnityBundle.message("action.show.hide.mode.text", mode), "", mode.getIcon()) {
override fun isSelected(e: AnActionEvent) = model.modeFilters.getShouldBeShown(mode)
override fun setSelected(e: AnActionEvent, value: Boolean) = model.modeFilters.setShouldBeShown(mode, value)
override fun update(e: AnActionEvent) {
if (isSelected(e))
e.presentation.text = UnityBundle.message("action.hide.mode.text", mode)
else
e.presentation.text = UnityBundle.message("action.show.mode.text", mode)
super.update(e)
}
}
fun collapseAll() = object : ToggleAction(UnityBundle.message("action.collapse.similar.items.text"), "", AllIcons.Actions.Collapseall) {
override fun isSelected(e: AnActionEvent) = model.mergeSimilarItems.value
override fun setSelected(e: AnActionEvent, value: Boolean) {
model.mergeSimilarItems.set(value)
}
}
fun autoscroll() = object : ToggleAction(UnityBundle.message("action.autoscroll.text"), "", AllIcons.RunConfigurations.Scroll_down) {
override fun isSelected(e: AnActionEvent) = model.autoscroll.value
override fun setSelected(e: AnActionEvent, value: Boolean) {
model.autoscroll.set(value)
model.events.onAutoscrollChanged.fire(value)
}
}
fun createBeforePlay() = object : ToggleAction(UnityBundle.message("action.messages.before.last.play.in.unity.text"), "", UnityIcons.LogView.FilterBeforePlay) {
override fun isSelected(e: AnActionEvent) = model.timeFilters.getShouldBeShownBeforePlay()
override fun setSelected(e: AnActionEvent, value: Boolean) {
model.timeFilters.setShowBeforePlay(value)
}
}
fun createBeforeInit() = object : ToggleAction(UnityBundle.message("action.messages.before.last.domain.reload.text"), "", UnityIcons.LogView.FilterBeforeRefresh) {
override fun isSelected(e: AnActionEvent) = model.timeFilters.getShouldBeShownBeforeInit()
override fun setSelected(e: AnActionEvent, value: Boolean) {
model.timeFilters.setShowBeforeLastBuild(value)
}
}
val actionGroup = DefaultActionGroup().apply {
addSeparator(UnityBundle.message("separator.mode.filters"))
add(createMode(LogEventMode.Edit))
add(createMode(LogEventMode.Play))
addSeparator(UnityBundle.message("separator.type.filters"))
add(createType(LogEventType.Error))
add(createType(LogEventType.Warning))
add(createType(LogEventType.Message))
addSeparator(UnityBundle.message("separator.time.filters"))
add(createBeforePlay())
add(createBeforeInit())
addSeparator(UnityBundle.message("separator.other"))
add(collapseAll())
add(autoscroll())
add(RiderAction(UnityBundle.message("action.clear.text"), AllIcons.Actions.GC) { model.events.clear() })
}
return create(actionGroup, BorderLayout.WEST, false)
}
} | apache-2.0 | 416c67f82c3db4d43bdd48f55f6d322f | 48.171171 | 171 | 0.663368 | 4.70431 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/security/CertificatePin.kt | 1 | 909 | package com.baulsupp.okurl.security
import com.baulsupp.oksocial.output.UsageException
import okhttp3.CertificatePinner
class CertificatePin(patternAndPin: String) {
val pattern: String
private val pin: String?
init {
val parts = patternAndPin.split(":".toRegex(), 2).toTypedArray()
pattern = parts[0]
pin = if (parts.size == 2) parts[1] else null
}
fun getPin(): String {
if (pin == null) {
throw UsageException(
"--certificatePin expects host:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
)
}
return pin
}
companion object {
fun buildFromCommandLine(pins: List<CertificatePin>): CertificatePinner {
val builder = CertificatePinner.Builder()
pins.groupBy { it.pattern }.forEach { (pattern, pins) ->
builder.add(pattern, *pins.map { it.pin!! }.toTypedArray())
Unit
}
return builder.build()
}
}
}
| apache-2.0 | 9a79f1f00cba5e5f4570af4d17174833 | 21.725 | 79 | 0.658966 | 4.208333 | false | false | false | false |
EyeSeeTea/QAApp | app/src/main/java/org/eyeseetea/malariacare/presentation/bugs/BugReport.kt | 1 | 1133 | package org.eyeseetea.malariacare.presentation.bugs
import android.content.Context
import android.util.Log
import com.google.firebase.crashlytics.FirebaseCrashlytics
import org.eyeseetea.malariacare.utils.AUtils.getCommitHash
private const val gitHashKey: String = "gitHash"
private const val serverKey: String = "server"
private const val userKey: String = "user"
private const val logPrefix: String = "BugReport"
fun addGitHash(context: Context) {
val commitHash = getCommitHash(context)
FirebaseCrashlytics.getInstance().setCustomKey(gitHashKey, commitHash)
Log.d("$logPrefix.$gitHashKey", commitHash)
}
fun addServerAndUser(server: String, user: String) {
FirebaseCrashlytics.getInstance().setCustomKey(serverKey, server)
FirebaseCrashlytics.getInstance().setCustomKey(userKey, user)
Log.d("$logPrefix.$serverKey", server)
Log.d("$logPrefix.$userKey", user)
}
fun removeServerAndUser() {
FirebaseCrashlytics.getInstance().setCustomKey(serverKey, "")
FirebaseCrashlytics.getInstance().setCustomKey(userKey, "")
Log.d("$logPrefix.$serverKey", "")
Log.d("$logPrefix.$userKey", "")
}
| gpl-3.0 | a465d7ecb2f3fddb3a974366d9216dec | 35.548387 | 74 | 0.764342 | 4.12 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/materials/Transparent.kt | 1 | 1727 | package net.dinkla.raytracer.materials
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.Shade
import net.dinkla.raytracer.brdf.PerfectSpecular
import net.dinkla.raytracer.btdf.PerfectTransmitter
import net.dinkla.raytracer.math.Ray
import net.dinkla.raytracer.worlds.World
class Transparent : Phong() {
var reflectiveBrdf: PerfectSpecular
var specularBtdf: PerfectTransmitter
init {
this.reflectiveBrdf = PerfectSpecular()
this.specularBtdf = PerfectTransmitter()
}
fun setKt(kt: Double) {
specularBtdf.kt = kt
}
fun setIor(ior: Double) {
specularBtdf.ior = ior
}
fun setKr(kr: Double) {
reflectiveBrdf.kr = kr
}
fun setCr(cr: Color) {
reflectiveBrdf.cr = cr
}
override fun shade(world: World, sr: Shade): Color {
var l = super.shade(world, sr)
val wo = sr.ray.direction.times(-1.0)
val brdf = reflectiveBrdf.sampleF(sr, wo)
// trace reflected ray
val reflectedRay = Ray(sr.hitPoint, brdf.wi!!)
val cr = world.tracer.trace(reflectedRay, sr.depth + 1)
if (specularBtdf.isTir(sr)) {
l = l.plus(cr)
} else {
// reflected
val cfr = Math.abs(sr.normal.dot(brdf.wi!!))
l = l.plus(brdf.color!!.times(cr).times(cfr))
// trace transmitted ray
val btdf = specularBtdf.sampleF(sr, wo)
val transmittedRay = Ray(sr.hitPoint, btdf.wt!!)
val ct = world.tracer.trace(transmittedRay, sr.depth + 1)
val cft = Math.abs(sr.normal.dot(btdf.wt!!))
l = l.plus(btdf.color!!.times(ct).times(cft))
}
return l
}
}
| apache-2.0 | 5cea2c6604f62fe95435140f5a2eee5d | 27.783333 | 69 | 0.610886 | 3.481855 | false | false | false | false |
AdityaAnand1/Morphing-Material-Dialogs | library/src/main/java/com/adityaanand/morphdialog/morphutil/MorphDrawable.kt | 1 | 2556 | package com.adityaanand.morphdialog.morphutil
import android.annotation.TargetApi
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Outline
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Property
import androidx.annotation.ColorInt
/**
* A drawable that can morph size, shape (via it's corner radius) and color. Specifically this is
* useful for animating between a FAB and a dialog.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class MorphDrawable(@ColorInt color: Int, private var cornerRadius: Float) : Drawable() {
private val paint: Paint
var color: Int
get() = paint.color
set(color) {
paint.color = color
invalidateSelf()
}
init {
paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = color
}
fun getCornerRadius(): Float {
return cornerRadius
}
fun setCornerRadius(cornerRadius: Float) {
this.cornerRadius = cornerRadius
invalidateSelf()
}
override fun draw(canvas: Canvas) {
canvas.drawRoundRect(bounds.left.toFloat(), bounds.top.toFloat(), bounds.right.toFloat(), bounds
.bottom.toFloat(), cornerRadius, cornerRadius, paint)//hujiawei
}
override fun getOutline(outline: Outline) {
outline.setRoundRect(bounds, cornerRadius)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
invalidateSelf()
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
invalidateSelf()
}
override fun getOpacity(): Int {
return paint.alpha
}
companion object {
val CORNER_RADIUS: Property<MorphDrawable, Float> = object : Property<MorphDrawable, Float>(Float::class.java, "cornerRadius") {
override fun set(morphDrawable: MorphDrawable, value: Float?) {
morphDrawable.setCornerRadius(value!!)
}
override fun get(morphDrawable: MorphDrawable): Float {
return morphDrawable.getCornerRadius()
}
}
val COLOR: Property<MorphDrawable, Int> = object : Property<MorphDrawable, Int>(Int::class.java, "color") {
override fun set(morphDrawable: MorphDrawable, value: Int) {
morphDrawable.color = value
}
override fun get(morphDrawable: MorphDrawable): Int {
return morphDrawable.color
}
}
}
}
| mit | 27ac4a7e910dabc1163c83bc1f56c0f1 | 27.4 | 136 | 0.643975 | 4.638838 | false | false | false | false |
Subsets and Splits