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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wordpress-mobile/AztecEditor-Android
|
app/src/androidTest/kotlin/org/wordpress/aztec/demo/tests/HtmlAttributeStyleColorTests.kt
|
1
|
2315
|
package org.wordpress.aztec.demo.tests
import androidx.test.espresso.intent.rule.IntentsTestRule
import org.junit.Rule
import org.junit.Test
import org.wordpress.aztec.demo.BaseTest
import org.wordpress.aztec.demo.MainActivity
import org.wordpress.aztec.demo.pages.EditorPage
/**
* Tests the parsing of the CSS 'color' style attribute.
* Example:
* <code>
* <u style="color:blue">Blue Underline</u>
* </code>
*/
class HtmlAttributeStyleColorTests : BaseTest() {
@Rule
@JvmField
val mActivityIntentsTestRule = IntentsTestRule<MainActivity>(MainActivity::class.java)
/**
* Tests that text appended to a string in the editor with a color style attribute applied, will
* produce properly formatted HTML when switched to the source editor.
*/
@Test
fun testAppendTextToColoredItem() {
val htmlStart = "<b style=\"color:blue\">Blue</b>"
val appendText = " is a beautiful color"
val htmlVerify = "<b style=\"color:blue\">Blue$appendText</b>"
val editorPage = EditorPage()
// insert starter text
editorPage
.toggleHtml()
.insertHTML(htmlStart)
.toggleHtml()
// append text
editorPage
.setCursorPositionAtEnd()
.insertText(appendText)
// verify html
editorPage
.toggleHtml()
.verifyHTML(htmlVerify)
}
/**
* Tests placing a newline in the middle of styled text and verifying the HTML was split
* and assigned the appropriate style attribute.
*/
@Test
fun testInsertNewlineInsideColoredItem() {
val htmlStart = "<b style=\"color:blue\">Blue</b>"
val htmlEnd = "<b style=\"color:blue\">Bl</b>\n\n<b style=\"color:blue\">ue</b>"
val editorPage = EditorPage()
// insert starter text
editorPage
.toggleHtml()
.insertHTML(htmlStart)
.toggleHtml()
// set cursor to middle of text and add newline
editorPage
.setCursorPositionAtEnd()
.moveCursorLeftAsManyTimes(2)
.insertNewLine()
// verify html
editorPage
.toggleHtml()
.verifyHTML(htmlEnd)
}
}
|
mpl-2.0
|
7c80d358e5c4eecca6063aaa23f5e811
| 28.679487 | 100 | 0.603024 | 4.686235 | false | true | false | false |
teobaranga/T-Tasks
|
t-tasks/src/test/kotlin/com/teo/ttasks/util/DateUtilTest.kt
|
1
|
1448
|
package com.teo.ttasks.util
import com.teo.ttasks.data.model.Task
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
import kotlin.test.Test
import kotlin.test.assertEquals
class DateUtilTest {
companion object {
private const val dateStringGoogle = "2019-01-23T02:19:56.000Z"
private const val dateStringNormalized = "2019-01-23T02:19:56Z"
}
@Test
fun parseFormat_normalizedDate_equals() {
val parsedDate = ZonedDateTime.parse(dateStringNormalized)
val reconstructedDateString = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(parsedDate)
assertEquals(dateStringNormalized, reconstructedDateString)
}
@Test
fun parse_googleAndNormalized_equals() {
val google = ZonedDateTime.parse(dateStringGoogle)
val normalized = ZonedDateTime.parse(dateStringNormalized)
assertEquals(normalized, google)
}
@Test
fun setDueDate_normalized_setsDue() {
val task = Task()
val zonedDateTime = ZonedDateTime.parse(dateStringNormalized)
task.dueDate = zonedDateTime
assertEquals(dateStringNormalized, task.due)
}
@Test
fun setCompletedDate_normalized_setsCompleted() {
val task = Task()
val zonedDateTime = ZonedDateTime.parse(dateStringNormalized)
task.completedDate = zonedDateTime
assertEquals(dateStringNormalized, task.completed)
}
}
|
apache-2.0
|
c527452faf9c6feba9a32240fe2f3611
| 27.392157 | 94 | 0.714779 | 4.539185 | false | true | false | false |
saki4510t/libcommon
|
app/src/main/java/com/serenegiant/libcommon/list/DummyContent.kt
|
1
|
2050
|
package com.serenegiant.libcommon.list
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.content.res.TypedArray
import androidx.annotation.ArrayRes
import java.util.*
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
*
* TODO: Replace all uses of this class before publishing your app.
*/
object DummyContent {
/**
* An array of sample (dummy) items.
*/
@JvmField
val ITEMS: MutableList<DummyItem> = ArrayList()
fun createItems(context: Context, @ArrayRes idItems: Int) {
// 文字列配列リソースから文字列配列を取得する
val items = context.resources.getStringArray(idItems)
// 文字列配列リソースから文字列リソース配列を取得する
val array: TypedArray = context.resources.obtainTypedArray(idItems)
val resourceIds = IntArray(array.length())
try {
for (i in resourceIds.indices) {
resourceIds[i] = array.getResourceId(i, 0)
}
} finally {
array.recycle()
}
ITEMS.clear()
for ((i, item) in items.withIndex()) {
addItem(DummyItem(resourceIds[i], item, null))
}
}
private fun addItem(item: DummyItem) {
ITEMS.add(item)
}
/**
* A dummy item representing a piece of content.
*/
class DummyItem(val id: Int, val content: String, val details: String?) {
override fun toString(): String {
return content
}
}
}
|
apache-2.0
|
400955c50bff2f0b155ba92ca0d95728
| 25.835616 | 76 | 0.717569 | 3.496429 | false | false | false | false |
westnordost/StreetComplete
|
app/src/test/java/de/westnordost/streetcomplete/data/osm/elementgeometry/ElementGeometryCreatorTest.kt
|
1
|
10064
|
package de.westnordost.streetcomplete.data.osm.elementgeometry
import de.westnordost.osmapi.map.MapData
import de.westnordost.osmapi.map.MutableMapData
import de.westnordost.osmapi.map.data.*
import org.junit.Test
import org.junit.Assert.*
class ElementGeometryCreatorTest {
@Test fun `create for node`() {
val g = create(OsmNode(0L, 0, P0, null))
assertEquals(P0, g.center)
}
@Test fun `create for empty way`() {
val geom = create(EMPTY_WAY)
assertNull(geom)
}
@Test fun `create for way with duplicate nodes`() {
val geom = create(WAY_DUPLICATE_NODES) as ElementPolylinesGeometry
assertEquals(listOf(P0, P1, P2), geom.polylines.single())
assertEquals(P1, geom.center)
}
@Test fun `create for simple area way`() {
val geom = create(AREA_WAY) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
assertEquals(O, geom.center)
}
@Test fun `create for simple clockwise-area way`() {
val geom = create(AREA_WAY_CLOCKWISE) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
}
@Test fun `create for simple non-area way`() {
val geom = create(SIMPLE_WAY1) as ElementPolylinesGeometry
assertEquals(listOf(P0, P1), geom.polylines.single())
}
@Test fun `create for multipolygon relation with single empty way`() {
val geom = create(areaRelation(outer(EMPTY_WAY)))
assertNull(geom)
}
@Test fun `create for multipolygon relation with single way with no role`() {
val geom = create(areaRelation(member(AREA_WAY)))
assertNull(geom)
}
@Test fun `create for multipolygon relation with single outer way`() {
val geom = create(areaRelation(outer(AREA_WAY))) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
assertEquals(O, geom.center)
}
@Test fun `create for multipolygon relation with single outer clockwise way`() {
val geom = create(areaRelation(outer(AREA_WAY_CLOCKWISE))) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
}
@Test fun `create for multipolygon relation with outer composed of several ways`() {
val geom = create(areaRelation(outer(SIMPLE_WAY1, SIMPLE_WAY3, SIMPLE_WAY2))) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
}
@Test fun `create for multipolygon relation consisting solely of a hole`() {
val geom = create(areaRelation(inner(AREA_WAY)))
assertNull(geom)
}
@Test fun `create for multipolygon relation with hole consisting of single way`() {
val geom = create(areaRelation(outer(AREA_WAY) + inner(AREA_WAY_CLOCKWISE))) as ElementPolygonsGeometry
assertEquals(listOf(CCW_RING, CW_RING), geom.polygons)
assertEquals(O, geom.center)
}
@Test fun `create for multipolygon relation with hole consisting of single counterclockwise way`() {
val geom = create(areaRelation(outer(AREA_WAY) + inner(AREA_WAY))) as ElementPolygonsGeometry
assertEquals(listOf(CCW_RING, CW_RING), geom.polygons)
assertEquals(O, geom.center)
}
@Test fun `create for multipolygon relation with hole consisting of several ways`() {
val geom = create(areaRelation(outer(AREA_WAY) + inner(SIMPLE_WAY1, SIMPLE_WAY3, SIMPLE_WAY2))) as ElementPolygonsGeometry
assertEquals(listOf(CCW_RING, CW_RING), geom.polygons)
assertEquals(O, geom.center)
}
@Test fun `creating for multipolygon relation ignores unusable parts`() {
val geom = create(areaRelation(
outer(EMPTY_WAY, AREA_WAY, SIMPLE_WAY1) +
inner(EMPTY_WAY) +
member(AREA_WAY))) as ElementPolygonsGeometry
assertEquals(CCW_RING, geom.polygons.single())
assertEquals(O, geom.center)
}
@Test fun `create for polyline relation with single empty way`() {
val geom = create(relation(member(EMPTY_WAY)))
assertNull(geom)
}
@Test fun `create for polyline relation with single way`() {
val geom = create(relation(member(AREA_WAY))) as ElementPolylinesGeometry
assertEquals(CCW_RING, geom.polylines.single())
}
@Test fun `create for polyline relation with two ways`() {
val geom = create(relation(member(AREA_WAY, SIMPLE_WAY1))) as ElementPolylinesGeometry
assertTrue(geom.polylines.containsAll(listOf(CCW_RING, listOf(P0, P1))))
}
@Test fun `create for polyline relation with ways joined together`() {
val geom = create(relation(member(SIMPLE_WAY1, SIMPLE_WAY2, SIMPLE_WAY3, WAY_DUPLICATE_NODES))) as ElementPolylinesGeometry
assertTrue(geom.polylines.containsAll(listOf(CCW_RING, listOf(P0, P1, P2))))
}
@Test fun `positions for way`() {
val nodes = listOf<Node>(
OsmNode(0, 1, P0, null, null, null),
OsmNode(1, 1, P1, null, null, null)
)
val mapData = MutableMapData()
mapData.addAll(nodes)
val geom = create(SIMPLE_WAY1, mapData) as ElementPolylinesGeometry
assertEquals(listOf(nodes.map { it.position }), geom.polylines)
}
@Test fun `returns null for non-existent way`() {
val way = OsmWay(1L, 1, listOf(1,2,3), null)
assertNull(create(way, MutableMapData()))
}
@Test fun `positions for relation`() {
val relation = OsmRelation(1L, 1, listOf(
OsmRelationMember(0L, "", Element.Type.WAY),
OsmRelationMember(1L, "", Element.Type.WAY),
OsmRelationMember(1L, "", Element.Type.NODE)
), null)
val ways = listOf<Way>(SIMPLE_WAY1, SIMPLE_WAY2)
val nodesByWayId = mapOf<Long, List<Node>>(
0L to listOf(
OsmNode(0, 1, P0, null, null, null),
OsmNode(1, 1, P1, null, null, null)
),
1L to listOf(
OsmNode(1, 1, P1, null, null, null),
OsmNode(2, 1, P2, null, null, null),
OsmNode(3, 1, P3, null, null, null)
)
)
val mapData = MutableMapData()
mapData.addAll(nodesByWayId.values.flatten() + ways)
val positions = listOf(P0, P1, P2, P3)
val geom = create(relation, mapData) as ElementPolylinesGeometry
assertEquals(listOf(positions), geom.polylines)
}
@Test fun `returns null for non-existent relation`() {
val relation = OsmRelation(1L, 1, listOf(
OsmRelationMember(1L, "", Element.Type.WAY),
OsmRelationMember(2L, "", Element.Type.WAY),
OsmRelationMember(1L, "", Element.Type.NODE)
), null)
assertNull(create(relation, MutableMapData()))
}
@Test fun `returns null for relation with a way that's missing from map data`() {
val relation = OsmRelation(1L, 1, listOf(
OsmRelationMember(0L, "", Element.Type.WAY),
OsmRelationMember(1L, "", Element.Type.WAY)
), null)
val mapData = MutableMapData()
mapData.addAll(listOf(
relation,
OsmWay(0, 0, listOf(0,1), null),
OsmNode(0, 0, P0, null),
OsmNode(1, 0, P1, null)
))
assertNull(create(relation, mapData))
}
@Test fun `does not return null for relation with a way that's missing from map data if returning incomplete geometries is ok`() {
val relation = OsmRelation(1L, 1, listOf(
OsmRelationMember(0L, "", Element.Type.WAY),
OsmRelationMember(1L, "", Element.Type.WAY)
), null)
val way = OsmWay(0, 0, listOf(0,1), null)
val mapData = MutableMapData()
mapData.addAll(listOf(
relation,
way,
OsmNode(0, 0, P0, null),
OsmNode(1, 0, P1, null)
))
assertEquals(
create(way),
create(relation, mapData, true)
)
}
}
private fun create(node: Node) =
ElementGeometryCreator().create(node)
private fun create(way: Way) =
ElementGeometryCreator().create(way, WAY_GEOMETRIES[way.id] ?: emptyList())
private fun create(relation: Relation) =
ElementGeometryCreator().create(relation, WAY_GEOMETRIES)
private fun create(element: Element, mapData: MapData, allowIncomplete: Boolean = false) =
ElementGeometryCreator().create(element, mapData, allowIncomplete)
private val WAY_AREA = mapOf("area" to "yes")
private val O: LatLon = OsmLatLon(1.0, 1.0)
private val P0: LatLon = OsmLatLon(0.0, 2.0)
private val P1: LatLon = OsmLatLon(0.0, 0.0)
private val P2: LatLon = OsmLatLon(2.0, 0.0)
private val P3: LatLon = OsmLatLon(2.0, 2.0)
private val SIMPLE_WAY1 = OsmWay(0, 0, listOf(0,1), null)
private val SIMPLE_WAY2 = OsmWay(1, 0, listOf(1,2,3), null)
private val SIMPLE_WAY3 = OsmWay(2, 0, listOf(0,3), null)
private val AREA_WAY = OsmWay(4, 0, listOf(0,1,2,3,0), WAY_AREA)
private val AREA_WAY_CLOCKWISE = OsmWay(5, 0, listOf(0,3,2,1,0), WAY_AREA)
private val WAY_DUPLICATE_NODES = OsmWay(6, 0, listOf(0,1,1,2), null)
private val EMPTY_WAY = OsmWay(7, 0, emptyList(), null)
private val CCW_RING = listOf(P0, P1, P2, P3, P0)
private val CW_RING = listOf(P0, P3, P2, P1, P0)
private val WAY_GEOMETRIES = mapOf(
0L to listOf(P0, P1),
1L to listOf(P1, P2, P3),
2L to listOf(P0, P3),
4L to listOf(P0, P1, P2, P3, P0),
5L to listOf(P0, P3, P2, P1, P0),
6L to listOf(P0, P1, P1, P2),
7L to listOf()
)
private fun areaRelation(members: List<RelationMember>) =
OsmRelation(0,0, members, mapOf("type" to "multipolygon"))
private fun relation(members: List<RelationMember>) = OsmRelation(0,0, members, null)
private fun outer(vararg ways: Way) = ways.map { OsmRelationMember(it.id, "outer", Element.Type.WAY) }
private fun inner(vararg ways: Way) = ways.map { OsmRelationMember(it.id, "inner", Element.Type.WAY) }
private fun member(vararg ways: Way) = ways.map { OsmRelationMember(it.id, "", Element.Type.WAY) }
|
gpl-3.0
|
069afc7752e8e5b1aa8d8c6b6c72d628
| 38.007752 | 134 | 0.640103 | 3.656977 | false | true | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/coroutines/unitTypeReturn/suspendNonLocalReturn.kt
|
1
|
777
|
// WITH_RUNTIME
// WITH_COROUTINES
// IGNORE_BACKEND: JS
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
var result = "0"
suspend fun suspendHere(x: Int): Unit {
run {
if (x == 0) return
if (x == 1) return@suspendHere
}
result = "OK"
return suspendCoroutineOrReturn { x ->
x.resume(Unit)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun box(): String {
builder {
if (suspendHere(0) != Unit) throw RuntimeException("fail 1")
if (suspendHere(1) != Unit) throw RuntimeException("fail 2")
if (suspendHere(2) != Unit) throw RuntimeException("fail 3")
}
return result
}
|
apache-2.0
|
a31cc52f7ed98eb570dc225ba4d7ab6a
| 20.583333 | 68 | 0.629344 | 3.885 | false | false | false | false |
WangDaYeeeeee/GeometricWeather
|
app/src/opensource/wangdaye/com/geometricweather/location/services/AndroidLocationService.kt
|
1
|
4213
|
package wangdaye.com.geometricweather.location.services
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.annotation.WorkerThread
// static.
private const val TIMEOUT_MILLIS = (10 * 1000).toLong()
private fun isLocationEnabled(
manager: LocationManager
) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
manager.isLocationEnabled
} else {
manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
|| manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
private fun getBestProvider(locationManager: LocationManager): String {
var provider = locationManager.getBestProvider(
Criteria().apply {
isBearingRequired = false
isAltitudeRequired = false
isSpeedRequired = false
accuracy = Criteria.ACCURACY_FINE
horizontalAccuracy = Criteria.ACCURACY_HIGH
powerRequirement = Criteria.POWER_HIGH
},
true
) ?: ""
if (provider.isEmpty()) {
provider = locationManager
.getProviders(true)
.getOrNull(0) ?: provider
}
return provider
}
@SuppressLint("MissingPermission")
private fun getLastKnownLocation(
locationManager: LocationManager
) = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
// interface.
@SuppressLint("MissingPermission")
open class AndroidLocationService : LocationService(), LocationListener {
private val timer = Handler(Looper.getMainLooper())
private var locationManager: LocationManager? = null
private var currentProvider = ""
private var locationCallback: LocationCallback? = null
private var lastKnownLocation: Location? = null
private var gmsLastKnownLocation: Location? = null
override fun requestLocation(context: Context, callback: LocationCallback) {
cancel()
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager?
if (locationManager == null
|| !hasPermissions(context)
|| !isLocationEnabled(locationManager!!)
|| getBestProvider(locationManager!!).also { currentProvider = it }.isEmpty()) {
callback.onCompleted(null)
return
}
locationCallback = callback
lastKnownLocation = getLastKnownLocation(locationManager!!)
locationManager!!.requestLocationUpdates(
currentProvider,
0L,
0F,
this,
Looper.getMainLooper()
)
timer.postDelayed({
cancel()
handleLocation(gmsLastKnownLocation ?: lastKnownLocation)
}, TIMEOUT_MILLIS)
}
override fun cancel() {
locationManager?.removeUpdates(this)
timer.removeCallbacksAndMessages(null)
}
override val permissions: Array<String>
get() = arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
private fun handleLocation(location: Location?) {
locationCallback?.onCompleted(
location?.let { buildResult(it) }
)
}
@WorkerThread
private fun buildResult(location: Location): Result {
return Result(
location.latitude.toFloat(),
location.longitude.toFloat()
)
}
// location listener.
override fun onLocationChanged(location: Location) {
cancel()
handleLocation(location)
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// do nothing.
}
override fun onProviderEnabled(provider: String) {
// do nothing.
}
override fun onProviderDisabled(provider: String) {
// do nothing.
}
}
|
lgpl-3.0
|
f999648c051cf6edab9716f692ea5d34
| 28.468531 | 96 | 0.67719 | 5.346447 | false | false | false | false |
huy-vuong/streamr
|
app/src/main/java/com/huyvuong/streamr/ui/activity/PhotostreamActivity.kt
|
1
|
11162
|
package com.huyvuong.streamr.ui.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.huyvuong.streamr.R
import com.huyvuong.streamr.accessor.PreferenceAccessor
import com.huyvuong.streamr.gateway.FlickrGateway
import com.huyvuong.streamr.model.transport.FlickrErrorCode
import com.huyvuong.streamr.model.transport.PhotoMetadata
import com.huyvuong.streamr.model.transport.ResponseStatus
import com.huyvuong.streamr.model.transport.interestingness.InterestingnessErrorCode
import com.huyvuong.streamr.model.transport.people.PeopleErrorCode
import com.huyvuong.streamr.ui.adapter.recyclerview.ThumbnailAdapter
import com.huyvuong.streamr.ui.component.PhotostreamActivityComponent
import com.huyvuong.streamr.util.consumeEvent
import io.reactivex.rxkotlin.subscribeBy
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import org.jetbrains.anko.setContentView
import org.jetbrains.anko.share
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.threeten.bp.LocalDate
class PhotostreamActivity : AppCompatActivity(), AnkoLogger {
companion object {
const val BUNDLE_KEY_USERNAME = "username"
const val BUNDLE_KEY_NSID = "nsid"
const val BUNDLE_KEY_RESULT = "result"
const val BUNDLE_KEY_PHOTOS = "photos"
}
private val ui = PhotostreamActivityComponent()
// TODO Refactor so that these variables always remain in sync.
private lateinit var username: String
private lateinit var nsid: String // TODO Save username -> NSID offline as cache to preload.
private lateinit var result: String
private lateinit var photos: MutableList<PhotoMetadata>
private lateinit var thumbnailAdapter: ThumbnailAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ui.setContentView(this)
initializeUiState(savedInstanceState)
initializeViewListeners()
ui.previewsRecyclerView.adapter = thumbnailAdapter
}
private fun initializeUiState(savedInstanceState: Bundle?) {
if (savedInstanceState == null &&
PreferenceAccessor.getDefaultUsernameToLoad(this).isEmpty()) {
username = ""
result = "Explore"
photos = mutableListOf()
showExplorePhotosForToday()
} else {
if (savedInstanceState != null) {
username = savedInstanceState.getString(BUNDLE_KEY_USERNAME)
nsid = savedInstanceState.getString(BUNDLE_KEY_NSID) ?: ""
result =
if (username.isNotEmpty() && nsid.isNotEmpty()) {
"$username ($nsid)"
} else {
"Explore"
}
photos = savedInstanceState.getParcelableArrayList(BUNDLE_KEY_PHOTOS)
} else {
username = PreferenceAccessor.getDefaultUsernameToLoad(this)
ui.usernameEditText.setText(username)
nsid = ""
photos = mutableListOf()
result = username
search()
}
supportActionBar?.title = result
}
thumbnailAdapter = ThumbnailAdapter(photos)
}
private fun initializeViewListeners() {
ui.searchButton.setOnClickListener { search() }
ui.usernameEditText.setOnKeyListener({ _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN &&
(keyCode in listOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER))) {
search()
true
} else {
false
}
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.photostream_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.action_explore ->
consumeEvent(this@PhotostreamActivity::showExplorePhotosForToday)
R.id.action_share -> consumeEvent {
if (username.isNotEmpty()) {
if (nsid.isNotEmpty()) {
share("https://www.flickr.com/photos/$nsid", "$username's Photostream")
} else {
val getUserIdObservable =
FlickrGateway.getUserId(username).autoConnect()
getUserIdObservable
.subscribeBy(
onNext = {
if (it.status == ResponseStatus.OK) {
nsid = it.user.nsid
share(
"https://www.flickr.com/photos/$nsid",
"$username's Photostream")
}
},
onError = {
toast(it.message!!)
error(
"Encountered error while getting " +
"user ID: ${it.message}")
})
}
} else {
share("https://www.flickr.com/explore", "Explore on Flickr")
}
}
R.id.action_settings -> consumeEvent { startActivity<SettingsActivity>() }
else -> super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
username = ui.usernameEditText.text.toString()
outState.putString(BUNDLE_KEY_USERNAME, username)
outState.putString(BUNDLE_KEY_NSID, nsid)
outState.putString(BUNDLE_KEY_RESULT, result)
outState.putParcelableArrayList(BUNDLE_KEY_PHOTOS, ArrayList(photos))
}
private fun search() {
username = ui.usernameEditText.text.toString()
val getUserIdObservable = FlickrGateway.getUserId(username).autoConnect()
getUserIdObservable
.subscribeBy(
onNext = {
when (it.status) {
ResponseStatus.OK -> {
nsid = it.user.nsid
result = "$username (${it.user.nsid})"
supportActionBar?.title = result
showPublicPhotosFor(it.user.nsid)
}
ResponseStatus.FAIL -> {
result = getPeopleErrorMessageForErrorCode(it.code)
supportActionBar?.title = result
}
}
},
onError = {
Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
error("Encountered error while getting user ID: ${it.message}")
})
}
private fun showPublicPhotosFor(userId: String) {
val getPublicPhotosObservable = FlickrGateway.getPublicPhotos(userId).autoConnect()
getPublicPhotosObservable
.subscribeBy(
onNext = {
when (it.status) {
ResponseStatus.OK -> {
loadPhotos(it.photoPage.photos)
}
ResponseStatus.FAIL -> {
result = getPeopleErrorMessageForErrorCode(it.code)
supportActionBar?.title = result
}
}
},
onError = {
Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
error("Encountered error while loading photos: ${it.message}")
})
}
private fun showExplorePhotosForToday() {
showExplorePhotos(LocalDate.now())
}
private fun showExplorePhotos(date: LocalDate, retriesRemaining: Int = 2) {
username = ""
nsid = ""
supportActionBar?.title = "Explore"
ui.usernameEditText.setText("")
val getInterestingPhotosObservable = FlickrGateway.getInterestingPhotos(date).autoConnect()
getInterestingPhotosObservable
.subscribeBy(
onNext = {
when (it.status) {
ResponseStatus.OK -> {
loadPhotos(it.photoPage.photos)
}
ResponseStatus.FAIL -> {
if (retriesRemaining <= 0) {
toast(getInterestingnessErrorMessageForErrorCode(it.code))
} else {
showExplorePhotos(date.minusDays(1), retriesRemaining - 1)
}
}
}
},
onError = {
toast("Encountered error while loading photos from Explore.")
error("Encountered error while loading photos: ${it.message}")
})
}
private fun getPeopleErrorMessageForErrorCode(errorCode: Int): String =
when (errorCode) {
PeopleErrorCode.USER_NOT_FOUND -> "User not found."
FlickrErrorCode.INVALID_API_KEY -> "Invalid API key."
FlickrErrorCode.SERVICE_CURRENTLY_UNAVAILABLE -> "Service currently unavailable."
else -> "Internal error occurred."
}
private fun getInterestingnessErrorMessageForErrorCode(errorCode: Int): String =
when (errorCode) {
InterestingnessErrorCode.INVALID_DATE_STRING -> "Invalid date string."
FlickrErrorCode.INVALID_API_KEY -> "Invalid API key."
FlickrErrorCode.SERVICE_CURRENTLY_UNAVAILABLE -> "Service currently unavailable."
else -> "Internal error occurred."
}
private fun loadPhotos(photosToLoad: List<PhotoMetadata>) {
photos.clear()
photos.addAll(photosToLoad)
thumbnailAdapter.notifyDataSetChanged()
}
}
|
gpl-3.0
|
c776e8065a3254a4ac592c1a20014f9e
| 43.47012 | 99 | 0.515947 | 5.865476 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
common_framework/src/main/java/com/vmenon/mpo/common/framework/retrofit/OAuthInterceptor.kt
|
1
|
3065
|
package com.vmenon.mpo.common.framework.retrofit
import com.vmenon.mpo.auth.domain.AuthService
import com.vmenon.mpo.auth.domain.CredentialsResult
import com.vmenon.mpo.system.domain.Clock
import com.vmenon.mpo.system.domain.Logger
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.net.HttpURLConnection
/**
* Will ensure we have a fresh access token prior to making the request. And also will try
* refreshing again in the event the server says not valid, although locally we think we're
* valid
*/
class OAuthInterceptor(
private val authService: AuthService,
private val logger: Logger,
private val clock: Clock,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return runBlocking {
val request: Request = chain.request()
if (authService.getCredentials() is CredentialsResult.None) {
chain.proceed(request)
} else {
handleAuthentication(chain, request)
}
}
}
private suspend fun handleAuthentication(chain: Interceptor.Chain, request: Request): Response {
val response = proceedWithCredentials(chain, request)
if (response.response.code() == HttpURLConnection.HTTP_UNAUTHORIZED
&& !response.tokenRefreshed
) {
val retriedResponse = proceedWithCredentials(chain, response.newRequest)
return retriedResponse.response
}
return response.response
}
private suspend fun proceedWithCredentials(
chain: Interceptor.Chain,
request: Request
): ResponseWithCredentials {
return authService.runWithFreshCredentialsIfNecessary(clock.currentTimeMillis()) { result ->
val refreshed = result.getOrThrow()
logger.println("Refreshed token $refreshed")
val newRequest = when (val credentialsResult = authService.getCredentials()) {
is CredentialsResult.Success -> {
request.newBuilder().addHeader(
"Authorization",
"${credentialsResult.credentials.tokenType} ${credentialsResult.credentials.accessToken}"
).build()
}
else -> request
// TODO: What if Biometric prompt is needed?
// Maybe implement an EventBus, and send an event notifying the listener (the HomeActivity maybe?)
// That we need to prompt for biometrics to stay authenticated. Then throw an error and hope
// the retry mechanism will eventually get it? Or maybe just do this from the AuthService??
}
val response = runCatching { chain.proceed(newRequest) }.getOrThrow()
ResponseWithCredentials(newRequest, response, refreshed)
}
}
internal data class ResponseWithCredentials(
val newRequest: Request,
val response: Response,
val tokenRefreshed: Boolean
)
}
|
apache-2.0
|
828fae8a477459a12792a78dd1bf3675
| 39.88 | 114 | 0.657749 | 5.284483 | false | false | false | false |
saletrak/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/mywykop/MyWykopRepository.kt
|
1
|
1741
|
package io.github.feelfreelinux.wykopmobilny.api.mywykop
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification
import io.github.feelfreelinux.wykopmobilny.models.mapToNotification
import io.github.feelfreelinux.wykopmobilny.models.pojo.NotificationCountResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.NotificationResponse
import io.github.feelfreelinux.wykopmobilny.utils.api.CredentialsPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.userSessionToken
import io.reactivex.Single
import retrofit2.Retrofit
interface MyWykopApi {
fun getNotificationCount(): Single<NotificationCountResponse>
fun getHashTagNotificationCount(): Single<NotificationCountResponse>
fun getHashTagNotifications(page : Int): Single<List<Notification>>
fun getNotifications(page : Int): Single<List<Notification>>
fun readNotifications(): Single<List<NotificationResponse>>
fun readHashTagNotifications(): Single<List<NotificationResponse>>
}
class MyWykopRepository(val retrofit: Retrofit) : MyWykopApi {
private val mywykopApi by lazy { retrofit.create(MyWykopRetrofitApi::class.java) }
override fun readNotifications() = mywykopApi.readNotifications()
override fun getNotifications(page : Int) = mywykopApi.getNotifications(page).map { it.map { it.mapToNotification() } }
override fun getNotificationCount() = mywykopApi.getNotificationCount()
override fun readHashTagNotifications() = mywykopApi.readHashTagsNotifications()
override fun getHashTagNotifications(page : Int) = mywykopApi.getHashTagsNotifications(page).map { it.map { it.mapToNotification() } }
override fun getHashTagNotificationCount() = mywykopApi.getHashTagsNotificationsCount()
}
|
mit
|
2227718b55531796227b8502cbb41f91
| 48.771429 | 138 | 0.816198 | 4.705405 | false | false | false | false |
Heiner1/AndroidAPS
|
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusTest.kt
|
1
|
1371
|
package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danars.DanaRSTestBase
import org.junit.Assert
import org.junit.Test
class DanaRsPacketBolusSetExtendedBolusTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRSPacketBolusSetExtendedBolus) {
it.aapsLogger = aapsLogger
}
}
}
@Test fun runTest() {
val packet = DanaRSPacketBolusSetExtendedBolus(packetInjector, 1.0, 1)
// test params
val testparams = packet.getRequestParams()
Assert.assertEquals(100.toByte(), testparams[0])
Assert.assertEquals(1.toByte(), testparams[2])
// test message decoding
packet.handleMessage(createArray(34, 0.toByte()))
// DanaRPump testPump = DanaRPump.getInstance();
Assert.assertEquals(false, packet.failed)
packet.handleMessage(createArray(34, 1.toByte()))
// int valueRequested = (((byte) 1 & 0x000000FF) << 8) + (((byte) 1) & 0x000000FF);
// assertEquals(valueRequested /100d, testPump.lastBolusAmount, 0);
Assert.assertEquals(true, packet.failed)
Assert.assertEquals("BOLUS__SET_EXTENDED_BOLUS", packet.friendlyName)
}
}
|
agpl-3.0
|
108f2bad45fa3151dfcabda2e36e980c
| 38.2 | 98 | 0.676878 | 4.57 | false | true | false | false |
joedanpar/improbable-bot
|
src/main/kotlin/com/joedanpar/improbabot/components/game/player/Player.kt
|
1
|
3162
|
/*******************************************************************************
* This file is part of Improbable Bot.
*
* Improbable Bot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Improbable Bot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Improbable Bot. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.joedanpar.improbabot.components.game.player
import com.joedanpar.improbabot.components.game.entity.GameEntity
import com.joedanpar.improbabot.components.game.world.Location
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageEmbed
import javax.persistence.*
@Entity
@Table(uniqueConstraints = [UniqueConstraint(columnNames = ["serverId", "userId"])])
data class Player (
@Column(nullable = false)
override val serverId: String,
@Column(nullable = false)
val userId: String,
@Column(nullable = false)
val name: String,
@Column(nullable = false)
val gender: String,
@Column(nullable = false)
val race: String,
@ManyToOne
val currentLocation: Location?
) : GameEntity(serverId) {
constructor(): this("", "", "", "", "", null)
override fun render(): Message = MessageBuilder().setEmbed(toEmbed()).build()
override fun toEmbed(): MessageEmbed = EmbedBuilder()
.setTitle(name)
.addField("Gender", gender, true)
.addField("Race", race, true)
.addField("Current Location", currentLocation?.name ?: "Unknown", true)
.build()
class Builder {
private var serverId: String? = null
private var userId: String? = null
private var name: String? = null
private var gender: String? = null
private var race: String? = null
fun setServerId(serverId: String): Builder {
this.serverId = serverId
return this
}
fun setUserId(userId: String): Builder {
this.userId = userId
return this
}
fun setName(name: String): Builder {
this.name = name
return this
}
fun setGender(gender: String): Builder {
this.gender = gender
return this
}
fun setRace(race: String): Builder {
this.race = race
return this
}
fun build(): Player {
return Player(serverId!!, userId!!, name!!, gender!!, race!!, null)
}
}
}
|
gpl-3.0
|
6c15b55dc55638d040745375707ee3a4
| 31.265306 | 84 | 0.592979 | 4.616058 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt
|
2
|
4185
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
binaryExpressionVisitor(fun(expression) {
if (expression.operationToken != KtTokens.ELVIS) return
val lhs = expression.left ?: return
val rhs = expression.right ?: return
if (!KtPsiUtil.isBooleanConstant(rhs)) return
val lhsType = lhs.analyze(BodyResolveMode.PARTIAL).getType(lhs) ?: return
if (TypeUtils.isNullableType(lhsType) && lhsType.isBooleanOrNullableBoolean()) {
val condition = when (val parentIfOrWhile =
PsiTreeUtil.getParentOfType(expression, KtIfExpression::class.java, KtWhileExpressionBase::class.java)) {
is KtIfExpression -> parentIfOrWhile.condition
is KtWhileExpressionBase -> parentIfOrWhile.condition
else -> null
}
val (highlightType, verb) = if (condition != null && condition in expression.parentsWithSelf)
GENERIC_ERROR_OR_WARNING to KotlinBundle.message("text.should")
else
INFORMATION to KotlinBundle.message("text.can")
holder.registerProblemWithoutOfflineInformation(
expression,
KotlinBundle.message("equality.cehck.0.be.used.instead.of.elvis.for.nullable.boolean.check", verb),
isOnTheFly,
highlightType,
ReplaceWithEqualityCheckFix()
)
}
})
private class ReplaceWithEqualityCheckFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.equality.check.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtBinaryExpression ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return
if (element.operationToken != KtTokens.ELVIS) return
val constPart = element.right as? KtConstantExpression ?: return
val exprPart = element.left ?: return
val constValue = when {
KtPsiUtil.isTrueConstant(constPart) -> true
KtPsiUtil.isFalseConstant(constPart) -> false
else -> return
}
val equalityCheckExpression = element.replaced(KtPsiFactory(constPart).buildExpression {
appendExpression(exprPart)
appendFixedText(if (constValue) " != false" else " == true")
})
val prefixExpression = equalityCheckExpression.getParentOfType<KtPrefixExpression>(strict = true) ?: return
val simplifier = SimplifyNegatedBinaryExpressionInspection()
if (simplifier.isApplicable(prefixExpression)) {
simplifier.applyTo(prefixExpression)
}
}
}
}
|
apache-2.0
|
8225f957c8922b3f0ef051d725c69490
| 51.3125 | 158 | 0.682915 | 5.372272 | false | false | false | false |
AcornUI/Acorn
|
acornui-core/src/main/kotlin/com/acornui/asset/Cache.kt
|
1
|
7647
|
/*
* Copyright 2019 Poly Forest, 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.
*/
@file:Suppress("MemberVisibilityCanBePrivate")
package com.acornui.asset
import com.acornui.Disposable
import com.acornui.di.Context
import com.acornui.di.ContextImpl
import com.acornui.di.dependencyFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.browser.window
import kotlin.jvm.Synchronized
import kotlin.time.Duration
import kotlin.time.seconds
/**
* Cache is a map with reference counting. When the reference counter on a cached element reaches zero, if it remains
* at zero for a certain number of frames, it will be removed and disposed.
*/
interface Cache {
/**
* Returns true if the key is found.
*/
fun containsKey(key: Any): Boolean
/**
* Retrieves the cache value for the given key.
* When cache items are retrieved, [refInc] should be used to indicate that it's in use.
* @return Returns the set value, or null if the key is not in this cache.
*/
operator fun <T : Any> get(key: Any): T?
operator fun set(key: Any, value: Any)
/**
* Retrieves the cache value for the given key if it exists. Otherwise, constructs a new value via the [factory]
* and adds the new value to the cache.
* @param key The key to use for the cache index.
* @return Returns the cached value.
*/
fun <T : Any> getOrPut(key: Any, factory: () -> T): T
/**
* Decrements the use count for the cache value with the given key.
* If the use count reaches zero, and remains at zero for a certain number of frames, the cache value will be
* removed and disposed if the value implements [Disposable].
*
* @throws IllegalArgumentException if key is not in this cache.
*/
fun refDec(key: Any)
/**
* Increments the reference count for the cache value. This should be paired with [refDec]
* @param key The cache key used in the lookup. If the key is not found, an exception is thrown.
*
* @see containsKey
* @throws IllegalArgumentException if key is not in this cache.
*/
fun refInc(key: Any)
companion object : Context.Key<Cache> {
override val factory = dependencyFactory {
CacheImpl(it)
}
}
}
val Context.cache: Cache
get() = inject(Cache)
class CacheImpl(
owner: Context,
/**
* The time before an unreferenced cache item is removed and destroyed.
*/
val disposalTime: Duration = 4.seconds
) : ContextImpl(owner), Cache, Disposable {
private val map = mutableMapOf<Any, CacheValue>()
@Synchronized
override fun containsKey(key: Any): Boolean {
checkDisposed()
return map.containsKey(key)
}
@Synchronized
override fun <T : Any> get(key: Any): T? {
checkDisposed()
@Suppress("UNCHECKED_CAST")
return map[key]?.value as T?
}
@Synchronized
override fun set(key: Any, value: Any) {
checkDisposed()
require(!containsKey(key)) { "Cache already contains key $key" }
val cacheValue = CacheValue(key, value)
map[key] = cacheValue
// Start in the death pool, it will be removed on refInc.
cacheValue.doom()
}
/**
* Retrieves the cache value for the given key if it exists. Otherwise, constructs a new value via the [factory]
* and adds the new value to the cache.
* @param key The key to use for the cache index.
* @return Returns the cached value.
*/
override fun <T : Any> getOrPut(key: Any, factory: () -> T): T {
@Suppress("UNCHECKED_CAST")
if (containsKey(key)) return get(key)!!
val value = factory()
set(key, value)
return value
}
@Synchronized
override fun refDec(key: Any) {
if (isDisposed) return
if (map.containsKey(key)) {
val cacheValue = map[key]!!
check(cacheValue.refCount > 0) { "refInc / refDec pairs are unbalanced." }
--cacheValue.refCount
}
}
@Synchronized
override fun refInc(key: Any) {
checkDisposed()
val cacheValue = map[key] ?: throw IllegalArgumentException("The key $key is not in the cache.")
cacheValue.refCount++
}
@Synchronized
override fun dispose() {
super.dispose()
map.values.forEach(CacheValue::dispose)
}
private inner class CacheValue(
val key: Any,
val value: Any
) : Disposable {
var refCount: Int = 0
set(value) {
if (field <= 0 && value > 0)
revive()
if (field > 0 && value <= 0)
doom()
field = value
}
private var disposalId: Int = -1
override fun dispose() {
if (disposalId != -1)
window.clearInterval(disposalId)
(value as? Job)?.cancel()
(value as? Disposable)?.dispose()
map.remove(key)
}
fun doom() {
disposalId = window.setInterval(::dispose, disposalTime.inMilliseconds.toInt())
}
fun revive() {
window.clearInterval(disposalId)
disposalId = -1
}
}
}
/**
* CacheSet is a set of keys that are reference incremented on the [Cache] when added, and
* reference decremented when this group is disposed.
*/
class CacheSet(
owner: Context
) : ContextImpl(owner), Set<Any> {
private val cache by Cache
private val keys = mutableSetOf<Any>()
override val size: Int
get() = keys.size
override fun contains(element: Any): Boolean = keys.contains(element)
override fun iterator(): MutableIterator<Any> = keys.iterator()
override fun containsAll(elements: Collection<Any>): Boolean = keys.containsAll(elements)
override fun isEmpty(): Boolean = keys.isEmpty()
/**
* Adds a key to be tracked.
* The key will be reference incremented on the [Cache].
* @return Returns `true` if the key has been added, `false` if the key is already contained in the set.
*/
private fun addKey(key: Any): Boolean {
checkDisposed()
if (keys.contains(key)) return false
cache.refInc(key)
keys.add(key)
return true
}
/**
* Retrieves the cache value for the given key if it exists. Otherwise, constructs a new value via the [factory]
* and adds the new value to the cache.
* @param key The key to use for the cache index. If this key is not currently in this set, it will be added
* and [Cache.refInc] will be called. When this set is disposed, [Cache.refDec] will be called for the added key.
*
* @return Returns the cached value.
*/
fun <T : Any> getOrPut(key: Any, factory: () -> T): T {
checkDisposed()
val r = cache.getOrPut(key, factory)
addKey(key)
return r
}
@Deprecated("Use getOrPutAsync", ReplaceWith("getOrPutAsync(key, factory)"))
fun <T> cacheAsync(key: Any, factory: suspend CoroutineScope.() -> T): Deferred<T> = getOrPutAsync(key, factory)
/**
* Invokes [getOrPut] with an [async] coroutine using the scope in which this set was created.
*/
fun <T> getOrPutAsync(key: Any, factory: suspend CoroutineScope.() -> T): Deferred<T> = getOrPut(key) {
async { factory() }
}
override fun dispose() {
super.dispose()
for (key in keys) {
cache.refDec(key)
}
keys.clear()
}
}
/**
* Constructs a new [CacheSet] object which will increment or decrement a list of keys on the [Cache].
*/
fun Context.cacheSet(): CacheSet {
return CacheSet(this)
}
@Deprecated("Use cacheSet", ReplaceWith("this.cacheSet()"))
fun Context.cachedGroup(): CacheSet {
return CacheSet(this)
}
|
apache-2.0
|
ffd77ad198ad9d44057bc078f5076b7c
| 26.217082 | 117 | 0.698052 | 3.535368 | false | false | false | false |
DankBots/GN4R
|
src/main/java/com/gmail/hexragon/gn4rBot/command/fun/ProgressionCommand.kt
|
1
|
2912
|
package com.gmail.hexragon.gn4rBot.command.`fun`
import com.gmail.hexragon.gn4rBot.GnarBot
import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor
import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command
import com.gmail.hexragon.gn4rBot.managers.users.PermissionLevel
import com.gmail.hexragon.gn4rBot.util.GnarMessage
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.text.WordUtils
import java.util.StringJoiner
import java.util.concurrent.TimeUnit
@Command(aliases = arrayOf("progress"), permissionRequired = PermissionLevel.BOT_MASTER, showInHelp = false)
class ProgressionCommand : CommandExecutor()
{
override fun execute(message : GnarMessage?, args : Array<out String>?)
{
val joiner = StringJoiner("\n", "```", "```")
joiner.add(" ___________________________ ")
joiner.add("| Progression [_][☐][✕]|")
joiner.add("|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾|")
val lines = WordUtils
.wrap(StringUtils.join(args, ' ').replace("```",""), 25)
.split("\n")
lines.forEach {
val builder = StringBuilder()
repeat(25 - it.trim().length) { builder.append(' ') }
var str = it.trim()
if (str.length > 25)
{
str = "${str.substring(0, 22)}..."
}
joiner.add("| $str$builder |")
}
joiner.add("| ____________________ |")
joiner.add("||var-A| var-B |")
joiner.add("| ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ |")
joiner.add(" ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ ")
val list = arrayListOf<String>()
for (i in 0..20)
{
val builder = StringBuilder()
repeat(20) {
if (it < i+1) builder.append('█')
else builder.append(' ')
}
var percent = (i * 5).toString()
while (percent.length < 3)
{
percent = " $percent"
}
list.add(joiner
.toString()
.replace("var-A", builder.toString())
.replace("var-B", percent))
}
try
{
val msg = message?.replyRaw(list[0])
list.forEachIndexed { i, s ->
GnarBot.scheduler.schedule({
msg?.updateMessage(list[i])
}, i + 1L, TimeUnit.SECONDS)
}
}
catch (e : UnsupportedOperationException)
{
message?.reply("Message was too long or something... no memes for you.")
}
}
}
|
mit
|
eb198e9df87f4be0d0ecd3e4d555b58f
| 31.435294 | 108 | 0.479318 | 3.574578 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/engagement/EngagedPeopleListActivity.kt
|
1
|
2751
|
package org.wordpress.android.ui.engagement
import android.os.Bundle
import android.view.MenuItem
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.EngagedPeopleListActivityBinding
import org.wordpress.android.ui.LocaleAwareActivity
import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper
import java.lang.IllegalArgumentException
import javax.inject.Inject
class EngagedPeopleListActivity : LocaleAwareActivity() {
@Inject lateinit var analyticsUtilsWrapper: AnalyticsUtilsWrapper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as WordPress).component().inject(this)
with(EngagedPeopleListActivityBinding.inflate(layoutInflater)) {
setContentView(root)
setSupportActionBar(toolbarMain)
}
val listScenario = intent.getParcelableExtra<ListScenario>(KEY_LIST_SCENARIO)
?: throw IllegalArgumentException(
"List Scenario cannot be null. Make sure to pass a valid List Scenario in the intent"
)
analyticsUtilsWrapper.trackLikeListOpened(
EngagementNavigationSource.getSourceDescription(listScenario.source),
ListScenarioType.getSourceDescription(listScenario.type)
)
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
val titleText = if (listScenario.headerData.numLikes == 1) {
getString(R.string.like_title_singular)
} else {
getString(R.string.like_title_plural, listScenario.headerData.numLikes)
}
it.title = titleText
// Important for talkback accessibility
title = getString(R.string.likes_list_screen_title, titleText)
}
val fm = supportFragmentManager
var likeListFragment = fm.findFragmentByTag(TAG_LIKE_LIST_FRAGMENT) as? EngagedPeopleListFragment
if (likeListFragment == null) {
likeListFragment = EngagedPeopleListFragment.newInstance(listScenario)
fm.beginTransaction()
.add(R.id.fragment_container, likeListFragment, TAG_LIKE_LIST_FRAGMENT)
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
const val KEY_LIST_SCENARIO = "list_scenario"
private const val TAG_LIKE_LIST_FRAGMENT = "tag_like_list_fragment"
}
}
|
gpl-2.0
|
3512b38813ced5fb36a8e5159401c945
| 37.208333 | 109 | 0.676118 | 5.038462 | false | false | false | false |
y20k/transistor
|
app/src/main/java/org/y20k/transistor/dialogs/YesNoDialog.kt
|
1
|
3115
|
/*
* YesNoDialog
* Implements the YesNoDialog class
* A YesNoDialog asks the user if he/she wants to do something or not
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.dialogs
import android.content.Context
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.y20k.transistor.Keys
import org.y20k.transistor.R
import org.y20k.transistor.helpers.LogHelper
/*
* YesNoDialog class
*/
class YesNoDialog (private var yesNoDialogListener: YesNoDialogListener) {
/* Interface used to communicate back to activity */
interface YesNoDialogListener {
fun onYesNoDialog(type: Int, dialogResult: Boolean, payload: Int, payloadString: String) {
}
}
/* Define log tag */
private val TAG = LogHelper.makeLogTag(YesNoDialog::class.java.simpleName)
/* Construct and show dialog - variant: message from string */
fun show(context: Context,
type: Int,
title: Int = Keys.EMPTY_STRING_RESOURCE,
message: Int,
yesButton: Int = R.string.dialog_yes_no_positive_button_default,
noButton: Int = R.string.dialog_generic_button_cancel,
payload: Int = Keys.DIALOG_EMPTY_PAYLOAD_INT,
payloadString: String = Keys.DIALOG_EMPTY_PAYLOAD_STRING) {
// extract string from message resource and feed into main show method
show(context, type, title, context.getString(message), yesButton, noButton, payload, payloadString)
}
/* Construct and show dialog */
fun show(context: Context,
type: Int,
title: Int = Keys.EMPTY_STRING_RESOURCE,
messageString: String,
yesButton: Int = R.string.dialog_yes_no_positive_button_default,
noButton: Int = R.string.dialog_generic_button_cancel,
payload: Int = Keys.DIALOG_EMPTY_PAYLOAD_INT,
payloadString: String = Keys.DIALOG_EMPTY_PAYLOAD_STRING) {
// prepare dialog builder
val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
// set title and message
builder.setMessage(messageString)
if (title != Keys.EMPTY_STRING_RESOURCE) {
builder.setTitle(context.getString(title))
}
// add yes button
builder.setPositiveButton(yesButton) { _, _ ->
// listen for click on yes button
yesNoDialogListener.onYesNoDialog(type, true, payload, payloadString)
}
// add no button
builder.setNegativeButton(noButton) { _, _ ->
// listen for click on no button
yesNoDialogListener.onYesNoDialog(type, false, payload, payloadString)
}
// handle outside-click as "no"
builder.setOnCancelListener {
yesNoDialogListener.onYesNoDialog(type, false, payload, payloadString)
}
// display dialog
builder.show()
}
}
|
mit
|
26e70553283e70f38b4f94339ef14e6b
| 32.138298 | 111 | 0.653933 | 4.412181 | false | false | false | false |
Yubico/yubioath-android
|
app/src/main/kotlin/com/yubico/yubioath/ui/main/IconManager.kt
|
1
|
3185
|
package com.yubico.yubioath.ui.main
import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import android.util.Base64
import com.yubico.yubioath.R
import com.yubico.yubioath.client.Credential
import java.io.ByteArrayOutputStream
class IconManager(context:Context) {
companion object {
private const val ICON_STORAGE = "ICON_STORAGE"
private const val SIZE = 128
private const val RADIUS = (SIZE / 2).toFloat()
}
private val iconStorage = context.getSharedPreferences(ICON_STORAGE, Context.MODE_PRIVATE)
private val colors = context.resources.obtainTypedArray(R.array.icon_colors).let {
(0 until it.length()).map { i -> it.getColor(i, 0) }
}
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = RADIUS
textAlign = Paint.Align.CENTER
color = ContextCompat.getColor(context, R.color.yubicoPrimaryWhite)
}
private val Credential.iconKey: String get() = issuer ?: ":$name"
fun setIcon(credential: Credential, icon: Bitmap) {
val baos = ByteArrayOutputStream()
Bitmap.createScaledBitmap(icon, SIZE, SIZE, true).compress(Bitmap.CompressFormat.PNG, 100, baos)
val bytes = baos.toByteArray()
iconStorage.edit().putString(credential.iconKey, Base64.encodeToString(bytes, Base64.DEFAULT)).apply()
}
fun setIcon(credential: Credential, icon: Drawable) {
setIcon(credential, Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888).apply {
icon.bounds = Rect(0, 0, SIZE, SIZE)
icon.draw(Canvas(this))
})
}
fun removeIcon(credential: Credential) {
iconStorage.edit().remove(credential.iconKey).apply()
}
fun clearIcons() {
iconStorage.edit().clear().apply()
}
fun hasIcon(credential: Credential) = iconStorage.contains(credential.iconKey)
fun getIcon(credential: Credential): Bitmap {
return iconStorage.getString(credential.iconKey, null)?.let {
getSavedIcon(it)
} ?: getLetterIcon(credential)
}
private fun getLetterIcon(credential: Credential): Bitmap {
return Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888).apply {
Canvas(this).apply {
drawCircle(RADIUS, RADIUS, RADIUS, Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = colors[Math.abs(credential.iconKey.hashCode()) % colors.size]
})
if ((credential.issuer ?: credential.name).isNotEmpty()) {
val letter = (credential.issuer
?: credential.name).substring(0, 1).toUpperCase()
drawText(letter, RADIUS, RADIUS - (textPaint.descent() + textPaint.ascent()) / 2, textPaint)
}
}
}
}
private fun getSavedIcon(data: String): Bitmap {
val bytes = Base64.decode(data, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
return if(bitmap.width == SIZE) bitmap else Bitmap.createScaledBitmap(bitmap, SIZE, SIZE, true)
}
}
|
bsd-2-clause
|
a43f73ea7ab34c6c6c999a88ba9a9ed0
| 36.928571 | 112 | 0.653689 | 4.309878 | false | false | false | false |
ingokegel/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/StringEntityImpl.kt
|
1
|
6030
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class StringEntityImpl : StringEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField
var _data: String? = null
override val data: String
get() = _data!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: StringEntityData?) : ModifiableWorkspaceEntityBase<StringEntity>(), StringEntity.Builder {
constructor() : this(StringEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity StringEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field StringEntity#data should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as StringEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override fun getEntityData(): StringEntityData = result ?: super.getEntityData() as StringEntityData
override fun getEntityClass(): Class<StringEntity> = StringEntity::class.java
}
}
class StringEntityData : WorkspaceEntityData<StringEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<StringEntity> {
val modifiable = StringEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): StringEntity {
val entity = StringEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return StringEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return StringEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as StringEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as StringEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
85a9d4408dcd26cb481262772e29bf9f
| 30.082474 | 120 | 0.725041 | 5.284838 | false | false | false | false |
InsideZhou/Instep
|
dao/src/main/kotlin/instep/dao/sql/dialect/SQLServerDialect.kt
|
1
|
4489
|
package instep.dao.sql.dialect
import instep.InstepLogger
import instep.dao.sql.*
import instep.dao.sql.impl.DefaultSQLPlan
import instep.dao.sql.impl.DefaultTableSelectPlan
import microsoft.sql.DateTimeOffset
import java.time.OffsetDateTime
open class SQLServerDialect : SeparateCommentDialect() {
override val returningClauseForInsert = ""
private val logger = InstepLogger.getLogger(SQLServerDialect::class.java)
class ResultSet(private val rs: java.sql.ResultSet) : AbstractDialect.ResultSet(rs) {
override fun getOffsetDateTime(index: Int): OffsetDateTime? {
return (rs.getObject(index) as? DateTimeOffset)?.offsetDateTime
}
override fun getOffsetDateTime(label: String): OffsetDateTime? {
return (rs.getObject(label) as? DateTimeOffset)?.offsetDateTime
}
}
class SelectPlan(from: Table) : DefaultTableSelectPlan(from) {
private val noOrderByButRowsLimited get() = orderBy.isEmpty() && limit > 0
override val selectWords get() = if (noOrderByButRowsLimited) "${super.selectWords} TOP $limit" else super.selectWords
override val statement: String
get() {
val sql = baseSql + whereTxt + groupByTxt + havingTxt + orderByTxt
return if (noOrderByButRowsLimited) sql else from.dialect.pagination.statement(sql, limit, offset)
}
override val parameters: List<Any?>
get() {
val params = where.parameters + having.parameters
return if (noOrderByButRowsLimited) params else from.dialect.pagination.parameters(params, limit, offset)
}
}
class Pagination : StandardPagination() {
override fun statement(statement: String, limit: Int, offset: Int): String {
return if (limit <= 0) {
if (offset > 0) "$statement\n OFFSET ? ROWS" else statement
}
else {
if (offset > 0) "$statement\nOFFSET ? ROWS\nFETCH NEXT ? ROWS ONLY" else "$statement\nOFFSET 0 ROWS\nFETCH NEXT ? ROWS ONLY"
}
}
}
override val pagination: instep.dao.sql.Pagination
get() = Pagination()
override fun addColumn(column: Column<*>): SQLPlan<*> {
val columnDefinition = definitionForColumns(column)
return InstepSQL.plan("ALTER TABLE ${column.table.tableName} ADD $columnDefinition")
}
override fun dropColumn(column: Column<*>): SQLPlan<*> {
return InstepSQL.plan("ALTER TABLE ${column.table.tableName} DROP ${column.name}")
}
override fun definitionForBooleanColumn(column: BooleanColumn): String = "BIT"
override fun definitionForAutoIncrementColumn(column: IntegerColumn): String = when (column.type) {
IntegerColumnType.Long -> "BIGINT IDENTITY"
IntegerColumnType.Int -> "INT IDENTITY"
IntegerColumnType.Small -> "SMALLINT IDENTITY"
IntegerColumnType.Tiny -> "TINYINT IDENTITY"
}
override fun definitionForDateTimeColumn(column: DateTimeColumn): String = when (column.type) {
DateTimeColumnType.DateTime -> "DATETIME2"
DateTimeColumnType.Instant -> "DATETIME2"
DateTimeColumnType.OffsetDateTime -> "DATETIMEOFFSET"
else -> super.definitionForDateTimeColumn(column)
}
override fun definitionForBinaryColumn(column: BinaryColumn): String = when (column.type) {
BinaryColumnType.BLOB -> "VARBINARY(MAX)"
else -> super.definitionForBinaryColumn(column)
}
override fun definitionForUUIDColumn(column: StringColumn): String = "UNIQUEIDENTIFIER"
override fun createTableIfNotExists(tableName: String, tableComment: String, columns: List<Column<*>>): SQLPlan<*> {
val existsTableCheck = DefaultSQLPlan("SELECT name FROM sys.tables WHERE name=\${name}")
.placeholderToParameter("name", tableName)
val existsTableName = existsTableCheck.executeString()
if (tableName == existsTableName) return existsTableCheck
val ddl = "CREATE TABLE $tableName (\n"
return createTable(tableName, tableComment, ddl, columns)
}
override fun createTable(tableName: String, tableComment: String, ddl: String, columns: List<Column<*>>): SQLPlan<*> {
if (columns.isEmpty()) {
logger.message("Table has no columns.").context("table", tableName).warn()
}
return InstepSQL.plan(ddl + definitionForColumns(*columns.toTypedArray()) + "\n)")
}
}
|
bsd-2-clause
|
5d6590b661137d37b9c05b45885d66c2
| 40.574074 | 140 | 0.674315 | 4.594678 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/clipper/ClipperUltralightTransitData.kt
|
1
|
4253
|
/*
* ClipperUltralightTransitData.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.clipper
import au.id.micolous.metrodroid.card.ultralight.UltralightCard
import au.id.micolous.metrodroid.card.ultralight.UltralightCardTransitFactory
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.Subscription
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.ui.ListItem
@Parcelize
class ClipperUltralightTransitData private constructor(private val mSerial: Long,
private val mBaseDate: Int,
override val trips: List<ClipperUltralightTrip>?,
private val mType: Int,
private val mSub: ClipperUltralightSubscription) : TransitData() {
override val serialNumber: String?
get() = mSerial.toString()
override val cardName: String
get() = NAME
override val subscriptions: List<Subscription>?
get() = listOf<Subscription>(mSub)
override val info: List<ListItem>?
get() = listOf(
when (mType) {
0x04 -> ListItem(R.string.ticket_type, R.string.clipper_ticket_type_adult)
0x44 -> ListItem(R.string.ticket_type, R.string.clipper_ticket_type_senior)
0x84 -> ListItem(R.string.ticket_type, R.string.clipper_ticket_type_rtc)
0xc4 -> ListItem(R.string.ticket_type, R.string.clipper_ticket_type_youth)
else -> ListItem(R.string.ticket_type, mType.toString(16))
}
)
companion object {
private const val NAME = "Clipper Ultralight"
private fun parse(card: UltralightCard): ClipperUltralightTransitData {
val page0 = card.getPage(4).data
val page1 = card.getPage(5).data
val mBaseDate = page1.byteArrayToInt(2, 2)
val rawTrips = intArrayOf(6, 11).map { offset -> card.readPages(offset, 5) }.
filter { !it.isAllZero() }. map { ClipperUltralightTrip(it, mBaseDate) }
var trLast: ClipperUltralightTrip? = null
for (tr in rawTrips) {
if (trLast == null || tr.isSeqGreater(trLast))
trLast = tr
}
return ClipperUltralightTransitData(
mSub = ClipperUltralightSubscription(page1.byteArrayToInt(0, 2),
trLast?.tripsRemaining ?: -1,
trLast?.transferExpiry ?: 0, mBaseDate),
trips = rawTrips.filter { ! it.isHidden },
mType = page0[1].toInt() and 0xff,
mSerial = getSerial(card),
mBaseDate = mBaseDate)
}
val FACTORY: UltralightCardTransitFactory = object : UltralightCardTransitFactory {
override fun check(card: UltralightCard) = card.getPage(4).data[0].toInt() == 0x13
override fun parseTransitData(card: UltralightCard) = parse(card)
override fun parseTransitIdentity(card: UltralightCard) =
TransitIdentity(NAME, getSerial(card).toString())
}
private fun getSerial(card: UltralightCard): Long {
val otp = card.getPage(3).data
return otp.byteArrayToLong(0, 4)
}
}
}
|
gpl-3.0
|
53bf992def7ba7fec3173aedba2e4dd9
| 43.302083 | 121 | 0.616271 | 4.587918 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell
|
ui/ui_image_list/src/main/kotlin/siarhei/luskanau/iot/doorbell/ui/imagelist/CameraAdapter.kt
|
1
|
1449
|
package siarhei.luskanau.iot.doorbell.ui.imagelist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import siarhei.luskanau.iot.doorbell.data.model.CameraData
import siarhei.luskanau.iot.doorbell.ui.common.adapter.BaseRecyclerClickableListAdapter
import siarhei.luskanau.iot.doorbell.ui.common.adapter.BindingViewHolder
import siarhei.luskanau.iot.doorbell.ui.common.databinding.ViewItemCameraBinding
class CameraAdapter : BaseRecyclerClickableListAdapter<CameraData, ViewItemCameraBinding>(
DIFF_CALLBACK
) {
override fun onCreateViewHolder(
inflater: LayoutInflater,
parent: ViewGroup,
viewType: Int
): BindingViewHolder<ViewItemCameraBinding> =
BindingViewHolder(ViewItemCameraBinding.inflate(inflater, parent, false))
override fun onBindViewHolder(holder: BindingViewHolder<ViewItemCameraBinding>, position: Int) {
getItem(position).let { item ->
holder.binding.name.text = item.name ?: run { item.cameraId }
}
}
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<CameraData>() {
override fun areItemsTheSame(oldItem: CameraData, newItem: CameraData) =
oldItem.cameraId == newItem.cameraId
override fun areContentsTheSame(oldItem: CameraData, newItem: CameraData) =
oldItem == newItem
}
}
}
|
mit
|
806517f40d26585f7162a6d502480089
| 38.162162 | 100 | 0.73637 | 4.813953 | false | false | false | false |
JetBrains/kotlin-spec
|
build-utils/src/org/jetbrains/kotlin/spec/copyPasteFilter.kt
|
1
|
2875
|
package org.jetbrains.kotlin.spec
import ru.spbstu.pandoc.*
import ru.spbstu.pandoc.helper.*
private class IdCollector : PandocVisitor() {
val blocks: MutableMap<String, Block> = mutableMapOf()
val inlines: MutableMap<String, Inline> = mutableMapOf()
override fun visit(b: Block): Block {
if(b is Attributes && b.attr.id.isNotBlank()) blocks[b.attr.id] = b
return super.visit(b)
}
override fun visit(i: Inline): Inline {
if(i is Attributes && i.attr.id.isNotBlank()) inlines[i.attr.id] = i
return super.visit(i)
}
}
private object SpecCopyPasteFilterVisitor : PandocVisitor() {
var nextId: Int = 0
private val collector = IdCollector()
override fun visit(doc: Pandoc): Pandoc {
collector.visit(doc)
return super.visit(doc)
}
private fun getBlock(id: String): Block =
when(id) {
in collector.inlines -> {
val i = collector.inlines[id]!!
Block.Plain(listOf(i))
}
in collector.blocks -> collector.blocks[id]!!
else -> Block.Plain(listOf(Inline.Strong(listOf(Inline.Str("Id $id not found")))))
}
private fun getInline(id: String): Inline =
when(id) {
in collector.inlines -> collector.inlines[id]!!
in collector.blocks ->
Inline.Strong(listOf(Inline.Str("[Cannot paste block $id as inline]")))
else -> Inline.Strong(listOf(Inline.Str("[Id $id not found]")))
}
override fun visit(b: Block.Div): Block {
when {
"paste" in b.attr.classes -> {
val props = b.attr.propertiesMap()
val target = props["target"] ?: return super.visit(b)
val block = getBlock(target)
if (block is Attributes) {
val id = if(b.attr.id.isNotBlank()) b.attr.id else "$target-pasted-${nextId++}"
return block.copy(attr = block.attr.copy(id = id)) as Block
}
return block
}
else -> return super.visit(b)
}
}
override fun visit(i: Inline.Span): Inline {
when {
"paste" in i.attr.classes -> {
val props = i.attr.propertiesMap()
val target = props["target"] ?: return super.visit(i)
val inline = getInline(target)
if (inline is Attributes) {
val id = if(i.attr.id.isNotBlank()) i.attr.id else "$target-pasted-${nextId++}"
return inline.copy(attr = inline.attr.copy(id = id)) as Inline
}
return inline
}
else -> return super.visit(i)
}
}
}
fun main() = makeFilter(SpecCopyPasteFilterVisitor)
|
apache-2.0
|
ca56912864e07115d65555d5aeba1dc3
| 32.823529 | 99 | 0.535652 | 4.190962 | false | false | false | false |
nonylene/MackerelAgentAndroid
|
app/src/main/java/net/nonylene/mackerelagent/LogRecyclerAdapter.kt
|
1
|
1208
|
package net.nonylene.mackerelagent
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import net.nonylene.mackerelagent.databinding.LogRecyclerItemBinding
import net.nonylene.mackerelagent.viewmodel.LogRecyclerItemViewModel
class LogRecyclerAdapter : RecyclerView.Adapter<LogRecyclerAdapter.ViewHolder>() {
var logs: List<AgentLog> = listOf()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.log_recycler_item, parent, false))
}
override fun getItemCount() = logs.count()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.binding.model!!.setAgentLog(logs[position])
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding: LogRecyclerItemBinding
init {
binding = DataBindingUtil.bind(itemView)
binding.model = LogRecyclerItemViewModel()
}
}
}
|
mit
|
7c3fb06f37c922c9ce7376bb414f3f3a
| 29.974359 | 113 | 0.735927 | 4.71875 | false | false | false | false |
OnyxDevTools/onyx-database-parent
|
onyx-database/src/main/kotlin/com/onyx/persistence/query/QueryOrder.kt
|
1
|
828
|
package com.onyx.persistence.query
import com.onyx.buffer.BufferStreamable
import com.onyx.persistence.manager.PersistenceManager
/**
* The purpose of this is to specify the query sort order while querying.
*
*
* @author Tim Osborn
* @since 1.0.0
*
* PersistenceManager manager = factory.getPersistenceManager(); // Get the Persistence manager from the persistence manager factory
*
* Query query = new Query(MyEntity.class, new QueryCriteria("attributeName", QueryCriteriaOperator.EQUAL, "key"));
* query.setQueryOrders(new QueryOrder("name", true)
*
* List results = manager.executeQuery(query);
*
* @see com.onyx.persistence.query.Query
* @see PersistenceManager.executeQuery
*/
data class QueryOrder @JvmOverloads constructor (var attribute: String = "", var isAscending:Boolean = true) : BufferStreamable
|
agpl-3.0
|
8c9adbf63f2d05c7b792225af2e58abd
| 35 | 132 | 0.763285 | 4.160804 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt
|
4
|
7142
|
// 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.console
import com.intellij.execution.configurations.CompositeParameterTargetedValue
import com.intellij.execution.configurations.JavaCommandLineState
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.TargetedCommandLine
import com.intellij.execution.target.local.LocalTargetEnvironmentRequest
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.KotlinIdeaReplBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.util.JavaParametersBuilder
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.projectStructure.version
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.platform.subplatformsOfType
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.absolutePathString
import kotlin.io.path.notExists
class KotlinConsoleKeeper(val project: Project) {
private val consoleMap: MutableMap<VirtualFile, KotlinConsoleRunner> = ConcurrentHashMap()
fun getConsoleByVirtualFile(virtualFile: VirtualFile) = consoleMap[virtualFile]
fun putVirtualFileToConsole(virtualFile: VirtualFile, console: KotlinConsoleRunner) = consoleMap.put(virtualFile, console)
fun removeConsole(virtualFile: VirtualFile) = consoleMap.remove(virtualFile)
fun run(module: Module, previousCompilationFailed: Boolean = false): KotlinConsoleRunner {
val path = module.moduleFilePath
val (environmentRequest, cmdLine) = createReplCommandLine(project, module)
val consoleRunner = KotlinConsoleRunner(
module,
environmentRequest,
cmdLine,
previousCompilationFailed,
project,
KotlinIdeaReplBundle.message("name.kotlin.repl"),
path
)
consoleRunner.initAndRun()
return consoleRunner
}
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.console")
@JvmStatic
fun getInstance(project: Project): KotlinConsoleKeeper = project.service()
fun createReplCommandLine(project: Project, module: Module?): Pair<TargetEnvironmentRequest, TargetedCommandLine> {
val javaParameters = JavaParametersBuilder(project)
.withSdkFrom(module, true)
.withMainClassName("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler")
.build()
val wslConfiguration = JavaCommandLineState.checkCreateWslConfiguration(javaParameters.jdk)
val request = wslConfiguration?.createEnvironmentRequest(project) ?: LocalTargetEnvironmentRequest()
javaParameters.charset = null
with(javaParameters.vmParametersList) {
add("-Dkotlin.repl.ideMode=true")
if (isUnitTestMode() && javaParameters.jdk?.version?.isAtLeast(JavaSdkVersion.JDK_1_9) == true) {
// TODO: Have to get rid of illegal access to java.util.ResourceBundle.setParent(java.util.ResourceBundle):
// WARNING: Illegal reflective access by com.intellij.util.ReflectionUtil (file:...kotlin-ide/intellij/out/kotlinc-dist/kotlinc/lib/kotlin-compiler.jar) to method java.util.ResourceBundle.setParent(java.util.ResourceBundle)
// WARNING: Please consider reporting this to the maintainers of com.intellij.util.ReflectionUtil
// WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
// WARNING: All illegal access operations will be denied in a future release
add("--add-opens")
add("java.base/java.util=ALL-UNNAMED")
}
}
javaParameters.classPath.apply {
val classPath = listOf( // KotlinPaths.ClassPaths.CompilerWithScripting + jetbrains-annotations
KotlinArtifacts.kotlinCompiler,
KotlinArtifacts.kotlinStdlib,
KotlinArtifacts.kotlinReflect,
KotlinArtifacts.kotlinScriptRuntime,
KotlinArtifacts.trove4j,
KotlinArtifacts.kotlinDaemon,
KotlinArtifacts.kotlinScriptingCompiler,
KotlinArtifacts.kotlinScriptingCompilerImpl,
KotlinArtifacts.kotlinScriptingCommon,
KotlinArtifacts.kotlinScriptingJvm,
KotlinArtifacts.jetbrainsAnnotations
)
addAll(classPath.map { file ->
val path = file.toPath()
val absolutePath = path.absolutePathString()
if (path.notExists()) {
LOG.warn("Compiler dependency classpath $absolutePath does not exist")
}
absolutePath
})
}
if (module != null) {
val classPath = JavaParametersBuilder.getModuleDependencies(module)
if (classPath.isNotEmpty()) {
javaParameters.setUseDynamicParameters(javaParameters.isDynamicClasspath)
with(javaParameters.programParametersList) {
add("-cp")
val compositeValue = CompositeParameterTargetedValue()
for ((index, s) in classPath.withIndex()) {
if (index > 0) {
compositeValue.addLocalPart(request.targetPlatform.platform.pathSeparator.toString())
}
compositeValue.addPathPart(s)
}
add(compositeValue)
}
}
module.platform.subplatformsOfType<JdkPlatform>().firstOrNull()?.targetVersion?.let {
with(javaParameters.programParametersList) {
add("-jvm-target")
add(it.description)
}
}
}
with(javaParameters.programParametersList) {
add("-kotlin-home")
val kotlinHome = KotlinPluginLayout.kotlinc
check(kotlinHome.exists()) { "Kotlin compiler is not found" }
add(CompositeParameterTargetedValue().addPathPart(kotlinHome.toPath().absolutePathString()))
}
return request to javaParameters.toCommandLine(request).build()
}
}
}
|
apache-2.0
|
a4c644fa3778b94770353ddb9ecccd42
| 49.295775 | 244 | 0.652058 | 5.619197 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/completion/testData/basic/multifile/PropertyKeysNoPrefix/PropertyKeysNoPrefix.kt
|
3
|
824
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
import org.jetbrains.annotations.PropertyKey
fun message(@PropertyKey(resourceBundle = "PropertyKeysNoPrefix") key: String) = key
fun test() {
message("<caret>foo")
}
// EXIST: { lookupString: "foo.bar", itemText: "foo.bar", tailText: "=1", typeText: "PropertyKeysNoPrefix", icon: "Property"}
// EXIST: { lookupString: "bar.baz", itemText: "bar.baz", tailText: "=2", typeText: "PropertyKeysNoPrefix", icon: "Property"}
// EXIST: { lookupString: "foo.bar.baz", itemText: "foo.bar.baz", tailText: "=3", typeText: "PropertyKeysNoPrefix", icon: "Property"}
// EXIST: { lookupString: "foo.test", itemText: "foo.test", tailText: "=4", typeText: "PropertyKeysNoPrefix", icon: "Property"}
// NOTHING_ELSE
|
apache-2.0
|
b2b2ad8102388b27dd94ff5dee53d91b
| 57.928571 | 133 | 0.709951 | 3.536481 | false | true | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryHolder.kt
|
2
|
1450
|
package eu.kanade.tachiyomi.ui.category
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.databinding.CategoriesItemBinding
/**
* Holder used to display category items.
*
* @param view The view used by category items.
* @param adapter The adapter containing this holder.
*/
class CategoryHolder(view: View, val adapter: CategoryAdapter) : FlexibleViewHolder(view, adapter) {
private val binding = CategoriesItemBinding.bind(view)
init {
setDragHandleView(binding.reorder)
}
/**
* Binds this holder with the given category.
*
* @param category The category to bind.
*/
fun bind(category: Category) {
binding.title.text = category.name
}
/**
* Called when an item is released.
*
* @param position The position of the released item.
*/
override fun onItemReleased(position: Int) {
super.onItemReleased(position)
adapter.onItemReleaseListener.onItemReleased(position)
binding.container.isDragged = false
}
override fun onActionStateChanged(position: Int, actionState: Int) {
super.onActionStateChanged(position, actionState)
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
binding.container.isDragged = true
}
}
}
|
apache-2.0
|
3dc297b941ee82e2ed64228b6bf77045
| 28.591837 | 100 | 0.702759 | 4.53125 | false | false | false | false |
cfieber/orca
|
orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/KayentaCanaryStageTest.kt
|
1
|
17931
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.pipeline
import com.netflix.spinnaker.orca.ext.mapTo
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.kayenta.CanaryScope
import com.netflix.spinnaker.orca.pipeline.WaitStage
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.spek.values
import com.netflix.spinnaker.spek.where
import com.netflix.spinnaker.time.fixedClock
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import java.time.Duration
import java.time.temporal.ChronoUnit.HOURS
import java.time.temporal.ChronoUnit.MINUTES
object KayentaCanaryStageTest : Spek({
val clock = fixedClock()
val builder = KayentaCanaryStage(clock)
describe("planning a canary stage") {
given("start/end times are specified") {
where(
"canary analysis should start after %s minutes",
values(null, listOf("runCanary")),
values("", listOf("runCanary")),
values("0", listOf("runCanary")),
values("30", listOf("wait", "runCanary"))
) { beginCanaryAnalysisAfterMins, expectedStageTypes ->
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"canaryConfigId" to "MySampleStackdriverCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "myapp-v010",
"experimentScope" to "myapp-v021",
"startTimeIso" to clock.instant().toString(),
"endTimeIso" to clock.instant().plus(4, HOURS).toString()
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"beginCanaryAnalysisAfterMins" to beginCanaryAnalysisAfterMins
)
}
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
it("should not introduce wait stages") {
assertThat(aroundStages).extracting("type").isEqualTo(expectedStageTypes)
}
}
where(
"canary should start after %s minutes with an interval of %s minutes and lookback of %s minutes",
values(null, null, null, CanaryRanges(0 to 240)),
values(null, "", "", CanaryRanges(0 to 240)),
values(null, "0", "0", CanaryRanges(0 to 240)),
values(null, "60", null, CanaryRanges(0 to 60, 0 to 120, 0 to 180, 0 to 240)),
values("15", null, "", CanaryRanges(0 to 240)),
values("15", "", "0", CanaryRanges(0 to 240)),
values("15", "0", null, CanaryRanges(0 to 240)),
values("15", "60", "", CanaryRanges(0 to 60, 0 to 120, 0 to 180, 0 to 240)),
values(null, null, "120", CanaryRanges(120 to 240)),
values(null, "", "60", CanaryRanges(180 to 240)),
values(null, "0", "60", CanaryRanges(180 to 240)),
values(null, "60", "60", CanaryRanges(0 to 60, 60 to 120, 120 to 180, 180 to 240)),
values("15", null, "120", CanaryRanges(120 to 240)),
values("15", "", "60", CanaryRanges(180 to 240)),
values("15", "0", "60", CanaryRanges(180 to 240)),
values("15", "60", "60", CanaryRanges(0 to 60, 60 to 120, 120 to 180, 180 to 240)),
values(null, "300", null, CanaryRanges(0 to 240))
) { warmupMins, intervalMins, lookbackMins, canaryRanges ->
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"canaryConfigId" to "MySampleStackdriverCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "myapp-v010",
"experimentScope" to "myapp-v021",
"startTimeIso" to clock.instant().toString(),
"endTimeIso" to clock.instant().plus(4, HOURS).toString()
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"beginCanaryAnalysisAfterMins" to warmupMins,
"canaryAnalysisIntervalMins" to intervalMins,
"lookbackMins" to lookbackMins
)
}
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
it("still handles canary intervals properly") {
aroundStages
.controlScopes()
.apply {
assertThat(map { clock.instant().until(it.start, MINUTES) }).isEqualTo(canaryRanges.startAtMin.map { it.toLong() })
assertThat(map { clock.instant().until(it.end, MINUTES) }).isEqualTo(canaryRanges.endAtMin.map { it.toLong() })
assertThat(map { it.step }).allMatch { it == Duration.ofMinutes(1).seconds }
}
}
if (warmupMins != null) {
val expectedWarmupWait = warmupMins.toInt()
it("inserts a warmup wait stage of $expectedWarmupWait minutes") {
aroundStages
.filter { it.name == "Warmup Wait" }
.apply {
assertThat(this).hasSize(1)
assertThat(first().context["waitTime"])
.isEqualTo(expectedWarmupWait.minutesInSeconds.toLong())
}
}
} else {
it("does not insert a warmup wait stage") {
assertThat(aroundStages).noneMatch { it.name == "Warmup Wait" }
}
}
}
}
given("start and end times are not specified") {
where(
"canary analysis should begin after %s minutes",
values(null, listOf("wait", "runCanary"), 0L),
values("", listOf("wait", "runCanary"), 0L),
values("0", listOf("wait", "runCanary"), 0L),
values("30", listOf("wait", "wait", "runCanary"), 30L)
) { warmupMins, expectedStageTypes, expectedWarmupMins ->
and("canary analysis should begin after $warmupMins minutes") {
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"canaryConfigId" to "MySampleStackdriverCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "myapp-v010",
"experimentScope" to "myapp-v021"
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"lifetimeHours" to "1",
"beginCanaryAnalysisAfterMins" to warmupMins
)
}
val builder = KayentaCanaryStage(clock)
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
it("should start now") {
assertThat(aroundStages).extracting("type").isEqualTo(expectedStageTypes)
assertThat(aroundStages.controlScopes().map { it.start })
.allMatch { it == clock.instant().plus(expectedWarmupMins, MINUTES) }
}
if (expectedWarmupMins > 0L) {
it("inserts a warmup wait stage of $expectedWarmupMins minutes") {
aroundStages
.first()
.apply {
assertThat(type).isEqualTo("wait")
assertThat(name).isEqualTo("Warmup Wait")
assertThat(context["waitTime"]).isEqualTo(expectedWarmupMins.minutesInSeconds)
}
}
} else {
it("does not insert a leading wait stage") {
assertThat(aroundStages.filter { it.name == "Warmup Wait" }).isEmpty()
}
}
}
}
where(
"canary should start after %s minutes with an interval of %s minutes and lookback of %s minutes",
values(null, null, null, CanaryRanges(0 to 48.hoursInMinutes)),
values(null, "", "", CanaryRanges(0 to 48.hoursInMinutes)),
values(null, "0", "0", CanaryRanges(0 to 48.hoursInMinutes)),
values(null, "${8.hoursInMinutes}", null, CanaryRanges(0 to 8.hoursInMinutes, 0 to 16.hoursInMinutes, 0 to 24.hoursInMinutes, 0 to 32.hoursInMinutes, 0 to 40.hoursInMinutes, 0 to 48.hoursInMinutes)),
values("45", null, "", CanaryRanges(45 to 45 + 48.hoursInMinutes)),
values("45", "", "0", CanaryRanges(45 to 45 + 48.hoursInMinutes)),
values("45", "0", null, CanaryRanges(45 to 45 + 48.hoursInMinutes)),
values("45", "${8.hoursInMinutes}", "", CanaryRanges(45 to 45 + 8.hoursInMinutes, 45 to 45 + 16.hoursInMinutes, 45 to (45 + 24.hoursInMinutes), 45 to 45 + 32.hoursInMinutes, 45 to 45 + 40.hoursInMinutes, 45 to 45 + 48.hoursInMinutes)),
values(null, null, "60", CanaryRanges(47.hoursInMinutes to 48.hoursInMinutes)),
values(null, "", "60", CanaryRanges(47.hoursInMinutes to 48.hoursInMinutes)),
values(null, "0", "60", CanaryRanges(47.hoursInMinutes to 48.hoursInMinutes)),
values(null, "${8.hoursInMinutes}", "60", CanaryRanges(7.hoursInMinutes to 8.hoursInMinutes, 15.hoursInMinutes to 16.hoursInMinutes, 23.hoursInMinutes to 24.hoursInMinutes, 31.hoursInMinutes to 32.hoursInMinutes, 39.hoursInMinutes to 40.hoursInMinutes, 47.hoursInMinutes to 48.hoursInMinutes)),
values("45", null, "60", CanaryRanges(45 + 47.hoursInMinutes to 45 + 48.hoursInMinutes)),
values("45", "", "60", CanaryRanges(45 + 47.hoursInMinutes to 45 + 48.hoursInMinutes)),
values("45", "0", "60", CanaryRanges(45 + 47.hoursInMinutes to 45 + 48.hoursInMinutes)),
values("45", "${8.hoursInMinutes}", "60", CanaryRanges(45 + 7.hoursInMinutes to 45 + 8.hoursInMinutes, 45 + 15.hoursInMinutes to 45 + 16.hoursInMinutes, 45 + 23.hoursInMinutes to 45 + 24.hoursInMinutes, 45 + 31.hoursInMinutes to 45 + 32.hoursInMinutes, 45 + 39.hoursInMinutes to 45 + 40.hoursInMinutes, 45 + 47.hoursInMinutes to 45 + 48.hoursInMinutes))
) { warmupMins, intervalMins, lookbackMins, canaryRanges ->
val canaryDuration = Duration.ofHours(48)
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"canaryConfigId" to "MySampleStackdriverCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "myapp-v010",
"experimentScope" to "myapp-v021"
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"beginCanaryAnalysisAfterMins" to warmupMins,
"canaryAnalysisIntervalMins" to intervalMins,
"lookbackMins" to lookbackMins,
"lifetimeDuration" to canaryDuration
)
}
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
if (warmupMins != null) {
val expectedWarmupWait = warmupMins.toInt()
it("inserts a warmup wait stage of $expectedWarmupWait minutes") {
aroundStages
.first()
.apply {
assertThat(type).isEqualTo("wait")
assertThat(name).isEqualTo("Warmup Wait")
assertThat(context["waitTime"]).isEqualTo(expectedWarmupWait.minutesInSeconds.toLong())
}
}
} else {
it("does not insert a leading wait stage") {
assertThat(aroundStages.filter { it.name == "Warmup Wait" }).isEmpty()
}
}
it("generates the correct ranges for each canary analysis phase") {
aroundStages.controlScopes()
.apply {
assertThat(map { clock.instant().until(it.start, MINUTES) }).isEqualTo(canaryRanges.startAtMin.map { it.toLong() })
assertThat(map { clock.instant().until(it.end, MINUTES) }).isEqualTo(canaryRanges.endAtMin.map { it.toLong() })
assertThat(map { it.step }).allMatch { it == Duration.ofMinutes(1).seconds }
}
}
if (intervalMins != null && intervalMins.isNotEmpty() && intervalMins != "0") {
val expectedIntervalWait = intervalMins.toInt()
it("interleaves wait stages of $expectedIntervalWait minutes") {
aroundStages
.filter { it.name.matches(Regex("Interval Wait #\\d+")) }
.waitTimes()
.apply {
assertThat(this).hasSize(canaryRanges.startAtMin.size)
assertThat(this).allMatch { it == expectedIntervalWait.minutesInSeconds.toLong() }
}
}
} else {
val expectedIntervalWait = canaryDuration
it("adds a single wait stage of the entire canary duration (${expectedIntervalWait.toHours()} hours)") {
aroundStages
.filter { it.name.matches(Regex("Interval Wait #\\d+")) }
.waitTimes()
.apply {
assertThat(this).hasSize(1)
assertThat(first()).isEqualTo(expectedIntervalWait.seconds)
}
}
}
}
}
given("additional canary attributes") {
val attributes = mapOf("type" to "node")
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"metricsAccountName" to "atlas-acct-1",
"canaryConfigId" to "MySampleAtlasCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "some.host.node",
"experimentScope" to "some.other.host.node",
"step" to 60,
"extendedScopeParams" to attributes
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"canaryAnalysisIntervalMins" to 6.hoursInMinutes,
"lifetimeHours" to "12"
)
}
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
it("propagates the additional attributes") {
assertThat(aroundStages.controlScopes())
.extracting("extendedScopeParams")
.allMatch { it == attributes }
}
}
given("canary deployments are requested") {
val kayentaCanaryStage = stage {
type = "kayentaCanary"
name = "Run Kayenta Canary"
context["canaryConfig"] = mapOf(
"metricsAccountName" to "atlas-acct-1",
"canaryConfigId" to "MySampleAtlasCanaryConfig",
"scopes" to listOf(mapOf(
"controlScope" to "some.host.node",
"experimentScope" to "some.other.host.node",
"step" to 60
)),
"scoreThresholds" to mapOf("marginal" to 75, "pass" to 90),
"canaryAnalysisIntervalMins" to 6.hoursInMinutes,
"lifetimeHours" to "12"
)
context["deployments"] = mapOf(
"clusters" to listOf(
mapOf("control" to mapOf<String, Any>()),
mapOf("experiment" to mapOf<String, Any>())
)
)
}
val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage)
.let { graph ->
builder.beforeStages(kayentaCanaryStage, graph)
graph.build()
}
it("injects a deploy canary stage") {
aroundStages.first().apply {
assertThat(type).isEqualTo(DeployCanaryClustersStage.STAGE_TYPE)
}
}
it("the canary analysis will only start once the deployment is complete") {
aroundStages.toList()[0..1].let { (first, second) ->
assertThat(second.requisiteStageRefIds).isEqualTo(setOf(first.refId))
}
}
}
}
})
private operator fun <E> List<E>.get(range: IntRange): List<E> {
return subList(range.start, range.endExclusive)
}
private val IntRange.endExclusive: Int
get() = endInclusive + 1
data class CanaryRanges(
val startAtMin: List<Int>,
val endAtMin: List<Int>
) {
constructor(vararg range: Pair<Int, Int>) :
this(range.map { it.first }, range.map { it.second })
}
/**
* Get [scopeName] control scope from all [RunCanaryPipelineStage]s.
*/
fun Iterable<Stage>.controlScopes(scopeName: String = "default"): List<CanaryScope> =
filter { it.type == RunCanaryPipelineStage.STAGE_TYPE }
.map { it.mapTo<CanaryScope>("/scopes/$scopeName/controlScope") }
/**
* Get wait time from any [WaitStage]s.
*/
fun List<Stage>.waitTimes(): List<Long> =
filter { it.type == "wait" }
.map { it.mapTo<Long>("/waitTime") }
val Int.hoursInMinutes: Int
get() = Duration.ofHours(this.toLong()).toMinutes().toInt()
val Int.hoursInSeconds: Int
get() = Duration.ofHours(this.toLong()).seconds.toInt()
val Int.minutesInSeconds: Int
get() = Duration.ofMinutes(this.toLong()).seconds.toInt()
val Long.minutesInSeconds: Long
get() = Duration.ofMinutes(this).seconds
|
apache-2.0
|
8fd5fbed34caaa95413be252f7529370
| 41.390071 | 361 | 0.609949 | 4.240009 | false | false | false | false |
tommykw/iweather
|
app/src/main/java/com/github/tommykw/colorpicker/Utils.kt
|
1
|
1103
|
package com.github.tommykw.colorpicker
import android.graphics.Color
import android.support.annotation.FloatRange
import android.support.annotation.NonNull
import java.lang.Math.round
/**
* Created by tommy on 2016/06/06.
*/
class Utils {
companion object {
fun interpreterColor(
@FloatRange(from = 0.0, to = 1.0) unit:Float,
@NonNull colors: IntArray): Int {
if (unit <= 0) return colors[0]
if (unit >= 1) return colors[colors.size - 1]
var p = unit * (colors.size - 1)
var i = p.toInt()
p -= i
val c0 = colors[i]
val c1 = colors[i + 1]
val a = avg(Color.alpha(c0), Color.alpha(c1), p)
val r = avg(Color.red(c0), Color.red(c1), p)
val g = avg(Color.green(c0), Color.green(c1), p)
val b = avg(Color.blue(c0), Color.blue(c1), p)
return Color.argb(a, r, g, b)
}
fun avg(s:Int,
e: Int,
@FloatRange(from = 0.0, to = 1.0) p:Float) = s + round(p * (e - s))
}
}
|
apache-2.0
|
93f432b4e1ed6349b562f7cc3075608f
| 28.052632 | 83 | 0.523119 | 3.362805 | false | false | false | false |
saffih/ElmDroid
|
app/src/main/java/elmdroid/elmdroid/example1/ExampleHelloWorldActivity.kt
|
1
|
5334
|
package elmdroid.elmdroid.example1
import android.Manifest
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.telephony.SmsMessage
import android.widget.TextView
import elmdroid.elmdroid.R
import elmdroid.elmdroid.example1.hello.Turtle
import kotlinx.android.synthetic.main.activity_helloworld.*
import saffih.elmdroid.ElmBase
import saffih.elmdroid.activityCheckForPermission
import saffih.elmdroid.sms.child.SmsChild
import elmdroid.elmdroid.example1.hello.Model as HelloModel
import elmdroid.elmdroid.example1.hello.Msg as HelloMsg
// POJO
class Greeting(val greet: String)
val intialGreating = Greeting("Hello")
// MODEL
data class Model(val activity: MActivity = MActivity())
data class MActivity(val greeting: Greeting = intialGreating,
val turtle: HelloModel = HelloModel(),
val sms: MSms = MSms()
)
typealias MSms = saffih.elmdroid.sms.child.Model
typealias SmsMsg = saffih.elmdroid.sms.child.Msg
// MSG
sealed class Msg {
object Init : Msg()
sealed class Activity : Msg() {
class Greeted(val v: Greeting) : Activity()
class GreetedToggle : Activity()
// poc with sub modules.
class Turtle(val smsg: HelloMsg) : Activity()
class Sms(val smsg: SmsMsg
) : Activity()
}
}
class ElmApp(override val me: ExampleHelloWorldActivity) : ElmBase<Model, Msg>(me) {
private val sms = object : SmsChild(me) {
override fun handleMSG(cur: saffih.elmdroid.sms.child.Msg) {
dispatch(Msg.Activity.Sms(cur))
}
override fun onSmsArrived(sms: List<SmsMessage>) {
sms.forEach { onSmsArrived(it) }
}
fun onSmsArrived(sms: SmsMessage) =
post { dispatch(Msg.Activity.Greeted(Greeting(sms.messageBody))) }
}
val turtle = object : Turtle(me) {
override fun handleMSG(cur: elmdroid.elmdroid.example1.hello.Msg) {
dispatch(Msg.Activity.Turtle(cur))
}
}
override fun init(): Model {
dispatch(Msg.Init)
return Model()
}
override fun update(msg: Msg, model: Model): Model {
return when (msg) {
is Msg.Init -> {
val m = update(msg, model.activity)
model.copy(activity = m)
}
is Msg.Activity -> {
// several updates
val sm = update(msg, model.activity)
model.copy(activity = sm)
}
}
}
private fun update(msg: Msg.Init, model: MActivity): MActivity {
val m = turtle.update(HelloMsg.Init(), model.turtle)
return model.copy(turtle = m)
}
fun update(msg: Msg.Activity, model: MActivity): MActivity {
return when (msg) {
is Msg.Activity.Greeted -> {
model.copy(greeting = msg.v)
}
is Msg.Activity.GreetedToggle -> {
val v = if (model.greeting == intialGreating) Greeting("world") else intialGreating
dispatch(Msg.Activity.Greeted(v))
model
}
is Msg.Activity.Turtle -> {
val m = turtle.update(msg.smsg, model.turtle)
model.copy(turtle = m)
}
is Msg.Activity.Sms -> {
val m = sms.update(msg.smsg, model.sms)
model.copy(sms = m)
}
}
}
/**
* Render view, app delegates myModel review changes to children
*/
override fun view(model: Model, pre: Model?) {
val setup = { }
checkView(setup, model, pre) {
view(model.activity, pre?.activity)
}
}
/**
* Activity impl setup the layout view. if has changes delegate render to impl views
*/
private fun view(model: MActivity, pre: MActivity?) {
val setup = { me.setContentView(R.layout.activity_helloworld) }
checkView(setup, model, pre) {
view(model.greeting, pre?.greeting)
turtle.view(model.turtle, pre?.turtle)
}
}
private fun view(model: Greeting, pre: Greeting?) {
val setup = {
val v = me.greetingToggleButton
v.setOnClickListener { v -> dispatch(Msg.Activity.GreetedToggle()) }
}
checkView(setup, model, pre) {
val view = me.greetingText as TextView
me.greetingText.text.clear()
me.greetingText.text.append(model.greet)
}
}
fun onPause() {
sms.onDestroy()
}
fun onResume() {
sms.onCreate()
}
}
class ExampleHelloWorldActivity : AppCompatActivity() {
val app = ElmApp(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityCheckForPermission(listOf(Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.SEND_SMS), 1)
app.onCreate()
}
override fun onResume() {
super.onResume()
app.onResume()
}
override fun onPause() {
super.onPause()
app.onPause()
}
override fun onDestroy() {
app.onDestroy()
super.onDestroy()
}
override fun onStart() {
super.onStart()
app.onCreate()
}
}
|
apache-2.0
|
4e5408725d410d21a6b8a37983a279b4
| 26.637306 | 99 | 0.591676 | 4.122102 | false | false | false | false |
McMoonLakeDev/MoonLake
|
API/src/main/kotlin/com/mcmoonlake/api/chat/ChatComponentText.kt
|
1
|
2182
|
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.chat
/**
* ## ChatComponentText (聊天组件文本)
*
* @see [ChatComponent]
* @see [ChatComponentAbstract]
* @author lgou2w
* @since 2.0
* @constructor ChatComponentText
* @param text Text.
* @param text 文本.
*/
open class ChatComponentText(
/**
* * Gets or sets the text object for this chat component text.
* * 获取或设置此聊天组件文本的文本对象.
*/
var text: String
) : ChatComponentAbstract() {
/**
* @constructor ChatComponentText
*
* * Using `empty` string.
* * 使用 `空` 字符串.
*/
constructor() : this("")
/**
* @constructor ChatComponentText
*
* @param text Chat component text.
* @param text 聊天组件文本.
*/
constructor(text: ChatComponentText) : this(text.text)
fun setText(text: String): ChatComponentText
{ this.text = text; return this; }
override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is ChatComponentText)
return super.equals(other) && text == other.text
return false
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + text.hashCode()
return result
}
override fun toString(): String {
return "ChatComponentText(text='$text', style=$style, extras=$extras)"
}
}
|
gpl-3.0
|
d6a2c7066ce102230720a82c2a134ede
| 26.736842 | 78 | 0.638046 | 4 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsFileEventLogger.kt
|
5
|
5708
|
// 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.internal.statistic.eventLog
import com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Disposer
import com.intellij.util.concurrency.AppExecutorUtil
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import com.jetbrains.fus.reporting.model.lion3.LogEventAction
import com.jetbrains.fus.reporting.model.lion3.LogEventGroup
import java.util.concurrent.CompletableFuture
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
open class StatisticsFileEventLogger(private val recorderId: String,
private val sessionId: String,
private val headless: Boolean,
private val build: String,
private val bucket: String,
private val recorderVersion: String,
private val writer: StatisticsEventLogWriter,
private val systemEventIdProvider: StatisticsSystemEventIdProvider,
private val mergeStrategy: StatisticsEventMergeStrategy = FilteredEventMergeStrategy(emptySet())
) : StatisticsEventLogger, Disposable {
protected val logExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("StatisticsFileEventLogger: $sessionId", 1)
private var lastEvent: FusEvent? = null
private var lastEventTime: Long = 0
private var lastEventCreatedTime: Long = 0
private var eventMergeTimeoutMs: Long
private var lastEventFlushFuture: ScheduledFuture<CompletableFuture<Void>>? = null
init {
if (StatisticsRecorderUtil.isTestModeEnabled(recorderId)) {
eventMergeTimeoutMs = 500L
}
else {
eventMergeTimeoutMs = 10000L
}
}
override fun logAsync(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean): CompletableFuture<Void> {
val eventTime = System.currentTimeMillis()
group.validateEventId(eventId)
return try {
CompletableFuture.runAsync(Runnable {
val validator = IntellijSensitiveDataValidator.getInstance(recorderId)
if (!validator.isGroupAllowed(group)) return@Runnable
val event = LogEvent(sessionId, build, bucket, eventTime,
LogEventGroup(group.id, group.version.toString()),
recorderVersion,
LogEventAction(eventId, isState, HashMap(data))).escape()
val validatedEvent = validator.validateEvent(event)
if (validatedEvent != null) {
log(validatedEvent, System.currentTimeMillis(), eventId, data)
}
}, logExecutor)
}
catch (e: RejectedExecutionException) {
//executor is shutdown
CompletableFuture<Void>().also { it.completeExceptionally(e) }
}
}
private fun log(event: LogEvent, createdTime: Long, rawEventId: String, rawData: Map<String, Any>) {
if (lastEvent != null && event.time - lastEventTime <= eventMergeTimeoutMs && mergeStrategy.shouldMerge(lastEvent!!.validatedEvent, event)) {
lastEventTime = event.time
lastEvent!!.validatedEvent.event.increment()
}
else {
logLastEvent()
lastEvent = if(StatisticsRecorderUtil.isTestModeEnabled(recorderId)) FusEvent(event, rawEventId, rawData) else FusEvent(event, null, null)
lastEventTime = event.time
lastEventCreatedTime = createdTime
}
if (StatisticsRecorderUtil.isTestModeEnabled(recorderId)) {
lastEventFlushFuture?.cancel(false)
// call flush() instead of logLastEvent() directly so that logLastEvent is executed on the logExecutor thread and not on scheduled executor pool thread
lastEventFlushFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(this::flush, eventMergeTimeoutMs, TimeUnit.MILLISECONDS)
}
}
private fun logLastEvent() {
lastEvent?.let {
val event = it.validatedEvent.event
if (event.isEventGroup()) {
event.data["last"] = lastEventTime
}
event.data["created"] = lastEventCreatedTime
var systemEventId = systemEventIdProvider.getSystemEventId(recorderId)
event.data["system_event_id"] = systemEventId
systemEventIdProvider.setSystemEventId(recorderId, ++systemEventId)
if (headless) {
event.data["system_headless"] = true
}
writer.log(it.validatedEvent)
ApplicationManager.getApplication().getService(EventLogListenersManager::class.java)
.notifySubscribers(recorderId, it.validatedEvent, it.rawEventId, it.rawData)
}
lastEvent = null
}
override fun getActiveLogFile(): EventLogFile? {
return writer.getActiveFile()
}
override fun getLogFilesProvider(): EventLogFilesProvider {
return writer.getLogFilesProvider()
}
override fun cleanup() {
writer.cleanup()
}
override fun rollOver() {
writer.rollOver()
}
override fun dispose() {
flush()
logExecutor.shutdown()
Disposer.dispose(writer)
}
fun flush(): CompletableFuture<Void> {
return CompletableFuture.runAsync({ logLastEvent() }, logExecutor)
}
private data class FusEvent(val validatedEvent: LogEvent,
val rawEventId: String?,
val rawData: Map<String, Any>?)
}
|
apache-2.0
|
cb21ca997a02c69c36e44a5b89d0261c
| 40.671533 | 158 | 0.701997 | 5.212785 | false | false | false | false |
imageprocessor/cv4j
|
app/src/main/java/com/cv4j/app/activity/LineDetectionActivity.kt
|
1
|
2215
|
package com.cv4j.app.activity
import android.content.res.Resources
import android.graphics.*
import android.os.Bundle
import com.cv4j.app.R
import com.cv4j.app.app.BaseActivity
import com.cv4j.core.binary.HoughLinesP
import com.cv4j.core.binary.Threshold
import com.cv4j.core.datamodel.ByteProcessor
import com.cv4j.core.datamodel.CV4JImage
import com.cv4j.core.datamodel.Line
import kotlinx.android.synthetic.main.activity_line_detection.*
import java.util.*
/**
*
* @FileName:
* com.cv4j.app.activity.LineDetectionActivity
* @author: Tony Shen
* @date: 2020-05-05 16:32
* @version: V1.0 <描述当前版本功能>
*/
class LineDetectionActivity : BaseActivity() {
var title: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_line_detection)
intent.extras?.let {
title = it.getString("Title","")
}?:{
title = ""
}()
toolbar.setOnClickListener {
finish()
}
initData()
}
private fun initData() {
toolbar.title = "< $title"
val res: Resources = resources
val bitmap = BitmapFactory.decodeResource(res, R.drawable.test_lines)
image0.setImageBitmap(bitmap)
val cv4JImage = CV4JImage(bitmap)
val threshold = Threshold()
threshold.process(cv4JImage.convert2Gray().processor as ByteProcessor, Threshold.THRESH_OTSU, Threshold.METHOD_THRESH_BINARY, 255)
image1.setImageBitmap(cv4JImage.processor.image.toBitmap())
val houghLinesP = HoughLinesP()
val lines: List<Line> = ArrayList<Line>()
houghLinesP.process(cv4JImage.processor as ByteProcessor, 12, 10, 50, lines)
val bm2 = Bitmap.createBitmap(cv4JImage.processor.image.toBitmap())
val canvas = Canvas(bm2)
val paint = Paint()
paint.style = Paint.Style.FILL_AND_STROKE
paint.strokeWidth = 4f
paint.color = Color.RED
for (line in lines) {
canvas.drawLine(line.x1.toFloat(), line.y1.toFloat(), line.x2.toFloat(), line.y2.toFloat(), paint)
}
image2.setImageBitmap(bm2)
}
}
|
apache-2.0
|
9dbd22ad2068ae47d94fafa80789fbd0
| 30.884058 | 138 | 0.664848 | 3.733447 | false | false | false | false |
arnab/adventofcode
|
src/main/kotlin/aoc2021/day3/Day3.kt
|
1
|
2101
|
package aoc2021.day3
object Day3 {
fun parse(data: String) = data.split("\n")
.map { readings -> readings.split("").filterNot { it.isBlank() } }
fun calculatePowerConsumption(readings: List<List<String>>): Int =
calculateGamma(readings) * calculateEpsilon(readings)
private fun calculateGamma(readings: List<List<String>>): Int {
val bits = readings.first().mapIndexed { i, _ ->
readings.map { it[i] }.groupingBy { it }.eachCount().maxBy { it.value }!!.key
}.joinToString("")
return Integer.parseInt(bits, 2)
}
private fun calculateEpsilon(readings: List<List<String>>): Int {
val bits = readings.first().mapIndexed { i, _ ->
readings.map { it[i] }.groupingBy { it }.eachCount().minBy { it.value }!!.key
}.joinToString("")
return Integer.parseInt(bits, 2)
}
fun calculateLifeSupport(readings: List<List<String>>) =
calculateO2Rating(readings, index = 0) * calculateCO2Rating(readings, index = 0)
private fun calculateO2Rating(readings: List<List<String>>, index: Int): Int {
if (readings.size == 1) {
return Integer.parseInt(readings.first().joinToString(""), 2)
}
val bitCounts = readings.map { it[index] }.groupingBy { it }.eachCount()
val filterBit = if (bitCounts["0"] == bitCounts["1"]) "1" else bitCounts.maxBy { it.value }!!.key
val remainingReadings = readings.filter { it[index] == filterBit }
return calculateO2Rating(remainingReadings, index + 1)
}
private fun calculateCO2Rating(readings: List<List<String>>, index: Int): Int {
if (readings.size == 1) {
return Integer.parseInt(readings.first().joinToString(""), 2)
}
val bitCounts = readings.map { it[index] }.groupingBy { it }.eachCount()
val filterBit = if (bitCounts["0"] == bitCounts["1"]) "0" else bitCounts.minBy { it.value }!!.key
val remainingReadings = readings.filter { it[index] == filterBit }
return calculateCO2Rating(remainingReadings, index + 1)
}
}
|
mit
|
1a9203dbc0672d968772b7591513cca5
| 39.403846 | 105 | 0.623037 | 4.03263 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/translations/lang/colors/LangColorSettingsPage.kt
|
1
|
1549
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.lang.colors
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.translations.lang.LangLexerAdapter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
class LangColorSettingsPage : ColorSettingsPage {
override fun getIcon() = PlatformAssets.MINECRAFT_ICON
override fun getHighlighter() = LangSyntaxHighlighter(LangLexerAdapter())
override fun getAdditionalHighlightingTagToDescriptorMap() = emptyMap<String, TextAttributesKey>()
override fun getAttributeDescriptors() = DESCRIPTORS
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName() = "Minecraft localization"
override fun getDemoText() =
"""
# This is a comment
path.to.key=This is a value
""".trimIndent()
companion object {
private val DESCRIPTORS = arrayOf(
AttributesDescriptor("Key", LangSyntaxHighlighter.KEY),
AttributesDescriptor("Separator", LangSyntaxHighlighter.EQUALS),
AttributesDescriptor("Value", LangSyntaxHighlighter.VALUE),
AttributesDescriptor("Comments", LangSyntaxHighlighter.COMMENT)
)
}
}
|
mit
|
11368a6a4fb8bb2076257205d6c31796
| 36.780488 | 102 | 0.748225 | 5.323024 | false | false | false | false |
nibarius/opera-park-android
|
app/src/prod/java/se/barsk/park/Injection.kt
|
1
|
734
|
package se.barsk.park
import android.content.Context
import se.barsk.park.datatypes.CarCollection
import se.barsk.park.datatypes.User
import se.barsk.park.network.NetworkManager
import se.barsk.park.storage.StorageManager
object Injection {
fun provideNetworkManager() = NetworkManager()
fun provideCarCollection() = CarCollection()
fun provideStorageManager(context: Context) = StorageManager(context)
fun provideSharedPreferencesFileName(context: Context): String = context.getString(R.string.shared_prefs_file_name)
fun provideSignInHandler(context: Context, listener: SignInHandler.StatusChangedListener) =
SignInHandler(context, listener)
fun provideUser(context: Context) = User(context)
}
|
mit
|
8cd50db81d6174227dabe1bade362997
| 42.176471 | 119 | 0.791553 | 4.343195 | false | false | false | false |
RuneSuite/client
|
patch-maven-plugin/src/main/java/org/runestar/client/patch/Injector.kt
|
1
|
5556
|
package org.runestar.client.patch
import com.google.common.io.Files
import net.bytebuddy.ByteBuddy
import net.bytebuddy.asm.Advice
import net.bytebuddy.description.method.ParameterList
import net.bytebuddy.description.type.TypeDescription
import net.bytebuddy.dynamic.ClassFileLocator
import net.bytebuddy.dynamic.scaffold.TypeValidation
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer
import net.bytebuddy.implementation.MethodCall
import net.bytebuddy.implementation.bytecode.assign.Assigner
import net.bytebuddy.jar.asm.Type
import net.bytebuddy.pool.TypePool
import org.runestar.client.raw.access.XClient
import org.runestar.client.updater.readHooks
import org.zeroturnaround.zip.ZipUtil
import java.lang.reflect.Modifier
import java.nio.file.Path
private val ACCESS_PKG = XClient::class.java.`package`.name
fun inject(sourceJar: Path, destinationJar: Path) {
val tempDir = Files.createTempDir().toPath()
val classFileLocator = ClassFileLocator.Compound(
ClassFileLocator.ForClassLoader.ofSystemLoader(),
ClassFileLocator.ForJarFile.of(sourceJar.toFile())
)
val typePool = TypePool.Default.of(classFileLocator)
ZipUtil.unpack(sourceJar.toFile(), tempDir.toFile())
val hooks = readHooks()
val classNameMap = hooks.associate { it.name to it.`class` }
val byteBuddy = ByteBuddy().with(TypeValidation.DISABLED)
val methodNameTransformer = MethodNameTransformer.Suffixing("0")
hookClassNames(hooks).forEach { cn ->
val typeDescription = typePool.describe(cn).resolve()
var typeBuilder = byteBuddy.rebase<Any>(typeDescription, classFileLocator, methodNameTransformer)
hooks.forEach { ch ->
val accessorInterface = Class.forName("$ACCESS_PKG.X${ch.`class`}")
if (cn == ch.name) {
typeBuilder = typeBuilder.implement(accessorInterface)
ch.fields.forEach { f ->
val fieldDescription = typePool.describe(f.owner).resolve().declaredFields.filter(f.matcher()).only
val fieldAccess = EncodedFieldAccess.of(fieldDescription, f.decoderNarrowed)
typeBuilder = typeBuilder.method(f.getterMatcher()).intercept(fieldAccess.getter)
if (!Modifier.isFinal(f.access)) {
typeBuilder = typeBuilder.method(f.setterMatcher()).intercept(fieldAccess.setter)
}
}
ch.methods.forEach { m ->
if (m.parameters != null && !Modifier.isAbstract(m.access)) {
val invokedMethodDescription = typePool.describe(m.owner).resolve().declaredMethods.filter(m.matcher()).only
typeBuilder = typeBuilder.method(m.proxyMatcher()).intercept(
MethodCall.invoke(invokedMethodDescription).withAllArgumentsThenDefaultValues().withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC)
)
}
}
if (cn == "client") {
hooks.filter { !Modifier.isAbstract(it.access) }.forEach { hc ->
hc.constructors.forEach { hcon ->
val conOwner = typePool.describe(hc.name).resolve()
val con = conOwner.declaredMethods.first { it.isConstructor && it.descriptor == hcon.descriptor }
typeBuilder = typeBuilder.method { it.name == hc.constructorName && descMatches(hcon.descriptor, it.parameters, classNameMap) }
.intercept(MethodCall.construct(con).withAllArguments().withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
}
}
}
}
ch.methods.forEach { m ->
if (m.parameters != null && m.owner == cn && !Modifier.isAbstract(m.access)) {
val execField = accessorInterface.getDeclaredField(m.method)
typeBuilder = typeBuilder.method(m.matcher())
.intercept(
Advice.withCustomMapping()
.bind(MethodAdvice.Execution::class.java, execField, Assigner.Typing.DYNAMIC)
.to(MethodAdvice::class.java)
)
}
}
}
typeBuilder.make().saveIn(tempDir.toFile())
}
ZipUtil.pack(tempDir.toFile(), destinationJar.toFile())
}
// todo
private fun descMatches(desc: String, params: ParameterList<*>, classNameMap: Map<String, String>): Boolean {
val args = Type.getArgumentTypes(desc)
if (args.size != params.size) return false
for (i in 0 until args.size) {
val at = args[i]
val bt = Type.getType((params[i].type.asErasure() as TypeDescription.AbstractBase).descriptor)
if (!typesEq(at, bt, classNameMap)) return false
}
return true
}
private fun typesEq(hookType: Type, accesorType: Type, classNameMap: Map<String, String>): Boolean {
if (hookType.sort != accesorType.sort) return false
var an = hookType.className
var bn = accesorType.className
if (hookType.sort == Type.ARRAY) {
if (hookType.dimensions != accesorType.dimensions) return false
an = hookType.elementType.className
bn = accesorType.elementType.className
}
if (an in classNameMap) {
an = ACCESS_PKG + ".X" + classNameMap[an]
}
return an == bn
}
|
mit
|
4582300670bb0906ba86586029a4b236
| 49.063063 | 167 | 0.62743 | 4.550369 | false | false | false | false |
androidessence/RichTextView
|
lib/src/main/java/com/androidessence/lib/RichTextView.kt
|
1
|
13550
|
package com.androidessence.lib
import android.animation.IntEvaluator
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Typeface
import android.os.Build
import androidx.appcompat.widget.AppCompatTextView
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.*
import android.util.AttributeSet
import android.util.Property
import android.widget.TextView
import java.util.*
/**
* Rich TextView Component that is an enhanced version of a TextView with certain styling.
*
*
* Created by adammcneilly on 4/1/16.
*/
class RichTextView @JvmOverloads constructor(private val mContext: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(mContext, attrs) {
/**
* The spannable string to display in this TextView.
*/
private var mSpannableString: SpannableString? = null
/**
* The number of spans applied to this SpannableString.
*/
var spanCount: Int = 0
private set
init {
this.spanCount = 0
initStyle(attrs, defStyleAttr)
}
private fun initStyle(attrs: AttributeSet?, defStyleAttr: Int) {
val typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.RichTextView, defStyleAttr, 0)
//TODO: Implement special attributes.
typedArray?.recycle()
}
override fun setText(text: CharSequence, type: TextView.BufferType) {
// Set our spannable string.
mSpannableString = SpannableString(text)
super.setText(mSpannableString, type)
}
/**
* Add a bullet at the start fo each line. You can specify start and endline
*
* @param start The index at which the text starts to fade.
* @param end The index at which the text fade ends.
* @param duration The duration for the text fade.
*/
fun formatFadeInSpan(start: Int, end: Int, duration: Int) {
spanCount++
val span = FadeInSpan()
mSpannableString!!.setSpan(span, start, end, 0)
val objectAnimator = ObjectAnimator.ofInt(
span, FADE_INT_PROPERTY, 0, 255)
objectAnimator.setEvaluator(IntEvaluator())
objectAnimator.addUpdateListener { text = mSpannableString }
objectAnimator.duration = duration.toLong()
objectAnimator.start()
}
/**
* Add a bullet at the start fo each line. You can specify start and endline
*
* @param startline The start line at which bullet is shown.
* @param endline The end line at which bullet is shown.
* @param gapWidth The gap width in pixel (px).
* @param endline The color of the bullet.
*/
fun formatBulletSpan(startline: Int, endline: Int, gapWidth: Int, color: Int) {
spanCount++
val splitter = mSpannableString!!.toString().split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var start = 0
splitter.indices
.asSequence()
.filter {
splitter[it] != "" && splitter[it] != "\n"
}
.forEach {
start += if (it >= startline - 1 && it < endline) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
mSpannableString?.setSpan(BulletSpan(gapWidth, color, 20), start, start + 1, 0)
} else {
mSpannableString?.setSpan(CustomBulletSpan(gapWidth, false, color, 20), start, start + 1, 0)
}
splitter[it].length + 1
} else {
splitter[it].length + 1
}
}
text = mSpannableString
}
/**
* Add a bullet at the start fo each line. You can specify start and endline
*
* @param startline The start line at which number is shown.
* @param endline The end line at which number is shown.
*/
fun formatNumberSpan(startline: Int, endline: Int) {
spanCount++
val splitter = mSpannableString!!.toString().split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var start = 0
var index = 1
splitter.indices
.asSequence()
.filter {
splitter[it] != "" && splitter[it] != "\n"
}
.forEach {
if (it >= startline - 1 && it < endline) {
mSpannableString!!.setSpan(NumberSpan(index++, 100, false, textSize), start, start + 1, 0)
start += splitter[it].length + 1
} else {
start += splitter[it].length + 1
}
}
text = mSpannableString
}
/**
* Add a Image at the specified index
*
* @param start The start index where image is shown.
* @param end The end index where image is shown.
*/
fun formatImageSpan(start: Int, end: Int, drawable: Bitmap) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid start index.")
} else if (end < start || end > (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid end index.")
}
// Add span
spanCount++
mSpannableString?.setSpan(ImageSpan(context, drawable), start, end, 0)
// Set text
text = mSpannableString
}
/**
* Formats a Span of text in the text view. This method was added as a convenience method
* so the user doesn't have to use EnumSet for one item.
*
* @param start The index of the first character to span.
* @param end The index of the last character to span.
* @param formatType The format to apply to this span.
*/
fun formatSpan(start: Int, end: Int, formatType: FormatType) {
// Call the other method as if this were an EnumSet.
formatSpan(start, end, EnumSet.of(formatType))
}
/**
* Formats a Span of text in the text view.
*
* @param start The index of the first character to span.
* @param end The index of the last character to span.
* @param formatTypes The formats to apply to this span.
*/
fun formatSpan(start: Int, end: Int, formatTypes: EnumSet<FormatType>) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid start index.")
} else if (end < start || end > (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid end index.")
}
// There is no need to consider a null FormatType. Since we have two method headers of (int, int, type)
// The compiler will claim that `formatSpan(int, int, null);` call is ambiguous.
spanCount += formatTypes.size
// Create span to be applied - Default to normal.
formatTypes.forEach { mSpannableString?.setSpan(it.span, start, end, 0) }
text = mSpannableString
}
/**
* Formats a text that is scaled.
*
* @param proportion proportion to which the text scales.
* Values > 1.0 will stretch the text wider. Values < 1.0 will stretch the text narrower.
* @param start The index of the first character to span.
* @param end The index of the last character to span.
*/
fun formatScaleXSpan(proportion: Float, start: Int, end: Int) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid start index.")
} else if (end < start || end > (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid end index.")
}
// Add span
spanCount++
mSpannableString!!.setSpan(ScaleXSpan(proportion), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
text = mSpannableString
}
/**
* Colors a portion of the string.
*
* @param start The index of the first character to color.
* @param end The index of the last character to color..
* @param formatType The type of format to apply to this span.
* @param color The color to apply to this substring.
*/
fun colorSpan(start: Int, end: Int, formatType: ColorFormatType?, color: Int) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid start index.")
} else if (end < start || end > (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid end index.")
} else if (formatType == null) {
throw IllegalArgumentException("Invalid FormatType.")
}
// Add span
spanCount++
mSpannableString!!.setSpan(formatType.getSpan(color), start, end, 0)
// Set text
text = mSpannableString
}
/**
* Adds a hyperlink to a portion of the string.
*
* @param start The index of the first character of the link.
* @param end The index of the last character of the link.
* @param url The URL that the hyperlink points to.
*/
fun addHyperlinkToSpan(start: Int, end: Int, url: String) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid start index.")
} else if (end < start || end > (mSpannableString?.length ?: 0)) {
throw IllegalArgumentException("Invalid end index.")
}
// Add span
spanCount++
this.movementMethod = LinkMovementMethod.getInstance()
val urlSpan = URLSpan(url)
mSpannableString!!.setSpan(urlSpan, start, end, 0)
// Set text
text = mSpannableString
}
/**
* Clears all spans applied to our SpannableString.
*/
fun clearSpans() {
// Get spans
val spans = mSpannableString?.getSpans(0, spanCount, Any::class.java)
// Loop through and remove each one.
spans?.forEach {
mSpannableString?.removeSpan(it)
spanCount--
}
// Set text again.
text = mSpannableString
}
/**
* Retrieves all spans applied to the string.
*
* @return An array of object representing the types of spans applied.
*/
val spans: Array<out Any>?
get() = mSpannableString?.getSpans(0, spanCount, Any::class.java)
//-- Inner classes --//
/**
* An enumeration of various ways to format the text.
*/
enum class FormatType {
NONE {
override val span: Any
get() = StyleSpan(Typeface.NORMAL)
},
BOLD {
override val span: Any
get() = StyleSpan(Typeface.BOLD)
},
ITALIC {
override val span: Any
get() = StyleSpan(Typeface.ITALIC)
},
UNDERLINE {
override val span: Any
get() = UnderlineSpan()
},
STRIKETHROUGH {
override val span: Any
get() = StrikethroughSpan()
},
SUPERSCRIPT {
override val span: Any
get() = SuperscriptSpan()
},
SUBSCRIPT {
override val span: Any
get() = SubscriptSpan()
};
abstract val span: Any
}
/**
* An enumeration of various ways to color the text.
*/
enum class ColorFormatType {
FOREGROUND {
override fun getSpan(color: Int): Any {
return ForegroundColorSpan(color)
}
},
HIGHLIGHT {
override fun getSpan(color: Int): Any {
return BackgroundColorSpan(color)
}
};
abstract fun getSpan(color: Int): Any
}
companion object {
/* Fade In */
private val FADE_INT_PROPERTY = object : Property<FadeInSpan, Int>(Int::class.java, "FADE_INT_PROPERTY") {
override fun set(span: FadeInSpan, value: Int?) {
span.alpha = value ?: 0
}
override fun get(`object`: FadeInSpan): Int {
return `object`.alpha
}
}
}
}
|
mit
|
e7da833525bb16318c0a10c37e59f31f
| 33.478372 | 166 | 0.58524 | 4.68696 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt
|
1
|
2936
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReturnSaver(val function: KtNamedFunction) {
companion object {
private val RETURN_KEY = Key<Unit>("RETURN_KEY")
}
val isEmpty: Boolean
init {
var hasReturn = false
val body = function.bodyExpression!!
body.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunction(it.analyze(BodyResolveMode.PARTIAL)) == function) {
hasReturn = true
it.putCopyableUserData(RETURN_KEY, Unit)
}
}
isEmpty = !hasReturn
}
private fun clear() {
val body = function.bodyExpression!!
body.forEachDescendantOfType<KtReturnExpression> { it.putCopyableUserData(RETURN_KEY, null) }
}
fun restore(lambda: KtLambdaExpression, label: Name) {
clear()
val psiFactory = KtPsiFactory(lambda.project)
val lambdaBody = lambda.bodyExpression!!
val returnToReplace = lambda.collectDescendantsOfType<KtReturnExpression>() { it.getCopyableUserData(RETURN_KEY) != null }
for (returnExpression in returnToReplace) {
val value = returnExpression.returnedExpression
val replaceWith = if (value != null && returnExpression.isValueOfBlock(lambdaBody)) {
value
} else if (value != null) {
psiFactory.createExpressionByPattern("return@$0 $1", label, value)
} else {
psiFactory.createExpressionByPattern("return@$0", label)
}
returnExpression.replace(replaceWith)
}
}
private fun KtExpression.isValueOfBlock(inBlock: KtBlockExpression): Boolean = when (val parent = parent) {
inBlock -> {
this == inBlock.statements.last()
}
is KtBlockExpression -> {
isValueOfBlock(parent) && parent.isValueOfBlock(inBlock)
}
is KtContainerNode -> {
val owner = parent.parent
if (owner is KtIfExpression) {
(this == owner.then || this == owner.`else`) && owner.isValueOfBlock(inBlock)
} else
false
}
is KtWhenEntry -> {
this == parent.expression && (parent.parent as KtWhenExpression).isValueOfBlock(inBlock)
}
else -> false
}
}
|
apache-2.0
|
ea37d8016d1c140e78f1349c0b56d3e0
| 33.552941 | 158 | 0.646798 | 4.993197 | false | false | false | false |
square/okhttp
|
okhttp-testing-support/src/main/kotlin/okhttp3/RetryFlakesTestRule.kt
|
2
|
8646
|
/*
* 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 android.annotation.SuppressLint
import java.util.concurrent.TimeUnit
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogManager
import java.util.logging.LogRecord
import java.util.logging.Logger
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.http2.Http2
import okhttp3.testing.Flaky
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
/**
* Apply this rule to all tests. It adds additional checks for leaked resources and uncaught
* exceptions.
*
* Use [newClient] as a factory for a OkHttpClient instances. These instances are specifically
* configured for testing.
*/
class RetryFlakesTestRule : BeforeEachCallback, AfterEachCallback {
private val clientEventsList = mutableListOf<String>()
private var testClient: OkHttpClient? = null
private var uncaughtException: Throwable? = null
private lateinit var testName: String
private var defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null
private var taskQueuesWereIdle: Boolean = false
var logger: Logger? = null
var recordEvents = true
var recordTaskRunner = false
var recordFrames = false
var recordSslDebug = false
private val sslExcludeFilter = "^(?:Inaccessible trust store|trustStore is|Reload the trust store|Reload trust certs|Reloaded|adding as trusted certificates|Ignore disabled cipher suite|Ignore unsupported cipher suite).*".toRegex()
private val testLogHandler = object : Handler() {
override fun publish(record: LogRecord) {
val recorded = when (record.loggerName) {
TaskRunner::class.java.name -> recordTaskRunner
Http2::class.java.name -> recordFrames
"javax.net.ssl" -> recordSslDebug && !sslExcludeFilter.matches(record.message)
else -> false
}
if (recorded) {
synchronized(clientEventsList) {
clientEventsList.add(record.message)
if (record.loggerName == "javax.net.ssl") {
val parameters = record.parameters
if (parameters != null) {
clientEventsList.add(parameters.first().toString())
}
}
}
}
}
override fun flush() {
}
override fun close() {
}
}.apply {
level = Level.FINEST
}
private fun applyLogger(fn: Logger.() -> Unit) {
Logger.getLogger(OkHttpClient::class.java.`package`.name).fn()
Logger.getLogger(OkHttpClient::class.java.name).fn()
Logger.getLogger(Http2::class.java.name).fn()
Logger.getLogger(TaskRunner::class.java.name).fn()
Logger.getLogger("javax.net.ssl").fn()
}
fun wrap(eventListener: EventListener) =
EventListener.Factory { ClientRuleEventListener(eventListener, ::addEvent) }
fun wrap(eventListenerFactory: EventListener.Factory) =
EventListener.Factory { call -> ClientRuleEventListener(eventListenerFactory.create(call), ::addEvent) }
/**
* Returns an OkHttpClient for tests to use as a starting point.
*
* The returned client installs a default event listener that gathers debug information. This will
* be logged if the test fails.
*
* This client is also configured to be slightly more deterministic, returning a single IP
* address for all hosts, regardless of the actual number of IP addresses reported by DNS.
*/
fun newClient(): OkHttpClient {
var client = testClient
if (client == null) {
client = OkHttpClient.Builder()
.fastFallback(true) // Test this by default, since it'll soon be the default.
.dns(SINGLE_INET_ADDRESS_DNS) // Prevent unexpected fallback addresses.
.eventListenerFactory { ClientRuleEventListener(logger = ::addEvent) }
.build()
testClient = client
}
return client
}
fun newClientBuilder(): OkHttpClient.Builder {
return newClient().newBuilder()
}
@Synchronized private fun addEvent(event: String) {
if (recordEvents) {
logger?.info(event)
synchronized(clientEventsList) {
clientEventsList.add(event)
}
}
}
@Synchronized private fun initUncaughtException(throwable: Throwable) {
if (uncaughtException == null) {
uncaughtException = throwable
}
}
fun ensureAllConnectionsReleased() {
testClient?.let {
val connectionPool = it.connectionPool
connectionPool.evictAll()
if (connectionPool.connectionCount() > 0) {
// Minimise test flakiness due to possible race conditions with connections closing.
// Some number of tests will report here, but not fail due to this delay.
println("Delaying to avoid flakes")
Thread.sleep(500L)
println("After delay: " + connectionPool.connectionCount())
}
assertEquals(0, connectionPool.connectionCount())
}
}
private fun ensureAllTaskQueuesIdle() {
val entryTime = System.nanoTime()
for (queue in TaskRunner.INSTANCE.activeQueues()) {
// We wait at most 1 second, so we don't ever turn multiple lost threads into
// a test timeout failure.
val waitTime = (entryTime + 1_000_000_000L - System.nanoTime())
if (!queue.idleLatch().await(waitTime, TimeUnit.NANOSECONDS)) {
TaskRunner.INSTANCE.cancelAll()
fail<Unit>("Queue still active after 1000 ms")
}
}
}
override fun beforeEach(context: ExtensionContext) {
testName = context.displayName
beforeEach()
}
private fun beforeEach() {
defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
initUncaughtException(throwable)
}
taskQueuesWereIdle = TaskRunner.INSTANCE.activeQueues().isEmpty()
applyLogger {
addHandler(testLogHandler)
level = Level.FINEST
useParentHandlers = false
}
}
@SuppressLint("NewApi")
override fun afterEach(context: ExtensionContext) {
val failure = context.executionException.orElseGet { null }
if (uncaughtException != null) {
throw failure + AssertionError("uncaught exception thrown during test", uncaughtException)
}
if (context.isFlaky()) {
logEvents()
}
LogManager.getLogManager().reset()
var result: Throwable? = failure
Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler)
try {
ensureAllConnectionsReleased()
releaseClient()
} catch (ae: AssertionError) {
result += ae
}
try {
if (taskQueuesWereIdle) {
ensureAllTaskQueuesIdle()
}
} catch (ae: AssertionError) {
result += ae
}
if (result != null) throw result
}
private fun releaseClient() {
testClient?.dispatcher?.executorService?.shutdown()
}
@SuppressLint("NewApi")
private fun ExtensionContext.isFlaky(): Boolean {
return (testMethod.orElseGet { null }?.isAnnotationPresent(Flaky::class.java) == true) ||
(testClass.orElseGet { null }?.isAnnotationPresent(Flaky::class.java) == true)
}
@Synchronized private fun logEvents() {
// Will be ineffective if test overrides the listener
synchronized(clientEventsList) {
println("$testName Events (${clientEventsList.size})")
for (e in clientEventsList) {
println(e)
}
}
}
companion object {
/**
* A network that resolves only one IP address per host. Use this when testing route selection
* fallbacks to prevent the host machine's various IP addresses from interfering.
*/
private val SINGLE_INET_ADDRESS_DNS = Dns { hostname ->
val addresses = Dns.SYSTEM.lookup(hostname)
listOf(addresses[0])
}
private operator fun Throwable?.plus(throwable: Throwable): Throwable {
if (this != null) {
addSuppressed(throwable)
return this
}
return throwable
}
}
}
|
apache-2.0
|
5f6f27707281b0019b5202607e03c52f
| 30.786765 | 233 | 0.695697 | 4.550526 | false | true | false | false |
leafclick/intellij-community
|
platform/diagnostic/src/startUpPerformanceReporter/IdeaFormatWriter.kt
|
1
|
8874
|
// 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.diagnostic.startUpPerformanceReporter
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonGenerator
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.ActivityImpl
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.icons.IconLoadMeasurer
import com.intellij.util.containers.ObjectIntHashMap
import com.intellij.util.containers.ObjectLongHashMap
import com.intellij.util.io.jackson.array
import com.intellij.util.io.jackson.obj
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import java.io.CharArrayWriter
import java.lang.management.ManagementFactory
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit
private class ExposingCharArrayWriter : CharArrayWriter(8192) {
fun toByteBuffer(offset: Int): ByteBuffer {
return Charsets.UTF_8.encode(CharBuffer.wrap(buf, offset, count - offset))
}
}
internal class IdeaFormatWriter(private val activities: Map<String, MutableList<ActivityImpl>>,
private val pluginCostMap: MutableMap<String, ObjectLongHashMap<String>>,
private val threadNameManager: ThreadNameManager) {
private val logPrefix = "=== Start: StartUp Measurement ===\n"
private val stringWriter = ExposingCharArrayWriter()
val publicStatMetrics = ObjectIntHashMap<String>()
fun write(timeOffset: Long, items: List<ActivityImpl>, services: List<ActivityImpl>, instantEvents: List<ActivityImpl>, end: Long, projectName: String) {
stringWriter.write(logPrefix)
val writer = JsonFactory().createGenerator(stringWriter)
writer.prettyPrinter = MyJsonPrettyPrinter()
writer.use {
writer.obj {
writer.writeStringField("version", StartUpPerformanceReporter.VERSION)
val appInfo = ApplicationInfo.getInstance()
writer.writeStringField("build", appInfo.build.asStringWithoutProductCode())
writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME))
writer.writeStringField("productCode", appInfo.build.productCode)
writer.writeStringField("generated", ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
writer.writeStringField("os", SystemInfo.getOsNameAndVersion())
writer.writeStringField("runtime", SystemInfo.JAVA_VENDOR + " " + SystemInfo.JAVA_VERSION + " " + SystemInfo.JAVA_RUNTIME_VERSION)
writer.writeStringField("cds", ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }.toString()) //see CDSManager from platform-impl)
writer.writeStringField("project", safeHashValue(projectName))
writeServiceStats(writer)
writeIcons(writer)
writer.array("traceEvents") {
val traceEventFormatWriter = TraceEventFormatWriter(timeOffset, instantEvents, threadNameManager)
traceEventFormatWriter.writeInstantEvents(writer)
traceEventFormatWriter.writeServiceEvents(writer, services, pluginCostMap)
}
var totalDuration = 0L
writer.array("items") {
for ((index, item) in items.withIndex()) {
writer.obj {
writer.writeStringField("name", item.name)
if (item.description != null) {
writer.writeStringField("description", item.description)
}
val duration = item.end - item.start
if (!isSubItem(item, index, items)) {
totalDuration += duration
}
if (item.name == "bootstrap" || item.name == "app initialization") {
publicStatMetrics.put(item.name, TimeUnit.NANOSECONDS.toMillis(duration).toInt())
}
writeItemTimeInfo(item, duration, timeOffset, writer)
}
}
}
totalDuration += end - items.last().end
writeParallelActivities(timeOffset, writer)
writer.writeNumberField("totalDurationComputed", TimeUnit.NANOSECONDS.toMillis(totalDuration))
val totalDurationActual = TimeUnit.NANOSECONDS.toMillis(end - timeOffset)
writer.writeNumberField("totalDurationActual", totalDurationActual)
publicStatMetrics.put("totalDuration", totalDurationActual.toInt())
}
}
}
fun toByteBuffer(): ByteBuffer {
return stringWriter.toByteBuffer(logPrefix.length)
}
fun writeToLog(log: Logger) {
stringWriter.write("\n=== Stop: StartUp Measurement ===")
log.info(stringWriter.toString())
}
private fun writeParallelActivities(startTime: Long, writer: JsonGenerator) {
// sorted to get predictable JSON
for (name in activities.keys.sorted()) {
val list = activities.getValue(name)
StartUpPerformanceReporter.sortItems(list)
val measureThreshold = if (name == ActivityCategory.APP_INIT.jsonName || name == ActivityCategory.REOPENING_EDITOR.jsonName) -1 else StartUpMeasurer.MEASURE_THRESHOLD
writeActivities(list, startTime, writer, activityNameToJsonFieldName(name), ObjectLongHashMap(), measureThreshold = measureThreshold)
}
}
private fun writeActivities(activities: List<ActivityImpl>,
offset: Long, writer: JsonGenerator,
fieldName: String,
ownDurations: ObjectLongHashMap<ActivityImpl>,
measureThreshold: Long = StartUpMeasurer.MEASURE_THRESHOLD) {
if (activities.isEmpty()) {
return
}
writer.array(fieldName) {
var skippedDuration = 0L
for (item in activities) {
val computedOwnDuration = ownDurations.get(item)
val duration = if (computedOwnDuration == -1L) item.end - item.start else computedOwnDuration
item.pluginId?.let {
StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", duration, pluginCostMap)
}
if (fieldName == "prepareAppInitActivities" && item.name == "splash initialization") {
publicStatMetrics.put("splash", TimeUnit.NANOSECONDS.toMillis(duration).toInt())
}
if (duration <= measureThreshold) {
skippedDuration += duration
continue
}
writer.obj {
writer.writeStringField("name", item.name)
writeItemTimeInfo(item, duration, offset, writer)
}
}
if (skippedDuration > 0) {
writer.obj {
writer.writeStringField("name", "Other")
writer.writeNumberField("duration", TimeUnit.NANOSECONDS.toMillis(skippedDuration))
writer.writeNumberField("start", TimeUnit.NANOSECONDS.toMillis(activities.last().start - offset))
writer.writeNumberField("end", TimeUnit.NANOSECONDS.toMillis(activities.last().end - offset))
}
}
}
}
private fun writeItemTimeInfo(item: ActivityImpl, duration: Long, offset: Long, writer: JsonGenerator) {
writer.writeNumberField("duration", TimeUnit.NANOSECONDS.toMillis(duration))
writer.writeNumberField("start", TimeUnit.NANOSECONDS.toMillis(item.start - offset))
writer.writeNumberField("end", TimeUnit.NANOSECONDS.toMillis(item.end - offset))
writer.writeStringField("thread", threadNameManager.getThreadName(item))
if (item.pluginId != null) {
writer.writeStringField("plugin", item.pluginId)
}
}
}
private fun activityNameToJsonFieldName(name: String): String {
return when (name.last()) {
'y' -> name.substring(0, name.length - 1) + "ies"
's' -> name
else -> name.substring(0) + 's'
}
}
private fun writeIcons(writer: JsonGenerator) {
writer.array("icons") {
for (stat in IconLoadMeasurer.getStats()) {
writer.obj {
writer.writeStringField("name", stat.type)
writer.writeNumberField("count", stat.counter)
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalTime))
}
}
}
}
private fun safeHashValue(value: String): String {
val generator = Argon2BytesGenerator()
generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build())
// 160 bit is enough for uniqueness
val result = ByteArray(20)
generator.generateBytes(value.toByteArray(), result, 0, result.size)
return Base64.getEncoder().withoutPadding().encodeToString(result)
}
|
apache-2.0
|
96b3048cd856b7e49af3884b27192eb7
| 41.061611 | 190 | 0.700361 | 4.7328 | false | true | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/casts/as.kt
|
2
|
258
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
fun foo(x: Any) = x as Runnable
fun box(): String {
val r = object : Runnable {
override fun run() {}
}
return if (foo(r) === r) "OK" else "Fail"
}
|
apache-2.0
|
5a4baa17703887a9c8e92da9a65c9c6a
| 22.454545 | 72 | 0.639535 | 3.035294 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/builtinStubMethods/customReadOnlyIterator.kt
|
5
|
1018
|
class A : Collection<Char> {
override val size: Int
get() = throw UnsupportedOperationException()
override fun contains(element: Char): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun containsAll(elements: Collection<Char>): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEmpty(): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun iterator() = MyIterator
}
object MyIterator : Iterator<Char> {
override fun hasNext() = true
override fun next() = 'a'
}
fun box(): String {
val it: MyIterator = A().iterator()
if (!it.hasNext()) return "fail 1"
if (it.next() != 'a') return "fail 2"
return "OK"
}
|
apache-2.0
|
294d2d9c9004ae7ea3bdebf78319b422
| 28.941176 | 138 | 0.674853 | 4.691244 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/dataClasses/multiDeclaration.kt
|
5
|
179
|
data class A(val x: Int, val y: Any?, val z: String)
fun box(): String {
val a = A(42, null, "OK")
val (x, y, z) = a
return if (x == 42 && y == null) z else "Fail"
}
|
apache-2.0
|
99b23f6c3b04a0a6580637888a292703
| 24.571429 | 52 | 0.50838 | 2.557143 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/reflection/callBy/companionObject.kt
|
2
|
818
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.test.assertEquals
class C {
companion object {
fun foo(a: String, b: String = "b") = a + b
}
}
fun box(): String {
val f = C.Companion::class.members.single { it.name == "foo" }
// Any object method currently requires the object instance passed
try {
f.callBy(mapOf(
f.parameters.single { it.name == "a" } to "a"
))
return "Fail: IllegalArgumentException should have been thrown"
}
catch (e: IllegalArgumentException) {
// OK
}
assertEquals("ab", f.callBy(mapOf(
f.parameters.first() to C,
f.parameters.single { it.name == "a" } to "a"
)))
return "OK"
}
|
apache-2.0
|
578809323e56925b0071e183b88d4321
| 23.058824 | 72 | 0.581907 | 3.769585 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/dataClasses/copy/constructorWithDefaultParam.kt
|
5
|
547
|
data class A(val a: Int = 1, val b: String = "$a") {}
fun box() : String {
var result = ""
val a = A()
val b = a.copy()
if (b.a == 1 && b.b == "1") {
result += "1"
}
val c = a.copy(a = 2)
if (c.a == 2 && c.b == "1") {
result += "2"
}
val d = a.copy(b = "2")
if (d.a == 1 && d.b == "2") {
result += "3"
}
val e = a.copy(a = 2, b = "2")
if (e.a == 2 && e.b == "2") {
result += "4"
}
if (result == "1234") {
return "OK"
}
return "fail"
}
|
apache-2.0
|
933c1ec525d3f07c8148a61564cf5c48
| 17.862069 | 53 | 0.345521 | 2.568075 | false | false | false | false |
smmribeiro/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/AbstractChangeListAction.kt
|
7
|
1652
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.ActionPlaces.isPopupPlace
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vcs.changes.ui.ChangesListView
abstract class AbstractChangeListAction : DumbAwareAction() {
protected fun updateEnabledAndVisible(e: AnActionEvent, enabled: Boolean, contextMenuVisible: Boolean = true) = with(e.presentation) {
isEnabled = enabled
isVisible = !isPopupPlace(e.place) || enabled && contextMenuVisible
}
protected fun getChangeLists(e: AnActionEvent): Sequence<LocalChangeList> {
val changeListManager = ChangeListManager.getInstance(e.project ?: return emptySequence())
val changeLists = e.getData(VcsDataKeys.CHANGE_LISTS)
if (!changeLists.isNullOrEmpty()) return changeLists.asSequence()
.filterIsInstance<LocalChangeList>()
.mapNotNull { changeListManager.findChangeList(it.name) }
if (e.getData(ChangesListView.DATA_KEY) != null) {
val changes = e.getData(VcsDataKeys.CHANGES)
return changes.orEmpty().asSequence().mapNotNull { changeListManager.getChangeList(it) }.distinct()
}
return emptySequence()
}
protected fun getTargetChangeList(e: AnActionEvent): LocalChangeList? = getChangeLists(e).singleOrNull()
}
|
apache-2.0
|
5c819bdac7ef513500f3d9c6b15d9602
| 46.228571 | 140 | 0.783293 | 4.693182 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTableItem.kt
|
2
|
4786
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.ide.CopyPasteManager
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.util.VersionNameComparator
import java.awt.datatransfer.StringSelection
internal sealed class PackagesTableItem<T : PackageModel> : DataProvider, CopyProvider {
val packageModel: T
get() = uiPackageModel.packageModel
abstract val uiPackageModel: UiPackageModel<T>
abstract val allScopes: List<PackageScope>
protected open val handledDataKeys: List<DataKey<*>> = listOf(PlatformDataKeys.COPY_PROVIDER)
fun canProvideDataFor(key: String) = handledDataKeys.any { it.`is`(key) }
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun performCopy(dataContext: DataContext) =
CopyPasteManager.getInstance().setContents(StringSelection(getTextForCopy(packageModel)))
private fun getTextForCopy(packageModel: PackageModel) = buildString {
appendLine("${packageModel.groupId}:${packageModel.artifactId}")
append(additionalCopyText())
packageModel.remoteInfo?.versions?.let { versions ->
if (versions.any()) {
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.availableVersions")} ")
append(
versions.map { it.version }
.distinct()
.sortedWith(VersionNameComparator)
.joinToString(", ")
.removeSuffix(", ")
)
}
}
packageModel.remoteInfo?.gitHub?.let { gitHub ->
appendLine()
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats"))
gitHub.stars?.let { ghStars ->
append(" ")
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.stars", ghStars))
}
gitHub.forks?.let { ghForks ->
if (gitHub.stars != null) append(',')
append(" ")
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.forks", ghForks))
}
}
packageModel.remoteInfo?.stackOverflow?.tags?.let { tags ->
if (tags.any()) {
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.stackOverflowTags")} ")
append(
tags.joinToString(", ") { "${it.tag} (${it.count})" }
.removeSuffix(", ")
)
}
}
}
protected abstract fun additionalCopyText(): String
override fun isCopyVisible(dataContext: DataContext) = true
override fun isCopyEnabled(dataContext: DataContext) = true
data class InstalledPackage(
override val uiPackageModel: UiPackageModel.Installed,
override val allScopes: List<PackageScope>
) : PackagesTableItem<PackageModel.Installed>() {
init {
require(allScopes.isNotEmpty()) { "An installed package must have at least one installed scope" }
}
override fun additionalCopyText() = buildString {
if (packageModel.usageInfo.isEmpty()) return@buildString
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.installedVersions")} ")
append(
packageModel.usageInfo.map { it.version }
.distinct()
.joinToString(", ")
.removeSuffix(", ")
)
}
}
data class InstallablePackage(
override val uiPackageModel: UiPackageModel.SearchResult,
override val allScopes: List<PackageScope>
) : PackagesTableItem<PackageModel.SearchResult>() {
init {
require(allScopes.isNotEmpty()) { "A package must have at least one available scope" }
}
override fun additionalCopyText() = ""
}
}
|
apache-2.0
|
3f2f259406072f147d7e7318a988a215
| 38.229508 | 116 | 0.645006 | 5.426304 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesDialog.kt
|
9
|
3114
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.ide.caches.CachesInvalidator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.Link
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.dsl.builder.DEFAULT_COMMENT_WIDTH
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import javax.swing.Action
import javax.swing.JPanel
private var Action.text
get() = getValue(Action.NAME)
set(value) = putValue(Action.NAME, value)
class InvalidateCachesDialog(
project: Project?,
private val canRestart: Boolean,
private val invalidators: List<CachesInvalidator>,
) : DialogWrapper(project) {
private val JUST_RESTART_CODE = NEXT_USER_EXIT_CODE + 3
private val invalidatorsOptions = mutableMapOf<JBCheckBox, CachesInvalidator>()
fun getSelectedInvalidators() : List<CachesInvalidator> {
if (!isOK) return emptyList()
val enabledInvalidators = invalidatorsOptions.filterKeys { it.isSelected }.values
return invalidators.filter {
it.description == null || it in enabledInvalidators
}
}
override fun getHelpId() = "invalidate-cache-restart"
init {
title = IdeBundle.message("dialog.title.invalidate.caches")
isResizable = false
init()
okAction.text = when {
canRestart -> IdeBundle.message("button.invalidate.and.restart")
else -> IdeBundle.message("button.invalidate.and.exit")
}
cancelAction.text = IdeBundle.message("button.cancel.without.mnemonic")
}
fun isRestartOnly() = canRestart && exitCode == JUST_RESTART_CODE
override fun createSouthAdditionalPanel(): JPanel? {
if (!canRestart) return null
val link = Link(IdeBundle.message("link.just.restart")) {
close(JUST_RESTART_CODE)
}
val panel = NonOpaquePanel(BorderLayout())
panel.border = JBUI.Borders.emptyLeft(10)
panel.add(link)
return panel
}
override fun createCenterPanel() = panel {
row {
text(IdeBundle.message("dialog.message.caches.will.be.invalidated"), maxLineLength = DEFAULT_COMMENT_WIDTH)
}
//we keep the original order as it comes from the extensions order
val invalidatorsWithDescriptor = invalidators.mapNotNull { it.description?.to(it) }
if (invalidatorsWithDescriptor.isNotEmpty()) {
buttonsGroup(IdeBundle.message("dialog.message.the.following.items")) {
for ((text, descr) in invalidatorsWithDescriptor) {
row {
val defaultValue = descr.optionalCheckboxDefaultValue()
val checkbox = checkBox(text)
.enabled(defaultValue != null)
.applyToComponent {
isSelected = defaultValue ?: true
}
.component
invalidatorsOptions[checkbox] = descr
}
}
}
}
}
}
|
apache-2.0
|
b7fea3749596e973538e9ddcb1ec7c17
| 31.778947 | 140 | 0.709377 | 4.355245 | false | false | false | false |
kpi-ua/ecampus-client-android
|
app/src/main/java/com/goldenpiedevs/schedule/app/ui/preference/ApplicationPreferenceFragment.kt
|
1
|
4553
|
package com.goldenpiedevs.schedule.app.ui.preference
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.goldenpiedevs.schedule.app.R
import com.goldenpiedevs.schedule.app.ScheduleApplication
import com.goldenpiedevs.schedule.app.core.api.lessons.LessonsManager
import com.goldenpiedevs.schedule.app.core.api.teachers.TeachersManager
import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoLessonModel
import com.goldenpiedevs.schedule.app.core.notifications.manger.NotificationManager
import com.goldenpiedevs.schedule.app.core.utils.preference.AppPreference
import com.goldenpiedevs.schedule.app.core.utils.preference.UserPreference
import com.goldenpiedevs.schedule.app.core.utils.util.isNetworkAvailable
import com.goldenpiedevs.schedule.app.core.utils.util.restartApp
import com.goldenpiedevs.schedule.app.ui.choose.group.ChooseGroupActivity
import com.goldenpiedevs.schedule.app.ui.widget.ScheduleWidgetProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.anko.indeterminateProgressDialog
import org.jetbrains.anko.toast
import javax.inject.Inject
class ApplicationPreferenceFragment : PreferenceFragmentCompat() {
@Inject
lateinit var notificationManager: NotificationManager
@Inject
lateinit var lessonsManager: LessonsManager
@Inject
lateinit var teachersManager: TeachersManager
companion object {
const val CHANGE_GROUP_CODE = 565
}
override fun onCreatePreferences(p0: Bundle?, p1: String?) {
(activity?.applicationContext as ScheduleApplication).appComponent.inject(this)
preferenceManager.sharedPreferencesName = getString(R.string.user_preference_file_name)
addPreferencesFromResource(R.xml.app_preference)
findPreference(getString(R.string.user_preference_notification_delay_key)).apply {
summary = "${UserPreference.notificationDelay} ${getString(R.string.min)}"
onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
UserPreference.notificationDelay = value.toString()
summary = "${UserPreference.notificationDelay} ${getString(R.string.min)}"
notificationManager.createNotification(DaoLessonModel.getLessonsForGroup(AppPreference.groupId))
true
}
}
findPreference(getString(R.string.change_group_key)).apply {
setOnPreferenceClickListener {
startActivityForResult(Intent(context, ChooseGroupActivity::class.java), CHANGE_GROUP_CODE)
true
}
}
findPreference(getString(R.string.user_preference_reverse_week_key)).apply {
onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
UserPreference.reverseWeek = value.toString().toBoolean()
ScheduleWidgetProvider.updateWidget(context)
Handler().postDelayed({
context.restartApp()
}, 200)
true
}
}
findPreference(getString(R.string.update_timetable_key)).apply {
setOnPreferenceClickListener {
if (!context.isNetworkAvailable()) {
context.toast(R.string.no_internet)
return@setOnPreferenceClickListener true
}
val dialog = activity?.indeterminateProgressDialog("Оновлення розкладу")
GlobalScope.launch {
lessonsManager.loadTimeTableAsync(AppPreference.groupId).await()
teachersManager.loadTeachersAsync(AppPreference.groupId).await()
launch(Dispatchers.Main) {
dialog?.dismiss()
ScheduleWidgetProvider.updateWidget(context)
}
}
true
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (resultCode == Activity.RESULT_OK) {
true -> {
when (requestCode) {
CHANGE_GROUP_CODE -> {
activity?.finish()
}
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}
|
apache-2.0
|
2b4ae6dbe8bc4fb9f369c541099b9a84
| 38.452174 | 112 | 0.675485 | 5.305263 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt
|
1
|
7613
|
package info.nightscout.androidaps.plugins.general.overview
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.OverviewInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
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.NotificationStore
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.extensions.*
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class OverviewPlugin @Inject constructor(
injector: HasAndroidInjector,
private val notificationStore: NotificationStore,
private val fabricPrivacy: FabricPrivacy,
private val rxBus: RxBusWrapper,
private val sp: SP,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val config: Config
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment::class.qualifiedName)
.alwaysVisible(true)
.alwaysEnabled(true)
.pluginIcon(R.drawable.ic_home)
.pluginName(R.string.overview)
.shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview),
aapsLogger, resourceHelper, injector
), OverviewInterface {
private var disposable: CompositeDisposable = CompositeDisposable()
override fun onStart() {
super.onStart()
notificationStore.createNotificationChannel()
disposable += rxBus
.toObservable(EventNewNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.add(n.notification))
rxBus.send(EventRefreshOverview("EventNewNotification"))
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventDismissNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.remove(n.id))
rxBus.send(EventRefreshOverview("EventDismissNotification"))
}, { fabricPrivacy.logException(it) })
}
override fun onStop() {
disposable.clear()
super.onStop()
}
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
if (config.NSCLIENT) {
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let {
it.isVisible = false
it.isEnabled = false
}
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let {
it.isVisible = false
it.isEnabled = false
}
}
}
override fun configuration(): JSONObject =
JSONObject()
.putString(R.string.key_quickwizard, sp, resourceHelper)
.putInt(R.string.key_eatingsoon_duration, sp, resourceHelper)
.putDouble(R.string.key_eatingsoon_target, sp, resourceHelper)
.putInt(R.string.key_activity_duration, sp, resourceHelper)
.putDouble(R.string.key_activity_target, sp, resourceHelper)
.putInt(R.string.key_hypo_duration, sp, resourceHelper)
.putDouble(R.string.key_hypo_target, sp, resourceHelper)
.putDouble(R.string.key_low_mark, sp, resourceHelper)
.putDouble(R.string.key_high_mark, sp, resourceHelper)
.putDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_res_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_res_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper)
override fun applyConfiguration(configuration: JSONObject) {
configuration
.storeString(R.string.key_quickwizard, sp, resourceHelper)
.storeInt(R.string.key_eatingsoon_duration, sp, resourceHelper)
.storeDouble(R.string.key_eatingsoon_target, sp, resourceHelper)
.storeInt(R.string.key_activity_duration, sp, resourceHelper)
.storeDouble(R.string.key_activity_target, sp, resourceHelper)
.storeInt(R.string.key_hypo_duration, sp, resourceHelper)
.storeDouble(R.string.key_hypo_target, sp, resourceHelper)
.storeDouble(R.string.key_low_mark, sp, resourceHelper)
.storeDouble(R.string.key_high_mark, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_res_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_res_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper)
}
}
|
agpl-3.0
|
ac853b78990731bbe1614fbd890be38b
| 51.868056 | 132 | 0.715355 | 4.400578 | false | true | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt
|
1
|
6196
|
package info.nightscout.androidaps.plugins.general.automation.triggers
import android.content.Context
import android.content.ContextWrapper
import android.view.Gravity
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerRemove
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.services.LastLocationDataContainer
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 kotlin.reflect.full.primaryConstructor
abstract class Trigger(val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var sp: SP
@Inject lateinit var locationDataContainer: LastLocationDataContainer
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
init {
injector.androidInjector().inject(this)
}
abstract fun shouldRun(): Boolean
abstract fun toJSON(): String
abstract fun fromJSON(data: String): Trigger
abstract fun friendlyName(): Int
abstract fun friendlyDescription(): String
abstract fun icon(): Optional<Int?>
abstract fun duplicate(): Trigger
companion object {
@JvmStatic
fun scanForActivity(cont: Context?): AppCompatActivity? {
when (cont) {
null -> return null
is AppCompatActivity -> return cont
is ContextWrapper -> return scanForActivity(cont.baseContext)
else -> return null
}
}
}
open fun generateDialog(root: LinearLayout) {
val title = TextView(root.context)
title.setText(friendlyName())
root.addView(title)
}
fun instantiate(obj: JSONObject): Trigger? {
try {
val type = obj.getString("type")
val data = obj.getJSONObject("data")
val clazz = Class.forName(type).kotlin
return (clazz.primaryConstructor?.call(injector) as Trigger).fromJSON(data?.toString()
?: "")
} catch (e: ClassNotFoundException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: InstantiationException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: IllegalAccessException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return null
}
fun createAddButton(context: Context, trigger: TriggerConnector): ImageButton {
// Button [+]
val buttonAdd = ImageButton(context)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.gravity = Gravity.CENTER
buttonAdd.layoutParams = params
buttonAdd.setImageResource(R.drawable.ic_add)
buttonAdd.contentDescription = resourceHelper.gs(R.string.add_short)
buttonAdd.setOnClickListener {
scanForActivity(context)?.supportFragmentManager?.let {
val dialog = ChooseTriggerDialog()
dialog.show(it, "ChooseTriggerDialog")
dialog.setOnClickListener(object : ChooseTriggerDialog.OnClickListener {
override fun onClick(newTriggerObject: Trigger) {
trigger.list.add(newTriggerObject)
rxBus.send(EventTriggerChanged())
}
})
}
}
return buttonAdd
}
fun createDeleteButton(context: Context, trigger: Trigger): ImageButton {
// Button [-]
val buttonRemove = ImageButton(context)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.gravity = Gravity.CENTER
buttonRemove.layoutParams = params
buttonRemove.setImageResource(R.drawable.ic_remove)
buttonRemove.contentDescription = resourceHelper.gs(R.string.delete_short)
buttonRemove.setOnClickListener {
rxBus.send(EventTriggerRemove(trigger))
}
return buttonRemove
}
fun createCloneButton(context: Context, trigger: Trigger): ImageButton {
// Button [*]
val buttonClone = ImageButton(context)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.gravity = Gravity.CENTER
buttonClone.layoutParams = params
buttonClone.setImageResource(R.drawable.ic_clone)
buttonClone.contentDescription = resourceHelper.gs(R.string.copy_short)
buttonClone.setOnClickListener {
rxBus.send(EventTriggerClone(trigger))
}
return buttonClone
}
}
|
agpl-3.0
|
1ab4b7b5a928940ab6f564deb7f6d153
| 40.039735 | 98 | 0.69561 | 5.295726 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/UiScene.kt
|
1
|
1514
|
package de.fabmax.kool.modules.ui2
import de.fabmax.kool.scene.OrthographicCamera
import de.fabmax.kool.scene.Scene
/**
* Creates a new scene and sets it up as a UI scene.
*
* @see [setupUiScene]
*/
fun UiScene(
name: String = "UiScene",
clearScreen: Boolean = false,
block: Scene.() -> Unit
) = Scene(name).apply {
setupUiScene(clearScreen)
block()
}
/**
* Sets up a scene to host UI content. To do so, this method installs an orthographic camera, which auto-adjusts its
* clip size to the viewport size. Also, by default, screen-clearing is disabled, because UIs usually are drawn on
* top of stuff, which should not be cleared away.
*/
fun Scene.setupUiScene(clearScreen: Boolean = false) {
if (!clearScreen) {
mainRenderPass.clearColor = null
}
camera = OrthographicCamera()
onUpdate += { ev ->
// Setup camera to cover viewport size with origin in upper left corner.
// Camera clip space uses OpenGL coordinates -> y-axis points downwards, i.e. bottom coordinate has to be
// set to negative viewport height. UI surface internally mirrors y-axis to get a regular UI coordinate
// system (however, this means triangle index order or face orientation has to be inverted).
(camera as? OrthographicCamera)?.let { cam ->
cam.left = 0f
cam.top = 0f
cam.right = ev.renderPass.viewport.width.toFloat()
cam.bottom = -ev.renderPass.viewport.height.toFloat()
}
}
}
|
apache-2.0
|
79b39dc64830675e0deb3ad6218a7f20
| 34.232558 | 116 | 0.669749 | 4.015915 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/viewmodels/LoginViewModel.kt
|
1
|
11022
|
package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair
import com.kickstarter.libs.rx.transformers.Transformers.ignoreValues
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.extensions.isEmail
import com.kickstarter.libs.utils.extensions.negate
import com.kickstarter.services.apiresponses.AccessTokenEnvelope
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.LoginActivity
import com.kickstarter.ui.data.ActivityResult
import com.kickstarter.ui.data.LoginReason
import rx.Notification
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface LoginViewModel {
interface Inputs {
/** Call when the email field changes. */
fun email(email: String)
/** Call when the log in button has been clicked. */
fun loginClick()
/** Call when the password field changes. */
fun password(password: String)
/** Call when the user cancels or dismisses the reset password success confirmation dialog. */
fun resetPasswordConfirmationDialogDismissed()
}
interface Outputs {
/** Emits a string to display when log in fails. */
fun genericLoginError(): Observable<String>
/** Emits a string to display when log in fails, specifically for invalid credentials. */
fun invalidLoginError(): Observable<String>
/** Emits a boolean that determines if the log in button is enabled. */
fun loginButtonIsEnabled(): Observable<Boolean>
/** Finish the activity with a successful result. */
fun loginSuccess(): Observable<Void>
/** Fill the view's email address when it's supplied from the intent. */
fun prefillEmail(): Observable<String>
/** Emits when a user has successfully changed their password and needs to login again. */
fun showChangedPasswordSnackbar(): Observable<Void>
/** Emits when a user has successfully created their password and needs to login again. */
fun showCreatedPasswordSnackbar(): Observable<Void>
/** Emits a boolean to determine whether reset password dialog should be shown. */
fun showResetPasswordSuccessDialog(): Observable<Pair<Boolean, String>>
/** Start two factor activity for result. */
fun tfaChallenge(): Observable<Void>
}
class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<LoginActivity>(environment), Inputs, Outputs {
private val emailEditTextChanged = BehaviorSubject.create<String>()
private val logInButtonClicked = BehaviorSubject.create<Void>()
private val passwordEditTextChanged = PublishSubject.create<String>()
private val resetPasswordConfirmationDialogDismissed = PublishSubject.create<Boolean>()
private val genericLoginError: Observable<String>
private val invalidloginError: Observable<String>
private val logInButtonIsEnabled = BehaviorSubject.create<Boolean>()
private val loginSuccess = PublishSubject.create<Void>()
private val prefillEmail = BehaviorSubject.create<String>()
private val showChangedPasswordSnackbar = BehaviorSubject.create<Void>()
private val showCreatedPasswordSnackbar = BehaviorSubject.create<Void>()
private val showResetPasswordSuccessDialog = BehaviorSubject.create<Pair<Boolean, String>>()
private val tfaChallenge: Observable<Void>
private val loginError = PublishSubject.create<ErrorEnvelope>()
val inputs: Inputs = this
val outputs: Outputs = this
private val client = requireNotNull(environment.apiClient())
private val currentUser = requireNotNull(environment.currentUser())
init {
val emailAndPassword = this.emailEditTextChanged
.compose<Pair<String, String>>(combineLatestPair(this.passwordEditTextChanged))
val isValid = emailAndPassword
.map<Boolean> { isValid(it.first, it.second) }
val emailAndReason = intent()
.filter { it.hasExtra(IntentKey.EMAIL) }
.map {
Pair.create(
it.getStringExtra(IntentKey.EMAIL) ?: "",
if (it.hasExtra(IntentKey.LOGIN_REASON)) {
it.getSerializableExtra(IntentKey.LOGIN_REASON) as LoginReason
} else {
LoginReason.DEFAULT
}
)
}
// - Contain the errors if any from the login endpoint response
val errors = PublishSubject.create<Throwable?>()
// - Contains success data if any from the login endpoint response
val successResponseData = PublishSubject.create<AccessTokenEnvelope>()
emailAndPassword
.compose(takeWhen(this.logInButtonClicked))
.compose(bindToLifecycle())
.switchMap { ep -> this.client.login(ep.first, ep.second).materialize() }
.share()
.subscribe {
this.logInButtonIsEnabled.onNext(true)
errors.onNext(unwrapNotificationEnvelopeError(it))
successResponseData.onNext(unwrapNotificationEnvelopeSuccess(it))
}
logInButtonClicked
.compose(bindToLifecycle())
.subscribe {
this.logInButtonIsEnabled.onNext(false)
this.analyticEvents.trackLogInButtonCtaClicked()
}
emailAndReason
.map { it.first }
.ofType(String::class.java)
.compose(bindToLifecycle())
.subscribe(this.prefillEmail)
emailAndReason
.filter { it.second == LoginReason.RESET_PASSWORD }
.map { it.first }
.ofType(String::class.java)
.map { e -> Pair.create(true, e) }
.compose(bindToLifecycle())
.subscribe(this.showResetPasswordSuccessDialog)
emailAndReason
.map { it.second }
.ofType(LoginReason::class.java)
.filter { LoginReason.CHANGE_PASSWORD == it }
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe(this.showChangedPasswordSnackbar)
emailAndReason
.map { it.second }
.ofType(LoginReason::class.java)
.filter { LoginReason.CREATE_PASSWORD == it }
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe(this.showCreatedPasswordSnackbar)
this.resetPasswordConfirmationDialogDismissed
.map<Boolean> { it.negate() }
.compose<Pair<Boolean, Pair<String, LoginReason>>>(combineLatestPair(emailAndReason))
.map { Pair.create(it.first, it.second.first) }
.compose(bindToLifecycle())
.subscribe(this.showResetPasswordSuccessDialog)
isValid
.compose(bindToLifecycle())
.subscribe(this.logInButtonIsEnabled)
successResponseData
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe { envelope ->
this.success(envelope)
}
errors
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.map { ErrorEnvelope.fromThrowable(it) }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe(this.loginError)
this.genericLoginError = this.loginError
.filter { it.isGenericLoginError }
.map { it.errorMessage() }
this.invalidloginError = this.loginError
.filter { it.isInvalidLoginError }
.map { it.errorMessage() }
this.tfaChallenge = this.loginError
.filter { it.isTfaRequiredError }
.map { null }
this.analyticEvents.trackLoginPagedViewed()
activityResult()
.filter { it.isRequestCode(ActivityRequestCodes.RESET_FLOW) }
.filter(ActivityResult::isOk)
.compose(bindToLifecycle())
.subscribe {
it.intent?.let { intent ->
intent(intent)
}
}
}
private fun unwrapNotificationEnvelopeError(notification: Notification<AccessTokenEnvelope>) =
if (notification.hasThrowable()) notification.throwable else null
private fun unwrapNotificationEnvelopeSuccess(notification: Notification<AccessTokenEnvelope>) =
if (notification.hasValue()) notification.value else null
private fun isValid(email: String, password: String) = email.isEmail() && password.isNotEmpty()
private fun success(envelope: AccessTokenEnvelope) {
this.currentUser.login(envelope.user(), envelope.accessToken())
this.loginSuccess.onNext(null)
}
override fun email(email: String) = this.emailEditTextChanged.onNext(email)
override fun loginClick() {
return this.logInButtonClicked.onNext(null)
}
override fun password(password: String) = this.passwordEditTextChanged.onNext(password)
override fun resetPasswordConfirmationDialogDismissed() = this.resetPasswordConfirmationDialogDismissed.onNext(true)
override fun genericLoginError() = this.genericLoginError
override fun invalidLoginError() = this.invalidloginError
override fun loginButtonIsEnabled(): BehaviorSubject<Boolean> = this.logInButtonIsEnabled
override fun loginSuccess(): PublishSubject<Void> = this.loginSuccess
override fun prefillEmail(): BehaviorSubject<String> = this.prefillEmail
override fun showChangedPasswordSnackbar(): Observable<Void> = this.showChangedPasswordSnackbar
override fun showCreatedPasswordSnackbar(): Observable<Void> = this.showCreatedPasswordSnackbar
override fun showResetPasswordSuccessDialog(): BehaviorSubject<Pair<Boolean, String>> = this.showResetPasswordSuccessDialog
override fun tfaChallenge() = this.tfaChallenge
}
}
|
apache-2.0
|
68594124dd1da2447a66c3692ddcfaab
| 40.908745 | 131 | 0.635184 | 5.464551 | false | false | false | false |
mdaniel/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/api/dependencies.kt
|
1
|
5515
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import java.io.Serializable
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
interface LibraryEntity : WorkspaceEntityWithPersistentId {
val name: String
val tableId: LibraryTableId
val roots: List<LibraryRoot>
val excludedRoots: List<VirtualFileUrl>
@Child val sdk: SdkEntity?
@Child val libraryProperties: LibraryPropertiesEntity?
@Child val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
override val persistentId: LibraryId
get() = LibraryId(name, tableId)
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: LibraryEntity, ModifiableWorkspaceEntity<LibraryEntity>, ObjBuilder<LibraryEntity> {
override var name: String
override var entitySource: EntitySource
override var tableId: LibraryTableId
override var roots: List<LibraryRoot>
override var excludedRoots: List<VirtualFileUrl>
override var sdk: SdkEntity?
override var libraryProperties: LibraryPropertiesEntity?
override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
}
companion object: Type<LibraryEntity, Builder>() {
operator fun invoke(name: String, tableId: LibraryTableId, roots: List<LibraryRoot>, excludedRoots: List<VirtualFileUrl>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryEntity {
val builder = builder()
builder.name = name
builder.entitySource = entitySource
builder.tableId = tableId
builder.roots = roots
builder.excludedRoots = excludedRoots
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LibraryEntity, modification: LibraryEntity.Builder.() -> Unit) = modifyEntity(LibraryEntity.Builder::class.java, entity, modification)
var LibraryEntity.Builder.externalSystemId: @Child LibraryExternalSystemIdEntity?
by WorkspaceEntity.extension()
//endregion
interface LibraryPropertiesEntity : WorkspaceEntity {
val library: LibraryEntity
val libraryType: String
val propertiesXmlTag: String?
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: LibraryPropertiesEntity, ModifiableWorkspaceEntity<LibraryPropertiesEntity>, ObjBuilder<LibraryPropertiesEntity> {
override var library: LibraryEntity
override var entitySource: EntitySource
override var libraryType: String
override var propertiesXmlTag: String?
}
companion object: Type<LibraryPropertiesEntity, Builder>() {
operator fun invoke(libraryType: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryPropertiesEntity {
val builder = builder()
builder.entitySource = entitySource
builder.libraryType = libraryType
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LibraryPropertiesEntity, modification: LibraryPropertiesEntity.Builder.() -> Unit) = modifyEntity(LibraryPropertiesEntity.Builder::class.java, entity, modification)
//endregion
interface SdkEntity : WorkspaceEntity {
val library: LibraryEntity
val homeUrl: VirtualFileUrl
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: SdkEntity, ModifiableWorkspaceEntity<SdkEntity>, ObjBuilder<SdkEntity> {
override var library: LibraryEntity
override var entitySource: EntitySource
override var homeUrl: VirtualFileUrl
}
companion object: Type<SdkEntity, Builder>() {
operator fun invoke(homeUrl: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SdkEntity {
val builder = builder()
builder.entitySource = entitySource
builder.homeUrl = homeUrl
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SdkEntity, modification: SdkEntity.Builder.() -> Unit) = modifyEntity(SdkEntity.Builder::class.java, entity, modification)
//endregion
data class LibraryRootTypeId(val name: String) : Serializable {
companion object {
val COMPILED = LibraryRootTypeId("CLASSES")
val SOURCES = LibraryRootTypeId("SOURCES")
}
}
data class LibraryRoot(
val url: VirtualFileUrl,
val type: LibraryRootTypeId,
val inclusionOptions: InclusionOptions = InclusionOptions.ROOT_ITSELF
) : Serializable {
enum class InclusionOptions {
ROOT_ITSELF, ARCHIVES_UNDER_ROOT, ARCHIVES_UNDER_ROOT_RECURSIVELY
}
}
|
apache-2.0
|
0c9feb4587214a803adfc4907003f256
| 36.263514 | 210 | 0.727652 | 5.487562 | false | false | false | false |
alphahelix00/Ordinator
|
kommandant-core/src/main/kotlin/com/github/kvnxiao/kommandant/utility/SplitString.kt
|
2
|
2032
|
/*
* Copyright 2017 Ze Hao Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.kommandant.utility
/**
* A container utility class for strings split into two.
*
* @param[content] The string to split into two based on the first available whitespace.
* @property[first] The first portion of the string before the first whitespace char.
* @property[second] The latter potion of the string after the first whitespace char.
*/
open class SplitString(content: String) {
val first: String?
val second: String?
init {
val splitInput = StringSplitter.split(content, StringSplitter.SPACE_LITERAL, 2)
this.first = if (splitInput.isNotEmpty()) splitInput[0] else null
this.second = if (splitInput.size == 2) splitInput[1] else null
}
/**
* Whether the first portion of the split string is not null or not empty.
*
* @return[Boolean] Whether the first portion is not null or not empty.
*/
fun hasFirst(): Boolean = !first.isNullOrEmpty()
/**
* Whether the latter portion of the split string is not null or not empty.
*
* @return[Boolean] Whether the latter portion is not null or not empty.
*/
fun hasSecond(): Boolean = !second.isNullOrEmpty()
/**
* Kotlin helper method for destructuring support.
*/
operator fun component1(): String? = this.first
/**
* Kotlin helper method for destructuring support.
*/
operator fun component2(): String? = this.second
}
|
apache-2.0
|
5e7f7779944c012bc74907927e13bece
| 32.883333 | 88 | 0.691929 | 4.251046 | false | false | false | false |
stefanmedack/cccTV
|
app/src/main/java/de/stefanmedack/ccctv/ui/events/EventsViewModel.kt
|
1
|
1738
|
package de.stefanmedack.ccctv.ui.events
import android.arch.lifecycle.ViewModel
import de.stefanmedack.ccctv.model.Resource
import de.stefanmedack.ccctv.persistence.entities.Event
import de.stefanmedack.ccctv.persistence.toEntity
import de.stefanmedack.ccctv.repository.ConferenceRepository
import de.stefanmedack.ccctv.util.EMPTY_STRING
import de.stefanmedack.ccctv.util.applySchedulers
import info.metadude.kotlin.library.c3media.RxC3MediaService
import io.reactivex.Flowable
import javax.inject.Inject
class EventsViewModel @Inject constructor(
private val c3MediaService: RxC3MediaService,
private val repository: ConferenceRepository
) : ViewModel() {
private var searchQuery: String? = null
private var conferenceAcronym: String? = null
lateinit var events: Flowable<Resource<List<Event>>>
fun initWithSearch(searchQuery: String) {
this.searchQuery = searchQuery
this.events = c3MediaService.searchEvents(searchQuery)
.applySchedulers()
.map<Resource<List<Event>>> { Resource.Success(it.events.mapNotNull { it.toEntity(EMPTY_STRING) }) }
.toFlowable()
}
fun initWithConference(conferenceAcronym: String) {
this.conferenceAcronym = conferenceAcronym
this.events = repository.conferenceWithEvents(conferenceAcronym)
.map<Resource<List<Event>>> {
when (it) {
is Resource.Success -> Resource.Success(it.data.events.sortedByDescending { it.viewCount })
is Resource.Loading -> Resource.Loading()
is Resource.Error -> Resource.Error(it.msg, it.data?.events)
}
}
}
}
|
apache-2.0
|
91b0baba0a75ae2d8108e9a7505b7272
| 39.44186 | 116 | 0.689298 | 4.672043 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/data/ispn/IspnUtils.kt
|
2
|
2175
|
package com.github.kerubistan.kerub.data.ispn
import org.infinispan.Cache
import org.infinispan.query.Search
import org.infinispan.query.dsl.FilterConditionContext
import org.infinispan.query.dsl.Query
import org.infinispan.query.dsl.QueryBuilder
import org.infinispan.query.dsl.SortOrder
import kotlin.reflect.KClass
fun <T> FilterConditionContext.list(): List<T> =
this.toBuilder<Query>()
.build()
.list<T>()
fun <T> QueryBuilder<*>.list(): List<T> =
this
.build()
.list<T>()
fun <T : Any, K, V> Cache<K, V>.queryBuilder(clazz: KClass<T>): QueryBuilder<Query> =
Search.getQueryFactory(this)
.from(clazz.java)
inline fun <reified K, reified V : Any> Cache<K, V>.fieldEq(
field: String,
value: String,
start: Long,
limit: Int): List<V> =
this.fieldEq(V::class, field, value, start, limit)
fun <K, V : Any> Cache<K, V>.fieldEq(
type: KClass<out V>,
field: String,
value: Any,
start: Long,
limit: Int): List<V> =
this.queryBuilder(type)
.startOffset(start)
.maxResults(limit)
.having(field).eq(value)
.list()
inline fun <reified K, reified V : Any> Cache<K, V>.fieldSearch(
field: String,
value: String,
start: Long,
limit: Int): List<V> =
this.fieldSearch(V::class, field, value, start, limit)
fun <K, V : Any> Cache<K, V>.fieldSearch(
type: KClass<out V>,
field: String,
value: String,
start: Long,
limit: Int): List<V> =
this.queryBuilder(type)
.startOffset(start)
.maxResults(limit)
.having(field).like("%$value%")
.list()
fun <K, V : Any> Cache<K, V>.parallelStream() = this.advancedCache.cacheEntrySet().parallelStream()
inline fun <reified K, reified V> Cache<K, V>.search(
start: Long = 0,
limit: Int,
order: SortOrder = SortOrder.DESC,
sortProp: String): List<V> =
Search.getQueryFactory(this)
.from(V::class.java)
.orderBy(sortProp, order)
.maxResults(limit)
.startOffset(start)
.list()
inline fun <K, V : Any, T> Cache<K, V>.batch(action: () -> T): T {
var success = false
this.advancedCache.startBatch()
return try {
val ret = action()
success = true
ret
} finally {
this.advancedCache.endBatch(success)
}
}
|
apache-2.0
|
e3cd88e92004e776f88a726947a5122e
| 23.715909 | 99 | 0.668506 | 2.911647 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt
|
1
|
9792
|
// 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.highlighter.markers
import com.intellij.codeInsight.daemon.DaemonBundle
import com.intellij.codeInsight.navigation.BackgroundUpdaterTask
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.util.MethodCellRenderer
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.PsiElementProcessorAdapter
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.FunctionalExpressionSearch
import com.intellij.util.CommonProcessors
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isTraitFakeOverride
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.presentation.DeclarationByModuleRenderer
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachDeclaredMemberOverride
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import java.awt.event.MouseEvent
import javax.swing.JComponent
private fun PsiMethod.isMethodWithDeclarationInOtherClass(): Boolean {
return this is KtLightMethod && this.isTraitFakeOverride()
}
internal fun <T> getOverriddenDeclarations(mappingToJava: MutableMap<PsiElement, T>, classes: Set<PsiClass>): Set<T> {
val overridden = HashSet<T>()
for (aClass in classes) {
aClass.forEachDeclaredMemberOverride { superMember, overridingMember ->
ProgressManager.checkCanceled()
val possiblyFakeLightMethods = overridingMember.toPossiblyFakeLightMethods()
possiblyFakeLightMethods.find { !it.isMethodWithDeclarationInOtherClass() }?.let {
mappingToJava.remove(superMember)?.let { declaration ->
// Light methods points to same methods
// and no reason to keep searching those methods
// those originals are found
if (mappingToJava.remove(it) == null) {
mappingToJava.values.removeIf(superMember::equals)
}
overridden.add(declaration)
}
false
}
mappingToJava.isNotEmpty()
}
}
return overridden
}
// Module-specific version of MarkerType.getSubclassedClassTooltip
fun getSubclassedClassTooltip(klass: PsiClass): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit(5, HashSet<PsiClass>())
ClassInheritorsSearch.search(klass).forEach(PsiElementProcessorAdapter(processor))
if (processor.isOverflow) {
return if (klass.isInterface) IdeDeprecatedMessagesBundle.message("interface.is.implemented.too.many") else DaemonBundle.message("class.is.subclassed.too.many")
}
val subclasses = processor.toArray(PsiClass.EMPTY_ARRAY)
if (subclasses.isEmpty()) {
val functionalImplementations = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiFunctionalExpression>())
FunctionalExpressionSearch.search(klass).forEach(PsiElementProcessorAdapter(functionalImplementations))
return if (functionalImplementations.collection.isNotEmpty())
KotlinBundle.message("highlighter.text.has.functional.implementations")
else
null
}
val start = IdeDeprecatedMessagesBundle.message(if (klass.isInterface) "interface.is.implemented.by.header" else "class.is.subclassed.by.header")
val shortcuts = ActionManager.getInstance().getAction(IdeActions.ACTION_GOTO_IMPLEMENTATION).shortcutSet.shortcuts
val shortcut = shortcuts.firstOrNull()
val shortCutText = if (shortcut != null)
KotlinBundle.message("highlighter.text.or.press", KeymapUtil.getShortcutText(shortcut))
else
""
val postfix = "<br><div style=''margin-top: 5px''><font size=''2''>" + KotlinBundle.message(
"highlighter.text.click.for.navigate",
shortCutText
) + "</font></div>"
val renderer = DeclarationByModuleRenderer()
val comparator = renderer.comparator
return subclasses.toList().sortedWith(comparator).joinToString(
prefix = "<html><body>$start", postfix = "$postfix</body</html>", separator = "<br>"
) { clazz ->
val moduleNameRequired = if (clazz is KtLightClass) {
val origin = clazz.kotlinOrigin
origin?.hasActualModifier() == true || origin?.isExpectDeclaration() == true
} else false
val moduleName = clazz.module?.name
val elementText = renderer.getElementText(clazz) + (moduleName?.takeIf { moduleNameRequired }?.let { " [$it]" } ?: "")
val refText = (moduleName?.let { "$it:" } ?: "") + ClassPresentationUtil.getNameForClass(clazz, /* qualified = */ true)
" <a href=\"#kotlinClass/$refText\">$elementText</a>"
}
}
fun getOverriddenMethodTooltip(method: PsiMethod): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(5)
method.forEachOverridingMethod(processor = PsiElementProcessorAdapter(processor)::process)
val isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT)
if (processor.isOverflow) {
return if (isAbstract) DaemonBundle.message("method.is.implemented.too.many") else DaemonBundle.message("method.is.overridden.too.many")
}
val comparator = MethodCellRenderer(false).comparator
val overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }.sortedWith(comparator)
if (overridingJavaMethods.isEmpty()) return null
val start = if (isAbstract) DaemonBundle.message("method.is.implemented.header") else DaemonBundle.message("method.is.overriden.header")
return com.intellij.codeInsight.daemon.impl.GutterIconTooltipHelper.composeText(
overridingJavaMethods,
start,
" {1}"
)
}
fun buildNavigateToOverriddenMethodPopup(e: MouseEvent?, element: PsiElement?): NavigationPopupDescriptor? {
val method = getPsiMethod(element) ?: return null
if (DumbService.isDumb(method.project)) {
DumbService.getInstance(method.project)
?.showDumbModeNotification(KotlinBundle.message("highlighter.notification.text.navigation.to.overriding.classes.is.not.possible.during.index.update"))
return null
}
val processor = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiMethod>())
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
method.forEachOverridingMethod {
runReadAction {
processor.execute(it)
}
}
},
KotlinBundle.message("highlighter.title.searching.for.overriding.declarations"),
true,
method.project,
e?.component as JComponent?
)
) {
return null
}
var overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }
if (overridingJavaMethods.isEmpty()) return null
val renderer = MethodCellRenderer(false)
overridingJavaMethods = overridingJavaMethods.sortedWith(renderer.comparator)
val methodsUpdater = OverridingMethodsUpdater(method, renderer.comparator)
return NavigationPopupDescriptor(
overridingJavaMethods,
methodsUpdater.getCaption(overridingJavaMethods.size),
KotlinBundle.message("highlighter.title.overriding.declarations.of", method.name),
renderer,
methodsUpdater
)
}
private class OverridingMethodsUpdater(
private val myMethod: PsiMethod,
comparator: Comparator<PsiMethod>,
) : BackgroundUpdaterTask(
myMethod.project,
KotlinBundle.message("highlighter.title.searching.for.overriding.methods"),
createComparatorWrapper { o1: PsiElement, o2: PsiElement ->
if (o1 is PsiMethod && o2 is PsiMethod) comparator.compare(o1, o2) else 0
}
) {
@Suppress("DialogTitleCapitalization")
override fun getCaption(size: Int): String {
return if (myMethod.hasModifierProperty(PsiModifier.ABSTRACT))
DaemonBundle.message("navigation.title.implementation.method", myMethod.name, size)
else
DaemonBundle.message("navigation.title.overrider.method", myMethod.name, size)
}
override fun run(indicator: ProgressIndicator) {
super.run(indicator)
val processor = object : CommonProcessors.CollectProcessor<PsiMethod>() {
override fun process(psiMethod: PsiMethod): Boolean {
if (!updateComponent(psiMethod)) {
indicator.cancel()
}
indicator.checkCanceled()
return super.process(psiMethod)
}
}
myMethod.forEachOverridingMethod { processor.process(it) }
}
}
|
apache-2.0
|
b102bb2949083706def034d45ff965e9
| 44.971831 | 168 | 0.721507 | 4.881356 | false | false | false | false |
PaleoCrafter/VanillaImmersion
|
src/main/kotlin/de/mineformers/vanillaimmersion/item/SpecialBlockItem.kt
|
1
|
2628
|
package de.mineformers.vanillaimmersion.item
import net.minecraft.advancements.CriteriaTriggers
import net.minecraft.block.Block
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.item.ItemBlock
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.SoundCategory
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Implementation of ItemBlockSpecial that actually extends ItemBlock.
*/
class SpecialBlockItem(block: Block) : ItemBlock(block) {
override fun onItemUse(player: EntityPlayer, world: World, pos: BlockPos, hand: EnumHand,
facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult {
val stack = player.getHeldItem(hand)
val state = world.getBlockState(pos)
val block = state.block
val placedPos =
if (!block.isReplaceable(world, pos)) {
pos.offset(facing)
} else {
pos
}
if (!stack.isEmpty && player.canPlayerEdit(placedPos, facing, stack)) {
var placedState = this.block.getStateForPlacement(world, placedPos, facing, hitX, hitY, hitZ, 0, player, hand)
if (!world.setBlockState(placedPos, placedState, 11)) {
return EnumActionResult.FAIL
} else {
placedState = world.getBlockState(placedPos)
if (placedState.block === this.block) {
ItemBlock.setTileEntityNBT(world, player, placedPos, stack)
placedState.block.onBlockPlacedBy(world, placedPos, placedState, player, stack)
if (player is EntityPlayerMP) {
CriteriaTriggers.PLACED_BLOCK.trigger(player, pos, stack)
}
}
val sound = placedState.block.getSoundType(placedState, world, pos, player)
world.playSound(player, pos, sound.placeSound, SoundCategory.BLOCKS, (sound.getVolume() + 1.0f) / 2.0f, sound.getPitch() * 0.8f)
stack.shrink(1)
return EnumActionResult.SUCCESS
}
} else {
return EnumActionResult.FAIL
}
}
override fun getUnlocalizedName(stack: ItemStack): String? {
return block.unlocalizedName.replace("tile.", "item.")
}
override fun getUnlocalizedName(): String? {
return block.unlocalizedName.replace("tile.", "item.")
}
}
|
mit
|
31216c9a3b043d8ea636c9c1af139ced
| 38.238806 | 144 | 0.642314 | 4.454237 | false | false | false | false |
Masterzach32/SwagBot
|
src/main/kotlin/extensions/VoiceChannel.kt
|
1
|
1786
|
package xyz.swagbot.extensions
import discord4j.core.`object`.entity.channel.*
import discord4j.core.event.domain.*
import discord4j.voice.*
import io.facet.common.*
import io.facet.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.reactive.*
import xyz.swagbot.features.music.*
private val VoiceChannel.musicFeature: Music
get() = client.feature(Music)
suspend fun VoiceChannel.join(): VoiceConnection = join {
it.setProvider(musicFeature.trackSchedulerFor(guildId).audioProvider)
}.await().also { connection ->
GlobalScope.launch main@{
suspend fun memberCountThresholdMet() = voiceStates.asFlow().count() == 1
launch {
delay(10_000)
if (memberCountThresholdMet()) {
connection.disconnect().await()
musicFeature.updateLastConnectedChannelFor(guildId, null)
[email protected]("Disconnecting from voice, no members left in channel.")
}
}
client.flowOf<VoiceStateUpdateEvent>()
.filter { event -> event.isLeaveEvent && event.old.flatMap { it.channelId }.unwrap() == id }
.collect { event ->
when {
memberCountThresholdMet() -> {
connection.disconnect().await()
musicFeature.updateLastConnectedChannelFor(guildId, null)
cancel("Disconnecting from voice, no members left in channel.")
}
event.current.userId == client.selfId -> {
musicFeature.updateLastConnectedChannelFor(guildId, null)
cancel("Bot was disconnected from voice.")
}
}
}
}
}
|
gpl-2.0
|
6fd1bfe692bfcacff5e14194398e544f
| 37 | 104 | 0.602464 | 4.97493 | false | false | false | false |
androidx/androidx
|
health/health-services-client/src/main/java/androidx/health/services/client/data/HeartRateAccuracy.kt
|
3
|
4202
|
/*
* 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.
*/
package androidx.health.services.client.data
import androidx.annotation.RestrictTo
import androidx.health.services.client.proto.DataProto
import androidx.health.services.client.proto.DataProto.DataPointAccuracy.HrAccuracy as HrAccuracyProto
import androidx.health.services.client.proto.DataProto.DataPointAccuracy.HrAccuracy.SensorStatus as SensorStatusProto
/** Accuracy for a [DataType.HEART_RATE_BPM] data point. */
@Suppress("ParcelCreator")
public class HeartRateAccuracy(public val sensorStatus: SensorStatus) : DataPointAccuracy() {
internal constructor(
proto: DataProto.DataPointAccuracy
) : this(SensorStatus.fromProto(proto.hrAccuracy.sensorStatus))
/** Status of the Heart Rate sensor in terms of accuracy. */
public class SensorStatus private constructor(public val id: Int, public val name: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SensorStatus) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id
override fun toString(): String = name
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal fun toProto(): SensorStatusProto =
SensorStatusProto.forNumber(id) ?: SensorStatusProto.HR_ACCURACY_SENSOR_STATUS_UNKNOWN
public companion object {
/**
* The availability is unknown, or is represented by a value too new for this library
* version to parse.
*/
@JvmField
public val UNKNOWN: SensorStatus = SensorStatus(0, "UNKNOWN")
/**
* The heart rate cannot be acquired because the sensor is not properly contacting skin.
*/
@JvmField
public val NO_CONTACT: SensorStatus = SensorStatus(1, "NO_CONTACT")
/** Heart rate data is currently too unreliable to be used. */
@JvmField
public val UNRELIABLE: SensorStatus = SensorStatus(2, "UNRELIABLE")
/** Heart rate data is available but the accuracy is low. */
@JvmField
public val ACCURACY_LOW: SensorStatus = SensorStatus(3, "ACCURACY_LOW")
/** Heart rate data is available and the accuracy is medium. */
@JvmField
public val ACCURACY_MEDIUM: SensorStatus = SensorStatus(4, "ACCURACY_MEDIUM")
/** Heart rate data is available with high accuracy. */
@JvmField
public val ACCURACY_HIGH: SensorStatus = SensorStatus(5, "ACCURACY_HIGH")
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
public val VALUES: List<SensorStatus> =
listOf(
UNKNOWN,
NO_CONTACT,
UNRELIABLE,
ACCURACY_LOW,
ACCURACY_MEDIUM,
ACCURACY_HIGH,
)
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public fun fromProto(proto: SensorStatusProto): SensorStatus =
VALUES.firstOrNull { it.id == proto.number } ?: UNKNOWN
}
}
internal fun getDataPointAccuracyProto(): DataProto.DataPointAccuracy {
return DataProto.DataPointAccuracy.newBuilder()
.setHrAccuracy(HrAccuracyProto.newBuilder().setSensorStatus(sensorStatus.toProto()))
.build()
}
override fun toString(): String = "HrAccuracy(sensorStatus=$sensorStatus)"
}
|
apache-2.0
|
06f1765e2e16ed2d333c7ccab8bf28ad
| 37.907407 | 117 | 0.638267 | 4.818807 | false | false | false | false |
HughG/yested
|
src/main/docsite/complex/spinner.kt
|
2
|
1273
|
package complex
import net.yested.div
import net.yested.Div
import net.yested.bootstrap.row
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.Medium
import net.yested.spin.spinner
import net.yested.spin.SpinnerOptions
fun createSpinner(): Div {
return div {
row {
col(Medium(12)) {
pageHeader { h3 { +"Spinner" } }
}
}
row {
col(Medium(4)) {
div {
+"""
This spinner is based on Spinner library:
"""
a(href = "http://fgnass.github.io/spin.js/") { +"http://fgnass.github.io/spin.js/"}
br()
+"You need to include spin.js library in your html file."
br()
+"All spinner options are supported."
}
br()
h4 { +"Demo" }
div {
style = "height: 200px"
spinner(SpinnerOptions(length = 7))
}
}
col(Medium(8)) {
h4 { +"Code" }
code(lang = "kotlin", content=
"""div {
style = "height: 200px"
spinner(SpinnerOptions(length = 7))
}""")
}
}
}
}
|
mit
|
28afa82cb5cee01142a7dda8279bd12e
| 24.46 | 103 | 0.454831 | 4.300676 | false | false | false | false |
oldcwj/iPing
|
app/src/main/java/com/wpapper/iping/ui/main/IViewInjectorExts.kt
|
1
|
2061
|
import android.widget.LinearLayout
import android.widget.TextView
import com.github.mikephil.charting.charts.PieChart
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import com.wpapper.iping.R
import com.wpapper.iping.base.rx.RxActivity
import com.wpapper.iping.ui.main.PieChartUtil
import com.wpapper.iping.model.CmdParser
import com.wpapper.iping.model.Info
import com.wpapper.iping.model.SshInfo
import com.wpapper.iping.ui.utils.SSHManager
import com.wpapper.iping.ui.utils.exts.subscribeNext
import com.wpapper.iping.ui.utils.exts.subscribeOnComputation
import com.wpapper.iping.ui.utils.exts.ui
import io.reactivex.Observable
import net.idik.lib.slimadapter.viewinjector.IViewInjector
fun IViewInjector<*>.pieChart(id: Int, sshInfo: SshInfo, context: RxActivity): IViewInjector<*> {
val layout: LinearLayout = findViewById<LinearLayout>(id)
val chartCpu: PieChart = layout.findViewById<PieChart>(R.id.chart_cpu)
val chartMem: PieChart = layout.findViewById(R.id.chart_mem)
val chartDisk: PieChart = layout.findViewById(R.id.chart_disk)
val daysView = layout.findViewById<TextView>(R.id.state)
val nameView = layout.findViewById<TextView>(R.id.name)
daysView.text = "loading"
nameView.text = sshInfo.name
PieChartUtil.getPieChart(chartCpu, 0f, 0f, 0)
PieChartUtil.getPieChart(chartMem, 0f, 0f, 1)
PieChartUtil.getPieChart(chartDisk, 0f, 0f, 2)
Observable.create<Info> {
val result = SSHManager.newInstance().ssh(sshInfo)
val info = CmdParser.newInstance().parse(result)
it.onNext(info)
}.subscribeOnComputation()
.ui()
.bindToLifecycle(context)
.subscribeNext {
PieChartUtil.getPieChart(chartCpu, 100 - it.cpu.idle, it.cpu.idle, 0)
PieChartUtil.getPieChart(chartMem, it.mem.used, it.mem.free + it.mem.cached, 1)
PieChartUtil.getPieChart(chartDisk, it.disk.used, it.disk.free, 2)
daysView.text = "Running " + it.days.toString() + "days"
}
return this
}
|
gpl-3.0
|
313a99196cf90a57b627e3c04ba59454
| 41.061224 | 97 | 0.724891 | 3.541237 | false | false | false | false |
siosio/intellij-community
|
platform/lang-impl/src/com/intellij/codeInspection/ex/ApplicationInspectionProfileManager.kt
|
2
|
4498
|
// 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.codeInspection.ex
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInsight.daemon.InspectionProfileConvertor
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.codeInsight.daemon.impl.SeveritiesProvider
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.processOpenedProjects
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.IconLoader
import com.intellij.profile.codeInspection.InspectionProfileManager
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.serviceContainer.NonInjectable
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
@State(name = "InspectionProfileManager", storages = [Storage("editor.xml")], additionalExportDirectory = InspectionProfileManager.INSPECTION_DIR)
open class ApplicationInspectionProfileManager @TestOnly @NonInjectable constructor(schemeManagerFactory: SchemeManagerFactory) : ApplicationInspectionProfileManagerBase(schemeManagerFactory),
PersistentStateComponent<Element> {
open val converter: InspectionProfileConvertor
get() = InspectionProfileConvertor(this)
val rootProfileName: String
get() = schemeManager.currentSchemeName ?: DEFAULT_PROFILE_NAME
constructor() : this(SchemeManagerFactory.getInstance())
companion object {
@JvmStatic
fun getInstanceImpl() = service<InspectionProfileManager>() as ApplicationInspectionProfileManager
private fun registerProvidedSeverities() {
val map = HashMap<String, HighlightInfoType>()
SeveritiesProvider.EP_NAME.forEachExtensionSafe { provider ->
for (t in provider.severitiesHighlightInfoTypes) {
val highlightSeverity = t.getSeverity(null)
val icon = when (t) {
is HighlightInfoType.Iconable -> {
IconLoader.createLazy { (t as HighlightInfoType.Iconable).icon }
}
else -> null
}
map.put(highlightSeverity.name, t)
HighlightDisplayLevel.registerSeverity(highlightSeverity, t.attributesKey, icon)
}
}
if (map.isNotEmpty()) {
SeverityRegistrar.registerStandard(map)
}
}
}
init {
registerProvidedSeverities()
}
@TestOnly
fun forceInitProfiles(flag: Boolean) {
LOAD_PROFILES = flag
profilesAreInitialized
}
override fun getState(): Element? {
val state = Element("state")
severityRegistrar.writeExternal(state)
return state
}
override fun loadState(state: Element) {
severityRegistrar.readExternal(state)
}
override fun fireProfileChanged(profile: InspectionProfileImpl) {
processOpenedProjects { project ->
ProjectInspectionProfileManager.getInstance(project).fireProfileChanged(profile)
}
}
@Throws(IOException::class, JDOMException::class)
override fun loadProfile(path: String): InspectionProfileImpl? {
try {
return super.loadProfile(path)
}
catch (e: IOException) {
throw e
}
catch (e: JDOMException) {
throw e
}
catch (ignored: Exception) {
val file = Paths.get(path)
ApplicationManager.getApplication().invokeLater({
Messages.showErrorDialog(
InspectionsBundle.message("inspection.error.loading.message", 0, file),
InspectionsBundle.message("inspection.errors.occurred.dialog.title"))
}, ModalityState.NON_MODAL)
}
return getProfile(path, false)
}
}
|
apache-2.0
|
58e8e8c8a9450e6f2325639a65b61b57
| 38.80531 | 192 | 0.706092 | 5.373955 | false | false | false | false |
siosio/intellij-community
|
platform/util-ex/src/com/intellij/util/ResettableLazy.kt
|
1
|
1543
|
// 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.
@file:Suppress("LocalVariableName", "ClassName")
package com.intellij.util
import java.io.Serializable
interface ResettableLazy<out T> : Lazy<T> {
fun reset()
}
fun <T> resettableLazy(initializer: () -> T): ResettableLazy<T> = ResettableSynchronizedLazy(initializer)
private object UNINITIALIZED_VALUE
private class ResettableSynchronizedLazy<out T>(initializer: () -> T, lock: Any? = null) : ResettableLazy<T>, Serializable {
private var initializer: (() -> T)? = initializer
@Volatile
private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
override fun reset() {
synchronized(lock) {
_value = UNINITIALIZED_VALUE
}
}
override val value: T
get() {
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
} else {
val typedValue = initializer!!()
_value = typedValue
typedValue
}
}
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value is not initialized."
}
|
apache-2.0
|
3ef4af1c6f1444a2450c4c4fa3253cc8
| 28.692308 | 140 | 0.653273 | 4.227397 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/create/CreateImageFactory.kt
|
2
|
1468
|
package com.github.kerubistan.kerub.planner.steps.storage.fs.create
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import com.github.kerubistan.kerub.model.collection.HostDataCollection
import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.storage.fs.base.AbstractCreateFileVirtualStorageFactory
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import com.github.kerubistan.kerub.utils.junix.qemu.QemuImg
import kotlin.reflect.KClass
object CreateImageFactory : AbstractCreateFileVirtualStorageFactory<CreateImage>() {
override val problemHints = setOf<KClass<out Problem>>()
override val expectationHints = setOf<KClass<out Expectation>>()
override val requiredOsCommand: OsCommand
get() = QemuImg
override
fun createStep(
storage: VirtualStorageDevice, hostData: HostDataCollection, mount: FsStorageCapability
): CreateImage =
CreateImage(
disk = storage,
host = hostData.stat,
format = (storage.expectations.firstOrNull { it is StorageAvailabilityExpectation }
as StorageAvailabilityExpectation?)?.format
?: VirtualDiskFormat.qcow2,
capability = mount
)
}
|
apache-2.0
|
1d1b604f246412be22ce9bd6c848b538
| 39.805556 | 104 | 0.816757 | 4.304985 | false | false | false | false |
loxal/FreeEthereum
|
free-ethereum-core/src/main/java/org/ethereum/manager/AdminInfo.kt
|
1
|
2310
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.manager
import org.springframework.stereotype.Component
import java.util.*
import javax.annotation.PostConstruct
/**
* @author Roman Mandeleil
* *
* @since 11.12.2014
*/
@Component
class AdminInfo {
private val blockExecTime = LinkedList<Long>()
var startupTimeStamp: Long = 0
private set
var isConsensus = true
private set
@PostConstruct
fun init() {
startupTimeStamp = System.currentTimeMillis()
}
fun lostConsensus() {
isConsensus = false
}
fun addBlockExecTime(time: Long) {
while (blockExecTime.size > ExecTimeListLimit) {
blockExecTime.removeAt(0)
}
blockExecTime.add(time)
}
val execAvg: Long?
get() {
if (blockExecTime.isEmpty()) return 0L
val sum: Long = blockExecTime.sum()
return sum / blockExecTime.size
}
fun getBlockExecTime(): List<Long> {
return blockExecTime
}
companion object {
private val ExecTimeListLimit = 10000
}
}
|
mit
|
cfa4dd26c79363f5bc684d43a50b3f84
| 28.240506 | 83 | 0.68961 | 4.285714 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddModifierFix.kt
|
2
|
6447
|
// 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.quickfix
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.psi.isInlineOrValue
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.quickFixesPsiBasedFactory
import org.jetbrains.kotlin.idea.inspections.KotlinUniversalQuickFix
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
open class AddModifierFix(
element: KtModifierListOwner,
@SafeFieldForPreview
protected val modifier: KtModifierKeywordToken
) : KotlinCrossLanguageQuickFixAction<KtModifierListOwner>(element), KotlinUniversalQuickFix {
override fun getText(): String {
val element = element ?: return ""
if (modifier in modalityModifiers || modifier in KtTokens.VISIBILITY_MODIFIERS || modifier == KtTokens.CONST_KEYWORD) {
return KotlinBundle.message("fix.add.modifier.text", RemoveModifierFixBase.getElementName(element), modifier.value)
}
return KotlinBundle.message("fix.add.modifier.text.generic", modifier.value)
}
override fun getFamilyName() = KotlinBundle.message("fix.add.modifier.family")
protected fun invokeOnElement(element: KtModifierListOwner?) {
element?.addModifier(modifier)
if (modifier == KtTokens.ABSTRACT_KEYWORD && (element is KtProperty || element is KtNamedFunction)) {
element.containingClass()?.run {
if (!hasModifier(KtTokens.ABSTRACT_KEYWORD) && !hasModifier(KtTokens.SEALED_KEYWORD)) {
addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
if (modifier == KtTokens.NOINLINE_KEYWORD) {
element?.removeModifier(KtTokens.CROSSINLINE_KEYWORD)
}
}
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
val originalElement = element
invokeOnElement(originalElement)
}
// TODO: consider checking if this fix is available by testing if the [element] can be refactored by calling
// FIR version of [org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtilKt#canRefactor]
override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean = element != null
interface Factory<T : AddModifierFix> {
fun createFactory(modifier: KtModifierKeywordToken): QuickFixesPsiBasedFactory<PsiElement> {
return createFactory(modifier, KtModifierListOwner::class.java)
}
fun <T : KtModifierListOwner> createFactory(
modifier: KtModifierKeywordToken,
modifierOwnerClass: Class<T>
): QuickFixesPsiBasedFactory<PsiElement> {
return quickFixesPsiBasedFactory { e ->
val modifierListOwner =
PsiTreeUtil.getParentOfType(e, modifierOwnerClass, false) ?: return@quickFixesPsiBasedFactory emptyList()
listOfNotNull(createIfApplicable(modifierListOwner, modifier))
}
}
fun createIfApplicable(modifierListOwner: KtModifierListOwner, modifier: KtModifierKeywordToken): T? {
when (modifier) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD -> {
if (modifierListOwner is KtObjectDeclaration) return null
if (modifierListOwner is KtEnumEntry) return null
if (modifierListOwner is KtDeclaration && modifierListOwner !is KtClass) {
val parentClassOrObject = modifierListOwner.containingClassOrObject ?: return null
if (parentClassOrObject is KtObjectDeclaration) return null
if (parentClassOrObject is KtEnumEntry) return null
}
if (modifier == KtTokens.ABSTRACT_KEYWORD
&& modifierListOwner is KtClass
&& modifierListOwner.isInlineOrValue()
) return null
}
KtTokens.INNER_KEYWORD -> {
if (modifierListOwner is KtObjectDeclaration) return null
if (modifierListOwner is KtClass) {
if (modifierListOwner.isInterface() ||
modifierListOwner.isSealed() ||
modifierListOwner.isEnum() ||
modifierListOwner.isData() ||
modifierListOwner.isAnnotation()
) return null
}
}
}
return createModifierFix(modifierListOwner, modifier)
}
fun createModifierFix(element: KtModifierListOwner, modifier: KtModifierKeywordToken): T
}
companion object : Factory<AddModifierFix> {
val addAbstractModifier = AddModifierFix.createFactory(KtTokens.ABSTRACT_KEYWORD)
val addAbstractToContainingClass = AddModifierFix.createFactory(KtTokens.ABSTRACT_KEYWORD, KtClassOrObject::class.java)
val addOpenToContainingClass = AddModifierFix.createFactory(KtTokens.OPEN_KEYWORD, KtClassOrObject::class.java)
val addFinalToProperty = AddModifierFix.createFactory(KtTokens.FINAL_KEYWORD, KtProperty::class.java)
val addInnerModifier = createFactory(KtTokens.INNER_KEYWORD)
val addOverrideModifier = createFactory(KtTokens.OVERRIDE_KEYWORD)
val modifiersWithWarning: Set<KtModifierKeywordToken> = setOf(KtTokens.ABSTRACT_KEYWORD, KtTokens.FINAL_KEYWORD)
private val modalityModifiers = modifiersWithWarning + KtTokens.OPEN_KEYWORD
override fun createModifierFix(element: KtModifierListOwner, modifier: KtModifierKeywordToken): AddModifierFix =
AddModifierFix(element, modifier)
}
}
|
apache-2.0
|
ee4cd6da723f5d088a04cdb6947c1d7d
| 50.576 | 158 | 0.688227 | 5.610966 | false | false | false | false |
howard-e/just-quotes-kt
|
app/src/main/java/com/heed/justquotes/models/Quote.kt
|
1
|
889
|
package com.heed.justquotes.models
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
/**
* @author Howard.
*/
open class Quote() : RealmObject() {
@PrimaryKey
@Index
lateinit var id: String
@Required
lateinit var quote: String
var author: String? = null
var imgUrl: String? = null
constructor(id: String, quote: String, author: String?, imgUrl: String?) : this() {
this.id = id
this.quote = quote
this.author = author
this.imgUrl = imgUrl
}
override fun equals(other: Any?): Boolean {
if (other is Quote) if (quote == other.quote) return true
return super.equals(other)
}
override fun toString(): String {
return "Quote(id='$id', quote='$quote', author=$author, imgUrl=$imgUrl)"
}
}
|
apache-2.0
|
d7625df05c4eb27dd18cbb03fa4843b6
| 21.820513 | 87 | 0.640045 | 3.986547 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/settings-repository/src/IcsSettings.kt
|
11
|
2932
|
// 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.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.Time
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.io.write
import java.nio.file.Files
import java.nio.file.Path
private const val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: Path) {
val serialized = ObjectMapper().writer(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size <= 2) {
Files.delete(settingsFile)
}
else {
settingsFile.write(serialized)
}
}
fun loadSettings(settingsFile: Path): IcsSettings {
if (!Files.exists(settingsFile)) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class IcsSettings {
var commitDelay = DEFAULT_COMMIT_DELAY
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
var includeHostIntoCommitMessage = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
val path: String?
@JsonIgnore
get() {
var fileName = PathUtilRt.getFileName(url ?: return null)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length - suffix.length)
}
// the convention is that the .git extension should be used for bare repositories
return "${sanitizeFileName(fileName)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
|
apache-2.0
|
ccf905cbb795214a661bf28c0e3ec413
| 29.873684 | 140 | 0.736357 | 4.188571 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/notification/impl/actions/TestNotificationRemindLaterHandler.kt
|
9
|
2408
|
// 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.notification.impl.actions
import com.intellij.notification.Notification
import com.intellij.notification.NotificationRemindLaterHandler
import com.intellij.notification.NotificationRemindLaterHandlerWithState
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.ui.Messages
import com.intellij.util.xmlb.annotations.CollectionBean
import org.jdom.Element
/**
* @author Alexander Lobas
*/
class TestNotificationRemindLaterHandler : NotificationRemindLaterHandler {
override fun getID(): String {
return "ZZZ_1"
}
override fun getActionsState(notification: Notification): Element {
val element = Element("ActionNames")
for ((index, action) in notification.actions.withIndex()) {
element.setAttribute("action$index", action.templateText)
}
return element
}
override fun setActions(notification: Notification, element: Element): Boolean {
var index = 0
while (true) {
val action = element.getAttributeValue("action$index")
if (action == null) {
return true
}
notification.addAction(object : AnAction(action) {
override fun actionPerformed(e: AnActionEvent) {
Messages.showInfoMessage("Run from Remind Later", "Action $action")
}
})
index++
}
}
}
class ActionsState : BaseState() {
@get:CollectionBean
val actions by list<String>()
}
class TestNotificationRemindLaterHandler2 : NotificationRemindLaterHandlerWithState<ActionsState>(ActionsState::class.java) {
override fun getID() = "ZZZ_2"
override fun getState(notification: Notification): ActionsState {
val state = ActionsState()
for (action in notification.actions) {
state.actions.add(action.templateText!!)
}
return state
}
override fun setState(notification: Notification, state: ActionsState): Boolean {
for (action in state.actions) {
notification.addAction(object : AnAction(action) {
override fun actionPerformed(e: AnActionEvent) {
Messages.showInfoMessage("Run2 from Remind Later", "Action $action")
}
})
}
return true
}
}
|
apache-2.0
|
4ec5000b5eb548279a2a0db399cc7fec
| 31.12 | 158 | 0.72799 | 4.475836 | false | false | false | false |
android/compose-samples
|
Reply/app/src/main/java/com/example/reply/ui/components/ReplyAppBars.kt
|
1
|
5404
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.reply.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.reply.R
import com.example.reply.data.Email
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReplySearchBar(modifier: Modifier = Modifier) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(top = 24.dp, bottom = 16.dp, start = 16.dp, end = 16.dp)
.background(MaterialTheme.colorScheme.surface, CircleShape),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = stringResource(id = R.string.search),
modifier = Modifier.padding(start = 16.dp),
tint = MaterialTheme.colorScheme.outline
)
Text(
text = stringResource(id = R.string.search_replies),
modifier = Modifier
.weight(1f)
.padding(16.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.outline
)
ReplyProfileImage(
drawableResource = R.drawable.avatar_6,
description = stringResource(id = R.string.profile),
modifier = Modifier
.padding(12.dp)
.size(32.dp)
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EmailDetailAppBar(
email: Email,
isFullScreen: Boolean,
modifier: Modifier = Modifier,
onBackPressed: () -> Unit
) {
TopAppBar(
modifier = modifier,
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = MaterialTheme.colorScheme.inverseOnSurface
),
title = {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = if (isFullScreen) Alignment.CenterHorizontally
else Alignment.Start
) {
Text(
text = email.subject,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
modifier = Modifier.padding(top = 4.dp),
text = "${email.threads.size} ${stringResource(id = R.string.messages)}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.outline
)
}
},
navigationIcon = {
if (isFullScreen) {
FilledIconButton(
onClick = onBackPressed,
modifier = Modifier.padding(8.dp),
colors = IconButtonDefaults.filledIconButtonColors(
containerColor = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface
)
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(id = R.string.back_button),
modifier = Modifier.size(14.dp)
)
}
}
},
actions = {
IconButton(
onClick = { /*TODO*/ },
) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(id = R.string.more_options_button),
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
)
}
|
apache-2.0
|
6255c32d59a1ae94bcfd1bbbf118075c
| 36.79021 | 93 | 0.628793 | 5.088512 | false | false | false | false |
smmribeiro/intellij-community
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ExternalSystemActionsCollector.kt
|
2
|
3206
|
// 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.openapi.externalSystem.statistics
import com.intellij.execution.Executor
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsEventLogGroup
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
class ExternalSystemActionsCollector : CounterUsagesCollector() {
enum class ActionId {
RunExternalSystemTaskAction,
ExecuteExternalSystemRunConfigurationAction
}
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("build.tools.actions", 6)
val EXTERNAL_SYSTEM_ID = EventFields.StringValidatedByEnum("system_id", "build_tools")
private val ACTION_EXECUTOR_FIELD = EventFields.StringValidatedByCustomRule("executor", "run_config_executor")
private val DELEGATE_ACTION_ID = EventFields.Enum<ActionId>("action_id")
private val ACTION_INVOKED = ActionsEventLogGroup.registerActionEvent(GROUP, "action.invoked", EXTERNAL_SYSTEM_ID)
private val DELEGATE_ACTION_INVOKED = GROUP.registerVarargEvent(
"action.invoked", DELEGATE_ACTION_ID, EventFields.ActionPlace,
ActionsEventLogGroup.CONTEXT_MENU, ACTION_EXECUTOR_FIELD, EXTERNAL_SYSTEM_ID
)
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
actionId: ActionId,
place: String?,
isFromContextMenu: Boolean,
executor: Executor? = null) {
val data: MutableList<EventPair<*>> = arrayListOf(DELEGATE_ACTION_ID.with(actionId))
if (place != null) {
data.add(EventFields.ActionPlace.with(place))
data.add(ActionsEventLogGroup.CONTEXT_MENU.with(isFromContextMenu))
}
executor?.let { data.add(ACTION_EXECUTOR_FIELD.with(it.id)) }
data.add(EXTERNAL_SYSTEM_ID.with(anonymizeSystemId(systemId)))
DELEGATE_ACTION_INVOKED.log(project, *data.toTypedArray())
}
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
action: AnAction,
event: AnActionEvent) {
ActionsCollectorImpl.record(ACTION_INVOKED, project, action, event, listOf(EXTERNAL_SYSTEM_ID with anonymizeSystemId(systemId)))
}
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
action: ActionId,
event: AnActionEvent,
executor : Executor? = null) {
trigger(project, systemId, action, event.place, event.isFromContextMenu, executor)
}
}
}
|
apache-2.0
|
d4aaf5d5413c13d4092af033f61054ba
| 42.917808 | 140 | 0.730505 | 4.687135 | false | false | false | false |
stakkato95/KotlinDroidPlayer
|
KMusic/app/src/main/java/com/github/stakkato95/kmusic/screen/main/widget/VerticalViewPager.kt
|
1
|
1712
|
package com.github.stakkato95.kmusic.screen.main.widget
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
/**
* Created by artsiomkaliaha on 14.07.17.
*/
class VerticalViewPager : ViewPager {
val normalizedScrollY: Float get() = scrollX / width.toFloat() * height
private var canInterceptTouchEvents = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
init {
setPageTransformer(true, VerticalViewPagerTransformer())
overScrollMode = View.OVER_SCROLL_NEVER
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
if (!canInterceptTouchEvents) {
return false
}
val isIntercepted = super.onInterceptTouchEvent(swapXY(ev))
swapXY(ev)
return isIntercepted
}
override fun onTouchEvent(ev: MotionEvent?) = super.onTouchEvent(swapXY(ev))
fun swapXY(motionEvent: MotionEvent?): MotionEvent? {
if (motionEvent == null) return motionEvent
val newX = motionEvent.y / height * width
val newY = motionEvent.x / width * height
motionEvent.setLocation(newX, newY)
return motionEvent
}
class VerticalViewPagerTransformer : ViewPager.PageTransformer {
override fun transformPage(page: View, position: Float) {
if (position <= 1) {
page.translationX = page.width * -position
page.translationY = page.height * position
} else {
page.alpha = 0.0f
}
}
}
}
|
gpl-3.0
|
7e9240836e4544fe3f6a5cd901c13632
| 26.190476 | 80 | 0.658879 | 4.627027 | false | false | false | false |
sksamuel/ktest
|
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/listeners/spec/instanceperleaf/FinalizeSpecTest.kt
|
1
|
1733
|
package com.sksamuel.kotest.listeners.spec.instanceperleaf
import io.kotest.core.listeners.FinalizeSpecListener
import io.kotest.core.listeners.TestListener
import io.kotest.core.spec.AutoScan
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.Spec
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.matchers.shouldBe
import java.util.concurrent.atomic.AtomicInteger
import kotlin.reflect.KClass
private val counter = AtomicInteger(0)
@AutoScan
class FinalizeSpecTestListener1 : TestListener {
override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {
if (kclass == FinalizeSpecTest::class) {
counter.incrementAndGet()
}
}
}
@AutoScan
class FinalizeSpecTestListener2 : FinalizeSpecListener {
override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {
if (kclass == FinalizeSpecTest::class) {
counter.incrementAndGet()
}
}
override val name: String = "FinalizeSpecTestListener2"
}
class FinalizeSpecTest : FunSpec() {
override fun isolationMode(): IsolationMode = IsolationMode.InstancePerLeaf
init {
afterProject {
// both listeners should have fired
counter.get() shouldBe 8
}
// will be added once per instance created
finalizeSpec {
counter.incrementAndGet()
}
test("ignored test").config(enabled = false) {}
test("a").config(enabled = true) {}
test("b").config(enabled = true) {}
test("c").config(enabled = true) {}
context("d") {
test("e").config(enabled = true) {}
}
}
}
|
mit
|
5f8391f3771e347655f11fc9dbf0cd67
| 27.409836 | 100 | 0.701673 | 4.106635 | false | true | false | false |
sksamuel/ktest
|
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/describe/DescribeSpecExample.kt
|
1
|
2619
|
package com.sksamuel.kotest.specs.describe
import io.kotest.assertions.fail
import io.kotest.core.spec.style.DescribeSpec
import kotlin.time.Duration
import kotlin.time.milliseconds
class DescribeSpecExample : DescribeSpec() {
init {
describe("some thing") {
it("test name") {
// test here
}
xit("disabled test") {
fail("should not be invoked")
}
describe("a nested describe!") {
it("test name") {
// test here
}
xit("disabled test") {
fail("should not be invoked")
}
}
describe("with some describe") {
it("test name") {
// test here
}
it("test name 2").config(enabled = false) {
// test here
}
describe("with some context") {
it("test name") {
// test here
}
it("test name 2").config(timeout = Duration.milliseconds(1512)) {
// test here
}
}
}
context("a context is like a describe") {
it("test name") {
// test here
}
}
xcontext("a disabled context") {
it("test name") {
// test here
}
}
xdescribe("disabled describe") {
fail("should not be invoked")
}
}
describe("some other thing") {
describe("with some describe") {
it("test name") {
// test here
}
it("test name 2").config(enabled = true) {
// test here
}
describe("with some context") {
it("test name") {
// test here
}
it("test name 2").config(timeout = Duration.milliseconds(1512)) {
// test here
}
}
}
}
xdescribe("disabled top level describe") {
fail("should not be invoked")
}
context("top level context") {
it("test name") {
// test here
}
xit("disabled test with config").config(invocations = 3) {
fail("should not be invoked")
}
}
xcontext("disabled top level context") {
fail("should not be invoked")
}
it("test without describe") {
// test here
}
xit("disabled test without describe") {
fail("should not be invoked")
}
}
}
|
mit
|
3f583598f5a474953e7f958fec3f135a
| 24.930693 | 80 | 0.439099 | 5.017241 | false | true | false | false |
parkee/messenger-send-api-client
|
src/main/kotlin/com/github/parkee/messenger/model/request/RequestPayload.kt
|
1
|
1314
|
package com.github.parkee.messenger.model.request
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class RequestPayload(
@JsonProperty("template_type") val templateType: TemplateType? = null,
@JsonProperty("text") val text: String? = null,
@JsonProperty("url") val url: String? = null,
@JsonProperty("buttons") val buttons: List<Button>? = null,
@JsonProperty("elements") val elements: List<Element>? = null,
@JsonProperty("recipient_name") val recipientName: String? = null,
@JsonProperty("order_number") val orderNumber: String? = null,
@JsonProperty("currency") val currencyIsoCode: String? = null,
@JsonProperty("payment_method") val paymentMethod: String? = null,
@JsonProperty("order_url") val orderUrl: String? = null,
@JsonProperty("timestamp") val timestamp: Long? = null,
@JsonProperty("address") val orderAddress: OrderAddress? = null,
@JsonProperty("summary") val orderSummary: OrderSummary? = null,
@JsonProperty("adjustments") val adjustments: List<PaymentAdjustment>? = null
)
|
mit
|
5093b793117212cd92c7a63c85809a68
| 53.791667 | 85 | 0.712329 | 4.409396 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-superheroes
|
app/src/main/java/com/example/superheroes/ui/theme/Type.kt
|
1
|
1555
|
/*
* 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 com.example.superheroes.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.superheroes.R
val Cabin = FontFamily(
Font(R.font.cabin_regular, FontWeight.Normal),
Font(R.font.cabin_bold, FontWeight.Bold)
)
// Set of Material typography styles to start with
val Typography = Typography(
defaultFontFamily = Cabin,
h1 = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 30.sp
),
h2 = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 20.sp
),
h3 = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 20.sp
),
body1 = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
)
|
apache-2.0
|
3e425915bdf1c93ddf0eb33b7908c8ee
| 29.509804 | 75 | 0.71254 | 3.966837 | false | false | false | false |
MaTriXy/gradle-play-publisher-1
|
play/android-publisher/src/test/kotlin/com/github/triplet/gradle/androidpublisher/internal/DefaultEditManagerTest.kt
|
1
|
20102
|
package com.github.triplet.gradle.androidpublisher.internal
import com.github.triplet.gradle.androidpublisher.EditManager
import com.github.triplet.gradle.androidpublisher.ReleaseNote
import com.github.triplet.gradle.androidpublisher.ReleaseStatus
import com.github.triplet.gradle.androidpublisher.ResolutionStrategy
import com.google.api.client.googleapis.testing.json.GoogleJsonResponseExceptionFactoryTesting
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.androidpublisher.model.Apk
import com.google.api.services.androidpublisher.model.AppDetails
import com.google.api.services.androidpublisher.model.Bundle
import com.google.api.services.androidpublisher.model.Image
import com.google.api.services.androidpublisher.model.Listing
import com.google.api.services.androidpublisher.model.LocalizedText
import com.google.api.services.androidpublisher.model.Track
import com.google.api.services.androidpublisher.model.TrackRelease
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import java.io.File
class DefaultEditManagerTest {
private var mockPublisher = mock(InternalPlayPublisher::class.java)
private var mockTracks = mock(TrackManager::class.java)
private var edits: EditManager = DefaultEditManager(mockPublisher, mockTracks, "edit-id")
private var mockFile = mock(File::class.java)
@Test
fun `uploadBundle forwards config to track manager`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenReturn(Bundle().apply {
versionCode = 888
})
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = null,
strategy = ResolutionStrategy.FAIL,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockTracks).update(TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888L),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
))
}
@Test
fun `uploadBundle skips mapping file upload when null`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenReturn(Bundle().apply {
versionCode = 888
})
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = null,
strategy = ResolutionStrategy.FAIL,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockPublisher, never()).uploadDeobfuscationFile(any(), any(), anyInt())
}
@Test
fun `uploadBundle skips mapping file upload when empty`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenReturn(Bundle().apply {
versionCode = 888
})
`when`(mockFile.length()).thenReturn(0)
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockPublisher, never()).uploadDeobfuscationFile(any(), any(), anyInt())
}
@Test
fun `uploadBundle uploads mapping file when non-empty`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenReturn(Bundle().apply {
versionCode = 888
})
`when`(mockFile.length()).thenReturn(1)
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockPublisher).uploadDeobfuscationFile(eq("edit-id"), eq(mockFile), eq(888))
}
@Test
fun `uploadBundle fails silently when conflict occurs with ignore strategy`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenThrow(
GoogleJsonResponseExceptionFactoryTesting.newMock(
JacksonFactory.getDefaultInstance(), 400, "apkUpgradeVersionConflict"))
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.IGNORE,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockTracks, never()).update(any())
}
@Test
fun `uploadBundle fails when conflict occurs with fail strategy`() {
`when`(mockPublisher.uploadBundle(any(), any())).thenThrow(
GoogleJsonResponseExceptionFactoryTesting.newMock(
JacksonFactory.getDefaultInstance(), 400, "apkUpgradeVersionConflict"))
assertThrows<IllegalStateException> {
edits.uploadBundle(
bundleFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
}
}
@Test
fun `uploadApk doesn't update tracks`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
val versionCode = edits.uploadApk(
apkFile = mockFile,
mappingFile = null,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockTracks, never()).update(any())
assertThat(versionCode).isEqualTo(888)
}
@Test
fun `uploadApk skips mapping file upload when null`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockPublisher, never()).uploadDeobfuscationFile(any(), any(), anyInt())
}
@Test
fun `uploadApk skips mapping file upload when empty`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
`when`(mockFile.length()).thenReturn(0)
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockPublisher, never()).uploadDeobfuscationFile(any(), any(), anyInt())
}
@Test
fun `uploadApk uploads mapping file when non-empty`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
`when`(mockFile.length()).thenReturn(1)
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockPublisher).uploadDeobfuscationFile(eq("edit-id"), eq(mockFile), eq(888))
}
@Test
fun `uploadApk fails silently when conflict occurs with ignore strategy`() {
`when`(mockPublisher.uploadApk(any(), any())).thenThrow(
GoogleJsonResponseExceptionFactoryTesting.newMock(
JacksonFactory.getDefaultInstance(), 400, "apkUpgradeVersionConflict"))
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.IGNORE,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockTracks, never()).update(any())
}
@Test
fun `uploadApk fails when conflict occurs with fail strategy`() {
`when`(mockPublisher.uploadApk(any(), any())).thenThrow(
GoogleJsonResponseExceptionFactoryTesting.newMock(
JacksonFactory.getDefaultInstance(), 400, "apkUpgradeVersionConflict"))
assertThrows<IllegalStateException> {
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
}
}
@Test
fun `uploadApk attaches OBBs when provided`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = 123,
patchObbRetainable = 321
)
verify(mockPublisher).attachObb(eq("edit-id"), eq("main"), eq(888), eq(123))
verify(mockPublisher).attachObb(eq("edit-id"), eq("patch"), eq(888), eq(321))
}
@Test
fun `uploadApk ignores OBBs when not provided`() {
`when`(mockPublisher.uploadApk(any(), any())).thenReturn(Apk().apply {
versionCode = 888
})
edits.uploadApk(
apkFile = mockFile,
mappingFile = mockFile,
strategy = ResolutionStrategy.FAIL,
mainObbRetainable = null,
patchObbRetainable = null
)
verify(mockPublisher, never()).attachObb(any(), any(), anyInt(), anyInt())
verify(mockPublisher, never()).attachObb(any(), any(), anyInt(), anyInt())
}
@Test
fun `publishApk ignores empty version codes`() {
edits.publishApk(
versionCodes = emptyList(),
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockTracks, never()).update(any())
}
@Test
fun `publishApk forwards config to track manager`() {
edits.publishApk(
versionCodes = listOf(888L),
didPreviousBuildSkipCommit = false,
trackName = "alpha",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockTracks).update(TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888L),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
))
}
@Test
fun `promoteRelease forwards config to track manager`() {
edits.promoteRelease(
promoteTrackName = "alpha",
fromTrackName = "internal",
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
verify(mockTracks).promote(TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
releaseName = "relname",
releaseNotes = mapOf("locale" to "notes"),
userFraction = .88,
updatePriority = 3,
retainableArtifacts = listOf(777)
)
))
}
@Test
fun `findMaxAppVersionCode returns 1 on empty tracks`() {
`when`(mockTracks.findHighestTrack()).thenReturn(null)
val max = edits.findMaxAppVersionCode()
assertThat(max).isEqualTo(1)
}
@Test
fun `findMaxAppVersionCode returns 1 on null releases`() {
`when`(mockTracks.findHighestTrack()).thenReturn(Track())
val max = edits.findMaxAppVersionCode()
assertThat(max).isEqualTo(1)
}
@Test
fun `findMaxAppVersionCode succeeds with single track, single release, singe version code`() {
`when`(mockTracks.findHighestTrack()).thenReturn(Track().apply {
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(5)
}
)
})
val max = edits.findMaxAppVersionCode()
assertThat(max).isEqualTo(5)
}
@Test
fun `findMaxAppVersionCode succeeds with single track, single release, multi version code`() {
`when`(mockTracks.findHighestTrack()).thenReturn(Track().apply {
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(5, 4, 8, 7)
}
)
})
val max = edits.findMaxAppVersionCode()
assertThat(max).isEqualTo(8)
}
@Test
fun `findMaxAppVersionCode succeeds with single track, multi release, multi version code`() {
`when`(mockTracks.findHighestTrack()).thenReturn(Track().apply {
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(5, 4, 8, 7)
},
TrackRelease().apply {
versionCodes = listOf(85, 7, 36, 5)
}
)
})
val max = edits.findMaxAppVersionCode()
assertThat(max).isEqualTo(85)
}
@Test
fun `findLeastStableTrackName returns null on null track`() {
`when`(mockTracks.findHighestTrack()).thenReturn(null)
val highest = edits.findLeastStableTrackName()
assertThat(highest).isNull()
}
@Test
fun `findLeastStableTrackName returns track name`() {
`when`(mockTracks.findHighestTrack()).thenReturn(Track().apply { track = "internal" })
val highest = edits.findLeastStableTrackName()
assertThat(highest).isEqualTo("internal")
}
@Test
fun `getReleaseNotes returns data from publisher`() {
`when`(mockTracks.getReleaseNotes()).thenReturn(mapOf(
"alpha" to listOf(LocalizedText().apply {
language = "en-US"
text = "foobar"
}),
"production" to listOf(
LocalizedText().apply {
language = "en-US"
text = "prod foobar"
},
LocalizedText().apply {
language = "fr-FR"
text = "french foobar"
}
)
))
val notes = edits.getReleaseNotes()
assertThat(notes).containsExactly(
ReleaseNote("alpha", "en-US", "foobar"),
ReleaseNote("production", "en-US", "prod foobar"),
ReleaseNote("production", "fr-FR", "french foobar")
)
}
@Test
fun `getImages returns data from publisher`() {
`when`(mockPublisher.getImages(any(), any(), any())).thenReturn(listOf(
Image().setSha256("a").setUrl("ha"),
Image().setSha256("b").setUrl("hb"),
Image().setSha256("c").setUrl("hc")
))
val result = edits.getImages("en-US", "phoneScreenshots")
assertThat(result.map { it.sha256 }).containsExactly("a", "b", "c")
assertThat(result.map { it.url }).containsExactly("ha=h16383", "hb=h16383", "hc=h16383")
}
@Test
fun `publishAppDetails forwards data to publisher`() {
edits.publishAppDetails("lang", "email", "phone", "website")
verify(mockPublisher).updateDetails(eq("edit-id"), eq(AppDetails().apply {
defaultLanguage = "lang"
contactEmail = "email"
contactPhone = "phone"
contactWebsite = "website"
}))
}
@Test
fun `publishListing forwards data to publisher`() {
edits.publishListing("lang", "title", "short", "full", "url")
verify(mockPublisher).updateListing(eq("edit-id"), eq("lang"), eq(Listing().apply {
title = "title"
shortDescription = "short"
fullDescription = "full"
video = "url"
}))
}
@Test
fun `publishImages forwards data to publisher`() {
edits.publishImages("lang", "phoneScreenshots", listOf(mockFile))
verify(mockPublisher).deleteImages(eq("edit-id"), eq("lang"), eq("phoneScreenshots"))
verify(mockPublisher).uploadImage(
eq("edit-id"), eq("lang"), eq("phoneScreenshots"), eq(mockFile))
}
}
|
mit
|
80fe3eb89e6386b277ae3e704f8eedb3
| 34.896429 | 98 | 0.558701 | 5.022989 | false | true | false | false |
koma-im/koma
|
src/main/kotlin/koma/gui/view/window/userinfo/actions/updateAvatar.kt
|
1
|
1900
|
package koma.gui.view.window.userinfo.actions
import javafx.stage.FileChooser
import koma.controller.requests.media.uploadFile
import koma.koma_app.appState
import koma.matrix.user.AvatarUrl
import koma.util.failureOrThrow
import koma.util.getOrThrow
import koma.util.onFailure
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.javafx.JavaFx
import kotlinx.coroutines.launch
import link.continuum.desktop.gui.JFX
import org.controlsfx.control.Notifications
fun chooseUpdateUserAvatar() {
val api = appState.apiClient
api ?: return
val dialog = FileChooser()
dialog.title = "Upload a new avatar"
val file = dialog.showOpenDialog(JFX.primaryStage)
file ?: return
GlobalScope.launch {
val upload = uploadFile(api, file)
when {
upload.isFailure -> {
val message = upload.failureOrThrow().message
launch(Dispatchers.JavaFx) {
Notifications.create()
.title("Failed to upload new avatar")
.text(message.toString())
.owner(JFX.primaryStage)
.showWarning()
}
}
upload.isSuccess -> {
val data = AvatarUrl(upload.getOrThrow().content_uri)
val result = api.updateAvatar(api.userId, data)
result.onFailure {
val message = it.message
launch(Dispatchers.JavaFx) {
Notifications.create()
.title("Failed to set new avatar")
.text(message.toString())
.owner(JFX.primaryStage)
.showWarning()
}
}
}
}
}
}
|
gpl-3.0
|
2e8586845aecf8d692dad7feb60cec0f
| 34.849057 | 69 | 0.558947 | 5.263158 | false | false | false | false |
slisson/intellij-community
|
platform/configuration-store-impl/src/StreamProvider.kt
|
11
|
2083
|
/*
* Copyright 2000-2015 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.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import java.io.InputStream
public interface StreamProvider {
public open val enabled: Boolean
get() = true
public open fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean = true
/**
* @param fileSpec
* @param content bytes of content, size of array is not actual size of data, you must use `size`
* @param size actual size of data
*/
public fun write(fileSpec: String, content: ByteArray, size: Int = content.size(), roamingType: RoamingType = RoamingType.DEFAULT)
public fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): InputStream?
/**
* You must close passed input stream.
*/
public fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean)
/**
* Delete file or directory
*/
public fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT)
}
public fun StreamProvider.write(path: String, content: String) {
write(path, content.toByteArray())
}
public fun StreamProvider.write(path: String, content: BufferExposingByteArrayOutputStream, roamingType: RoamingType = RoamingType.DEFAULT) {
write(path, content.getInternalBuffer(), content.size(), roamingType)
}
|
apache-2.0
|
ff5e1e580d605929010c5bfb2f45e4ac
| 37.592593 | 180 | 0.75132 | 4.441365 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/BookmarkItemAdapter.kt
|
1
|
7405
|
/*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.bookmark.view
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import jp.hazuki.bookmark.R
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkFolder
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkItem
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkSite
import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor
import jp.hazuki.yuzubrowser.core.utility.utils.FontUtils
import jp.hazuki.yuzubrowser.favicon.FaviconManager
import jp.hazuki.yuzubrowser.ui.extensions.getColorFromThemeRes
import jp.hazuki.yuzubrowser.ui.widget.recycler.ArrayRecyclerAdapter
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
open class BookmarkItemAdapter(
protected val context: Context,
list: MutableList<BookmarkItem>,
private val pickMode: Boolean,
private val openNewTab: Boolean,
protected val fontSize: Int,
private val faviconManager: FaviconManager,
private val bookmarkItemListener: OnBookmarkRecyclerListener
) : ArrayRecyclerAdapter<BookmarkItem, BookmarkItemAdapter.BookmarkFolderHolder>(context, list, null) {
private val defaultColorFilter: PorterDuffColorFilter =
PorterDuffColorFilter(context.getColorFromThemeRes(R.attr.iconColor), PorterDuff.Mode.SRC_ATOP)
private val foregroundOverlay =
ColorDrawable(context.getResColor(R.color.selected_overlay))
init {
setRecyclerListener(object : OnRecyclerListener {
override fun onRecyclerItemClicked(v: View, position: Int) {
if (isMultiSelectMode) {
toggle(position)
} else {
bookmarkItemListener.onRecyclerItemClicked(v, position)
}
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
return bookmarkItemListener.onRecyclerItemLongClicked(v, position)
}
})
}
override fun onBindViewHolder(holder: BookmarkFolderHolder, item: BookmarkItem, position: Int) {
if (item is BookmarkSite) {
holder as SimpleBookmarkSiteHolder
if (!openNewTab || pickMode || isMultiSelectMode) {
holder.imageButton.isEnabled = false
holder.imageButton.isClickable = false
} else {
holder.imageButton.isEnabled = true
holder.imageButton.isClickable = true
}
val bitmap = faviconManager[item.url]
if (bitmap != null) {
holder.imageButton.setImageBitmap(bitmap)
holder.imageButton.clearColorFilter()
} else {
holder.imageButton.setImageResource(R.drawable.ic_bookmark_white_24dp)
holder.imageButton.colorFilter = defaultColorFilter
}
}
if (isMultiSelectMode && isSelected(position)) {
holder.foreground.background = foregroundOverlay
} else {
holder.foreground.background = null
}
}
protected fun onIconClick(v: View, position: Int, item: BookmarkItem) {
val calPosition = searchPosition(position, item)
if (calPosition < 0) return
bookmarkItemListener.onIconClick(v, calPosition)
}
protected fun onOverflowButtonClick(v: View, position: Int, item: BookmarkItem) {
val calPosition = searchPosition(position, item)
if (calPosition < 0) return
bookmarkItemListener.onShowMenu(v, calPosition)
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup?, viewType: Int): BookmarkFolderHolder {
return when (viewType) {
TYPE_SITE -> SimpleBookmarkSiteHolder(inflater.inflate(R.layout.bookmark_item_site, parent, false), this)
TYPE_FOLDER -> BookmarkFolderHolder(inflater.inflate(R.layout.bookmark_item_folder, parent, false), this)
else -> throw IllegalStateException("Unknown BookmarkItem type")
}
}
fun getFavicon(site: BookmarkSite): ByteArray? {
return faviconManager.getFaviconBytes(site.url)
}
override fun setSelect(position: Int, isSelect: Boolean) {
super.setSelect(position, isSelect)
if (selectedItemCount == 0) {
bookmarkItemListener.onCancelMultiSelectMode()
} else {
bookmarkItemListener.onSelectionStateChange(selectedItemCount)
}
}
override fun getItemViewType(position: Int): Int {
val item = get(position)
return when (item) {
is BookmarkSite -> TYPE_SITE
is BookmarkFolder -> TYPE_FOLDER
else -> throw IllegalStateException("Unknown BookmarkItem type")
}
}
open class BookmarkFolderHolder(itemView: View, adapter: BookmarkItemAdapter) : ArrayRecyclerAdapter.ArrayViewHolder<BookmarkItem>(itemView, adapter) {
val title: TextView = itemView.findViewById(R.id.titleTextView)
val more: ImageButton = itemView.findViewById(R.id.overflowButton)
val foreground: View = itemView.findViewById(R.id.foreground)
init {
val fontSize = adapter.fontSize
if (fontSize >= 0) {
title.textSize = FontUtils.getTextSize(fontSize).toFloat()
}
more.setOnClickListener {
if (adapter.isMultiSelectMode) {
adapter.toggle(adapterPosition)
} else {
adapter.onOverflowButtonClick(more, adapterPosition, item)
}
}
}
override fun setUp(item: BookmarkItem) {
super.setUp(item)
title.text = item.title
}
}
open class SimpleBookmarkSiteHolder(itemView: View, adapter: BookmarkItemAdapter) : BookmarkFolderHolder(itemView, adapter) {
val imageButton: ImageButton = itemView.findViewById(R.id.imageButton)
init {
imageButton.setOnClickListener {
if (adapter.isMultiSelectMode) {
adapter.toggle(adapterPosition)
} else {
adapter.onIconClick(it, adapterPosition, item)
}
}
}
}
interface OnBookmarkRecyclerListener : OnRecyclerListener {
fun onIconClick(v: View, position: Int)
fun onShowMenu(v: View, position: Int)
fun onSelectionStateChange(items: Int)
fun onCancelMultiSelectMode()
}
companion object {
const val TYPE_SITE = 1
const val TYPE_FOLDER = 2
}
}
|
apache-2.0
|
486913b8270368f25818fe25cd1ddcf6
| 36.780612 | 155 | 0.667927 | 4.993257 | false | false | false | false |
seventhroot/elysium
|
bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/database/table/RPKWarningTable.kt
|
1
|
6122
|
/*
* Copyright 2018 Ross 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.moderation.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.database.jooq.rpkit.Tables.RPKIT_WARNING
import com.rpkit.moderation.bukkit.warning.RPKWarning
import com.rpkit.moderation.bukkit.warning.RPKWarningImpl
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
import java.sql.Timestamp
class RPKWarningTable(database: Database, private val plugin: RPKModerationBukkit): Table<RPKWarning>(database, RPKWarning::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_warning.id.enabled")) {
database.cacheManager.createCache("rpk-moderation-bukkit.rpkit_warning.id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKWarning::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_warning.id.size"))))
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_WARNING)
.column(RPKIT_WARNING.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_WARNING.REASON, SQLDataType.VARCHAR.length(1024))
.column(RPKIT_WARNING.PROFILE_ID, SQLDataType.INTEGER)
.column(RPKIT_WARNING.ISSUER_ID, SQLDataType.INTEGER)
.column(RPKIT_WARNING.TIME, SQLDataType.TIMESTAMP)
.constraints(
constraint("pk_rpkit_warning").primaryKey(RPKIT_WARNING.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.5.2")
}
if (database.getTableVersion(this) == "1.5.0") {
database.create
.alterTable(RPKIT_WARNING)
.alterColumn(RPKIT_WARNING.ID)
.set(SQLDataType.INTEGER.identity(true))
.execute()
database.setTableVersion(this, "1.5.2")
}
}
override fun insert(entity: RPKWarning): Int {
database.create
.insertInto(
RPKIT_WARNING,
RPKIT_WARNING.REASON,
RPKIT_WARNING.PROFILE_ID,
RPKIT_WARNING.ISSUER_ID,
RPKIT_WARNING.TIME
)
.values(
entity.reason,
entity.profile.id,
entity.issuer.id,
Timestamp.valueOf(entity.time)
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKWarning) {
database.create
.update(RPKIT_WARNING)
.set(RPKIT_WARNING.REASON, entity.reason)
.set(RPKIT_WARNING.PROFILE_ID, entity.profile.id)
.set(RPKIT_WARNING.ISSUER_ID, entity.issuer.id)
.set(RPKIT_WARNING.TIME, Timestamp.valueOf(entity.time))
.where(RPKIT_WARNING.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKWarning? {
val result = database.create
.select(
RPKIT_WARNING.REASON,
RPKIT_WARNING.PROFILE_ID,
RPKIT_WARNING.ISSUER_ID,
RPKIT_WARNING.TIME
)
.from(RPKIT_WARNING)
.where(RPKIT_WARNING.ID.eq(id))
.fetchOne() ?: return null
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = profileProvider.getProfile(result[RPKIT_WARNING.PROFILE_ID])
val issuer = profileProvider.getProfile(result[RPKIT_WARNING.ISSUER_ID])
if (profile != null && issuer != null) {
val warning = RPKWarningImpl(
id,
result[RPKIT_WARNING.REASON],
profile,
issuer,
result[RPKIT_WARNING.TIME].toLocalDateTime()
)
cache?.put(id, warning)
return warning
} else {
database.create
.deleteFrom(RPKIT_WARNING)
.where(RPKIT_WARNING.ID.eq(id))
.execute()
cache?.remove(id)
return null
}
}
fun get(profile: RPKProfile): List<RPKWarning> {
val results = database.create
.select(RPKIT_WARNING.ID)
.from(RPKIT_WARNING)
.where(RPKIT_WARNING.PROFILE_ID.eq(profile.id))
.fetch()
return results.map { get(it[RPKIT_WARNING.ID]) }.filterNotNull()
}
override fun delete(entity: RPKWarning) {
database.create
.deleteFrom(RPKIT_WARNING)
.where(RPKIT_WARNING.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
}
|
apache-2.0
|
941afbe3e16f4338b58ec08486875833
| 38.25 | 132 | 0.58592 | 4.666159 | false | false | false | false |
square/sqldelight
|
extensions/rxjava2-extensions/src/test/kotlin/com/squareup/sqldelight/runtime/rx/ObservingTest.kt
|
1
|
4423
|
package com.squareup.sqldelight.runtime.rx
import com.squareup.sqldelight.runtime.rx.Employee.Companion.MAPPER
import com.squareup.sqldelight.runtime.rx.Employee.Companion.SELECT_EMPLOYEES
import com.squareup.sqldelight.runtime.rx.Employee.Companion.USERNAME
import com.squareup.sqldelight.runtime.rx.TestDb.Companion.TABLE_EMPLOYEE
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import io.reactivex.schedulers.TestScheduler
import io.reactivex.subjects.PublishSubject
import org.junit.After
import org.junit.Before
import org.junit.Test
class ObservingTest {
private val o = RecordingObserver()
private lateinit var db: TestDb
@Before fun setup() {
db = TestDb()
}
@After fun tearDown() {
o.assertNoMoreEvents()
db.close()
}
@Test fun query() {
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(Schedulers.trampoline())
.subscribe(o)
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.isExhausted()
}
@Test fun `query observes notification`() {
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(Schedulers.trampoline())
.subscribe(o)
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.isExhausted()
db.employee(Employee("john", "John Johnson"))
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.hasRow("john", "John Johnson")
.isExhausted()
}
@Test fun queryInitialValueAndTriggerUsesScheduler() {
val scheduler = TestScheduler()
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(scheduler)
.subscribe(o)
o.assertNoMoreEvents()
scheduler.triggerActions()
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.isExhausted()
db.employee(Employee("john", "John Johnson"))
o.assertNoMoreEvents()
scheduler.triggerActions()
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.hasRow("john", "John Johnson")
.isExhausted()
}
@Test fun queryNotNotifiedWhenQueryTransformerUnsubscribes() {
val killSwitch = PublishSubject.create<Any>()
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(Schedulers.trampoline())
.takeUntil(killSwitch)
.subscribe(o)
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.isExhausted()
killSwitch.onNext("kill")
o.assertIsCompleted()
db.employee(Employee("john", "John Johnson"))
o.assertNoMoreEvents()
}
@Test fun queryNotNotifiedAfterDispose() {
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(Schedulers.trampoline())
.subscribe(o)
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.isExhausted()
o.dispose()
db.employee(Employee("john", "John Johnson"))
o.assertNoMoreEvents()
}
@Test fun queryOnlyNotifiedAfterSubscribe() {
val query = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asObservable(Schedulers.trampoline())
o.assertNoMoreEvents()
db.employee(Employee("john", "John Johnson"))
o.assertNoMoreEvents()
query.subscribe(o)
o.assertResultSet()
.hasRow("alice", "Alice Allison")
.hasRow("bob", "Bob Bobberson")
.hasRow("eve", "Eve Evenson")
.hasRow("john", "John Johnson")
.isExhausted()
}
@Test fun queryCanBeSubscribedToTwice() {
val query = db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES WHERE $USERNAME = 'john'", MAPPER)
.asObservable(Schedulers.trampoline())
.mapToOneNonNull()
val testObserver = query.zipWith(query, BiFunction { one: Employee, two: Employee -> one to two })
.test()
testObserver.assertNoValues()
val employee = Employee("john", "John Johnson")
db.employee(employee)
testObserver.assertValue(employee to employee)
}
}
|
apache-2.0
|
803a126eddd5db4f5ad811f7e4b97341
| 28.291391 | 102 | 0.671716 | 3.757859 | false | true | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/search/gene/collection/FlexibleMapGene.kt
|
1
|
2259
|
package org.evomaster.core.search.gene.collection
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.optional.FlexibleGene
import org.evomaster.core.search.gene.optional.FlexibleGene.Companion.wrapWithFlexibleGene
/**
* This represents a MapGene whose values do not follow a specific gene type, ie [FlexibleGene],
* however, its key has the fixed type
*
* when adding elements into the map, we do not restrict values of the element, it could have
* a different type with [template].
* For instance, if the value template is FlexibleGene attached with [StringGene], a FlexibleGene
* attached with [ObjectGene] is accepted to be added into this map. but for [FixedMapGene], this
* case is not acceptable
*/
class FlexibleMapGene<T>(
name: String,
template: PairGene<T, FlexibleGene>,
maxSize: Int? = null,
minSize: Int? = null,
elements: MutableList<PairGene<T, FlexibleGene>> = mutableListOf()
) : MapGene<T, FlexibleGene>(name, template, maxSize, minSize, elements)
where T : Gene {
constructor(name : String, key: T, value: Gene, maxSize: Int? = null, minSize: Int? = null): this(name,
PairGene("template", key, wrapWithFlexibleGene(value)), maxSize, minSize)
override fun copyContent(): Gene {
return FlexibleMapGene(
name,
template.copy() as PairGene<T, FlexibleGene>,
maxSize,
minSize,
elements.map { e -> e.copy() as PairGene<T, FlexibleGene> }.toMutableList()
)
}
override fun copyValueFrom(other: Gene) {
//TODO
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is FlexibleMapGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.elements.size == other.elements.size
&& this.elements.zip(other.elements) { thisElem, otherElem ->
thisElem.containsSameValueAs(otherElem)
}.all { it }
}
override fun bindValueBasedOn(gene: Gene): Boolean {
//TODO
return false
}
override fun isPrintable(): Boolean {
return elements.all { it.isPrintable() }
}
}
|
lgpl-3.0
|
dd4aa0655be8e8808ce1d3760244dbaa
| 34.873016 | 107 | 0.671979 | 4.183333 | false | false | false | false |
rohitsuratekar/NCBSinfo
|
app/src/main/java/com/rohitsuratekar/NCBSinfo/viewmodels/EditTransportViewModel.kt
|
1
|
5230
|
package com.rohitsuratekar.NCBSinfo.viewmodels
import android.os.AsyncTask
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.serverTimestamp
import com.rohitsuratekar.NCBSinfo.database.TripData
import com.rohitsuratekar.NCBSinfo.di.Repository
import com.rohitsuratekar.NCBSinfo.models.EditTransportStep
import com.rohitsuratekar.NCBSinfo.models.Route
import java.util.*
class EditTransportViewModel : ViewModel() {
val origin = MutableLiveData<String>()
val destination = MutableLiveData<String>()
val stepUpdate = MutableLiveData<MutableList<EditTransportStep>>()
val tripList = MutableLiveData<MutableList<String>>()
val tripSelected = MutableLiveData<Boolean>()
val transportType = MutableLiveData<Int>()
val transportFrequency = MutableLiveData<Int>()
val frequencyDetails = MutableLiveData<MutableList<Int>>()
val inputRouteID = MutableLiveData<Int>()
val currentRoute = MutableLiveData<Route>()
val routeDeleted = MutableLiveData<Boolean>()
val selectedTrip = MutableLiveData<TripData>()
fun setInputRouteID(routeID: Int) {
inputRouteID.postValue(routeID)
}
fun setOrigin(string: String) {
origin.postValue(string)
}
fun setDestination(string: String) {
destination.postValue(string)
}
fun setRoute(route: Route) {
currentRoute.postValue(route)
}
fun setSelectedTrip(tripData: TripData) {
selectedTrip.postValue(tripData)
}
fun addSteps(list: List<EditTransportStep>) {
val k = mutableListOf<EditTransportStep>()
k.addAll(list)
stepUpdate.postValue(k)
}
fun setType(type: Int) {
transportType.postValue(type)
updateConfirmState(Constants.EDIT_TYPE, true)
}
fun setFrequency(id: Int) {
transportFrequency.postValue(id)
}
fun setFrequencyData(list: MutableList<Int>) {
frequencyDetails.postValue(list)
if (list.sum() > 0) {
updateConfirmState(Constants.EDIT_FREQUENCY, true)
} else {
updateConfirmState(Constants.EDIT_FREQUENCY, false)
}
}
fun updateReadState(step: Int) {
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
if (t.number == step) {
t.isSeen = true
}
returnList.add(t)
}
}
if (returnList.isNotEmpty()) {
stepUpdate.postValue(returnList)
}
}
fun updateConfirmState(step: Int, isConfirmed: Boolean) {
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
if (t.number == step) {
t.isComplete = isConfirmed
}
returnList.add(t)
}
}
if (returnList.isNotEmpty()) {
stepUpdate.postValue(returnList)
}
}
fun updateTrips(list: List<String>) {
val k = mutableListOf<String>()
k.addAll(list)
tripList.postValue(k)
updateConfirmState(Constants.EDIT_TRIPS, k.isNotEmpty())
}
fun updateTripSelection(value: Boolean) {
tripSelected.postValue(value)
updateConfirmState(Constants.EDIT_START_TRIP, value)
}
fun clearAllAttributes() {
origin.postValue(null)
destination.postValue(null)
transportType.postValue(null)
transportFrequency.postValue(null)
tripList.postValue(null)
frequencyDetails.postValue(null)
tripSelected.postValue(null)
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
t.isSeen = false
t.isComplete = false
returnList.add(t)
}
}
stepUpdate.postValue(returnList)
}
fun deleteRoute(repository: Repository, route: Route, selectedTrip: TripData?) {
DeleteRoute(repository, route, selectedTrip, object : OnDeleteRoute {
override fun deleted() {
routeDeleted.postValue(true)
}
}).execute()
}
class DeleteRoute(
private val repository: Repository,
private val route: Route,
private val selectedTrip: TripData?,
private val listener: OnDeleteRoute
) : AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
selectedTrip?.let {
repository.data().updateModifiedDate(route.routeData, Calendar.getInstance().serverTimestamp())
repository.data().deleteTrip(it)
} ?: kotlin.run {
repository.data().deleteRoute(route.routeData)
}
listener.deleted()
return null
}
}
interface OnDeleteRoute {
fun deleted()
}
}
|
mit
|
00ae22a23fc065fae323ea6243cb6cc2
| 29.518072 | 111 | 0.603824 | 4.806985 | false | false | false | false |
BlueBoxWare/LibGDXPlugin
|
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaMissingFlushInspection.kt
|
1
|
2597
|
/*
* Copyright 2016 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.resolveCall
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.*
class JavaMissingFlushInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("missing.flush.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() {
override fun visitMethod(method: PsiMethod?) {
val methodChecker = MissingFlushInspectionMethodChecker()
method?.accept(methodChecker)
methodChecker.lastPreferenceChange?.let { lastPreferenceChange ->
holder.registerProblem(lastPreferenceChange, message("missing.flush.problem.descriptor"))
}
}
}
private class MissingFlushInspectionMethodChecker : JavaRecursiveElementVisitor() {
var lastPreferenceChange: PsiExpression? = null
override fun visitMethodCallExpression(expression: PsiMethodCallExpression?) {
super.visitMethodCallExpression(expression)
if (expression == null) return
val (receiverClass, method) = expression.resolveCall() ?: return
var isPreferences = false
val superTypes = receiverClass.supers.flatMap { it.supers.toList() }.toMutableList()
superTypes.add(receiverClass)
for (superType in superTypes) {
if (superType.qualifiedName == "com.badlogic.gdx.Preferences") {
isPreferences = true
break
}
}
if (!isPreferences) return
if (method.name.startsWith("put") || method.name == "remove") {
lastPreferenceChange = expression
} else if (method.name == "flush") {
lastPreferenceChange = null
}
}
}
}
|
apache-2.0
|
3ea142b6dd704e2fd29401593ff84a1f
| 32.727273 | 108 | 0.671544 | 5.142574 | false | false | false | false |
premnirmal/StockTicker
|
app/src/main/kotlin/com/github/premnirmal/ticker/settings/WidgetSettingsFragment.kt
|
1
|
11101
|
package com.github.premnirmal.ticker.settings
import android.appwidget.AppWidgetManager
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ArrayRes
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.github.premnirmal.ticker.AppPreferences
import com.github.premnirmal.ticker.base.BaseFragment
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.createTimeString
import com.github.premnirmal.ticker.home.ChildFragment
import com.github.premnirmal.ticker.home.MainViewModel
import com.github.premnirmal.ticker.model.StocksProvider
import com.github.premnirmal.ticker.model.StocksProvider.FetchState
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.ui.SettingsTextView
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.ticker.widget.WidgetData
import com.github.premnirmal.ticker.widget.WidgetDataProvider
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.databinding.FragmentWidgetSettingsBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import javax.inject.Inject
@AndroidEntryPoint
class WidgetSettingsFragment : BaseFragment<FragmentWidgetSettingsBinding>(), ChildFragment, OnClickListener {
override val binding: (FragmentWidgetSettingsBinding) by viewBinding(FragmentWidgetSettingsBinding::inflate)
companion object {
private const val ARG_WIDGET_ID = AppWidgetManager.EXTRA_APPWIDGET_ID
private const val ARG_SHOW_ADD_STOCKS = "show_add_stocks"
private const val TRANSPARENT_BG = "transparent_bg"
fun newInstance(widgetId: Int, showAddStocks: Boolean, transparentBg: Boolean = false): WidgetSettingsFragment {
val fragment = WidgetSettingsFragment()
val args = Bundle()
args.putInt(ARG_WIDGET_ID, widgetId)
args.putBoolean(ARG_SHOW_ADD_STOCKS, showAddStocks)
args.putBoolean(TRANSPARENT_BG, transparentBg)
fragment.arguments = args
return fragment
}
}
@Inject internal lateinit var widgetDataProvider: WidgetDataProvider
@Inject internal lateinit var stocksProvider: StocksProvider
private lateinit var adapter: WidgetPreviewAdapter
private var showAddStocks = true
private var transparentBg = true
internal var widgetId = 0
private val mainViewModel: MainViewModel by activityViewModels()
override val simpleName: String = "WidgetSettingsFragment"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
widgetId = requireArguments().getInt(ARG_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
showAddStocks = requireArguments().getBoolean(ARG_SHOW_ADD_STOCKS, true)
transparentBg = requireArguments().getBoolean(TRANSPARENT_BG, false)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
binding.settingAddStock.visibility = if (showAddStocks) View.VISIBLE else View.GONE
if (!transparentBg) {
binding.previewContainer.setBackgroundResource(R.drawable.bg_header)
}
val widgetData = widgetDataProvider.dataForWidgetId(widgetId)
setWidgetNameSetting(widgetData)
setLayoutTypeSetting(widgetData)
setWidgetSizeSetting(widgetData)
setBoldSetting(widgetData)
setAutoSortSetting(widgetData)
setHideHeaderSetting(widgetData)
setCurrencySetting(widgetData)
setBgSetting(widgetData)
setTextColorSetting(widgetData)
adapter = WidgetPreviewAdapter(widgetData)
binding.widgetLayout.list.adapter = adapter
updatePreview(widgetData)
arrayOf(
binding.settingAddStock, binding.settingWidgetName, binding.settingLayoutType , binding.settingWidgetWidth,
binding.settingBold, binding.settingAutosort, binding.settingHideHeader, binding.settingCurrency, binding.settingBackground, binding.settingTextColor
).forEach {
it.setOnClickListener(this@WidgetSettingsFragment)
}
lifecycleScope.launch {
stocksProvider.fetchState.collect {
updatePreview(widgetData)
}
}
lifecycleScope.launch {
widgetData.autoSortEnabled.collect {
binding.settingAutosortCheckbox.isChecked = it
}
}
}
override fun onClick(v: View) {
val widgetData = widgetDataProvider.dataForWidgetId(widgetId)
when (v.id) {
R.id.setting_add_stock -> {
mainViewModel.openSearch(widgetId)
}
R.id.setting_widget_name -> {
v.setOnClickListener(null)
(v as SettingsTextView).setIsEditable(true) { s ->
widgetData.setWidgetName(s)
setWidgetNameSetting(widgetData)
v.setIsEditable(false)
v.setOnClickListener(this)
InAppMessage.showMessage(view as ViewGroup, R.string.widget_name_updated)
}
}
R.id.setting_layout_type -> {
showDialogPreference(R.array.layout_types) { dialog, which ->
widgetData.setLayoutPref(which)
setLayoutTypeSetting(widgetData)
dialog.dismiss()
broadcastUpdateWidget()
if (which == 2) {
showDialog(getString(R.string.change_instructions))
}
InAppMessage.showMessage(view as ViewGroup, R.string.layout_updated_message)
}
}
R.id.setting_background -> {
showDialogPreference(R.array.backgrounds) { dialog, which ->
widgetData.setBgPref(which)
if (which == AppPreferences.SYSTEM) {
widgetData.setTextColorPref(which)
setTextColorSetting(widgetData)
} else if (which == AppPreferences.TRANSLUCENT) {
widgetData.setTextColorPref(AppPreferences.LIGHT)
setTextColorSetting(widgetData)
}
setBgSetting(widgetData)
dialog.dismiss()
broadcastUpdateWidget()
InAppMessage.showMessage(view as ViewGroup, R.string.bg_updated_message)
}
}
R.id.setting_text_color -> {
showDialogPreference(R.array.text_colors) { dialog, which ->
widgetData.setTextColorPref(which)
setTextColorSetting(widgetData)
dialog.dismiss()
broadcastUpdateWidget()
InAppMessage.showMessage(view as ViewGroup, R.string.text_color_updated_message)
}
}
R.id.setting_widget_width -> {
showDialogPreference(
R.array.widget_width_types
) { dialog, which ->
widgetData.setWidgetSizePref(which)
setWidgetSizeSetting(widgetData)
dialog.dismiss()
broadcastUpdateWidget()
InAppMessage.showMessage(view as ViewGroup, R.string.widget_width_updated_message)
}
}
R.id.setting_bold -> {
val isChecked = !binding.settingBoldCheckbox.isChecked
widgetData.setBoldEnabled(isChecked)
setBoldSetting(widgetData)
broadcastUpdateWidget()
}
R.id.setting_autosort -> {
val isChecked = !binding.settingAutosortCheckbox.isChecked
widgetData.setAutoSort(isChecked)
setAutoSortSetting(widgetData)
broadcastUpdateWidget()
}
R.id.setting_hide_header -> {
val isChecked = !binding.settingHideHeaderCheckbox.isChecked
widgetData.setHideHeader(isChecked)
setHideHeaderSetting(widgetData)
broadcastUpdateWidget()
}
R.id.setting_currency -> {
val isChecked = !binding.settingCurrencyCheckbox.isChecked
widgetData.setCurrencyEnabled(isChecked)
setCurrencySetting(widgetData)
broadcastUpdateWidget()
}
}
}
private fun broadcastUpdateWidget() {
widgetDataProvider.broadcastUpdateWidget(widgetId)
updatePreview(widgetDataProvider.dataForWidgetId(widgetId))
}
private fun showDialogPreference(
@ArrayRes itemRes: Int,
listener: DialogInterface.OnClickListener
) {
AlertDialog.Builder(requireContext())
.setItems(itemRes, listener)
.create()
.show()
}
private fun setWidgetNameSetting(widgetData: WidgetData) {
binding.settingWidgetName.setSubtitle(widgetData.widgetName())
}
private fun setWidgetSizeSetting(widgetData: WidgetData) {
val widgetSizeTypeDesc = resources.getStringArray(R.array.widget_width_types)[widgetData.widgetSizePref()]
binding.settingWidgetWidth.setSubtitle(widgetSizeTypeDesc)
}
private fun setLayoutTypeSetting(widgetData: WidgetData) {
val layoutTypeDesc = resources.getStringArray(R.array.layout_types)[widgetData.layoutPref()]
binding.settingLayoutType.setSubtitle(layoutTypeDesc)
}
private fun setBoldSetting(widgetData: WidgetData) {
binding.settingBoldCheckbox.isChecked = widgetData.isBoldEnabled()
}
private fun setAutoSortSetting(widgetData: WidgetData) {
binding.settingAutosortCheckbox.isChecked = widgetData.autoSortEnabled()
}
private fun setHideHeaderSetting(widgetData: WidgetData) {
binding.settingHideHeaderCheckbox.isChecked = widgetData.hideHeader()
}
private fun setCurrencySetting(widgetData: WidgetData) {
binding.settingCurrencyCheckbox.isChecked = widgetData.isCurrencyEnabled()
}
private fun setBgSetting(widgetData: WidgetData) {
val bgDesc = resources.getStringArray(R.array.backgrounds)[widgetData.bgPref()]
binding.settingBackground.setSubtitle(bgDesc)
}
private fun setTextColorSetting(widgetData: WidgetData) {
val textColorDesc = resources.getStringArray(R.array.text_colors)[widgetData.textColorPref()]
binding.settingTextColor.setSubtitle(textColorDesc)
}
private fun updatePreview(widgetData: WidgetData) {
binding.widgetLayout.root.setBackgroundResource(widgetData.backgroundResource())
val lastUpdatedText = when (val fetchState = stocksProvider.fetchState.value) {
is FetchState.Success -> getString(R.string.last_fetch, fetchState.displayString)
is FetchState.Failure -> getString(R.string.refresh_failed)
else -> FetchState.NotFetched.displayString
}
binding.widgetLayout.root.findViewById<TextView>(R.id.last_updated).text = lastUpdatedText
val nextUpdateMs = stocksProvider.nextFetchMs.value
val instant = Instant.ofEpochMilli(nextUpdateMs)
val time = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
val nextUpdate = time.createTimeString()
val nextUpdateText: String = getString(R.string.next_fetch, nextUpdate)
binding.widgetLayout.root.findViewById<TextView>(R.id.next_update).text = nextUpdateText
binding.widgetLayout.root.findViewById<View>(R.id.widget_header).isVisible = !widgetData.hideHeader()
adapter.refresh(widgetData)
}
override fun scrollToTop() {
binding.scrollView.smoothScrollTo(0, 0)
}
}
|
gpl-3.0
|
1960f2cbd6de348831a7993c1e4d4522
| 38.091549 | 157 | 0.739933 | 4.465406 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/people/PeopleActivity.kt
|
1
|
3880
|
package com.battlelancer.seriesguide.people
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.ActivityPeopleBinding
import com.battlelancer.seriesguide.people.PeopleFragment.OnShowPersonListener
import com.battlelancer.seriesguide.ui.BaseActivity
/**
* Displays a list of people, and on wide enough screens person details.
* Otherwise lets [PersonActivity] show details.
*/
class PeopleActivity : BaseActivity(), OnShowPersonListener {
private var isTwoPane = false
internal interface InitBundle {
companion object {
const val MEDIA_TYPE = "media_title"
const val ITEM_TMDB_ID = "item_tmdb_id"
const val PEOPLE_TYPE = "people_type"
}
}
enum class MediaType(private val value: String) {
SHOW("SHOW"),
MOVIE("MOVIE");
override fun toString(): String = value
}
internal enum class PeopleType(private val value: String) {
CAST("CAST"),
CREW("CREW");
override fun toString(): String = value
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityPeopleBinding.inflate(layoutInflater)
setContentView(binding.root)
setupActionBar()
// If there is a pane shadow, this is using a two pane layout.
isTwoPane = binding.viewPeopleShadowStart != null
if (savedInstanceState == null) {
// Check if this should directly show a person.
val personTmdbId = intent.getIntExtra(PersonFragment.ARG_PERSON_TMDB_ID, -1)
if (personTmdbId != -1) {
showPerson(personTmdbId)
// If this is not a dual pane layout, allow to go back directly by removing
// this from back stack.
if (!isTwoPane) {
finish()
return
}
}
val f = PeopleFragment()
f.arguments = intent.extras
// In two-pane mode, list items should be activated when touched.
if (isTwoPane) {
f.setActivateOnItemClick()
}
supportFragmentManager.beginTransaction()
.add(R.id.containerPeople, f, "people-list")
.commit()
}
}
override fun setupActionBar() {
super.setupActionBar()
val peopleType = PeopleType.valueOf(
intent.getStringExtra(InitBundle.PEOPLE_TYPE)!!
)
setTitle(if (peopleType == PeopleType.CAST) R.string.movie_cast else R.string.movie_crew)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_clear_24dp)
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setTitle(
if (peopleType == PeopleType.CAST) R.string.movie_cast else R.string.movie_crew
)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressedDispatcher.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun showPerson(tmdbId: Int) {
if (isTwoPane) {
// show inline
val f = PersonFragment.newInstance(tmdbId)
supportFragmentManager.beginTransaction()
.replace(R.id.containerPeoplePerson, f)
.commit()
} else {
// start new activity
val i = Intent(this, PersonActivity::class.java)
i.putExtra(PersonFragment.ARG_PERSON_TMDB_ID, tmdbId)
startActivity(i)
}
}
}
|
apache-2.0
|
139c2d95d669e1b3eae2463de6b0158e
| 32.456897 | 97 | 0.60232 | 4.868256 | false | false | false | false |
droibit/quickly
|
app/src/main/kotlin/com/droibit/quickly/main/ShowSettingsTask.kt
|
1
|
1313
|
package com.droibit.quickly.main
import com.droibit.quickly.data.repository.settings.ShowSettingsRepository
import com.droibit.quickly.data.repository.settings.ShowSettingsRepository.Order
import com.droibit.quickly.data.repository.settings.ShowSettingsRepository.SortBy
import rx.Completable
import rx.Single
import rx.lang.kotlin.singleOf
class ShowSettingsTask(private val showSettingsRepository: ShowSettingsRepository)
: MainContract.ShowSettingsTask {
override fun loadSortBy(): Single<Pair<SortBy, Order>> {
return singleOf(Pair(showSettingsRepository.sortBy, showSettingsRepository.order))
}
override fun storeSortBy(sortBy: SortBy, order: Order): Single<Boolean> {
return Single.fromCallable {
val updated = showSettingsRepository.sortBy != sortBy || showSettingsRepository.order != order
showSettingsRepository.sortBy = sortBy
showSettingsRepository.order = order
return@fromCallable updated
}
}
override fun loadShowSystem(): Single<Boolean> {
return singleOf(showSettingsRepository.isShowSystem)
}
override fun storeShowSystem(showSystem: Boolean): Completable {
return Completable.fromAction {
showSettingsRepository.isShowSystem = showSystem
}
}
}
|
apache-2.0
|
caddc0180699415472bb343ded1b59b1
| 34.513514 | 106 | 0.743336 | 5.069498 | false | false | false | false |
reid112/Reidit
|
app/src/main/java/ca/rjreid/reidit/ui/main/MainAdapter.kt
|
1
|
2839
|
package ca.rjreid.reidit.ui.main
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ca.rjreid.reidit.R
import ca.rjreid.reidit.data.model.Post
import ca.rjreid.reidit.data.model.PostHolder
import ca.rjreid.reidit.extensions.image
import kotlinx.android.synthetic.main.list_item_post.view.*
class MainAdapter(
val postClick: (Post) -> Unit,
val upVoteClick: (Post) -> Unit,
val downVoteClick: (Post) -> Unit,
val commentsClick: (Post) -> Unit) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
//region Variables
private var postHolders = mutableListOf<PostHolder>()
//endregion
//region Adapter Implementation
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.list_item_post, parent, false)
return ViewHolder(view, postClick, upVoteClick, downVoteClick, commentsClick)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bindPost(postHolders[position].post)
}
override fun getItemCount(): Int {
return postHolders.count()
}
//endregion
//region Commands
fun replacePosts(postHolders: List<PostHolder>) {
clearPosts()
appendNewPosts(postHolders)
}
fun appendNewPosts(postHolders: List<PostHolder>) {
this.postHolders.addAll(postHolders)
notifyDataSetChanged()
}
fun clearPosts() {
this.postHolders.clear()
notifyDataSetChanged()
}
//endregion
//region View Holder Inner Class
class ViewHolder(
view: View,
val postClick: (Post) -> Unit,
val upVoteClick: (Post) -> Unit,
val downVoteClick: (Post) -> Unit,
val commentsClick: (Post) -> Unit) : RecyclerView.ViewHolder(view) {
fun bindPost(post: Post) {
with(post) {
itemView.postThumbnail.image(thumbnailUrl)
itemView.postSubreddit.text = String.format(itemView.context.getString(R.string.label_subreddit), subreddit)
itemView.postTitle.text = title
itemView.postAuthor.text = author
itemView.postUpVotes.text = ups.toString()
itemView.postDownVotes.text = downs.toString()
itemView.postComments.text = numComments.toString()
itemView.setOnClickListener { postClick(this) }
itemView.postUpVotes.setOnClickListener { upVoteClick(this) }
itemView.postDownVotes.setOnClickListener { downVoteClick(this) }
itemView.postComments.setOnClickListener { commentsClick(this) }
}
}
}
//endregion
}
|
apache-2.0
|
65edad538a58a761c32f23a01806c9e0
| 34.936709 | 124 | 0.656217 | 4.321157 | false | false | false | false |
Blankj/AndroidUtilCode
|
feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/bar/status/BarStatusActivityDrawer.kt
|
1
|
4092
|
package com.blankj.utilcode.pkg.feature.bar.status
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import com.blankj.common.activity.CommonActivity
import com.blankj.common.item.CommonItem
import com.blankj.common.item.CommonItemClick
import com.blankj.common.item.CommonItemSeekBar
import com.blankj.common.item.CommonItemSwitch
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import kotlinx.android.synthetic.main.bar_status_drawer_activity.*
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2017/05/27
* desc : demo about BarUtils
* ```
*/
class BarStatusActivityDrawer : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, BarStatusActivityDrawer::class.java)
context.startActivity(starter)
}
}
private var mColor: Int = ColorUtils.getColor(R.color.colorPrimary)
private var mAlpha: Int = 112
private var mAlphaStatus: Boolean = false
private var mFrontStatus: Boolean = false
override fun isSwipeBack(): Boolean {
return false
}
override fun bindDrawer(): Boolean {
return true
}
override fun bindLayout(): Int {
return R.layout.bar_status_drawer_activity
}
private fun getItems(): MutableList<CommonItem<*>> {
val randomColorItem = CommonItemClick(R.string.bar_status_random_color, ColorUtils.int2ArgbString(mColor)).setOnClickUpdateContentListener {
mColor = ColorUtils.getRandomColor()
updateStatusBar()
return@setOnClickUpdateContentListener ColorUtils.int2ArgbString(mColor)
}
val alphaItem: CommonItem<*> = CommonItemSeekBar("Status Bar Alpha", 255, object : CommonItemSeekBar.ProgressListener() {
override fun getCurValue(): Int {
return mAlpha
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
mAlpha = progress
updateStatusBar()
}
})
return CollectionUtils.newArrayList(
CommonItemSwitch(
R.string.bar_status_title_alpha,
{
updateStatusBar()
mAlphaStatus
},
{
mAlphaStatus = it
if (mAlphaStatus) {
barStatusDrawerRootLl.setBackgroundResource(R.drawable.image_lena)
commonItemAdapter.replaceItem(2, alphaItem, true)
} else {
barStatusDrawerRootLl.setBackgroundColor(Color.TRANSPARENT)
commonItemAdapter.replaceItem(2, randomColorItem, true)
}
}
),
CommonItemSwitch(
R.string.bar_status_is_front,
{ mFrontStatus },
{
mFrontStatus = it
updateStatusBar()
}
),
randomColorItem
)
}
override fun initView(savedInstanceState: Bundle?, contentView: View?) {
super.initView(savedInstanceState, contentView)
setCommonItems(findViewById(R.id.commonItemRv), getItems())
}
private fun updateStatusBar() {
if (mAlphaStatus) {
BarUtils.setStatusBarColor4Drawer(drawerView.mBaseDrawerRootLayout, barStatusDrawerFakeStatusBar, Color.argb(mAlpha, 0, 0, 0), mFrontStatus)
} else {
BarUtils.setStatusBarColor4Drawer(drawerView.mBaseDrawerRootLayout, barStatusDrawerFakeStatusBar, mColor, mFrontStatus)
}
}
}
|
apache-2.0
|
95d7ca00a9d395041ff89f7009896af3
| 34.275862 | 152 | 0.598974 | 5.166667 | false | false | false | false |
ericberman/MyFlightbookAndroid
|
app/src/main/java/com/myflightbook/android/PropertyEdit.kt
|
1
|
13534
|
/*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myflightbook.android
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.text.InputType
import android.text.format.DateFormat
import android.text.method.TextKeyListener
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.*
import com.myflightbook.android.DlgDatePicker.DateTimeUpdate
import com.myflightbook.android.webservices.UTCDate.formatDate
import com.myflightbook.android.webservices.UTCDate.isNullDate
import model.CustomPropertyType
import model.CustomPropertyType.CFPPropertyType
import model.CustomPropertyType.Companion.isPinnedProperty
import model.CustomPropertyType.Companion.removePinnedProperty
import model.CustomPropertyType.Companion.setPinnedProperty
import model.DecimalEdit
import model.DecimalEdit.CrossFillDelegate
import model.FlightProperty
import java.util.*
class PropertyEdit : LinearLayout, DateTimeUpdate {
interface PropertyListener {
fun updateProperty(id: Int, fp: FlightProperty)
fun dateOfFlightShouldReset(dt: Date)
}
//endregion
var flightProperty: FlightProperty? = null
private set
private var mId = 0
private var mPl: PropertyListener? = null
private var mCfd: CrossFillDelegate? = null
private var mTxtnumericfield: DecimalEdit? = null
private var mTxtstringval: AutoCompleteTextView? = null
private var mCk: CheckBox? = null
private var mTvdate: TextView? = null
private var mTvlabel: TextView? = null
private var mIspinned = false
//region constructors
constructor(context: Context) : super(context) {
initializeViews(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initializeViews(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initializeViews(context)
}
private fun initializeViews(context: Context) {
val inflater = (context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
inflater.inflate(R.layout.propertyedit, this)
}
override fun updateDate(id: Int, dt: Date?) {
flightProperty!!.dateValue = dt
updateForProperty()
notifyDelegate()
}
private fun notifyDelegate() {
if (mPl != null && flightProperty != null) {
mPl!!.updateProperty(mId, flightProperty!!)
}
}
private fun handlePinClick() {
val pref = context.getSharedPreferences(
CustomPropertyType.prefSharedPinnedProps,
Activity.MODE_PRIVATE
)
if (mIspinned) removePinnedProperty(
pref,
flightProperty!!.idPropType
) else setPinnedProperty(pref, flightProperty!!.idPropType)
mIspinned = !mIspinned
updateForProperty()
}
@SuppressLint("ClickableViewAccessibility")
private fun handleStupidFocusStuffInListViews(tv: TextView?) {
// Wow. See https://stackoverflow.com/questions/38890059/edittext-in-expandablelistview. EditTexts inside ListView's are a pain in the ass
// because of all of the re-using of the controls.
tv!!.isFocusable = false
tv.setOnTouchListener { view: View, _: MotionEvent? ->
view.isFocusableInTouchMode = true
view.performClick()
false
}
}
fun initForProperty(
fp: FlightProperty,
id: Int,
pl: PropertyListener?,
cfd: CrossFillDelegate?
) {
flightProperty = fp
mId = id
mPl = pl
mCfd = cfd
mTxtnumericfield = findViewById(R.id.txtEditNumericProp)
mTxtstringval = findViewById(R.id.txtStringVal)
mCk = findViewById(R.id.ckBoolValue)
mTvdate = findViewById(R.id.txtDate)
mTvlabel = findViewById(R.id.txtLabel)
// Initialize labels and values (whether or not visible)
val ck = mCk
ck?.text = flightProperty!!.labelString()
ck?.isChecked = flightProperty!!.boolValue
val tvLabel = mTvlabel
tvLabel?.text = flightProperty!!.labelString()
updateLabelTypefaceForProperty()
val pref = context.getSharedPreferences(
CustomPropertyType.prefSharedPinnedProps,
Activity.MODE_PRIVATE
)
mIspinned = isPinnedProperty(pref, flightProperty!!.idPropType)
findViewById<View>(R.id.layoutPropEdit).setOnLongClickListener {
handlePinClick()
true
}
findViewById<View>(R.id.imgFavorite).setOnLongClickListener {
handlePinClick()
true
}
findViewById<View>(R.id.imgAboutProp).setOnClickListener {
val inflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val layout = inflater.inflate(R.layout.toastlayout, findViewById(R.id.toastLayout))
val txt = layout.findViewById<TextView>(R.id.txtToastText)
val t = Toast.makeText(context, fp.descriptionString(), Toast.LENGTH_SHORT)
val location = IntArray(2)
findViewById<View>(R.id.layoutPropEdit).getLocationOnScreen(location)
t.setGravity(Gravity.TOP or Gravity.START, location[0], location[1])
txt.text = fp.descriptionString()
t.view = layout
t.show()
}
val txtStringVal = mTxtstringval
val txtNumericField = mTxtnumericfield
handleStupidFocusStuffInListViews(txtStringVal)
handleStupidFocusStuffInListViews(txtNumericField)
txtNumericField?.setOnFocusChangeListener { view: View, hasFocus: Boolean ->
if (!hasFocus) {
when (fp.getType()) {
CFPPropertyType.cfpCurrency, CFPPropertyType.cfpDecimal -> flightProperty!!.decValue =
txtNumericField.doubleValue
CFPPropertyType.cfpInteger -> flightProperty!!.intValue =
txtNumericField.intValue
else -> {}
}
view.isFocusable = false
updateForProperty()
notifyDelegate()
}
}
txtStringVal?.setOnFocusChangeListener { view: View, hasFocus: Boolean ->
if (!hasFocus) {
flightProperty!!.stringValue = txtStringVal.text.toString()
view.isFocusable = false
updateForProperty()
notifyDelegate()
}
}
ck?.setOnCheckedChangeListener { _: CompoundButton?, fChecked: Boolean ->
flightProperty!!.boolValue = fChecked
updateForProperty()
notifyDelegate()
}
val tvDate = mTvdate
tvDate?.setOnClickListener {
if (flightProperty!!.dateValue == null || isNullDate(
flightProperty!!.dateValue
)
) {
val dt = Date()
updateDate(mId, dt)
if (mPl != null) mPl!!.dateOfFlightShouldReset(dt)
} else {
val ddp = DlgDatePicker(
context,
if (fp.getType() === CFPPropertyType.cfpDate) DlgDatePicker.DatePickMode.LOCALDATEONLY else DlgDatePicker.DatePickMode.UTCDATETIME,
(if (fp.dateValue == null) Date() else fp.dateValue)!!
)
ddp.mDelegate = this@PropertyEdit
ddp.mId = mId
ddp.show()
}
}
updateForProperty()
invalidate()
requestLayout()
}
private fun updateLabelTypefaceForProperty() {
val txtLabel = findViewById<TextView>(R.id.txtLabel)
txtLabel.setTypeface(
null,
if (flightProperty!!.isDefaultValue()) Typeface.NORMAL else Typeface.BOLD
)
val ckLabel = findViewById<CheckBox>(R.id.ckBoolValue)
ckLabel.setTypeface(
null,
if (flightProperty!!.isDefaultValue()) Typeface.NORMAL else Typeface.BOLD
)
}
private fun updateForProperty() {
updateLabelTypefaceForProperty()
val cptType = flightProperty!!.getType()!!
val fIsBasicDecimal =
cptType === CFPPropertyType.cfpDecimal && flightProperty!!.getCustomPropertyType()!!.cptFlag and 0x00200000 != 0
mTvlabel!!.visibility = VISIBLE
mTxtstringval!!.visibility = GONE
mTxtnumericfield!!.visibility = GONE
mCk!!.visibility = GONE
mTvdate!!.visibility = GONE
when (cptType) {
CFPPropertyType.cfpInteger -> {
mTxtnumericfield!!.visibility = VISIBLE
mTxtnumericfield!!.setMode(DecimalEdit.EditMode.INTEGER)
mTxtnumericfield!!.intValue = flightProperty!!.intValue
}
CFPPropertyType.cfpDecimal -> {
mTxtnumericfield!!.visibility = VISIBLE
mTxtnumericfield!!.setMode(if (DecimalEdit.DefaultHHMM && !fIsBasicDecimal) DecimalEdit.EditMode.HHMM else DecimalEdit.EditMode.DECIMAL)
mTxtnumericfield!!.doubleValue = flightProperty!!.decValue
if (mCfd != null) mTxtnumericfield!!.setDelegate(mCfd)
}
CFPPropertyType.cfpCurrency -> {
mTxtnumericfield!!.visibility = VISIBLE
mTxtnumericfield!!.setMode(DecimalEdit.EditMode.DECIMAL)
mTxtnumericfield!!.doubleValue = flightProperty!!.decValue
}
CFPPropertyType.cfpString -> {
mTxtstringval!!.visibility = VISIBLE
mTxtstringval!!.hint = ""
val capFlag =
if (flightProperty!!.getCustomPropertyType()!!.cptFlag and 0x04000000 != 0) InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS else if (flightProperty!!.getCustomPropertyType()!!.cptFlag and 0x10000000 != 0) InputType.TYPE_TEXT_FLAG_CAP_WORDS else InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
mTxtstringval!!.inputType =
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_CLASS_TEXT or capFlag
mTxtstringval!!.keyListener = TextKeyListener.getInstance()
mTxtstringval!!.setText(flightProperty.toString())
val rgPrevVals = flightProperty!!.getCustomPropertyType()!!.previousValues
if (rgPrevVals.isNotEmpty()) {
val adapter = ArrayAdapter(
this.context, android.R.layout.simple_list_item_1,
rgPrevVals
)
mTxtstringval!!.setAdapter(adapter)
}
mTxtstringval!!.threshold = 1
}
CFPPropertyType.cfpBoolean -> {
mCk!!.visibility = VISIBLE
mTvlabel!!.visibility = GONE
}
CFPPropertyType.cfpDate -> {
mTvdate!!.visibility = VISIBLE
setPropDate(flightProperty!!.dateValue, false)
}
CFPPropertyType.cfpDateTime -> {
mTvdate!!.visibility = VISIBLE
setPropDate(flightProperty!!.dateValue, true)
}
}
findViewById<View>(R.id.imgFavorite).visibility = if (mIspinned) VISIBLE else INVISIBLE
}
private fun setPropDate(d: Date?, fUTC: Boolean) {
if (d == null || isNullDate(d)) mTvdate!!.text =
context.getString(if (fUTC) R.string.lblTouchForNow else R.string.lblTouchForToday) else mTvdate!!.text =
if (fUTC) formatDate(
DlgDatePicker.fUseLocalTime,
d,
context
) else DateFormat.getDateFormat(
context
).format(d)
}
val property: FlightProperty?
get() {
when (flightProperty?.getType()) {
CFPPropertyType.cfpInteger -> flightProperty!!.intValue = mTxtnumericfield!!.intValue
CFPPropertyType.cfpDecimal, CFPPropertyType.cfpCurrency -> flightProperty!!.decValue =
mTxtnumericfield!!.doubleValue
CFPPropertyType.cfpString -> flightProperty!!.stringValue = mTxtstringval!!.text.toString()
CFPPropertyType.cfpBoolean -> flightProperty!!.boolValue = mCk!!.isChecked
else -> {}
}
if (mPl != null)
mPl!!.updateProperty(mId, flightProperty!!)
return flightProperty
}
}
|
gpl-3.0
|
6c12100f729e217fb1a320aec172c6e3
| 39.768072 | 295 | 0.624058 | 4.807815 | false | false | false | false |
kmizu/kollection
|
src/test/kotlin/com/github/kmizu/kollection/KListSpec.kt
|
1
|
6701
|
package com.github.kmizu.kollection
import org.jetbrains.spek.api.Spek
import kotlin.test.assertEquals
import com.github.kmizu.kollection.KList.*
import com.github.kmizu.kollection.type_classes.KMonoid
import org.jetbrains.spek.api.dsl.*
class KListSpec(): Spek({
given("A nested KList") {
val a = KList(KList(1, 2), KList(3, 4), KList(5, 6))
on("performing sum") {
val result = a.sum(KMonoid.KLIST())
it("returns KList(1, 2, 3, 4, 5, 6)") {
assertEquals(KList(1, 2, 3, 4, 5, 6), result)
}
}
}
given("A KList of 1, 1, 2, 3, 3, 4, 5") {
val klist = KList(1, 1, 2, 3, 3, 4, 5)
on("performing distinct on the list") {
val result = klist.distinct()
it("produces KList(1, 2, 3, 4, 5)") {
assertEquals(KList(1, 2, 3, 4, 5), result)
}
}
}
given("A KList of 1, 2, 3, 4, 5") {
val klist = KList(1, 2, 3, 4, 5)
on("performing cons to each element") {
it("produces the same KList") {
val result = 1 cons (2 cons (3 cons (4 cons (5 cons Nil))))
assertEquals(klist, result)
}
}
on("performing contains") {
it("returns true on 5"){
assertEquals(true, klist.contains(5))
}
it("returns false on 6") {
assertEquals(false, klist.contains(6))
}
}
on("performing reverse") {
val result = klist.reverse()
it("produces KList(5, 4, 3, 2, 1)") {
assertEquals(KList(5, 4, 3, 2, 1), result)
}
}
on("calculating sum of the list using foldLeft") {
val result = klist.foldLeft(0){l, r -> l + r}
it("returns 15") {
assertEquals(15, result)
}
}
on("performing map") {
val result = klist.map{it + 1}
it("produces KList(2, 3, 4, 5)") {
assertEquals(KList(2, 3, 4, 5, 6), result)
}
}
on("calculating -sum using foldRight") {
val result = klist.foldRight(0){l, r -> r - l}
it("returns -15") {
assertEquals(-15, result)
}
}
on("performing flatMap") {
val result = klist.flatMap { x -> KList(x, x) }
it("produces KList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5)") {
assertEquals(KList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5), result)
}
}
on("performing zip to itself") {
val result = klist zip klist
it("produces KList(1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 5)") {
assertEquals(KList(1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 5), result)
}
}
on("performing zip to KList of 1, 2, 3") {
val result = klist zip KList(1, 2, 3)
it("produces KList(1 to 1, 2 to 2, 3 to 3)") {
assertEquals(KList(1 to 1, 2 to 2, 3 to 3), result)
}
}
on("performing length") {
val result = klist.length
it("returns 5") {
assertEquals(5, result)
}
}
on("performing isEmpty") {
val result = klist.isEmpty
it("returns false") {
assertEquals(false, result)
}
}
on("performing concat to KList of 1, 2, 3") {
val result = klist concat KList(1, 2, 3)
it("produces KList(1, 2, 3, 4, 5, 1, 2, 3") {
assertEquals(KList(1, 2, 3, 4, 5, 1, 2, 3), result)
}
}
on("performing unzip") {
val result = (klist zip KList(2, 3, 4, 5, 6)).unzip()
it("produces Pair(KList(1, 2, 3, 4, 5), KList(2, 3, 4, 5, 6") {
assertEquals(Pair(KList(1, 2, 3, 4, 5), KList(2, 3, 4, 5, 6)), result)
}
}
on("performing forAll [1]") {
val result = klist.forAll { it < 6}
it("returns true") {
assertEquals(true, result)
}
}
on("performing forAll [2]") {
val result = klist.forAll { it % 2 == 0}
it("returns false") {
assertEquals(false, result)
}
}
on("performing exists [1]") {
val result = klist.exists { it % 2 == 0}
it("returns true") {
assertEquals(true, result)
}
}
on("performing exists [2]") {
val result = klist.exists { it > 5}
it("returns false") {
assertEquals(false, result)
}
}
on("performing get which arg is 4") {
val result = klist[4]
it("returns 5") {
assertEquals(5, result)
}
}
}
given("A KList of KList of 1, 2 and KList of 3, 4 and KList of 5, 6") {
on("performing flatten") {
val result = KList(KList(1, 2), KList(3, 4), KList(5, 6)).flatten()
it("produces KList(1, 2, 3, 4, 5, 6") {
assertEquals(KList(1, 2, 3, 4, 5, 6), result)
}
}
}
given("A Nil") {
val knil: KList<Int> = Nil
on("performing reverse") {
it("produces Nil") {
assertEquals(Nil, knil.reverse())
}
}
on("performing foldLeft") {
it("produces 0") {
assertEquals(0, knil.foldRight(0){x, y -> x + y})
}
}
on("performing foldRight") {
it("produces 0") {
assertEquals(0, knil.foldRight(0){x, y -> x + y})
}
}
on("performing map") {
it("produces Nil") {
assertEquals(Nil, knil.map {it + 1})
}
}
on("performing flatMap") {
it("produces Nil") {
assertEquals(Nil, knil.flatMap{ x -> KList(x, x)})
}
}
on("performing concat to KList of 1, 2, 3") {
val list = KList(1, 2, 3)
it("produces KList(1, 2, 3)") {
assertEquals(KList(1, 2, 3), knil concat list)
}
}
on("performing isEmpty") {
it("returns true") {
assertEquals(true, knil.isEmpty)
}
}
on("performing length") {
it("returns 0") {
assertEquals(0, knil.length)
}
}
on("performing zip") {
it("returns Nil") {
assertEquals(Nil, knil zip KList(1))
}
}
}
})
|
mit
|
3f2483b640e2e0069546dddf3b3f2de6
| 33.015228 | 86 | 0.442322 | 3.794451 | false | false | false | false |
indy256/codelibrary
|
kotlin/MaxBipartiteMatchingEV.kt
|
1
|
823
|
// https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs in O(V * E)
fun maxMatching(graph: Array<out List<Int>>, n2: Int): Int {
val n1 = graph.size
val vis = BooleanArray(n1)
val matching = IntArray(n2) { -1 }
val findPath = DeepRecursiveFunction { u1 ->
vis[u1] = true
for (v in graph[u1]) {
val u2 = matching[v]
if (u2 == -1 || !vis[u2] && callRecursive(u2) == 1) {
matching[v] = u1
return@DeepRecursiveFunction 1
}
}
0
}
return (0 until n1).sumOf { vis.fill(false); findPath(it) }
}
// Usage example
fun main() {
val g = (1..2).map { arrayListOf<Int>() }.toTypedArray()
g[0].add(0)
g[0].add(1)
g[1].add(1)
println(2 == maxMatching(g, 2))
}
|
unlicense
|
6aa97c4de04f44dadff17bed99f7c007
| 27.37931 | 99 | 0.53706 | 3.048148 | false | false | false | false |
eugeis/ee
|
ee-design/src/main/kotlin/ee/design/gen/ts/DesignTsPojos.kt
|
1
|
8247
|
import ee.common.ext.joinSurroundIfNotEmptyToString
import ee.common.ext.then
import ee.design.EntityI
import ee.design.ModuleI
import ee.lang.*
import ee.lang.gen.ts.*
fun <T : ModuleI<*>> T.toAngularModuleTypeScript(c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """import {Component, Input} from '@angular/core';
${this.toAngularModuleImportServices()}
${this.toAngularGenerateComponentPart(c, "module", "view", hasProviders = true, hasClass = false)}
export class ${this.name()}ViewComponent {${"\n"}
${this.toAngularModuleConstructor(tab)}
}"""
}
fun <T : ModuleI<*>> T.toAngularModuleService(modules: List<ModuleI<*>>, c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """export class ${this.name()}ViewService {
pageElement = [${modules.filter { !it.isEMPTY() }.joinSurroundIfNotEmptyToString(", ") { """'${it.name()}'""" }}];
tabElement = [${this.entities().filter { !it.isEMPTY() }.joinSurroundIfNotEmptyToString() {
it.toAngularModuleTabElement()
}}];
pageName = '${this.name()}';
}
"""
}
fun <T : CompilationUnitI<*>> T.toAngularEntityViewTypeScript(c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """import {Component, OnInit} from '@angular/core';
import {TableDataService} from '@template/services/data.service';
import {${c.n(this)}DataService} from '@${this.parent().parent().name().toLowerCase()}/${this.parent().name().toLowerCase()}/${this.name().toLowerCase()}/service/${this.name().toLowerCase()}-data.service';
${this.toAngularGenerateComponentPart(c, "entity", "view", hasProviders = true, hasClass = true)}
${isOpen().then("export ")}class ${c.n(this)}ViewComponent implements ${c.n("OnInit")} {
${this.toTypeScriptEntityProp(c, tab)}
${this.toAngularConstructorDataService(tab)}
${this.toAngularViewOnInit(c, tab)}
}
"""
}
fun <T : CompilationUnitI<*>> T.toAngularEntityFormTypeScript(c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """import {Component, OnInit, Input} from '@angular/core';
import {${c.n(this)}DataService} from '@${this.parent().parent().name().toLowerCase()}/${this.parent().name().toLowerCase()}/${this.name().toLowerCase()}/service/${this.name().toLowerCase()}-data.service';
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularImportEntityComponent(it.type().findParentNonInternal())
else -> ""
}
}}
${this.toAngularGenerateComponentPart(c, "entity", "form", hasProviders = false, hasClass = false)}
${isOpen().then("export ")}class ${c.n(this)}FormComponent implements ${c.n("OnInit")} {
${props().filter { it.type() is EnumTypeI<*> }.joinSurroundIfNotEmptyToString("") {
it.type().toAngularGenerateEnumElement(c, tab, this)
}}
${this.toTypeScriptFormProp(c, tab)}
constructor(public ${this.name().toLowerCase()}DataService: ${this.name()}DataService,
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularPropOnConstructor()
else -> ""
}
}}) {}
${this.toAngularFormOnInit(c, tab)}
}
"""
}
fun <T : CompilationUnitI<*>> T.toAngularEntityListTypeScript(c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {TableDataService} from '@template/services/data.service';
import {${this.name()}DataService} from '@${this.parent().parent().name().toLowerCase()}/${this.parent().name().toLowerCase()}/${this.name().toLowerCase()}/service/${this.name().toLowerCase()}-data.service';
import {MatTableDataSource} from '@angular/material/table';
import {MatSort} from '@angular/material/sort';
${this.toAngularGenerateComponentPart(c, "entity", "list", hasProviders = true, hasClass = true)}
${isOpen().then("export ")}class ${c.n(this)}ListComponent implements ${c.n("OnInit")}, ${c.n("AfterViewInit")} {
${this.toTypeScriptEntityPropInit(c, tab)}
tableHeader: Array<String> = [];
@ViewChild(MatSort) sort: MatSort;
${this.toAngularConstructorDataService(tab)}
ngAfterViewInit() {
this.${this.name().toLowerCase()}DataService.dataSources.sort = this.sort;
}
${this.toAngularListOnInit(tab)}
generateTableHeader() {
return ['Box', 'Actions', ${props().filter { !it.isEMPTY() }.joinSurroundIfNotEmptyToString(", ") {
it.toAngularGenerateTableHeader(c)
}}];
}
}
"""
}
fun <T : CompilationUnitI<*>> T.toAngularEntityDataService(c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API): String {
return """
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularControlServiceImport(it.type().findParentNonInternal())
else -> ""
}
}}
import {Injectable} from '@angular/core';
import {TableDataService} from '@template/services/data.service';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@${c.n("Injectable")}()
${isOpen().then("export ")}class ${c.n(this)}DataService extends TableDataService {
itemName = '${c.n(this).toLowerCase()}';
pageName = '${c.n(this)}Component';
isHidden = true;
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularControlService()
else -> ""
}
}}
${this.props().filter { it.type().name().toLowerCase() == "blob" }.joinSurroundIfNotEmptyToString {
"""
selectedFiles?: FileList;
previews: string[] = [];
"""
}}
getFirst() {
return new ${c.n(this)}();
}
toggleHidden() {
this.isHidden = !this.isHidden;
}
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularControlServiceFunctions(it.type().props().first { element -> element.type().name() == "String" })
else -> ""
}
}}
initObservable() {
${this.props().filter { it.type() !is EnumTypeI<*> && it.type().name() !in arrayOf("boolean", "date", "list", "string") }.joinSurroundIfNotEmptyToString("") {
when(it.type()) {
is EntityI<*>, is ValuesI<*> -> it.type().toAngularInitObservable(it.type().props().first { element -> element.type().name() == "String" })
else -> ""
}
}}
}
${this.props().filter { it.type().name().toLowerCase() == "blob" }.joinSurroundIfNotEmptyToString {
"""
selectFiles(event: any): void {
this.selectedFiles = event.target.files;
this.previews = [];
if (this.selectedFiles) {
const fileReader = new FileReader();
fileReader.onload = (e: any) => {
this.previews.push(e.target.result);
};
fileReader.readAsDataURL(this.selectedFiles[0]);
}
}
"""
}}
}
"""
}
|
apache-2.0
|
1ba05ad01267de4bb852e529bc5f1e19
| 41.953125 | 207 | 0.616952 | 3.927143 | false | false | false | false |
googlecodelabs/admob-firebase-codelabs-android
|
102-complete/app/src/main/java/com/google/codelab/awesomedrawingquiz/ui/game/LevelFragment.kt
|
3
|
3492
|
/*
* 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
*
* 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.codelab.awesomedrawingquiz.ui.game
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.google.codelab.awesomedrawingquiz.AwesomeDrawingQuiz
import com.google.codelab.awesomedrawingquiz.R
import com.google.codelab.awesomedrawingquiz.databinding.DialogAnswerBinding
import com.google.codelab.awesomedrawingquiz.databinding.FragmentLevelBinding
class LevelFragment : Fragment() {
private var _binding: FragmentLevelBinding? = null
private var _dialogBinding: DialogAnswerBinding? = null
private val binding get() = _binding!!
private val dialogBinding get() = _dialogBinding!!
private val answerDialog by lazy {
AlertDialog.Builder(requireContext())
.setTitle(R.string.enter_your_answer)
.setView(dialogBinding.root)
.setPositiveButton(android.R.string.ok) { _, _ ->
viewModel.checkAnswer(dialogBinding.etAnswer.text.toString())
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
private val viewModel by activityViewModels<GameViewModel>() {
(requireActivity().application as AwesomeDrawingQuiz).provideViewModelFactory()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentLevelBinding.inflate(inflater, container, false)
_dialogBinding = DialogAnswerBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnAnswer.setOnClickListener {
dialogBinding.etAnswer.setText("")
answerDialog.show()
}
viewModel.registerGameEventListener {
when (it) {
is NewLevelEvent -> {
with (binding) {
tvLevel.text = getString(
R.string.level_indicator,
it.currentLevel,
GameSettings.MAX_GAME_LEVEL,
)
btnAnswer.text = it.clue
qvCanvas.draw(it.drawing)
}
dialogBinding.etAnswer.hint = it.clue
}
is ClueUpdateEvent -> {
binding.btnAnswer.text = it.newClue
dialogBinding.etAnswer.hint = it.newClue
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
_dialogBinding = null
}
}
|
apache-2.0
|
6d52ced10683410644218dcb638283eb
| 32.902913 | 87 | 0.640034 | 4.738128 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/libraries/LibraryConnectionProvider.kt
|
2
|
3371
|
package com.lasthopesoftware.bluewater.client.connection.libraries
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus
import com.lasthopesoftware.bluewater.client.connection.ConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.builder.live.ProvideLiveUrl
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.ValidateConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.client.connection.waking.WakeLibraryServer
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.propagation.CancellationProxy
class LibraryConnectionProvider(
private val validateConnectionSettings: ValidateConnectionSettings,
private val lookupConnectionSettings: LookupConnectionSettings,
private val wakeAlarm: WakeLibraryServer,
private val liveUrlProvider: ProvideLiveUrl,
private val okHttpFactory: OkHttpFactory
) : ProvideLibraryConnections {
override fun promiseLibraryConnection(libraryId: LibraryId): ProgressingPromise<BuildingConnectionStatus, IConnectionProvider?> =
object : ProgressingPromise<BuildingConnectionStatus, IConnectionProvider?>() {
private val cancellationProxy = CancellationProxy()
init {
respondToCancellation(cancellationProxy)
fulfillPromise()
}
private fun fulfillPromise() {
reportProgress(BuildingConnectionStatus.GettingLibrary)
lookupConnectionSettings
.lookupConnectionSettings(libraryId)
.eventually({ c ->
when {
c == null || !validateConnectionSettings.isValid(c) -> {
reportProgress(BuildingConnectionStatus.GettingLibraryFailed)
resolve(null)
empty()
}
c.isWakeOnLanEnabled -> wakeAndBuildConnection()
else -> buildConnection()
}
}, {
reportProgress(BuildingConnectionStatus.GettingLibraryFailed)
reject(it)
empty()
})
.then({
if (it != null) {
reportProgress(BuildingConnectionStatus.BuildingConnectionComplete)
resolve(ConnectionProvider(it, okHttpFactory))
} else {
reportProgress(BuildingConnectionStatus.BuildingConnectionFailed)
resolve(null)
}
}, {
reportProgress(BuildingConnectionStatus.BuildingConnectionFailed)
reject(it)
})
}
private fun wakeAndBuildConnection(): Promise<IUrlProvider?> {
if (cancellationProxy.isCancelled) return empty()
reportProgress(BuildingConnectionStatus.SendingWakeSignal)
return wakeAlarm
.awakeLibraryServer(libraryId)
.also(cancellationProxy::doCancel)
.eventually { buildConnection() }
}
private fun buildConnection(): Promise<IUrlProvider?> {
if (cancellationProxy.isCancelled) return empty()
reportProgress(BuildingConnectionStatus.BuildingConnection)
return liveUrlProvider.promiseLiveUrl(libraryId).also(cancellationProxy::doCancel)
}
}
}
|
lgpl-3.0
|
5d0db16477d8596c79795b7a639399e4
| 38.658824 | 130 | 0.789973 | 5.016369 | false | false | false | false |
thomasvolk/alkali
|
src/test/kotlin/net/t53k/alkali/PingPongTest.kt
|
1
|
2444
|
/*
* Copyright 2017 Thomas Volk
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package net.t53k.alkali
import net.t53k.alkali.test.actorTest
import org.junit.Assert
import org.junit.Test
class PingPongTest {
class PingActor: Actor() {
object Start
object Stop
object Ping
private var lastPongId = 0
private var starter: ActorReference? = null
override fun receive(message: Any) {
when(message) {
Start -> {
system().find("pong")!! send Ping
starter = sender()
}
Stop -> {
sender() send PoisonPill
self() send PoisonPill
starter!! send lastPongId
}
is PongActor.Pong -> {
lastPongId = message.id
sender() send Ping
}
}
}
}
class PongActor: Actor() {
data class Pong(val id: Int)
private var count = 0
override fun receive(message: Any) {
when(message) {
PingActor.Ping -> {
count++
if(count < 100) sender() send Pong(count)
else sender() send PingActor.Stop
}
}
}
}
@Test
fun pingPong() {
actorTest {
val ping = testSystem().actor("ping", PingActor::class)
testSystem().actor("pong", PongActor::class)
ping send PingActor.Start
onMessage { message ->
Assert.assertEquals(99, message)
}
}
}
}
|
apache-2.0
|
595fd53ecc526fd61f693c4fe3c0ab95
| 29.5625 | 67 | 0.558101 | 4.736434 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.